context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
// Copyright (c) H. Ibrahim Penekli. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using UnityEngine;
namespace GameToolkit.Localization
{
[Serializable]
public class Language : IEquatable<Language>
{
public static Language[] BuiltinLanguages
{
get
{
return new[]
{
Afrikaans,
Arabic,
Basque,
Belarusian,
Bulgarian,
Catalan,
Chinese,
Czech,
Danish,
Dutch,
English,
Estonian,
Faroese,
Finnish,
French,
German,
Greek,
Hebrew,
Hungarian,
Icelandic,
Indonesian,
Italian,
Japanese,
Korean,
Latvian,
Lithuanian,
Norwegian,
Polish,
Portuguese,
Romanian,
Russian,
SerboCroatian,
Slovak,
Slovenian,
Spanish,
Swedish,
Thai,
Turkish,
Ukrainian,
Vietnamese,
ChineseSimplified,
ChineseTraditional,
Unknown
};
}
}
public static Language Afrikaans
{
get { return new Language(SystemLanguage.Afrikaans.ToString(), "af", false); }
}
public static Language Arabic
{
get { return new Language(SystemLanguage.Arabic.ToString(), "ar", false); }
}
public static Language Basque
{
get { return new Language(SystemLanguage.Basque.ToString(), "eu", false); }
}
public static Language Belarusian
{
get { return new Language(SystemLanguage.Belarusian.ToString(), "be", false); }
}
public static Language Bulgarian
{
get { return new Language(SystemLanguage.Bulgarian.ToString(), "bg", false); }
}
public static Language Catalan
{
get { return new Language(SystemLanguage.Catalan.ToString(), "ca", false); }
}
public static Language Chinese
{
get { return new Language(SystemLanguage.Chinese.ToString(), "zh", false); }
}
public static Language Czech
{
get { return new Language(SystemLanguage.Czech.ToString(), "cs", false); }
}
public static Language Danish
{
get { return new Language(SystemLanguage.Danish.ToString(), "da", false); }
}
public static Language Dutch
{
get { return new Language(SystemLanguage.Dutch.ToString(), "nl", false); }
}
public static Language English
{
get { return new Language(SystemLanguage.English.ToString(), "en", false); }
}
public static Language Estonian
{
get { return new Language(SystemLanguage.Estonian.ToString(), "et", false); }
}
public static Language Faroese
{
get { return new Language(SystemLanguage.Faroese.ToString(), "fo", false); }
}
public static Language Finnish
{
get { return new Language(SystemLanguage.Finnish.ToString(), "fi", false); }
}
public static Language French
{
get { return new Language(SystemLanguage.French.ToString(), "fr", false); }
}
public static Language German
{
get { return new Language(SystemLanguage.German.ToString(), "de", false); }
}
public static Language Greek
{
get { return new Language(SystemLanguage.Greek.ToString(), "el", false); }
}
public static Language Hebrew
{
get { return new Language(SystemLanguage.Hebrew.ToString(), "he", false); }
}
public static Language Hungarian
{
get { return new Language(SystemLanguage.Hungarian.ToString(), "hu", false); }
}
public static Language Icelandic
{
get { return new Language(SystemLanguage.Icelandic.ToString(), "is", false); }
}
public static Language Indonesian
{
get { return new Language(SystemLanguage.Indonesian.ToString(), "id", false); }
}
public static Language Italian
{
get { return new Language(SystemLanguage.Italian.ToString(), "it", false); }
}
public static Language Japanese
{
get { return new Language(SystemLanguage.Japanese.ToString(), "ja", false); }
}
public static Language Korean
{
get { return new Language(SystemLanguage.Korean.ToString(), "ko", false); }
}
public static Language Latvian
{
get { return new Language(SystemLanguage.Latvian.ToString(), "lv", false); }
}
public static Language Lithuanian
{
get { return new Language(SystemLanguage.Lithuanian.ToString(), "lt", false); }
}
public static Language Norwegian
{
get { return new Language(SystemLanguage.Norwegian.ToString(), "no", false); }
}
public static Language Polish
{
get { return new Language(SystemLanguage.Polish.ToString(), "pl", false); }
}
public static Language Portuguese
{
get { return new Language(SystemLanguage.Portuguese.ToString(), "pt", false); }
}
public static Language Romanian
{
get { return new Language(SystemLanguage.Romanian.ToString(), "ro", false); }
}
public static Language Russian
{
get { return new Language(SystemLanguage.Russian.ToString(), "ru", false); }
}
public static Language SerboCroatian
{
get { return new Language(SystemLanguage.SerboCroatian.ToString(), "hr", false); }
}
public static Language Slovak
{
get { return new Language(SystemLanguage.Slovak.ToString(), "sk", false); }
}
public static Language Slovenian
{
get { return new Language(SystemLanguage.Slovenian.ToString(), "sl", false); }
}
public static Language Spanish
{
get { return new Language(SystemLanguage.Spanish.ToString(), "es", false); }
}
public static Language Swedish
{
get { return new Language(SystemLanguage.Swedish.ToString(), "sv", false); }
}
public static Language Thai
{
get { return new Language(SystemLanguage.Thai.ToString(), "th", false); }
}
public static Language Turkish
{
get { return new Language(SystemLanguage.Turkish.ToString(), "tr", false); }
}
public static Language Ukrainian
{
get { return new Language(SystemLanguage.Ukrainian.ToString(), "uk", false); }
}
public static Language Vietnamese
{
get { return new Language(SystemLanguage.Vietnamese.ToString(), "vi", false); }
}
public static Language ChineseSimplified
{
get { return new Language(SystemLanguage.ChineseSimplified.ToString(), "zh-Hans", false); }
}
public static Language ChineseTraditional
{
get { return new Language(SystemLanguage.ChineseTraditional.ToString(), "zh-Hant", false); }
}
public static Language Unknown
{
get { return new Language(SystemLanguage.Unknown.ToString(), "", false); }
}
[SerializeField]
private string m_Name = "";
[SerializeField]
private string m_Code = "";
[SerializeField]
private bool m_Custom = true;
/// <summary>
/// Language name.
/// </summary>
public string Name
{
get { return m_Name; }
}
/// <summary>
/// Gets the <see href="https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes">ISO-639-1</see> language code.
/// </summary>
/// <returns>ISO-639-1 code.</returns>
public string Code
{
get { return m_Code; }
}
/// <summary>
/// Language is whether custom or built-in that supports <see cref="SystemLanguage"/> conversions.
/// </summary>
public bool Custom
{
get { return m_Custom; }
}
public Language(string name, string code)
{
m_Name = name ?? "";
m_Code = code ?? "";
m_Custom = true;
}
public Language(Language other)
{
m_Name = other.m_Name;
m_Code = other.m_Code;
m_Custom = other.m_Custom;
}
internal Language(string name, string code, bool custom)
{
m_Name = name ?? "";
m_Code = code ?? "";
m_Custom = custom;
}
public bool Equals(Language other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return Code == other.Code;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((Language) obj);
}
public override int GetHashCode()
{
return Code.GetHashCode();
}
public static bool operator ==(Language left, Language right)
{
return Equals(left, right);
}
public static bool operator !=(Language left, Language right)
{
return !Equals(left, right);
}
public override string ToString()
{
return Name;
}
public static implicit operator Language(SystemLanguage systemLanguage)
{
var index = Array.FindIndex(BuiltinLanguages, x => x.Name == systemLanguage.ToString());
return index >= 0 ? BuiltinLanguages[index] : Unknown;
}
public static explicit operator SystemLanguage(Language language)
{
if (language.Custom) return SystemLanguage.Unknown;
var systemLanguages = (SystemLanguage[]) Enum.GetValues(typeof(SystemLanguage));
var index = Array.FindIndex(systemLanguages, x => x.ToString() == language.Name);
return index >= 0 ? systemLanguages[index] : SystemLanguage.Unknown;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Web.Routing;
using Nop.Core.Domain.Orders;
using Nop.Core.Domain.Payments;
using Nop.Core.Plugins;
using Nop.Plugin.Payments.CashOnDelivery.Controllers;
using Nop.Services.Configuration;
using Nop.Services.Localization;
using Nop.Services.Orders;
using Nop.Services.Payments;
namespace Nop.Plugin.Payments.CashOnDelivery
{
/// <summary>
/// CashOnDelivery payment processor
/// </summary>
public class CashOnDeliveryPaymentProcessor : BasePlugin, IPaymentMethod
{
#region Fields
private readonly CashOnDeliveryPaymentSettings _cashOnDeliveryPaymentSettings;
private readonly ISettingService _settingService;
private readonly IOrderTotalCalculationService _orderTotalCalculationService;
#endregion
#region Ctor
public CashOnDeliveryPaymentProcessor(CashOnDeliveryPaymentSettings cashOnDeliveryPaymentSettings,
ISettingService settingService, IOrderTotalCalculationService orderTotalCalculationService)
{
this._cashOnDeliveryPaymentSettings = cashOnDeliveryPaymentSettings;
this._settingService = settingService;
this._orderTotalCalculationService = orderTotalCalculationService;
}
#endregion
#region Methods
/// <summary>
/// Process a payment
/// </summary>
/// <param name="processPaymentRequest">Payment info required for an order processing</param>
/// <returns>Process payment result</returns>
public ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest)
{
var result = new ProcessPaymentResult();
result.NewPaymentStatus = PaymentStatus.Pending;
return result;
}
/// <summary>
/// Post process payment (used by payment gateways that require redirecting to a third-party URL)
/// </summary>
/// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
{
//nothing
}
/// <summary>
/// Gets additional handling fee
/// </summary>
/// <param name="cart">Shoping cart</param>
/// <returns>Additional handling fee</returns>
public decimal GetAdditionalHandlingFee(IList<ShoppingCartItem> cart)
{
var result = this.CalculateAdditionalFee(_orderTotalCalculationService, cart,
_cashOnDeliveryPaymentSettings.AdditionalFee, _cashOnDeliveryPaymentSettings.AdditionalFeePercentage);
return result;
}
/// <summary>
/// Captures payment
/// </summary>
/// <param name="capturePaymentRequest">Capture payment request</param>
/// <returns>Capture payment result</returns>
public CapturePaymentResult Capture(CapturePaymentRequest capturePaymentRequest)
{
var result = new CapturePaymentResult();
result.AddError("Capture method not supported");
return result;
}
/// <summary>
/// Refunds a payment
/// </summary>
/// <param name="refundPaymentRequest">Request</param>
/// <returns>Result</returns>
public RefundPaymentResult Refund(RefundPaymentRequest refundPaymentRequest)
{
var result = new RefundPaymentResult();
result.AddError("Refund method not supported");
return result;
}
/// <summary>
/// Voids a payment
/// </summary>
/// <param name="voidPaymentRequest">Request</param>
/// <returns>Result</returns>
public VoidPaymentResult Void(VoidPaymentRequest voidPaymentRequest)
{
var result = new VoidPaymentResult();
result.AddError("Void method not supported");
return result;
}
/// <summary>
/// Process recurring payment
/// </summary>
/// <param name="processPaymentRequest">Payment info required for an order processing</param>
/// <returns>Process payment result</returns>
public ProcessPaymentResult ProcessRecurringPayment(ProcessPaymentRequest processPaymentRequest)
{
var result = new ProcessPaymentResult();
result.AddError("Recurring payment not supported");
return result;
}
/// <summary>
/// Cancels a recurring payment
/// </summary>
/// <param name="cancelPaymentRequest">Request</param>
/// <returns>Result</returns>
public CancelRecurringPaymentResult CancelRecurringPayment(CancelRecurringPaymentRequest cancelPaymentRequest)
{
var result = new CancelRecurringPaymentResult();
result.AddError("Recurring payment not supported");
return result;
}
/// <summary>
/// Gets a value indicating whether customers can complete a payment after order is placed but not completed (for redirection payment methods)
/// </summary>
/// <param name="order">Order</param>
/// <returns>Result</returns>
public bool CanRePostProcessPayment(Order order)
{
if (order == null)
throw new ArgumentNullException("order");
//it's not a redirection payment method. So we always return false
return false;
}
/// <summary>
/// Gets a route for provider configuration
/// </summary>
/// <param name="actionName">Action name</param>
/// <param name="controllerName">Controller name</param>
/// <param name="routeValues">Route values</param>
public void GetConfigurationRoute(out string actionName, out string controllerName, out RouteValueDictionary routeValues)
{
actionName = "Configure";
controllerName = "PaymentCashOnDelivery";
routeValues = new RouteValueDictionary() { { "Namespaces", "Nop.Plugin.Payments.CashOnDelivery.Controllers" }, { "area", null } };
}
/// <summary>
/// Gets a route for payment info
/// </summary>
/// <param name="actionName">Action name</param>
/// <param name="controllerName">Controller name</param>
/// <param name="routeValues">Route values</param>
public void GetPaymentInfoRoute(out string actionName, out string controllerName, out RouteValueDictionary routeValues)
{
actionName = "PaymentInfo";
controllerName = "PaymentCashOnDelivery";
routeValues = new RouteValueDictionary() { { "Namespaces", "Nop.Plugin.Payments.CashOnDelivery.Controllers" }, { "area", null } };
}
public Type GetControllerType()
{
return typeof(PaymentCashOnDeliveryController);
}
public override void Install()
{
var settings = new CashOnDeliveryPaymentSettings()
{
DescriptionText = "<p>In cases where an order is placed, an authorized representative will contact you, personally or over telephone, to confirm the order.<br />After the order is confirmed, it will be processed.<br />Orders once confirmed, cannot be cancelled.</p><p>P.S. You can edit this text from admin panel.</p>"
};
_settingService.SaveSetting(settings);
this.AddOrUpdatePluginLocaleResource("Plugins.Payment.CashOnDelivery.DescriptionText", "Description");
this.AddOrUpdatePluginLocaleResource("Plugins.Payment.CashOnDelivery.DescriptionText.Hint", "Enter info that will be shown to customers during checkout");
this.AddOrUpdatePluginLocaleResource("Plugins.Payment.CashOnDelivery.AdditionalFee", "Additional fee");
this.AddOrUpdatePluginLocaleResource("Plugins.Payment.CashOnDelivery.AdditionalFee.Hint", "The additional fee.");
this.AddOrUpdatePluginLocaleResource("Plugins.Payment.CashOnDelivery.AdditionalFeePercentage", "Additional fee. Use percentage");
this.AddOrUpdatePluginLocaleResource("Plugins.Payment.CashOnDelivery.AdditionalFeePercentage.Hint", "Determines whether to apply a percentage additional fee to the order total. If not enabled, a fixed value is used.");
base.Install();
}
public override void Uninstall()
{
//settings
_settingService.DeleteSetting<CashOnDeliveryPaymentSettings>();
//locales
this.DeletePluginLocaleResource("Plugins.Payment.CashOnDelivery.DescriptionText");
this.DeletePluginLocaleResource("Plugins.Payment.CashOnDelivery.DescriptionText.Hint");
this.DeletePluginLocaleResource("Plugins.Payment.CashOnDelivery.AdditionalFee");
this.DeletePluginLocaleResource("Plugins.Payment.CashOnDelivery.AdditionalFee.Hint");
this.DeletePluginLocaleResource("Plugins.Payment.CashOnDelivery.AdditionalFeePercentage");
this.DeletePluginLocaleResource("Plugins.Payment.CashOnDelivery.AdditionalFeePercentage.Hint");
base.Uninstall();
}
#endregion
#region Properies
/// <summary>
/// Gets a value indicating whether capture is supported
/// </summary>
public bool SupportCapture
{
get
{
return false;
}
}
/// <summary>
/// Gets a value indicating whether partial refund is supported
/// </summary>
public bool SupportPartiallyRefund
{
get
{
return false;
}
}
/// <summary>
/// Gets a value indicating whether refund is supported
/// </summary>
public bool SupportRefund
{
get
{
return false;
}
}
/// <summary>
/// Gets a value indicating whether void is supported
/// </summary>
public bool SupportVoid
{
get
{
return false;
}
}
/// <summary>
/// Gets a recurring payment type of payment method
/// </summary>
public RecurringPaymentType RecurringPaymentType
{
get
{
return RecurringPaymentType.NotSupported;
}
}
/// <summary>
/// Gets a payment method type
/// </summary>
public PaymentMethodType PaymentMethodType
{
get
{
return PaymentMethodType.Standard;
}
}
/// <summary>
/// Gets a value indicating whether we should display a payment information page for this plugin
/// </summary>
public bool SkipPaymentInfo
{
get
{
return false;
}
}
#endregion
}
}
| |
using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
using DevExpress.Utils;
using bv.common.Configuration;
using bv.common.Core;
using bv.common.Resources;
using bv.winclient.Localization;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using Localizer = bv.common.Core.Localizer;
namespace bv.winclient.Core
{
public class WinUtils
{
private static readonly Graphics m_Graphics;
static WinUtils()
{
var label = new Label();
m_Graphics = label.CreateGraphics();
}
public static SizeF MeasureString(String text, Font font, int width)
{
return m_Graphics.MeasureString(text, font, width);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public static string AppPath()
{
return Path.GetDirectoryName(Application.ExecutablePath);
}
/// <summary>
///
/// </summary>
/// <param name="msg"></param>
/// <param name="caption"></param>
/// <returns></returns>
public static bool ConfirmMessage(string msg, string caption)
{
return MessageForm.Show(msg, caption, MessageBoxButtons.YesNo, MessageBoxIcon.Question).Equals(DialogResult.Yes);
}
public static bool ConfirmMessage(string msg)
{
return MessageForm.Show(msg, BvMessages.Get("Warning"), MessageBoxButtons.YesNo, MessageBoxIcon.Question).Equals(DialogResult.Yes);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public static bool ConfirmDelete()
{
return ConfirmMessage(BvMessages.Get("msgDeleteRecordPrompt", "The record will be deleted. Delete record?"), BvMessages.Get("Delete Record", null));
}
public static bool ConfirmLookupClear()
{
return ConfirmMessage(BvMessages.Get("msgConfirmClearLookup"), BvMessages.Get("Confirmation"));
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public static bool ConfirmCancel(Form owner)
{
if (owner != null)
{
owner.Activate();
owner.BringToFront();
}
return ConfirmMessage(BvMessages.Get("msgCancelPrompt", "Do you want to cancel all the changes and close the form?"), BvMessages.Get("Confirmation", null));
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public static bool ConfirmSave()
{
return ConfirmMessage(BvMessages.Get("msgSavePrompt", "Do you want to save changes?"), BvMessages.Get("Confirmation", null));
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public static bool ConfirmOk()
{
return ConfirmMessage(BvMessages.Get("msgOKPrompt", "Do you want to save changes and close the form?"), BvMessages.Get("Confirmation", null));
}
/// <summary>
///
/// </summary>
public static void SwitchInputLanguage()
{
foreach (InputLanguage lang in InputLanguage.InstalledInputLanguages)
{
if (lang.Culture.TwoLetterISOLanguageName == Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName)
{
InputLanguage.CurrentInputLanguage = lang;
return;
}
}
}
private static readonly Regex ControlLanguageRegExp = new Regex("\\[(?<lng>.*)\\]", RegexOptions.IgnoreCase);
private static string GetLanguageTag(Control c)
{
if (c != null && (c.Tag) is string)
{
Match m = ControlLanguageRegExp.Match(Convert.ToString(c.Tag));
if (m.Success)
return m.Result("${lng}");
}
return null;
}
public static void SetControlLanguage(Control c, ref string lastInputLanguage)
{
lastInputLanguage = Localizer.GetLanguageID(InputLanguage.CurrentInputLanguage.Culture);
string s = GetLanguageTag(c);
if (!string.IsNullOrEmpty(s))
SystemLanguages.SwitchInputLanguage(s);
}
public static string GetControlLanguage(Control c)
{
string lang = GetLanguageTag(c);
if (!string.IsNullOrEmpty(lang))
{
string Res = "";
if (lang == "def")
lang = BaseSettings.DefaultLanguage;
if (Localizer.SupportedLanguages.ContainsKey(lang))
Res = Convert.ToString(Localizer.SupportedLanguages[lang]);
if (Res != "")
{
foreach (InputLanguage language in InputLanguage.InstalledInputLanguages)
{
if (language.Culture.Name == Res)
{
return language.Culture.TwoLetterISOLanguageName;
}
}
}
}
return "";
//return InputLanguage.CurrentInputLanguage.Culture.TwoLetterISOLanguageName;
}
public static bool HasControlAssignedLanguage(Control c)
{
if (c.Tag != null)
{
System.Text.RegularExpressions.Match m = ControlLanguageRegExp.Match(Convert.ToString(c.Tag));
return m.Success;
}
return false;
}
public static void AddClearButton(ButtonEdit ctl)
{
foreach (EditorButton button in ctl.Properties.Buttons)
{
if (button.Kind == ButtonPredefines.Delete)
{
return;
}
}
ctl.ButtonClick += ClearButtonClick;
var btn = new EditorButton(ButtonPredefines.Delete, BvMessages.Get("btnClear", "Clear the field contents"));
ctl.Properties.Buttons.Add(btn);
}
public static void AddClearButtons(Control container)
{
foreach (Control ctl in container.Controls)
{
if ((ctl) is ButtonEdit)
{
AddClearButton((ButtonEdit)ctl);
}
}
}
private static void ClearButtonClick(object sender, ButtonPressedEventArgs e)
{
if (e.Button.Kind == ButtonPredefines.Delete)
{
((BaseEdit)sender).EditValue = null;
}
}
private const int START_FRAME = 4;
public static bool IsComponentInDesignMode(IComponent component)
{
//' if all is simple
if (!(component.Site == null))
{
return component.Site.DesignMode;
}
//' not so simple...
Type sm_Interface_Match = typeof(IDesignerHost);
StackTrace stack = new StackTrace();
int frameCount = stack.FrameCount - 1;
//' look up in stack trace for type that implements interface IDesignerHost
for (int frame = START_FRAME; frame <= frameCount; frame++)
{
Type typeFromStack = stack.GetFrame(frame).GetMethod().DeclaringType;
if (sm_Interface_Match.IsAssignableFrom(typeFromStack))
{
return true;
}
}
//' small stack trace or IDesignerHost absence is not characteristic of designers
return false;
}
public static bool CheckMandatoryField(string fieldName, object value)
{
if (Utils.IsEmpty(value))
{
ErrorForm.ShowWarningFormat("ErrMandatoryFieldRequired", "The field '{0}' is mandatory. You must enter data to this field before form saving", fieldName);
return false;
}
return true;
}
public static bool CompareDates(object lessDate, object moreDate, string errMsg)
{
if (Utils.IsEmpty(lessDate) || Utils.IsEmpty(moreDate))
return true;
if (((DateTime)lessDate).Date > ((DateTime)moreDate).Date)
{
ErrorForm.ShowWarning(errMsg);
return false;
}
return true;
}
public static bool CompareDates(object lessDate, object moreDate)
{
if (Utils.IsEmpty(lessDate) || Utils.IsEmpty(moreDate))
return true;
if (((DateTime)lessDate).Date > ((DateTime)moreDate).Date)
return false;
return true;
}
public static bool ValidateDateInRange(object date, object startDate, object endDate)
{
if (Utils.IsEmpty(date))
return true;
if ((!Utils.IsEmpty(startDate) && ((DateTime)date).Date < ((DateTime)startDate).Date) ||
(!Utils.IsEmpty(endDate) && ((DateTime)date).Date > ((DateTime)endDate).Date))
{
return false;
}
return true;
}
public static void SetClearTooltip(BaseEdit ctl)
{
var tooltip = BvMessages.Get("msgClearControl", "Press Ctrl-Del to clear value.");
if (ctl.ToolTip == null || !ctl.ToolTip.Contains(tooltip))
{
ctl.ToolTip = tooltip;
ctl.ToolTipIconType = ToolTipIconType.None;
}
}
}
}
| |
#region License, Terms and Author(s)
//
// JSON Checker
// Copyright (c) 2007 Atif Aziz. All rights reserved.
//
// Author(s):
//
// Atif Aziz, http://www.raboof.com
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the New BSD License, a copy of which should have
// been delivered along with this 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
// 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.
//
#endregion
#region Original JSON_checker.c License
/* 2007-08-24 */
/*
Copyright (c) 2005 JSON.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
The Software shall be used for Good, not Evil.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#endregion
namespace JsonCheckerTool
{
#region Imports
using System;
using System.Collections.Generic;
#endregion
/// <summary>
/// JsonChecker is a Pushdown Automaton that very quickly determines if a
/// JSON text is syntactically correct. It could be used to filter inputs
/// to a system, or to verify that the outputs of a system are
/// syntactically correct.
/// </summary>
/// <remarks>
/// This implementation is a C# port of the original
/// <a href="http://www.json.org/JSON_checker/">JSON_checker</a> program
/// written in C.
/// </remarks>
internal sealed class JsonChecker
{
private int _state;
private long _offset;
private readonly int _depth;
private readonly Stack<Mode> _stack;
private const int __ = -1; /* the universal error code */
/*
Characters are mapped into these 31 character classes. This allows for
a significant reduction in the size of the state transition table.
*/
private const int C_SPACE = 0; /* space */
private const int C_WHITE = 1; /* other whitespace */
private const int C_LCURB = 2; /* { */
private const int C_RCURB = 3; /* } */
private const int C_LSQRB = 4; /* [ */
private const int C_RSQRB = 5; /* ] */
private const int C_COLON = 6; /* : */
private const int C_COMMA = 7; /* ; */
private const int C_QUOTE = 8; /* " */
private const int C_BACKS = 9; /* \ */
private const int C_SLASH = 10; /* / */
private const int C_PLUS = 11; /* + */
private const int C_MINUS = 12; /* - */
private const int C_POINT = 13; /* . */
private const int C_ZERO = 14; /* 0 */
private const int C_DIGIT = 15; /* 123456789 */
private const int C_LOW_A = 16; /* a */
private const int C_LOW_B = 17; /* b */
private const int C_LOW_C = 18; /* c */
private const int C_LOW_D = 19; /* d */
private const int C_LOW_E = 20; /* e */
private const int C_LOW_F = 21; /* f */
private const int C_LOW_L = 22; /* l */
private const int C_LOW_N = 23; /* n */
private const int C_LOW_R = 24; /* r */
private const int C_LOW_S = 25; /* s */
private const int C_LOW_T = 26; /* t */
private const int C_LOW_U = 27; /* u */
private const int C_ABCDF = 28; /* ABCDF */
private const int C_E = 29; /* E */
private const int C_ETC = 30; /* everything else */
private const int NR_CLASSES = 31;
private static readonly int[] ascii_class = new int[128]
{
/*
This array maps the 128 ASCII characters into character classes.
The remaining Unicode characters should be mapped to C_ETC.
Non-whitespace control characters are errors.
*/
__, __, __, __, __, __, __, __,
__, C_WHITE, C_WHITE, __, __, C_WHITE, __, __,
__, __, __, __, __, __, __, __,
__, __, __, __, __, __, __, __,
C_SPACE, C_ETC, C_QUOTE, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC,
C_ETC, C_ETC, C_ETC, C_PLUS, C_COMMA, C_MINUS, C_POINT, C_SLASH,
C_ZERO, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT,
C_DIGIT, C_DIGIT, C_COLON, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC,
C_ETC, C_ABCDF, C_ABCDF, C_ABCDF, C_ABCDF, C_E, C_ABCDF, C_ETC,
C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC,
C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC,
C_ETC, C_ETC, C_ETC, C_LSQRB, C_BACKS, C_RSQRB, C_ETC, C_ETC,
C_ETC, C_LOW_A, C_LOW_B, C_LOW_C, C_LOW_D, C_LOW_E, C_LOW_F, C_ETC,
C_ETC, C_ETC, C_ETC, C_ETC, C_LOW_L, C_ETC, C_LOW_N, C_ETC,
C_ETC, C_ETC, C_LOW_R, C_LOW_S, C_LOW_T, C_LOW_U, C_ETC, C_ETC,
C_ETC, C_ETC, C_ETC, C_LCURB, C_ETC, C_RCURB, C_ETC, C_ETC
};
/*
The state codes.
*/
private const int GO = 00; /* start */
private const int OK = 01; /* ok */
private const int OB = 02; /* object */
private const int KE = 03; /* key */
private const int CO = 04; /* colon */
private const int VA = 05; /* value */
private const int AR = 06; /* array */
private const int ST = 07; /* string */
private const int ES = 08; /* escape */
private const int U1 = 09; /* u1 */
private const int U2 = 10; /* u2 */
private const int U3 = 11; /* u3 */
private const int U4 = 12; /* u4 */
private const int MI = 13; /* minus */
private const int ZE = 14; /* zero */
private const int IN = 15; /* integer */
private const int FR = 16; /* fraction */
private const int E1 = 17; /* e */
private const int E2 = 18; /* ex */
private const int E3 = 19; /* exp */
private const int T1 = 20; /* tr */
private const int T2 = 21; /* tru */
private const int T3 = 22; /* true */
private const int F1 = 23; /* fa */
private const int F2 = 24; /* fal */
private const int F3 = 25; /* fals */
private const int F4 = 26; /* false */
private const int N1 = 27; /* nu */
private const int N2 = 28; /* nul */
private const int N3 = 29; /* null */
private const int NR_STATES = 30;
private static readonly int[,] state_transition_table = new int[NR_STATES, NR_CLASSES]
{
/*
The state transition table takes the current state and the current symbol,
and returns either a new state or an action. An action is represented as a
negative number. A JSON text is accepted if at the end of the text the
state is OK and if the mode is Done.
white 1-9 ABCDF etc
space | { } [ ] : , " \ / + - . 0 | a b c d e f l n r s t u | E |*/
/*start GO*/ {GO,GO,-6,__,-5,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__},
/*ok OK*/ {OK,OK,__,-8,__,-7,__,-3,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__},
/*object OB*/ {OB,OB,__,-9,__,__,__,__,ST,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__},
/*key KE*/ {KE,KE,__,__,__,__,__,__,ST,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__},
/*colon CO*/ {CO,CO,__,__,__,__,-2,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__},
/*value VA*/ {VA,VA,-6,__,-5,__,__,__,ST,__,__,__,MI,__,ZE,IN,__,__,__,__,__,F1,__,N1,__,__,T1,__,__,__,__},
/*array AR*/ {AR,AR,-6,__,-5,-7,__,__,ST,__,__,__,MI,__,ZE,IN,__,__,__,__,__,F1,__,N1,__,__,T1,__,__,__,__},
/*string ST*/ {ST,__,ST,ST,ST,ST,ST,ST,-4,ES,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST},
/*escape ES*/ {__,__,__,__,__,__,__,__,ST,ST,ST,__,__,__,__,__,__,ST,__,__,__,ST,__,ST,ST,__,ST,U1,__,__,__},
/*u1 U1*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,U2,U2,U2,U2,U2,U2,U2,U2,__,__,__,__,__,__,U2,U2,__},
/*u2 U2*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,U3,U3,U3,U3,U3,U3,U3,U3,__,__,__,__,__,__,U3,U3,__},
/*u3 U3*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,U4,U4,U4,U4,U4,U4,U4,U4,__,__,__,__,__,__,U4,U4,__},
/*u4 U4*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,ST,ST,ST,ST,ST,ST,ST,ST,__,__,__,__,__,__,ST,ST,__},
/*minus MI*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,ZE,IN,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__},
/*zero ZE*/ {OK,OK,__,-8,__,-7,__,-3,__,__,__,__,__,FR,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__},
/*int IN*/ {OK,OK,__,-8,__,-7,__,-3,__,__,__,__,__,FR,IN,IN,__,__,__,__,E1,__,__,__,__,__,__,__,__,E1,__},
/*frac FR*/ {OK,OK,__,-8,__,-7,__,-3,__,__,__,__,__,__,FR,FR,__,__,__,__,E1,__,__,__,__,__,__,__,__,E1,__},
/*e E1*/ {__,__,__,__,__,__,__,__,__,__,__,E2,E2,__,E3,E3,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__},
/*ex E2*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,E3,E3,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__},
/*exp E3*/ {OK,OK,__,-8,__,-7,__,-3,__,__,__,__,__,__,E3,E3,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__},
/*tr T1*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,T2,__,__,__,__,__,__},
/*tru T2*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,T3,__,__,__},
/*true T3*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,OK,__,__,__,__,__,__,__,__,__,__},
/*fa F1*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,F2,__,__,__,__,__,__,__,__,__,__,__,__,__,__},
/*fal F2*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,F3,__,__,__,__,__,__,__,__},
/*fals F3*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,F4,__,__,__,__,__},
/*false F4*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,OK,__,__,__,__,__,__,__,__,__,__},
/*nu N1*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,N2,__,__,__},
/*nul N2*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,N3,__,__,__,__,__,__,__,__},
/*null N3*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,OK,__,__,__,__,__,__,__,__},
};
/*
These modes can be pushed on the stack.
*/
private enum Mode
{
Array,
Done,
Key,
Object,
};
public const int NoDepthLimit = 0;
public JsonChecker() : this(NoDepthLimit) { }
public JsonChecker(int depth)
{
if (depth < 0)
throw new ArgumentOutOfRangeException("depth", depth, null);
/*
Starts the checking process by constructing a JsonChecker
object. It takes a depth parameter that restricts the level of maximum
nesting.
To continue the process, call Check for each character in the
JSON text, and then call FinalCheck to obtain the final result.
These functions are fully reentrant.
The JsonChecker object will be deleted by FinalCheck.
Check will delete the JsonChecker object if it sees an error.
*/
_state = GO;
_depth = depth;
_stack = new Stack<Mode>(depth);
Push(Mode.Done);
}
public void Check(int ch)
{
/*
After calling new_JSON_checker, call this function for each character (or
partial character) in your JSON text. It can accept UTF-8, UTF-16, or
UTF-32. It returns if things are looking ok so far. If it rejects the
text, it throws an exception.
*/
int nextClass, nextState;
/*
Determine the character's class.
*/
if (ch < 0)
OnError();
if (ch >= 128)
nextClass = C_ETC;
else
{
nextClass = ascii_class[ch];
if (nextClass <= __)
OnError();
}
/*
Get the next state from the state transition table.
*/
nextState = state_transition_table[_state, nextClass];
if (nextState >= 0)
{
/*
Change the state.
*/
_state = nextState;
}
else
{
/*
Or perform one of the actions.
*/
switch (nextState)
{
/* empty } */
case -9:
Pop(Mode.Key);
_state = OK;
break;
/* } */
case -8:
Pop(Mode.Object);
_state = OK;
break;
/* ] */
case -7:
Pop(Mode.Array);
_state = OK;
break;
/* { */
case -6:
Push(Mode.Key);
_state = OB;
break;
/* [ */
case -5:
Push(Mode.Array);
_state = AR;
break;
/* " */
case -4:
switch (_stack.Peek())
{
case Mode.Key:
_state = CO;
break;
case Mode.Array:
case Mode.Object:
_state = OK;
break;
default:
OnError();
break;
}
break;
/* , */
case -3:
switch (_stack.Peek())
{
case Mode.Object:
/*
A comma causes a flip from object mode to key mode.
*/
Pop(Mode.Object);
Push(Mode.Key);
_state = KE;
break;
case Mode.Array:
_state = VA;
break;
default:
OnError();
break;
}
break;
/* : */
case -2:
/*
A colon causes a flip from key mode to object mode.
*/
Pop(Mode.Key);
Push(Mode.Object);
_state = VA;
break;
/*
Bad action.
*/
default:
OnError();
break;
}
}
_offset++;
}
public void FinalCheck()
{
/*
The FinalCheck function should be called after all of the characters
have been processed, but only if every call to Check returned
without throwing an exception. This method throws an exception if the
JSON text was not accepted; in other words, the final check failed.
*/
if (_state != OK)
OnError();
Pop(Mode.Done);
}
private void Push(Mode mode)
{
/*
Push a mode onto the stack or throw if there is overflow.
*/
if (_depth > 0 && _stack.Count >= _depth)
OnError();
_stack.Push(mode);
}
private void Pop(Mode mode)
{
/*
Pop the stack, assuring that the current mode matches the expectation.
Throws if there is underflow or if the modes mismatch.
*/
if (_stack.Pop() != mode)
OnError();
}
private void OnError()
{
throw new Exception(string.Format("Invalid JSON text at character offset {0}.", _offset.ToString("N0")));
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Orleans.CodeGeneration;
using Orleans.Runtime.Configuration;
using Orleans.Serialization;
using Orleans.Reactive;
namespace Orleans.Runtime
{
internal class Message : IOutgoingMessage
{
// NOTE: These are encoded on the wire as bytes for efficiency. They are only integer enums to avoid boxing
// This means we can't have over byte.MaxValue of them.
public enum Header
{
ALWAYS_INTERLEAVE = 1,
CACHE_INVALIDATION_HEADER,
CATEGORY,
CORRELATION_ID,
DEBUG_CONTEXT,
DIRECTION,
EXPIRATION,
FORWARD_COUNT,
INTERFACE_ID, // DEPRECATED - leave that enum value to maintain next enum numerical values
METHOD_ID, // DEPRECATED - leave that enum value to maintain next enum numerical values
NEW_GRAIN_TYPE,
GENERIC_GRAIN_TYPE,
RESULT,
REJECTION_INFO,
REJECTION_TYPE,
READ_ONLY,
RESEND_COUNT,
SENDING_ACTIVATION,
SENDING_GRAIN,
SENDING_SILO,
IS_NEW_PLACEMENT,
TARGET_ACTIVATION,
TARGET_GRAIN,
TARGET_SILO,
TARGET_OBSERVER,
TIMESTAMPS, // DEPRECATED - leave that enum value to maintain next enum numerical values
IS_UNORDERED,
PRIOR_MESSAGE_ID,
PRIOR_MESSAGE_TIMES,
REQUEST_CONTEXT,
// Reactive Computations
RC_MSG,
RC_RESULT,
RC_ACTIVATION_KEY,
RC_CLIENT_OBJECT
// Do not add over byte.MaxValue of these.
}
public static class Metadata
{
public const string MAX_RETRIES = "MaxRetries";
public const string EXCLUDE_TARGET_ACTIVATIONS = "#XA";
public const string TARGET_HISTORY = "TargetHistory";
public const string ACTIVATION_DATA = "ActivationData";
}
public static int LargeMessageSizeThreshold { get; set; }
public const int LENGTH_HEADER_SIZE = 8;
public const int LENGTH_META_HEADER = 4;
private readonly Dictionary<Header, object> headers;
[NonSerialized]
private Dictionary<string, object> metadata;
/// <summary>
/// NOTE: The contents of bodyBytes should never be modified
/// </summary>
private List<ArraySegment<byte>> bodyBytes;
private List<ArraySegment<byte>> headerBytes;
private object bodyObject;
// Cache values of TargetAddess and SendingAddress as they are used very frequently
private ActivationAddress targetAddress;
private ActivationAddress sendingAddress;
private static readonly Logger logger;
static Message()
{
logger = LogManager.GetLogger("Message", LoggerType.Runtime);
}
public enum Categories
{
Ping,
System,
Application,
}
public enum Directions
{
Request,
Response,
OneWay
}
public enum ResponseTypes
{
Success,
Error,
Rejection
}
public enum RejectionTypes
{
Transient,
Overloaded,
DuplicateRequest,
Unrecoverable,
GatewayTooBusy,
}
public enum ReactiveComputationTypes
{
None,
Execute,
KeepAlive
}
public Categories Category
{
get { return GetScalarHeader<Categories>(Header.CATEGORY); }
set { SetHeader(Header.CATEGORY, value); }
}
public Directions Direction
{
get { return GetScalarHeader<Directions>(Header.DIRECTION); }
set { SetHeader(Header.DIRECTION, value); }
}
public bool IsReadOnly
{
get { return GetScalarHeader<bool>(Header.READ_ONLY); }
set { SetHeader(Header.READ_ONLY, value); }
}
public bool IsAlwaysInterleave
{
get { return GetScalarHeader<bool>(Header.ALWAYS_INTERLEAVE); }
set { SetHeader(Header.ALWAYS_INTERLEAVE, value); }
}
public bool IsUnordered
{
get { return GetScalarHeader<bool>(Header.IS_UNORDERED); }
set
{
if (value || ContainsHeader(Header.IS_UNORDERED))
SetHeader(Header.IS_UNORDERED, value);
}
}
public CorrelationId Id
{
get { return GetSimpleHeader<CorrelationId>(Header.CORRELATION_ID); }
set { SetHeader(Header.CORRELATION_ID, value); }
}
public int ResendCount
{
get { return GetScalarHeader<int>(Header.RESEND_COUNT); }
set { SetHeader(Header.RESEND_COUNT, value); }
}
public int ForwardCount
{
get { return GetScalarHeader<int>(Header.FORWARD_COUNT); }
set { SetHeader(Header.FORWARD_COUNT, value); }
}
public SiloAddress TargetSilo
{
get { return (SiloAddress)GetHeader(Header.TARGET_SILO); }
set
{
SetHeader(Header.TARGET_SILO, value);
targetAddress = null;
}
}
public GrainId TargetGrain
{
get { return GetSimpleHeader<GrainId>(Header.TARGET_GRAIN); }
set
{
SetHeader(Header.TARGET_GRAIN, value);
targetAddress = null;
}
}
public ActivationId TargetActivation
{
get { return GetSimpleHeader<ActivationId>(Header.TARGET_ACTIVATION); }
set
{
SetHeader(Header.TARGET_ACTIVATION, value);
targetAddress = null;
}
}
public ActivationAddress TargetAddress
{
get { return targetAddress ?? (targetAddress = ActivationAddress.GetAddress(TargetSilo, TargetGrain, TargetActivation)); }
set
{
TargetGrain = value.Grain;
TargetActivation = value.Activation;
TargetSilo = value.Silo;
targetAddress = value;
}
}
public GuidId TargetObserverId
{
get { return GetSimpleHeader<GuidId>(Header.TARGET_OBSERVER); }
set
{
SetHeader(Header.TARGET_OBSERVER, value);
targetAddress = null;
}
}
public SiloAddress SendingSilo
{
get { return (SiloAddress)GetHeader(Header.SENDING_SILO); }
set
{
SetHeader(Header.SENDING_SILO, value);
sendingAddress = null;
}
}
public GrainId SendingGrain
{
get { return GetSimpleHeader<GrainId>(Header.SENDING_GRAIN); }
set
{
SetHeader(Header.SENDING_GRAIN, value);
sendingAddress = null;
}
}
public ActivationId SendingActivation
{
get { return GetSimpleHeader<ActivationId>(Header.SENDING_ACTIVATION); }
set
{
SetHeader(Header.SENDING_ACTIVATION, value);
sendingAddress = null;
}
}
public ActivationAddress SendingAddress
{
get { return sendingAddress ?? (sendingAddress = ActivationAddress.GetAddress(SendingSilo, SendingGrain, SendingActivation)); }
set
{
SendingGrain = value.Grain;
SendingActivation = value.Activation;
SendingSilo = value.Silo;
sendingAddress = value;
}
}
public bool IsNewPlacement
{
get { return GetScalarHeader<bool>(Header.IS_NEW_PLACEMENT); }
set
{
if (value || ContainsHeader(Header.IS_NEW_PLACEMENT))
SetHeader(Header.IS_NEW_PLACEMENT, value);
}
}
public ResponseTypes Result
{
get { return GetScalarHeader<ResponseTypes>(Header.RESULT); }
set { SetHeader(Header.RESULT, value); }
}
public DateTime Expiration
{
get { return GetScalarHeader<DateTime>(Header.EXPIRATION); }
set { SetHeader(Header.EXPIRATION, value); }
}
public bool IsExpired
{
get { return (ContainsHeader(Header.EXPIRATION)) && DateTime.UtcNow > Expiration; }
}
public bool IsExpirableMessage(IMessagingConfiguration config)
{
if (!config.DropExpiredMessages) return false;
GrainId id = TargetGrain;
if (id == null) return false;
// don't set expiration for one way, system target and system grain messages.
return Direction != Directions.OneWay && !id.IsSystemTarget && !Constants.IsSystemGrain(id);
}
public string DebugContext
{
get { return GetStringHeader(Header.DEBUG_CONTEXT); }
set { SetHeader(Header.DEBUG_CONTEXT, value); }
}
public IEnumerable<ActivationAddress> CacheInvalidationHeader
{
get
{
object obj = GetHeader(Header.CACHE_INVALIDATION_HEADER);
return obj == null ? null : ((IEnumerable)obj).Cast<ActivationAddress>();
}
}
internal void AddToCacheInvalidationHeader(ActivationAddress address)
{
var list = new List<ActivationAddress>();
if (ContainsHeader(Header.CACHE_INVALIDATION_HEADER))
{
var prevList = ((IEnumerable)GetHeader(Header.CACHE_INVALIDATION_HEADER)).Cast<ActivationAddress>();
list.AddRange(prevList);
}
list.Add(address);
SetHeader(Header.CACHE_INVALIDATION_HEADER, list);
}
// Resends are used by the sender, usualy due to en error to send or due to a transient rejection.
public bool MayResend(IMessagingConfiguration config)
{
return ResendCount < config.MaxResendCount;
}
// Forwardings are used by the receiver, usualy when it cannot process the message and forwars it to another silo to perform the processing
// (got here due to outdated cache, silo is shutting down/overloaded, ...).
public bool MayForward(GlobalConfiguration config)
{
return ForwardCount < config.MaxForwardCount;
}
/// <summary>
/// Set by sender's placement logic when NewPlacementRequested is true
/// so that receiver knows desired grain type
/// </summary>
public string NewGrainType
{
get { return GetStringHeader(Header.NEW_GRAIN_TYPE); }
set { SetHeader(Header.NEW_GRAIN_TYPE, value); }
}
/// <summary>
/// Set by caller's grain reference
/// </summary>
public string GenericGrainType
{
get { return GetStringHeader(Header.GENERIC_GRAIN_TYPE); }
set { SetHeader(Header.GENERIC_GRAIN_TYPE, value); }
}
public RejectionTypes RejectionType
{
get { return GetScalarHeader<RejectionTypes>(Header.REJECTION_TYPE); }
set { SetHeader(Header.REJECTION_TYPE, value); }
}
public string RejectionInfo
{
get { return GetStringHeader(Header.REJECTION_INFO); }
set { SetHeader(Header.REJECTION_INFO, value); }
}
public Dictionary<string, object> RequestContextData
{
get { return GetScalarHeader<Dictionary<string, object>>(Header.REQUEST_CONTEXT); }
set { SetHeader(Header.REQUEST_CONTEXT, value); }
}
public ReactiveComputationTypes RcType
{
get { return GetScalarHeader<ReactiveComputationTypes>(Header.RC_MSG); }
set { SetHeader(Header.RC_MSG, value); }
}
public Guid RcActivationKey
{
get { return GetScalarHeader<Guid>(Header.RC_ACTIVATION_KEY); }
set { SetHeader(Header.RC_ACTIVATION_KEY, value); }
}
public object RcResult
{
get { return GetHeader(Header.RC_RESULT); }
set { SetHeader(Header.RC_RESULT, value); }
}
public IRcManager RcClientObject
{
get { return GetScalarHeader<IRcManager>(Header.RC_CLIENT_OBJECT); }
set { SetHeader(Header.RC_CLIENT_OBJECT, value); }
}
public bool IsRcExecute()
{
return RcType == ReactiveComputationTypes.Execute;
}
public bool IsRcKeepAlive()
{
return RcType == ReactiveComputationTypes.KeepAlive;
}
public object BodyObject
{
get
{
if (bodyObject != null)
{
return bodyObject;
}
try
{
bodyObject = DeserializeBody(bodyBytes);
}
finally
{
if (bodyBytes != null)
{
BufferPool.GlobalPool.Release(bodyBytes);
bodyBytes = null;
}
}
return bodyObject;
}
set
{
bodyObject = value;
if (bodyBytes == null) return;
BufferPool.GlobalPool.Release(bodyBytes);
bodyBytes = null;
}
}
private static object DeserializeBody(List<ArraySegment<byte>> bytes)
{
if (bytes == null)
{
return null;
}
try
{
var stream = new BinaryTokenStreamReader(bytes);
return SerializationManager.Deserialize(stream);
}
catch (Exception ex)
{
logger.Error(ErrorCode.Messaging_UnableToDeserializeBody, "Exception deserializing message body", ex);
throw;
}
}
public Message()
{
// average headers items count is 14 items, and while the Header enum contains 18 entries
// the closest prime number is 17; assuming that possibility of all 18 headers being at the same time is low enough to
// choose 17 in order to avoid allocations of two additional items on each call, and allocate 37 instead of 19 in rare cases
headers = new Dictionary<Header, object>(17);
metadata = new Dictionary<string, object>();
bodyObject = null;
bodyBytes = null;
headerBytes = null;
}
private Message(Categories type, Directions subtype)
: this()
{
Category = type;
Direction = subtype;
}
internal static Message CreateMessage(InvokeMethodRequest request, InvokeMethodOptions options)
{
var message = new Message(
Categories.Application,
(options & InvokeMethodOptions.OneWay) != 0 ? Directions.OneWay : Directions.Request)
{
Id = CorrelationId.GetNext(),
IsReadOnly = (options & InvokeMethodOptions.ReadOnly) != 0,
IsUnordered = (options & InvokeMethodOptions.Unordered) != 0,
BodyObject = request
};
if ((options & InvokeMethodOptions.AlwaysInterleave) != 0)
message.IsAlwaysInterleave = true;
var contextData = RequestContext.Export();
if (contextData != null)
{
message.RequestContextData = contextData;
}
return message;
}
// Initializes body and header but does not take ownership of byte.
// Caller must clean up bytes
public Message(List<ArraySegment<byte>> header, List<ArraySegment<byte>> body, bool deserializeBody = false)
{
metadata = new Dictionary<string, object>();
var input = new BinaryTokenStreamReader(header);
headers = SerializationManager.DeserializeMessageHeaders(input);
if (deserializeBody)
{
bodyObject = DeserializeBody(body);
}
else
{
bodyBytes = body;
}
}
public Message CreateResponseMessage()
{
var response = new Message(this.Category, Directions.Response)
{
Id = this.Id,
IsReadOnly = this.IsReadOnly,
IsAlwaysInterleave = this.IsAlwaysInterleave,
TargetSilo = this.SendingSilo
};
if (this.ContainsHeader(Header.SENDING_GRAIN))
{
response.SetHeader(Header.TARGET_GRAIN, this.GetHeader(Header.SENDING_GRAIN));
if (this.ContainsHeader(Header.SENDING_ACTIVATION))
{
response.SetHeader(Header.TARGET_ACTIVATION, this.GetHeader(Header.SENDING_ACTIVATION));
}
}
response.SendingSilo = this.TargetSilo;
if (this.ContainsHeader(Header.TARGET_GRAIN))
{
response.SetHeader(Header.SENDING_GRAIN, this.GetHeader(Header.TARGET_GRAIN));
if (this.ContainsHeader(Header.TARGET_ACTIVATION))
{
response.SetHeader(Header.SENDING_ACTIVATION, this.GetHeader(Header.TARGET_ACTIVATION));
}
else if (this.TargetGrain.IsSystemTarget)
{
response.SetHeader(Header.SENDING_ACTIVATION, ActivationId.GetSystemActivation(TargetGrain, TargetSilo));
}
}
if (this.ContainsHeader(Header.DEBUG_CONTEXT))
{
response.SetHeader(Header.DEBUG_CONTEXT, this.GetHeader(Header.DEBUG_CONTEXT));
}
if (this.ContainsHeader(Header.CACHE_INVALIDATION_HEADER))
{
response.SetHeader(Header.CACHE_INVALIDATION_HEADER, this.GetHeader(Header.CACHE_INVALIDATION_HEADER));
}
if (this.ContainsHeader(Header.EXPIRATION))
{
response.SetHeader(Header.EXPIRATION, this.GetHeader(Header.EXPIRATION));
}
var contextData = RequestContext.Export();
if (contextData != null)
{
response.RequestContextData = contextData;
}
return response;
}
public Message CreateRejectionResponse(RejectionTypes type, string info, OrleansException ex = null)
{
var response = CreateResponseMessage();
response.Result = ResponseTypes.Rejection;
response.RejectionType = type;
response.RejectionInfo = info;
response.BodyObject = ex;
if (logger.IsVerbose) logger.Verbose("Creating {0} rejection with info '{1}' for {2} at:" + Environment.NewLine + "{3}", type, info, this, new System.Diagnostics.StackTrace(true));
return response;
}
public Message CreatePromptExceptionResponse(Exception exception)
{
return new Message(Category, Directions.Response)
{
Result = ResponseTypes.Error,
BodyObject = Response.ExceptionResponse(exception)
};
}
internal static Message CreateRcRequest(InvokeMethodRequest request, bool refresh)
{
var message = new Message(
Categories.Application, Directions.OneWay)
{
Id = CorrelationId.GetNext(),
BodyObject = request,
IsAlwaysInterleave = true
};
message.SetHeader(Header.RC_MSG, refresh ? ReactiveComputationTypes.KeepAlive : ReactiveComputationTypes.Execute);
var contextData = RequestContext.Export();
message.RequestContextData = contextData;
return message;
}
public bool ContainsHeader(Header tag)
{
return headers.ContainsKey(tag);
}
public void RemoveHeader(Header tag)
{
lock (headers)
{
headers.Remove(tag);
if (tag == Header.TARGET_ACTIVATION || tag == Header.TARGET_GRAIN | tag == Header.TARGET_SILO)
targetAddress = null;
}
}
public void SetHeader(Header tag, object value)
{
lock (headers)
{
headers[tag] = value;
}
}
public object GetHeader(Header tag)
{
object val;
bool flag;
lock (headers)
{
flag = headers.TryGetValue(tag, out val);
}
return flag ? val : null;
}
public string GetStringHeader(Header tag)
{
object val;
if (!headers.TryGetValue(tag, out val)) return String.Empty;
var s = val as string;
return s ?? String.Empty;
}
public T GetScalarHeader<T>(Header tag)
{
object val;
if (headers.TryGetValue(tag, out val))
{
return (T)val;
}
return default(T);
}
public T GetSimpleHeader<T>(Header tag)
{
object val;
if (!headers.TryGetValue(tag, out val) || val == null) return default(T);
return val is T ? (T) val : default(T);
}
public bool ContainsMetadata(string tag)
{
return metadata != null && metadata.ContainsKey(tag);
}
public void SetMetadata(string tag, object data)
{
metadata = metadata ?? new Dictionary<string, object>();
metadata[tag] = data;
}
public void RemoveMetadata(string tag)
{
if (metadata != null)
{
metadata.Remove(tag);
}
}
public object GetMetadata(string tag)
{
object data;
if (metadata != null && metadata.TryGetValue(tag, out data))
{
return data;
}
return null;
}
/// <summary>
/// Tell whether two messages are duplicates of one another
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public bool IsDuplicate(Message other)
{
return Equals(SendingSilo, other.SendingSilo) && Equals(Id, other.Id);
}
#region Serialization
public List<ArraySegment<byte>> Serialize(out int headerLength)
{
int dummy;
return Serialize_Impl(out headerLength, out dummy);
}
private List<ArraySegment<byte>> Serialize_Impl(out int headerLengthOut, out int bodyLengthOut)
{
var headerStream = new BinaryTokenStreamWriter();
lock (headers) // Guard against any attempts to modify message headers while we are serializing them
{
SerializationManager.SerializeMessageHeaders(headers, headerStream);
}
if (bodyBytes == null)
{
var bodyStream = new BinaryTokenStreamWriter();
SerializationManager.Serialize(bodyObject, bodyStream);
// We don't bother to turn this into a byte array and save it in bodyBytes because Serialize only gets called on a message
// being sent off-box. In this case, the likelihood of needed to re-serialize is very low, and the cost of capturing the
// serialized bytes from the steam -- where they're a list of ArraySegment objects -- into an array of bytes is actually
// pretty high (an array allocation plus a bunch of copying).
bodyBytes = bodyStream.ToBytes() as List<ArraySegment<byte>>;
}
if (headerBytes != null)
{
BufferPool.GlobalPool.Release(headerBytes);
}
headerBytes = headerStream.ToBytes() as List<ArraySegment<byte>>;
int headerLength = headerBytes.Sum(ab => ab.Count);
int bodyLength = bodyBytes.Sum(ab => ab.Count);
var bytes = new List<ArraySegment<byte>>();
bytes.Add(new ArraySegment<byte>(BitConverter.GetBytes(headerLength)));
bytes.Add(new ArraySegment<byte>(BitConverter.GetBytes(bodyLength)));
bytes.AddRange(headerBytes);
bytes.AddRange(bodyBytes);
if (headerLength + bodyLength > LargeMessageSizeThreshold)
{
logger.Info(ErrorCode.Messaging_LargeMsg_Outgoing, "Preparing to send large message Size={0} HeaderLength={1} BodyLength={2} #ArraySegments={3}. Msg={4}",
headerLength + bodyLength + LENGTH_HEADER_SIZE, headerLength, bodyLength, bytes.Count, this.ToString());
if (logger.IsVerbose3) logger.Verbose3("Sending large message {0}", this.ToLongString());
}
headerLengthOut = headerLength;
bodyLengthOut = bodyLength;
return bytes;
}
public void ReleaseBodyAndHeaderBuffers()
{
ReleaseHeadersOnly();
ReleaseBodyOnly();
}
public void ReleaseHeadersOnly()
{
if (headerBytes == null) return;
BufferPool.GlobalPool.Release(headerBytes);
headerBytes = null;
}
public void ReleaseBodyOnly()
{
if (bodyBytes == null) return;
BufferPool.GlobalPool.Release(bodyBytes);
bodyBytes = null;
}
#endregion
// For testing and logging/tracing
public string ToLongString()
{
var sb = new StringBuilder();
string debugContex = DebugContext;
if (!string.IsNullOrEmpty(debugContex))
{
// if DebugContex is present, print it first.
sb.Append(debugContex).Append(".");
}
lock (headers)
{
foreach (var pair in headers)
{
if (pair.Key != Header.DEBUG_CONTEXT)
{
sb.AppendFormat("{0}={1};", pair.Key, pair.Value);
}
sb.AppendLine();
}
}
return sb.ToString();
}
public override string ToString()
{
string response = String.Empty;
if (Direction == Directions.Response)
{
switch (Result)
{
case ResponseTypes.Error:
response = "Error ";
break;
case ResponseTypes.Rejection:
response = string.Format("{0} Rejection (info: {1}) ", RejectionType, RejectionInfo);
break;
default:
break;
}
}
return String.Format("{0}{1}{2}{3}{4} {5}->{6} #{7}{8}{9}: {10}",
IsReadOnly ? "ReadOnly " : "", //0
IsAlwaysInterleave ? "IsAlwaysInterleave " : "", //1
IsNewPlacement ? "NewPlacement " : "", // 2
response, //3
Direction, //4
String.Format("{0}{1}{2}", SendingSilo, SendingGrain, SendingActivation), //5
String.Format("{0}{1}{2}{3}", TargetSilo, TargetGrain, TargetActivation, TargetObserverId), //6
Id, //7
ResendCount > 0 ? "[ResendCount=" + ResendCount + "]" : "", //8
ForwardCount > 0 ? "[ForwardCount=" + ForwardCount + "]" : "", //9
DebugContext); //10
}
internal void SetTargetPlacement(PlacementResult value)
{
if ((value.IsNewPlacement ||
(ContainsHeader(Header.TARGET_ACTIVATION) &&
!TargetActivation.Equals(value.Activation))))
{
RemoveHeader(Header.PRIOR_MESSAGE_ID);
RemoveHeader(Header.PRIOR_MESSAGE_TIMES);
}
TargetActivation = value.Activation;
TargetSilo = value.Silo;
if (value.IsNewPlacement)
IsNewPlacement = true;
if (!String.IsNullOrEmpty(value.GrainType))
NewGrainType = value.GrainType;
}
public string GetTargetHistory()
{
var history = new StringBuilder();
history.Append("<");
if (ContainsHeader(Header.TARGET_SILO))
{
history.Append(TargetSilo).Append(":");
}
if (ContainsHeader(Header.TARGET_GRAIN))
{
history.Append(TargetGrain).Append(":");
}
if (ContainsHeader(Header.TARGET_ACTIVATION))
{
history.Append(TargetActivation);
}
history.Append(">");
if (ContainsMetadata(Message.Metadata.TARGET_HISTORY))
{
history.Append(" ").Append(GetMetadata(Message.Metadata.TARGET_HISTORY));
}
return history.ToString();
}
public bool IsSameDestination(IOutgoingMessage other)
{
var msg = (Message)other;
return msg != null && Object.Equals(TargetSilo, msg.TargetSilo);
}
// For statistical measuring of time spent in queues.
private ITimeInterval timeInterval;
public void Start()
{
timeInterval = TimeIntervalFactory.CreateTimeInterval(true);
timeInterval.Start();
}
public void Stop()
{
timeInterval.Stop();
}
public void Restart()
{
timeInterval.Restart();
}
public TimeSpan Elapsed
{
get { return timeInterval.Elapsed; }
}
internal void DropExpiredMessage(MessagingStatisticsGroup.Phase phase)
{
MessagingStatisticsGroup.OnMessageExpired(phase);
if (logger.IsVerbose2) logger.Verbose2("Dropping an expired message: {0}", this);
ReleaseBodyAndHeaderBuffers();
}
}
}
| |
using System;
using System.Collections;
using Fonet.DataTypes;
namespace Fonet.Fo.Properties
{
internal class GenericCondBorderWidth : CondLengthProperty.Maker
{
internal class Enums
{
internal class Conditionality
{
public const int DISCARD = Constants.DISCARD;
public const int RETAIN = Constants.RETAIN;
}
}
private class SP_LengthMaker : LengthProperty.Maker
{
protected internal SP_LengthMaker(string sPropName) : base(sPropName) { }
private static Hashtable s_htKeywords;
private static void initKeywords()
{
s_htKeywords = new Hashtable(3);
s_htKeywords.Add("thin", "0.5pt");
s_htKeywords.Add("medium", "1pt");
s_htKeywords.Add("thick", "2pt");
}
protected override string CheckValueKeywords(string keyword)
{
if (s_htKeywords == null)
{
initKeywords();
}
string value = (string)s_htKeywords[keyword];
if (value == null)
{
return base.CheckValueKeywords(keyword);
}
else
{
return value;
}
}
}
private static readonly PropertyMaker s_LengthMaker =
new SP_LengthMaker("border-cond-width-template.length");
private class SP_ConditionalityMaker : EnumProperty.Maker
{
protected internal SP_ConditionalityMaker(string sPropName) : base(sPropName) { }
protected internal static readonly EnumProperty s_propDISCARD = new EnumProperty(Enums.Conditionality.DISCARD);
protected internal static readonly EnumProperty s_propRETAIN = new EnumProperty(Enums.Conditionality.RETAIN);
public override Property CheckEnumValues(string value)
{
if (value.Equals("discard"))
{
return s_propDISCARD;
}
if (value.Equals("retain"))
{
return s_propRETAIN;
}
return base.CheckEnumValues(value);
}
}
private static readonly PropertyMaker s_ConditionalityMaker =
new SP_ConditionalityMaker("border-cond-width-template.conditionality");
new public static PropertyMaker Maker(string propName)
{
return new GenericCondBorderWidth(propName);
}
protected GenericCondBorderWidth(string name)
: base(name)
{
m_shorthandMaker = GetSubpropMaker("length");
}
private PropertyMaker m_shorthandMaker;
public override Property CheckEnumValues(string value)
{
return m_shorthandMaker.CheckEnumValues(value);
}
protected override bool IsCompoundMaker()
{
return true;
}
protected override PropertyMaker GetSubpropMaker(string subprop)
{
if (subprop.Equals("length"))
{
return s_LengthMaker;
}
if (subprop.Equals("conditionality"))
{
return s_ConditionalityMaker;
}
return base.GetSubpropMaker(subprop);
}
protected override Property SetSubprop(Property baseProp, string subpropName, Property subProp)
{
CondLength val = baseProp.GetCondLength();
val.SetComponent(subpropName, subProp, false);
return baseProp;
}
public override Property GetSubpropValue(Property baseProp, string subpropName)
{
CondLength val = baseProp.GetCondLength();
return val.GetComponent(subpropName);
}
private Property m_defaultProp = null;
public override Property Make(PropertyList propertyList)
{
if (m_defaultProp == null)
{
m_defaultProp = MakeCompound(propertyList, propertyList.getParentFObj());
}
return m_defaultProp;
}
protected override Property MakeCompound(PropertyList pList, FObj fo)
{
CondLength p = new CondLength();
Property subProp;
subProp = GetSubpropMaker("length").Make(pList,
getDefaultForLength(), fo);
p.SetComponent("length", subProp, true);
subProp = GetSubpropMaker("conditionality").Make(pList,
getDefaultForConditionality(), fo);
p.SetComponent("conditionality", subProp, true);
return new CondLengthProperty(p);
}
protected virtual String getDefaultForLength()
{
return "medium";
}
protected virtual String getDefaultForConditionality()
{
return "";
}
public override Property ConvertProperty(Property p, PropertyList pList, FObj fo)
{
if (p is CondLengthProperty)
{
return p;
}
if (!(p is EnumProperty))
{
p = m_shorthandMaker.ConvertProperty(p, pList, fo);
}
if (p != null)
{
Property prop = MakeCompound(pList, fo);
CondLength pval = prop.GetCondLength();
pval.SetComponent("length", p, false);
return prop;
}
else
{
return null;
}
}
public override bool IsInherited()
{
return false;
}
private static Hashtable s_htKeywords;
private static void initKeywords()
{
s_htKeywords = new Hashtable(3);
s_htKeywords.Add("thin", "0.5pt");
s_htKeywords.Add("medium", "1pt");
s_htKeywords.Add("thick", "2pt");
}
protected override string CheckValueKeywords(string keyword)
{
if (s_htKeywords == null)
{
initKeywords();
}
string value = (string)s_htKeywords[keyword];
if (value == null)
{
return base.CheckValueKeywords(keyword);
}
else
{
return value;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Consul;
using FluentAssertions;
using Moq;
using Winton.Extensions.Configuration.Consul.Parsers;
using Xunit;
using Range = Moq.Range;
namespace Winton.Extensions.Configuration.Consul
{
public class ConsulConfigurationProviderTests
{
private readonly Mock<IKVEndpoint> _kvEndpoint;
private readonly Mock<IConfigurationParser> _parser;
private readonly ConsulConfigurationProvider _provider;
private readonly IConsulConfigurationSource _source;
public ConsulConfigurationProviderTests()
{
_kvEndpoint = new Mock<IKVEndpoint>(MockBehavior.Strict);
var consulClient = new Mock<IConsulClient>(MockBehavior.Strict);
consulClient
.Setup(cc => cc.KV)
.Returns(_kvEndpoint.Object);
consulClient
.Setup(cc => cc.Dispose());
var consulClientFactory = new Mock<IConsulClientFactory>(MockBehavior.Strict);
consulClientFactory
.Setup(ccf => ccf.Create())
.Returns(consulClient.Object);
_parser = new Mock<IConfigurationParser>(MockBehavior.Strict);
_source = new ConsulConfigurationSource("Test")
{
Parser = _parser.Object
};
_provider = new ConsulConfigurationProvider(
_source,
consulClientFactory.Object);
}
public sealed class Constructor : ConsulConfigurationProviderTests
{
[Fact]
public void ShouldThrowIfParserIsNull()
{
var source = new ConsulConfigurationSource("Test")
{
Parser = null!
};
// ReSharper disable once ObjectCreationAsStatement
Action constructing =
() =>
new ConsulConfigurationProvider(source, new Mock<IConsulClientFactory>().Object);
constructing
.Should()
.Throw<ArgumentNullException>()
.And.Message.Should().Contain(nameof(IConsulConfigurationSource.Parser));
}
}
public sealed class Dispose : ConsulConfigurationProviderTests
{
[Fact]
private async Task ShouldCancelPollingTaskWhenReloading()
{
var expectedKvCalls = 0;
var pollingCancelled = new TaskCompletionSource<bool>();
_source.ReloadOnChange = true;
_source.Optional = true;
_kvEndpoint
.Setup(kv => kv.List("Test", It.IsAny<QueryOptions>(), It.IsAny<CancellationToken>()))
.Callback<string, QueryOptions, CancellationToken>(
(_, __, token) =>
{
if (pollingCancelled.Task.IsCompleted)
{
return;
}
expectedKvCalls++;
if (token.CanBeCanceled)
{
token.Register(() => pollingCancelled.TrySetResult(true));
}
})
.Returns<string, QueryOptions, CancellationToken>(
(_, __, token) =>
token.IsCancellationRequested
? Task.FromCanceled<QueryResult<KVPair[]>>(token)
: Task.Delay(5).ContinueWith(t => new QueryResult<KVPair[]> { StatusCode = HttpStatusCode.OK }));
_provider.Load();
// allow polling loop to spin up
await Task.Delay(25);
_provider.Dispose();
await pollingCancelled.Task;
// It's possible that one additional call to KV List endpoint is made depending on when the loop is interrupted.
_kvEndpoint.Verify(
kv => kv.List("Test", It.IsAny<QueryOptions>(), It.IsAny<CancellationToken>()),
Times.Between(expectedKvCalls, expectedKvCalls + 1, Range.Inclusive));
}
[Fact]
private void ShouldNotThrowOnMultipleDisposeCalls()
{
_source.ReloadOnChange = true;
_source.Optional = true;
_kvEndpoint
.Setup(kv => kv.List("Test", It.IsAny<QueryOptions>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(new QueryResult<KVPair[]> { StatusCode = HttpStatusCode.OK });
_provider.Load();
_provider.Dispose();
var secondDispose = _provider.Invoking(p => p.Dispose());
secondDispose.Should().NotThrow();
}
}
public sealed class DoNotReloadOnChange : ConsulConfigurationProviderTests
{
public DoNotReloadOnChange()
{
_source.ReloadOnChange = false;
}
[Fact]
private void ShouldCallLoadExceptionWhenConsulReturnsBadRequest()
{
var calledOnLoadException = false;
_source.OnLoadException = ctx =>
{
ctx.Ignore = true;
calledOnLoadException = true;
};
_kvEndpoint
.Setup(kv => kv.List("Test", It.IsAny<QueryOptions>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(
new QueryResult<KVPair[]>
{
StatusCode = HttpStatusCode.BadRequest
});
_provider.Load();
calledOnLoadException.Should().BeTrue();
}
[Fact]
private void ShouldCallOnLoadExceptionActionWhenLoadingThrows()
{
var calledOnLoadException = false;
_kvEndpoint
.Setup(kv => kv.List("Test", It.IsAny<QueryOptions>(), It.IsAny<CancellationToken>()))
.ThrowsAsync(new Exception());
_source.OnLoadException = ctx =>
{
ctx.Ignore = true;
calledOnLoadException = true;
};
_provider.Load();
calledOnLoadException.Should().BeTrue();
}
[Fact]
private void ShouldHaveEmptyDataWhenConfigDoesNotExistAndIsOptional()
{
_source.Optional = true;
_kvEndpoint
.Setup(kv => kv.List("Test", It.IsAny<QueryOptions>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(new QueryResult<KVPair[]> { StatusCode = HttpStatusCode.NotFound });
_provider.Load();
_provider.GetChildKeys(Enumerable.Empty<string>(), string.Empty).Should().BeEmpty();
}
[Fact]
private void ShouldNotMakeABlockingCall()
{
var allQueryOptions = new List<QueryOptions>();
_parser
.Setup(cp => cp.Parse(It.IsAny<MemoryStream>()))
.Returns(new Dictionary<string, string> { { "Key", "Value" } });
_kvEndpoint
.Setup(
kv =>
kv.List(
"Test",
It.IsAny<QueryOptions>(),
It.IsAny<CancellationToken>()))
.Callback<string, QueryOptions, CancellationToken>(
(_, options, __) => allQueryOptions.Add(options))
.ReturnsAsync(
new QueryResult<KVPair[]>
{
LastIndex = 1234,
Response = new[]
{
new KVPair("Test") { Value = new List<byte> { 1 }.ToArray() }
},
StatusCode = HttpStatusCode.OK
});
_provider.Load();
_provider.Load();
allQueryOptions
.Should()
.NotBeEmpty()
.And
.AllBeEquivalentTo(new QueryOptions { WaitIndex = 0, WaitTime = _source.PollWaitTime });
}
[Fact]
private void ShouldNotThrowExceptionIfOnLoadExceptionIsSetToIgnore()
{
_source.OnLoadException = ctx => ctx.Ignore = true;
_kvEndpoint
.Setup(kv => kv.List("Test", It.IsAny<QueryOptions>(), It.IsAny<CancellationToken>()))
.ThrowsAsync(new Exception("Failed to load from Consul agent"));
Action loading = () => _provider.Load();
loading.Should().NotThrow();
}
[Fact]
private void ShouldReloadWhenNotPolling()
{
_source.Optional = true;
_kvEndpoint
.Setup(kv => kv.List("Test", It.IsAny<QueryOptions>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(new QueryResult<KVPair[]> { StatusCode = HttpStatusCode.NotFound });
_provider.Load();
_provider.Load();
_kvEndpoint.Verify(
kv => kv.List("Test", It.IsAny<QueryOptions>(), It.IsAny<CancellationToken>()),
Times.Exactly(2));
}
[Fact]
private void ShouldSetData()
{
_parser
.Setup(cp => cp.Parse(It.IsAny<MemoryStream>()))
.Returns(new Dictionary<string, string> { { "Key", "Value" } });
_kvEndpoint
.Setup(kv => kv.List("Test", It.IsAny<QueryOptions>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(
new QueryResult<KVPair[]>
{
Response = new[]
{
new KVPair("Test") { Value = new List<byte> { 1 }.ToArray() }
},
StatusCode = HttpStatusCode.OK
});
_provider.Load();
_provider.TryGet("Key", out var value);
value.Should().Be("Value");
}
[Fact]
private void ShouldSetLoadExceptionContextWhenExceptionDuringLoad()
{
ConsulLoadExceptionContext? exceptionContext = null;
var exception = new Exception("Failed to load from Consul agent");
_kvEndpoint
.Setup(kv => kv.List("Test", It.IsAny<QueryOptions>(), It.IsAny<CancellationToken>()))
.ThrowsAsync(exception);
_source.OnLoadException = ctx =>
{
ctx.Ignore = true;
exceptionContext = ctx;
};
_provider.Load();
exceptionContext
.Should()
.BeEquivalentTo(new ConsulLoadExceptionContext(_source, exception) { Ignore = true });
}
[Fact]
private void ShouldThrowExceptionIfNotIgnoredByClient()
{
_source.OnLoadException = ctx => ctx.Ignore = false;
_kvEndpoint
.Setup(kv => kv.List("Test", It.IsAny<QueryOptions>(), It.IsAny<CancellationToken>()))
.ThrowsAsync(new Exception("Error"));
var loading = _provider.Invoking(p => p.Load());
loading.Should().Throw<Exception>().WithMessage("Error");
}
[Fact]
private void ShouldThrowWhenConfigDoesNotExistAndIsNotOptional()
{
_source.Optional = false;
_source.OnLoadException = ctx => ctx.Ignore = false;
_kvEndpoint
.Setup(kv => kv.List("Test", It.IsAny<QueryOptions>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(new QueryResult<KVPair[]> { StatusCode = HttpStatusCode.NotFound });
var loading = _provider.Invoking(p => p.Load());
loading
.Should()
.Throw<Exception>()
.WithMessage("The configuration for key Test was not found and is not optional.");
}
}
public sealed class ReloadOnChange : ConsulConfigurationProviderTests
{
public ReloadOnChange()
{
_source.ReloadOnChange = true;
}
[Fact]
private async Task ShouldCallOnWatchExceptionWithCountOfConsecutiveFailures()
{
var exceptionContexts = new List<ConsulWatchExceptionContext>();
_source.Optional = true;
_source.OnWatchException = ctx =>
{
exceptionContexts.Add(ctx);
return TimeSpan.Zero;
};
var pollingCompleted = new TaskCompletionSource<bool>();
var exception1 = new Exception("Error during watch 1.");
var exception2 = new Exception("Error during watch 2.");
_kvEndpoint
.SetupSequence(kv => kv.List("Test", It.IsAny<QueryOptions>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(new QueryResult<KVPair[]> { LastIndex = 13, StatusCode = HttpStatusCode.OK })
.ThrowsAsync(exception1)
.ThrowsAsync(exception2)
.Returns(
() =>
{
pollingCompleted.SetResult(true);
return new TaskCompletionSource<QueryResult<KVPair[]>>().Task;
});
_provider.Load();
await pollingCompleted.Task;
exceptionContexts
.Should()
.BeEquivalentTo(
new List<ConsulWatchExceptionContext>
{
new ConsulWatchExceptionContext(exception1, 1, _source),
new ConsulWatchExceptionContext(exception2, 2, _source)
});
}
[Fact]
private async Task ShouldNotOverwriteNonOptionalConfigIfDoesNotExist()
{
var pollingCompleted = new TaskCompletionSource<bool>();
_source.Optional = false;
_kvEndpoint
.SetupSequence(kv => kv.List("Test", It.IsAny<QueryOptions>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(
new QueryResult<KVPair[]>
{
Response = new[]
{
new KVPair("Test") { Value = new List<byte> { 1 }.ToArray() }
},
StatusCode = HttpStatusCode.OK
})
.ReturnsAsync(new QueryResult<KVPair[]> { StatusCode = HttpStatusCode.NotFound })
.Returns(
() =>
{
pollingCompleted.SetResult(true);
return new TaskCompletionSource<QueryResult<KVPair[]>>().Task;
});
_parser
.Setup(cp => cp.Parse(It.IsAny<MemoryStream>()))
.Returns(new Dictionary<string, string> { { "Key", "Test" } });
_provider.Load();
await pollingCompleted.Task;
_provider.TryGet("Key", out _).Should().BeTrue();
}
[Fact]
private void ShouldNotReloadWhenPolling()
{
_source.Optional = true;
_kvEndpoint
.Setup(kv => kv.List("Test", It.IsAny<QueryOptions>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(new QueryResult<KVPair[]> { LastIndex = 13, StatusCode = HttpStatusCode.OK });
_provider.Load();
_provider.Load();
_kvEndpoint.Verify(
kv =>
kv.List(
"Test",
It.Is<QueryOptions>(options => options.WaitIndex == 0),
It.IsAny<CancellationToken>()),
Times.Once);
}
[Fact]
private async Task ShouldReloadConfigWhenDataInConsulHasChanged()
{
var reload = new TaskCompletionSource<bool>();
_provider
.GetReloadToken()
.RegisterChangeCallback(_ => reload.TrySetResult(true), new object());
_kvEndpoint
.SetupSequence(kv => kv.List("Test", It.IsAny<QueryOptions>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(
new QueryResult<KVPair[]>
{
LastIndex = 12,
Response = new[]
{
new KVPair("Test") { Value = new List<byte> { 1 }.ToArray() }
},
StatusCode = HttpStatusCode.OK
})
.ReturnsAsync(
new QueryResult<KVPair[]>
{
LastIndex = 13,
Response = new[]
{
new KVPair("Test") { Value = new List<byte> { 1 }.ToArray() }
},
StatusCode = HttpStatusCode.OK
})
.Returns(new TaskCompletionSource<QueryResult<KVPair[]>>().Task);
_parser
.SetupSequence(p => p.Parse(It.IsAny<Stream>()))
.Returns(new Dictionary<string, string> { { "Key", "Test" } })
.Returns(new Dictionary<string, string> { { "Key", "Test2" } });
_provider.Load();
await reload.Task;
_provider.TryGet("Key", out var value);
value.Should().Be("Test2");
}
[Fact]
private async Task ShouldResetConsecutiveFailureCountAfterASuccessfulPoll()
{
var exceptionContexts = new List<ConsulWatchExceptionContext>();
_source.Optional = true;
_source.OnWatchException = ctx =>
{
exceptionContexts.Add(ctx);
return TimeSpan.Zero;
};
var pollingCompleted = new TaskCompletionSource<bool>();
var exception1 = new Exception("Error during watch 1.");
var exception2 = new Exception("Error during watch 2.");
_kvEndpoint
.SetupSequence(kv => kv.List("Test", It.IsAny<QueryOptions>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(new QueryResult<KVPair[]> { LastIndex = 13, StatusCode = HttpStatusCode.OK })
.ThrowsAsync(exception1)
.ReturnsAsync(new QueryResult<KVPair[]> { LastIndex = 13, StatusCode = HttpStatusCode.OK })
.ThrowsAsync(exception2)
.Returns(
() =>
{
pollingCompleted.SetResult(true);
return new TaskCompletionSource<QueryResult<KVPair[]>>().Task;
});
_provider.Load();
await pollingCompleted.Task;
exceptionContexts
.Should()
.BeEquivalentTo(
new List<ConsulWatchExceptionContext>
{
new ConsulWatchExceptionContext(exception1, 1, _source),
new ConsulWatchExceptionContext(exception2, 1, _source)
});
}
[Fact]
private async Task ShouldResetLastIndexWhenItGoesBackwards()
{
_source.Optional = true;
var queryOptions = new List<QueryOptions>();
var pollingCompleted = new TaskCompletionSource<bool>();
var results = new Queue<QueryResult<KVPair[]>>(
new List<QueryResult<KVPair[]>>
{
new QueryResult<KVPair[]> { LastIndex = 13, StatusCode = HttpStatusCode.OK },
new QueryResult<KVPair[]> { LastIndex = 12, StatusCode = HttpStatusCode.OK }
});
_kvEndpoint
.Setup(kv => kv.List("Test", It.IsAny<QueryOptions>(), It.IsAny<CancellationToken>()))
.Returns<string, QueryOptions, CancellationToken>(
(_, options, __) =>
{
queryOptions.Add(options);
if (results.TryDequeue(out var result))
{
return Task.FromResult(result);
}
pollingCompleted.SetResult(true);
return new TaskCompletionSource<QueryResult<KVPair[]>>().Task;
});
_provider.Load();
await pollingCompleted.Task;
queryOptions
.Should()
.BeEquivalentTo(
new List<QueryOptions>
{
new QueryOptions { WaitIndex = 0, WaitTime = _source.PollWaitTime },
new QueryOptions { WaitIndex = 13, WaitTime = _source.PollWaitTime },
new QueryOptions { WaitIndex = 0, WaitTime = _source.PollWaitTime }
});
}
[Fact]
private async Task ShouldSetLastIndexToOneWhenConsulReturnsIndexNotGreaterThanZero()
{
_source.Optional = true;
var queryOptions = new List<QueryOptions>();
var pollingCompleted = new TaskCompletionSource<bool>();
var results = new Queue<QueryResult<KVPair[]>>(
new List<QueryResult<KVPair[]>>
{
new QueryResult<KVPair[]> { LastIndex = 13, StatusCode = HttpStatusCode.OK },
new QueryResult<KVPair[]> { LastIndex = 0, StatusCode = HttpStatusCode.OK },
new QueryResult<KVPair[]> { LastIndex = 0, StatusCode = HttpStatusCode.OK }
});
_kvEndpoint
.Setup(kv => kv.List("Test", It.IsAny<QueryOptions>(), It.IsAny<CancellationToken>()))
.Returns<string, QueryOptions, CancellationToken>(
(_, options, __) =>
{
queryOptions.Add(options);
if (results.TryDequeue(out var result))
{
return Task.FromResult(result);
}
pollingCompleted.SetResult(true);
return new TaskCompletionSource<QueryResult<KVPair[]>>().Task;
});
_provider.Load();
await pollingCompleted.Task;
queryOptions
.Should()
.BeEquivalentTo(
new List<QueryOptions>
{
new QueryOptions { WaitIndex = 0, WaitTime = _source.PollWaitTime },
new QueryOptions { WaitIndex = 13, WaitTime = _source.PollWaitTime },
new QueryOptions { WaitIndex = 1, WaitTime = _source.PollWaitTime },
new QueryOptions { WaitIndex = 1, WaitTime = _source.PollWaitTime }
});
}
[Fact]
private async Task ShouldWaitForChangesAfterInitialLoad()
{
_source.Optional = true;
var queryOptions = new List<QueryOptions>();
var pollingCompleted = new TaskCompletionSource<bool>();
var results = new Queue<QueryResult<KVPair[]>>(
new List<QueryResult<KVPair[]>>
{
new QueryResult<KVPair[]> { LastIndex = 13, StatusCode = HttpStatusCode.OK }
});
_kvEndpoint
.Setup(kv => kv.List("Test", It.IsAny<QueryOptions>(), It.IsAny<CancellationToken>()))
.Returns<string, QueryOptions, CancellationToken>(
(_, options, __) =>
{
queryOptions.Add(options);
if (results.TryDequeue(out var result))
{
return Task.FromResult(result);
}
pollingCompleted.SetResult(true);
return new TaskCompletionSource<QueryResult<KVPair[]>>().Task;
});
_provider.Load();
await pollingCompleted.Task;
queryOptions
.Should()
.BeEquivalentTo(
new List<QueryOptions>
{
new QueryOptions { WaitIndex = 0, WaitTime = _source.PollWaitTime },
new QueryOptions { WaitIndex = 13, WaitTime = _source.PollWaitTime }
});
}
[Fact]
private async Task ShouldWatchForChangesIfSourceReloadOnChangesIsTrue()
{
var pollingCompleted = new TaskCompletionSource<bool>();
_source.Optional = true;
_kvEndpoint
.SetupSequence(kv => kv.List("Test", It.IsAny<QueryOptions>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(new QueryResult<KVPair[]> { StatusCode = HttpStatusCode.OK })
.Returns(
() =>
{
pollingCompleted.SetResult(true);
return new TaskCompletionSource<QueryResult<KVPair[]>>().Task;
});
_provider.Load();
await pollingCompleted.Task;
_kvEndpoint.Verify(
kv => kv.List("Test", It.IsAny<QueryOptions>(), It.IsAny<CancellationToken>()),
Times.Exactly(2));
}
}
public sealed class CustomizeConvertConsulKVPairToConfig : ConsulConfigurationProviderTests
{
public CustomizeConvertConsulKVPairToConfig()
{
_source.ReloadOnChange = false;
}
[Fact]
private void ShouldSetData()
{
_parser
.Setup(cp => cp.Parse(It.IsAny<MemoryStream>()))
.Throws(new Exception("Should not get here..."));
_kvEndpoint
.Setup(kv => kv.List("Test", It.IsAny<QueryOptions>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(
new QueryResult<KVPair[]>
{
Response = new[]
{
new KVPair("Test/key__with__double__underscores") { Value = Encoding.UTF8.GetBytes("Value") }
},
StatusCode = HttpStatusCode.OK
});
_source.ConvertConsulKVPairToConfig = kvPair =>
{
var normalizedKey = kvPair.Key
.Replace("__", ":")
.Replace(_source.KeyToRemove, string.Empty)
.Trim('/');
using Stream valueStream = new MemoryStream(kvPair.Value);
using var streamReader = new StreamReader(valueStream);
var parsedValue = streamReader.ReadToEnd();
return new Dictionary<string, string>()
{
{ normalizedKey, parsedValue }
};
};
_provider.Load();
_provider.TryGet("key:with:double:underscores", out var value);
value.Should().Be("Value");
}
[Fact]
private void ShouldSetDataUsingDefinedParser()
{
_parser
.Setup(cp => cp.Parse(It.IsAny<MemoryStream>()))
.Returns(new Dictionary<string, string> { { string.Empty, "Value" } });
_kvEndpoint
.Setup(kv => kv.List("Test", It.IsAny<QueryOptions>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(
new QueryResult<KVPair[]>
{
Response = new[]
{
new KVPair("Test/key__with__double__underscores") { Value = Encoding.UTF8.GetBytes("Value") }
},
StatusCode = HttpStatusCode.OK
});
_source.ConvertConsulKVPairToConfig = kvPair =>
{
var normalizedKey = kvPair.Key
.Replace("__", ":")
.Replace(_source.KeyToRemove, string.Empty)
.Trim('/');
using Stream valueStream = new MemoryStream(kvPair.Value);
var parsedPairs = _source.Parser.Parse(valueStream);
return parsedPairs.Select(parsedPair =>
{
return new KeyValuePair<string, string>(
$"{normalizedKey}/{parsedPair.Key}".Trim('/'),
parsedPair.Value);
});
};
_provider.Load();
_provider.TryGet("key:with:double:underscores", out var value);
value.Should().Be("Value");
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.Routing.Matching;
using Microsoft.Extensions.DependencyInjection;
namespace Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure
{
internal class DynamicPageEndpointMatcherPolicy : MatcherPolicy, IEndpointSelectorPolicy
{
private readonly DynamicPageEndpointSelectorCache _selectorCache;
private readonly PageLoader _loader;
private readonly EndpointMetadataComparer _comparer;
public DynamicPageEndpointMatcherPolicy(DynamicPageEndpointSelectorCache selectorCache, PageLoader loader, EndpointMetadataComparer comparer)
{
if (selectorCache == null)
{
throw new ArgumentNullException(nameof(selectorCache));
}
if (loader == null)
{
throw new ArgumentNullException(nameof(loader));
}
if (comparer == null)
{
throw new ArgumentNullException(nameof(comparer));
}
_selectorCache = selectorCache;
_loader = loader;
_comparer = comparer;
}
public override int Order => int.MinValue + 100;
public bool AppliesToEndpoints(IReadOnlyList<Endpoint> endpoints)
{
if (endpoints == null)
{
throw new ArgumentNullException(nameof(endpoints));
}
if (!ContainsDynamicEndpoints(endpoints))
{
// Dynamic page endpoints are always dynamic endpoints.
return false;
}
for (var i = 0; i < endpoints.Count; i++)
{
if (endpoints[i].Metadata.GetMetadata<DynamicPageMetadata>() != null)
{
// Found a dynamic page endpoint
return true;
}
if (endpoints[i].Metadata.GetMetadata<DynamicPageRouteValueTransformerMetadata>() != null)
{
// Found a dynamic page endpoint
return true;
}
}
return false;
}
public async Task ApplyAsync(HttpContext httpContext, CandidateSet candidates)
{
if (httpContext == null)
{
throw new ArgumentNullException(nameof(httpContext));
}
if (candidates == null)
{
throw new ArgumentNullException(nameof(candidates));
}
DynamicPageEndpointSelector? selector = null;
// There's no real benefit here from trying to avoid the async state machine.
// We only execute on nodes that contain a dynamic policy, and thus always have
// to await something.
for (var i = 0; i < candidates.Count; i++)
{
if (!candidates.IsValidCandidate(i))
{
continue;
}
var endpoint = candidates[i].Endpoint;
var originalValues = candidates[i].Values;
RouteValueDictionary? dynamicValues = null;
// We don't expect both of these to be provided, and they are internal so there's
// no realistic way this could happen.
var dynamicPageMetadata = endpoint.Metadata.GetMetadata<DynamicPageMetadata>();
var transformerMetadata = endpoint.Metadata.GetMetadata<DynamicPageRouteValueTransformerMetadata>();
DynamicRouteValueTransformer? transformer = null;
if (dynamicPageMetadata != null)
{
dynamicValues = dynamicPageMetadata.Values;
}
else if (transformerMetadata != null)
{
transformer = (DynamicRouteValueTransformer)httpContext.RequestServices.GetRequiredService(transformerMetadata.SelectorType);
if (transformer.State != null)
{
throw new InvalidOperationException(Resources.FormatStateShouldBeNullForRouteValueTransformers(transformerMetadata.SelectorType.Name));
}
transformer.State = transformerMetadata.State;
dynamicValues = await transformer.TransformAsync(httpContext, originalValues!);
}
else
{
// Not a dynamic page
continue;
}
if (dynamicValues == null)
{
candidates.ReplaceEndpoint(i, null, null);
continue;
}
selector = ResolveSelector(selector, endpoint);
var endpoints = selector.SelectEndpoints(dynamicValues);
if (endpoints.Count == 0 && dynamicPageMetadata != null)
{
// Having no match for a fallback is a configuration error. We can't really check
// during startup that the action you configured exists, so this is the best we can do.
throw new InvalidOperationException(
"Cannot find the fallback endpoint specified by route values: " +
"{ " + string.Join(", ", dynamicValues.Select(kvp => $"{kvp.Key}: {kvp.Value}")) + " }.");
}
else if (endpoints.Count == 0)
{
candidates.ReplaceEndpoint(i, null, null);
continue;
}
// We need to provide the route values associated with this endpoint, so that features
// like URL generation work.
var values = new RouteValueDictionary(dynamicValues);
// Include values that were matched by the fallback route.
if (originalValues != null)
{
foreach (var kvp in originalValues)
{
values.TryAdd(kvp.Key, kvp.Value);
}
}
if (transformer != null)
{
endpoints = await transformer.FilterAsync(httpContext, values, endpoints);
if (endpoints.Count == 0)
{
candidates.ReplaceEndpoint(i, null, null);
continue;
}
}
// Update the route values
candidates.ReplaceEndpoint(i, endpoint, values);
var loadedEndpoints = new List<Endpoint>(endpoints);
for (var j = 0; j < loadedEndpoints.Count; j++)
{
var metadata = loadedEndpoints[j].Metadata;
var actionDescriptor = metadata.GetMetadata<PageActionDescriptor>();
if (actionDescriptor is CompiledPageActionDescriptor)
{
// Nothing to do here. The endpoint already represents a compiled page.
}
else
{
// We're working with a runtime-compiled page and have to Load it.
var compiled = actionDescriptor!.CompiledPageDescriptor ??
await _loader.LoadAsync(actionDescriptor, endpoint.Metadata);
loadedEndpoints[j] = compiled.Endpoint!;
}
}
// Expand the list of endpoints
candidates.ExpandEndpoint(i, loadedEndpoints, _comparer);
}
}
private DynamicPageEndpointSelector ResolveSelector(DynamicPageEndpointSelector? currentSelector, Endpoint endpoint)
{
var selector = _selectorCache.GetEndpointSelector(endpoint);
Debug.Assert(currentSelector == null || ReferenceEquals(currentSelector, selector));
return selector!;
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
namespace Microsoft.DeviceModels.Chipset.MM9691LP.Drivers
{
using System;
using System.Runtime.CompilerServices;
using RT = Microsoft.Zelig.Runtime;
public abstract class RealTimeClock
{
public delegate void Callback( Timer timer, ulong currentTime );
public class Timer
{
//
// State
//
private RealTimeClock m_owner;
private RT.KernelNode< Timer > m_node;
private ulong m_timeout;
private Callback m_callback;
//
// Constructor Methods
//
internal Timer( RealTimeClock owner ,
Callback callback )
{
m_owner = owner;
m_node = new RT.KernelNode< Timer >( this );
m_callback = callback;
}
//
// Helper Methods
//
public void Cancel()
{
m_owner.Deregister( this );
}
internal void Invoke( ulong currentTime )
{
m_callback( this, currentTime );
}
//
// Access Methods
//
internal RT.KernelNode< Timer > Node
{
get
{
return m_node;
}
}
public ulong Timeout
{
get
{
return m_timeout;
}
set
{
m_timeout = value;
m_owner.Register( this );
}
}
public ulong RelativeTimeout
{
get
{
return m_timeout - RealTimeClock.Instance.CurrentTime;
}
set
{
m_timeout = value + RealTimeClock.Instance.CurrentTime;
m_owner.Register( this );
}
}
}
//
// State
//
private InterruptController.Handler m_interrupt;
private RT.KernelList< Timer > m_timers;
//
// Helper Methods
//
public void Initialize()
{
m_timers = new RT.KernelList< Timer >();
m_interrupt = InterruptController.Handler.Create( MM9691LP.INTC.IRQ_MASK_Real_Time_Clock, ProcessTimeout );
InterruptController.Instance.Register( m_interrupt );
}
public Timer CreateTimer( Callback callback )
{
return new Timer( this, callback );
}
//--//
private void Register( Timer timer )
{
RT.KernelNode< Timer > node = timer.Node;
node.RemoveFromList();
ulong timeout = timer.Timeout;
RT.KernelNode< Timer > node2 = m_timers.StartOfForwardWalk;
while(node2.IsValidForForwardMove)
{
if(node2.Target.Timeout > timeout)
{
break;
}
node2 = node2.Next;
}
node.InsertBefore( node2 );
Refresh();
}
private void Deregister( Timer timer )
{
var node = timer.Node;
if(node.IsLinked)
{
node.RemoveFromList();
Refresh();
}
}
//--//
private void ProcessTimeout( InterruptController.Handler handler )
{
ulong currentTime = this.CurrentTime;
while(true)
{
RT.KernelNode< Timer > node = m_timers.StartOfForwardWalk;
if(node.IsValidForForwardMove == false)
{
break;
}
if(node.Target.Timeout > currentTime)
{
break;
}
node.RemoveFromList();
node.Target.Invoke( currentTime );
}
Refresh();
}
void Refresh()
{
RT.KernelNode< Timer > node = m_timers.FirstNode();
if(node != null)
{
MM9691LP.RTC.Instance.COMP = node.Target.Timeout;
m_interrupt.Enable();
}
else
{
m_interrupt.Disable();
}
}
//
// Access Methods
//
public static extern RealTimeClock Instance
{
[RT.SingletonFactory()]
[MethodImpl( MethodImplOptions.InternalCall )]
get;
}
public ulong CurrentTime
{
get
{
MM9691LP.RTC.Instance.LD_HREG = 1;
Processor.Delay( 12 );
return MM9691LP.RTC.Instance.HREG;
}
}
}
}
| |
//
// Batcher.cs
//
// Author:
// Zachary Gramana <[email protected]>
//
// Copyright (c) 2013, 2014 Xamarin Inc (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
/**
* Original iOS version by Jens Alfke
* Ported to Android by Marty Schoch, Traun Leyden
*
* Copyright (c) 2012, 2013, 2014 Couchbase, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
using System;
using System.Collections.Generic;
using Couchbase.Lite;
using Couchbase.Lite.Support;
using Couchbase.Lite.Util;
using Sharpen;
using System.Threading.Tasks;
using System.Threading;
using Couchbase.Lite.Internal;
namespace Couchbase.Lite.Support
{
/// <summary>
/// Utility that queues up objects until the queue fills up or a time interval elapses,
/// then passes all the objects at once to a client-supplied processor block.
/// </summary>
/// <remarks>
/// Utility that queues up objects until the queue fills up or a time interval elapses,
/// then passes all the objects at once to a client-supplied processor block.
/// </remarks>
internal class Batcher<T>
{
private readonly static string Tag = "Batcher";
private readonly TaskFactory workExecutor;
private Task flushFuture;
private readonly int capacity;
private readonly int delay;
private int scheduledDelay;
private IList<T> inbox;
private readonly Action<IList<T>> processor;
private Boolean scheduled;
private long lastProcessedTime;
private readonly Action processNowRunnable;
private readonly Object locker;
public Batcher(TaskFactory workExecutor, int capacity, int delay, Action<IList<T>> processor, CancellationTokenSource tokenSource = null)
{
processNowRunnable = new Action(()=>
{
try
{
if (tokenSource != null && tokenSource.IsCancellationRequested) return;
ProcessNow();
}
catch (Exception e)
{
// we don't want this to crash the batcher
Log.E(Tag, this + ": BatchProcessor throw exception", e);
}
});
this.locker = new Object ();
this.workExecutor = workExecutor;
this.cancellationSource = tokenSource;
this.capacity = capacity;
this.delay = delay;
this.processor = processor;
}
public void ProcessNow()
{
Log.D(Tag, this + ": processNow() called");
scheduled = false;
IList<T> toProcess;
lock (locker)
{
if (inbox == null || inbox.Count == 0)
{
Log.D(Tag, this + ": processNow() called, but inbox is empty");
return;
}
else
{
if (inbox.Count <= capacity)
{
toProcess = inbox;
inbox = null;
}
else
{
toProcess = new AList<T>();
int i = 0;
foreach (T item in inbox)
{
toProcess.AddItem(item);
i += 1;
if (i >= capacity)
{
break;
}
}
foreach (T item in toProcess)
{
Log.D(Tag, this + ": processNow() removing " + item + " from inbox");
inbox.Remove(item);
}
Log.D(Tag, this + ": inbox.size() > capacity, moving " + toProcess.Count + " items from inbox -> toProcess array");
// There are more objects left, so schedule them Real Soon:
ScheduleWithDelay(0);
}
}
}
if (toProcess != null && toProcess.Count > 0)
{
Log.D(Tag, this + ": invoking processor with " + toProcess.Count + " items ");
processor(toProcess);
}
else
{
Log.D(Tag, this + ": nothing to process");
}
lastProcessedTime = Runtime.CurrentTimeMillis();
}
CancellationTokenSource cancellationSource;
public void QueueObjects(IList<T> objects)
{
lock (locker)
{
Log.D(Tag, "queuObjects called with " + objects.Count + " objects. ");
if (objects.Count == 0)
{
return;
}
if (inbox == null)
{
inbox = new AList<T>();
}
Log.D(Tag, "inbox size before adding objects: " + inbox.Count);
foreach (T item in objects)
{
inbox.Add(item);
}
Log.D(Tag, objects.Count + " objects added to inbox. inbox size: " + inbox.Count);
if (inbox.Count < capacity)
{
// Schedule the processing. To improve latency, if we haven't processed anything
// in at least our delay time, rush these object(s) through ASAP:
Log.D(Tag, "inbox.size() < capacity, schedule processing");
int delayToUse = delay;
long delta = (Runtime.CurrentTimeMillis() - lastProcessedTime);
if (delta >= delay)
{
Log.D(Tag, "delta " + delta + " >= delay " + delay + " --> using delay 0");
delayToUse = 0;
}
else
{
Log.D(Tag, "delta " + delta + " < delay " + delay + " --> using delay " + delayToUse);
}
ScheduleWithDelay(delayToUse);
}
else
{
// If inbox fills up, process it immediately:
Log.D(Tag, "inbox.size() >= capacity, process immediately");
Unschedule();
ProcessNow();
}
}
}
public void QueueObject(T o)
{
IList<T> objects = new AList<T>();
objects.Add(o);
QueueObjects(objects);
}
public void Flush()
{
lock (locker)
{
Unschedule();
ProcessNow();
}
}
public void FlushAll()
{
lock (locker)
{
while(inbox.Count > 0)
{
Unschedule();
IList<T> toProcess = new AList<T>();
foreach (T item in inbox)
{
toProcess.Add(item);
}
processor(toProcess);
lastProcessedTime = Runtime.CurrentTimeMillis();
}
}
}
public int Count()
{
lock (locker) {
if (inbox == null) {
return 0;
}
return inbox.Count;
}
}
public void Clear()
{
lock (locker) {
Unschedule();
inbox.Clear();
inbox = null;
}
}
private void ScheduleWithDelay(Int32 suggestedDelay)
{
Log.D(Tag, "scheduleWithDelay called with delay: " + suggestedDelay + " ms");
if (scheduled && (suggestedDelay < scheduledDelay))
{
Log.D(Tag, "already scheduled and : " + suggestedDelay + " < " + scheduledDelay + " --> unscheduling");
Unschedule();
}
if (!scheduled)
{
Log.D(Database.Tag, "not already scheduled");
scheduled = true;
scheduledDelay = suggestedDelay;
Log.D(Tag, "workExecutor.schedule() with delay: " + suggestedDelay + " ms");
cancellationSource = new CancellationTokenSource();
flushFuture = Task.Delay(scheduledDelay)
.ContinueWith(task =>
{
if(!(task.IsCanceled && cancellationSource.IsCancellationRequested))
{
processNowRunnable();
}
}, cancellationSource.Token);
}
}
private void Unschedule()
{
Log.D(Tag, this + ": unschedule() called");
scheduled = false;
if (cancellationSource != null && flushFuture != null)
{
try
{
cancellationSource.Cancel(false);
}
catch (Exception) { } // Swallow it.
Log.D(Tag, "tried to cancel flushFuture.");
}
}
}
}
| |
namespace UnityStandardAssets.CinematicEffects
{
using UnityEngine;
using UnityEditor;
using UnityEditorInternal;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;
[CanEditMultipleObjects, CustomEditor(typeof(TonemappingColorGrading))]
public class TonemappingColorGradingEditor : Editor
{
#region Property drawers
[CustomPropertyDrawer(typeof(TonemappingColorGrading.ColorWheelGroup))]
private class ColorWheelGroupDrawer : PropertyDrawer
{
int m_RenderSizePerWheel;
int m_NumberOfWheels;
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
var wheelAttribute = (TonemappingColorGrading.ColorWheelGroup)attribute;
property.isExpanded = true;
m_NumberOfWheels = property.CountInProperty() - 1;
if (m_NumberOfWheels == 0)
return 0f;
m_RenderSizePerWheel = Mathf.FloorToInt((EditorGUIUtility.currentViewWidth) / m_NumberOfWheels) - 30;
m_RenderSizePerWheel = Mathf.Clamp(m_RenderSizePerWheel, wheelAttribute.minSizePerWheel, wheelAttribute.maxSizePerWheel);
m_RenderSizePerWheel = Mathf.FloorToInt(pixelRatio * m_RenderSizePerWheel);
return ColorWheel.GetColorWheelHeight(m_RenderSizePerWheel);
}
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
if (m_NumberOfWheels == 0)
return;
var width = position.width;
Rect newPosition = new Rect(position.x, position.y, width / m_NumberOfWheels, position.height);
foreach (SerializedProperty prop in property)
{
if (prop.propertyType == SerializedPropertyType.Color)
prop.colorValue = ColorWheel.DoGUI(newPosition, prop.displayName, prop.colorValue, m_RenderSizePerWheel);
newPosition.x += width / m_NumberOfWheels;
}
}
}
[CustomPropertyDrawer(typeof(TonemappingColorGrading.IndentedGroup))]
private class IndentedGroupDrawer : PropertyDrawer
{
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
return 0f;
}
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
EditorGUILayout.LabelField(label, EditorStyles.boldLabel);
EditorGUI.indentLevel++;
foreach (SerializedProperty prop in property)
EditorGUILayout.PropertyField(prop);
EditorGUI.indentLevel--;
}
}
[CustomPropertyDrawer(typeof(TonemappingColorGrading.ChannelMixer))]
private class ChannelMixerDrawer : PropertyDrawer
{
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
return 0f;
}
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
// TODO: Hardcoded variable names, rewrite this function
if (property.type != "ChannelMixerSettings")
return;
SerializedProperty currentChannel = property.FindPropertyRelative("currentChannel");
int intCurrentChannel = currentChannel.intValue;
EditorGUILayout.LabelField(label, EditorStyles.boldLabel);
EditorGUI.indentLevel++;
EditorGUILayout.BeginHorizontal();
{
EditorGUILayout.PrefixLabel("Channel");
if (GUILayout.Toggle(intCurrentChannel == 0, "Red", EditorStyles.miniButtonLeft)) intCurrentChannel = 0;
if (GUILayout.Toggle(intCurrentChannel == 1, "Green", EditorStyles.miniButtonMid)) intCurrentChannel = 1;
if (GUILayout.Toggle(intCurrentChannel == 2, "Blue", EditorStyles.miniButtonRight)) intCurrentChannel = 2;
}
EditorGUILayout.EndHorizontal();
SerializedProperty serializedChannel = property.FindPropertyRelative("channels").GetArrayElementAtIndex(intCurrentChannel);
currentChannel.intValue = intCurrentChannel;
Vector3 v = serializedChannel.vector3Value;
v.x = EditorGUILayout.Slider("Red", v.x, -2f, 2f);
v.y = EditorGUILayout.Slider("Green", v.y, -2f, 2f);
v.z = EditorGUILayout.Slider("Blue", v.z, -2f, 2f);
serializedChannel.vector3Value = v;
EditorGUI.indentLevel--;
}
}
[CustomPropertyDrawer(typeof(TonemappingColorGrading.Curve))]
private class CurveDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
TonemappingColorGrading.Curve attribute = (TonemappingColorGrading.Curve)base.attribute;
if (property.propertyType != SerializedPropertyType.AnimationCurve)
{
EditorGUI.LabelField(position, label.text, "Use ClampCurve with an AnimationCurve.");
return;
}
property.animationCurveValue = EditorGUI.CurveField(position, label, property.animationCurveValue, attribute.color, new Rect(0f, 0f, 1f, 1f));
}
}
#endregion
#region Styling
private static Styles s_Styles;
private class Styles
{
public GUIStyle thumb2D = "ColorPicker2DThumb";
public Vector2 thumb2DSize;
internal Styles()
{
thumb2DSize = new Vector2(
!Mathf.Approximately(thumb2D.fixedWidth, 0f) ? thumb2D.fixedWidth : thumb2D.padding.horizontal,
!Mathf.Approximately(thumb2D.fixedHeight, 0f) ? thumb2D.fixedHeight : thumb2D.padding.vertical
);
}
}
public static readonly Color masterCurveColor = new Color(1f, 1f, 1f, 2f);
public static readonly Color redCurveColor = new Color(1f, 0f, 0f, 2f);
public static readonly Color greenCurveColor = new Color(0f, 1f, 0f, 2f);
public static readonly Color blueCurveColor = new Color(0f, 1f, 1f, 2f);
#endregion
private TonemappingColorGrading concreteTarget
{
get { return target as TonemappingColorGrading; }
}
private static float pixelRatio
{
get
{
#if !(UNITY_3 || UNITY_4 || UNITY_5_0 || UNITY_5_1 || UNITY_5_2 || UNITY_5_3)
return EditorGUIUtility.pixelsPerPoint;
#else
return 1f;
#endif
}
}
private bool isHistogramSupported
{
get
{
return concreteTarget.histogramComputeShader != null
&& ImageEffectHelper.supportsDX11
&& concreteTarget.histogramShader != null
&& concreteTarget.histogramShader.isSupported;
}
}
private enum HistogramMode
{
Red = 0,
Green = 1,
Blue = 2,
Luminance = 3,
RGB,
}
private HistogramMode m_HistogramMode = HistogramMode.RGB;
private Rect m_HistogramRect;
private Material m_HistogramMaterial;
private ComputeBuffer m_HistogramBuffer;
private RenderTexture m_HistogramTexture;
// settings group <setting, property reference>
private Dictionary<FieldInfo, List<SerializedProperty>> m_GroupFields = new Dictionary<FieldInfo, List<SerializedProperty>>();
private void PopulateMap(FieldInfo group)
{
var searchPath = group.Name + ".";
foreach (var setting in group.FieldType.GetFields(BindingFlags.Instance | BindingFlags.Public))
{
List<SerializedProperty> settingsGroup;
if (!m_GroupFields.TryGetValue(group, out settingsGroup))
{
settingsGroup = new List<SerializedProperty>();
m_GroupFields[group] = settingsGroup;
}
var property = serializedObject.FindProperty(searchPath + setting.Name);
if (property != null)
settingsGroup.Add(property);
}
}
private void OnEnable()
{
var settingsGroups = typeof(TonemappingColorGrading).GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).Where(x => x.GetCustomAttributes(typeof(TonemappingColorGrading.SettingsGroup), false).Any());
foreach (var settingGroup in settingsGroups)
PopulateMap(settingGroup);
concreteTarget.onFrameEndEditorOnly = OnFrameEnd;
}
private void OnDisable()
{
concreteTarget.onFrameEndEditorOnly = null;
if (m_HistogramMaterial != null)
DestroyImmediate(m_HistogramMaterial);
if (m_HistogramTexture != null)
DestroyImmediate(m_HistogramTexture);
if (m_HistogramBuffer != null)
m_HistogramBuffer.Release();
}
private void SetLUTImportSettings(TextureImporter importer)
{
importer.textureType = TextureImporterType.Advanced;
importer.anisoLevel = 0;
importer.mipmapEnabled = false;
importer.linearTexture = true;
importer.textureFormat = TextureImporterFormat.RGB24;
importer.SaveAndReimport();
}
private void DrawFields()
{
foreach (var group in m_GroupFields)
{
var enabledField = group.Value.FirstOrDefault(x => x.propertyPath == group.Key.Name + ".enabled");
var groupProperty = serializedObject.FindProperty(group.Key.Name);
GUILayout.Space(5);
bool display = EditorGUIHelper.Header(groupProperty, enabledField);
if (!display)
continue;
GUILayout.BeginHorizontal();
{
GUILayout.Space(10);
GUILayout.BeginVertical();
{
GUILayout.Space(3);
foreach (var field in group.Value.Where(x => x.propertyPath != group.Key.Name + ".enabled"))
{
// Special case for the tonemapping curve field
if (group.Key.FieldType == typeof(TonemappingColorGrading.TonemappingSettings) &&
field.propertyType == SerializedPropertyType.AnimationCurve &&
concreteTarget.tonemapping.tonemapper != TonemappingColorGrading.Tonemapper.Curve)
continue;
// Special case for the neutral tonemapper
bool neutralParam = field.name.StartsWith("neutral");
if (group.Key.FieldType == typeof(TonemappingColorGrading.TonemappingSettings) &&
concreteTarget.tonemapping.tonemapper != TonemappingColorGrading.Tonemapper.Neutral &&
neutralParam)
continue;
if (neutralParam)
EditorGUILayout.PropertyField(field, new GUIContent(ObjectNames.NicifyVariableName(field.name.Substring(7))));
else
EditorGUILayout.PropertyField(field);
}
// Bake button
if (group.Key.FieldType == typeof(TonemappingColorGrading.ColorGradingSettings))
{
EditorGUI.BeginDisabledGroup(!enabledField.boolValue);
if (GUILayout.Button("Export LUT as PNG", EditorStyles.miniButton))
{
string path = EditorUtility.SaveFilePanelInProject("Export LUT as PNG", "LUT.png", "png", "Please enter a file name to save the LUT texture to");
if (!string.IsNullOrEmpty(path))
{
Texture2D lut = concreteTarget.BakeLUT();
if (!concreteTarget.isGammaColorSpace)
{
var pixels = lut.GetPixels();
for (int i = 0; i < pixels.Length; i++)
pixels[i] = pixels[i].linear;
lut.SetPixels(pixels);
lut.Apply();
}
byte[] bytes = lut.EncodeToPNG();
System.IO.File.WriteAllBytes(path, bytes);
DestroyImmediate(lut);
AssetDatabase.Refresh();
TextureImporter importer = (TextureImporter)AssetImporter.GetAtPath(path);
SetLUTImportSettings(importer);
}
}
EditorGUI.EndDisabledGroup();
}
}
GUILayout.EndVertical();
}
GUILayout.EndHorizontal();
}
}
public override void OnInspectorGUI()
{
if (s_Styles == null)
s_Styles = new Styles();
serializedObject.Update();
GUILayout.Label("All following effects will use LDR color buffers.", EditorStyles.miniBoldLabel);
if (concreteTarget.tonemapping.enabled)
{
Camera camera = concreteTarget.GetComponent<Camera>();
if (camera != null && !camera.hdr)
EditorGUILayout.HelpBox("The camera is not HDR enabled. This will likely break the tonemapper.", MessageType.Warning);
else if (!concreteTarget.validRenderTextureFormat)
EditorGUILayout.HelpBox("The input to tonemapper is not in HDR. Make sure that all effects prior to this are executed in HDR.", MessageType.Warning);
}
if (concreteTarget.lut.enabled && concreteTarget.lut.texture != null)
{
if (!concreteTarget.validUserLutSize)
{
EditorGUILayout.HelpBox("Invalid LUT size. Should be \"height = sqrt(width)\" (e.g. 256x16).", MessageType.Error);
}
else
{
// Checks import settings on the lut, offers to fix them if invalid
TextureImporter importer = (TextureImporter)AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(concreteTarget.lut.texture));
bool valid = importer.anisoLevel == 0
&& importer.mipmapEnabled == false
&& importer.linearTexture == true
&& (importer.textureFormat == TextureImporterFormat.RGB24 || importer.textureFormat == TextureImporterFormat.AutomaticTruecolor);
if (!valid)
{
EditorGUILayout.HelpBox("Invalid LUT import settings.", MessageType.Warning);
GUILayout.Space(-32);
EditorGUILayout.BeginHorizontal();
{
GUILayout.FlexibleSpace();
if (GUILayout.Button("Fix", GUILayout.Width(60)))
{
SetLUTImportSettings(importer);
AssetDatabase.Refresh();
}
GUILayout.Space(8);
}
EditorGUILayout.EndHorizontal();
GUILayout.Space(11);
}
}
}
DrawFields();
serializedObject.ApplyModifiedProperties();
}
private static readonly GUIContent k_HistogramTitle = new GUIContent("Histogram");
public override GUIContent GetPreviewTitle()
{
return k_HistogramTitle;
}
public override bool HasPreviewGUI()
{
return isHistogramSupported && targets.Length == 1 && concreteTarget != null && concreteTarget.enabled;
}
public override void OnPreviewGUI(Rect r, GUIStyle background)
{
serializedObject.Update();
if (Event.current.type == EventType.Repaint)
{
// If m_HistogramRect isn't set the preview was just opened so refresh the render to get the histogram data
if (m_HistogramRect.width == 0 && m_HistogramRect.height == 0)
InternalEditorUtility.RepaintAllViews();
// Sizing
float width = Mathf.Min(512f, r.width);
float height = Mathf.Min(128f, r.height);
m_HistogramRect = new Rect(
Mathf.Floor(r.x + r.width / 2f - width / 2f),
Mathf.Floor(r.y + r.height / 2f - height / 2f),
width, height
);
if (m_HistogramTexture != null)
GUI.DrawTexture(m_HistogramRect, m_HistogramTexture);
}
// Toolbar
GUILayout.BeginHorizontal();
EditorGUI.BeginChangeCheck();
{
concreteTarget.histogramRefreshOnPlay = GUILayout.Toggle(concreteTarget.histogramRefreshOnPlay, new GUIContent("Refresh on Play", "Keep refreshing the histogram in play mode; this may impact performances."), EditorStyles.miniButton);
GUILayout.FlexibleSpace();
m_HistogramMode = (HistogramMode)EditorGUILayout.EnumPopup(m_HistogramMode);
}
GUILayout.EndHorizontal();
serializedObject.ApplyModifiedProperties();
if (EditorGUI.EndChangeCheck())
InternalEditorUtility.RepaintAllViews();
}
private void OnFrameEnd(RenderTexture source)
{
if (Application.isPlaying && !concreteTarget.histogramRefreshOnPlay)
return;
if (Mathf.Approximately(m_HistogramRect.width, 0) || Mathf.Approximately(m_HistogramRect.height, 0) || !isHistogramSupported)
return;
// No need to process the full frame to get an histogram, resize the input to a max-size of 512
int rw = Mathf.Min(Mathf.Max(source.width, source.height), 512);
RenderTexture rt = RenderTexture.GetTemporary(rw, rw, 0);
Graphics.Blit(source, rt);
UpdateHistogram(rt, m_HistogramRect, m_HistogramMode);
Repaint();
RenderTexture.ReleaseTemporary(rt);
RenderTexture.active = null;
}
private static readonly int[] k_EmptyBuffer = new int[256 << 2];
void UpdateHistogram(RenderTexture source, Rect rect, HistogramMode mode)
{
if (m_HistogramMaterial == null)
m_HistogramMaterial = ImageEffectHelper.CheckShaderAndCreateMaterial(concreteTarget.histogramShader);
if (m_HistogramBuffer == null)
m_HistogramBuffer = new ComputeBuffer(256, sizeof(uint) << 2);
m_HistogramBuffer.SetData(k_EmptyBuffer);
ComputeShader cs = concreteTarget.histogramComputeShader;
int kernel = cs.FindKernel("KHistogramGather");
cs.SetBuffer(kernel, "_Histogram", m_HistogramBuffer);
cs.SetTexture(kernel, "_Source", source);
int[] channels = null;
switch (mode)
{
case HistogramMode.Luminance:
channels = new[] { 0, 0, 0, 1 };
break;
case HistogramMode.RGB:
channels = new[] { 1, 1, 1, 0 };
break;
case HistogramMode.Red:
channels = new[] { 1, 0, 0, 0 };
break;
case HistogramMode.Green:
channels = new[] { 0, 1, 0, 0 };
break;
case HistogramMode.Blue:
channels = new[] { 0, 0, 1, 0 };
break;
}
cs.SetInts("_Channels", channels);
cs.SetInt("_IsLinear", concreteTarget.isGammaColorSpace ? 0 : 1);
cs.Dispatch(kernel, Mathf.CeilToInt(source.width / 32f), Mathf.CeilToInt(source.height / 32f), 1);
kernel = cs.FindKernel("KHistogramScale");
cs.SetBuffer(kernel, "_Histogram", m_HistogramBuffer);
cs.SetFloat("_Height", rect.height);
cs.Dispatch(kernel, 1, 1, 1);
if (m_HistogramTexture == null)
{
DestroyImmediate(m_HistogramTexture);
m_HistogramTexture = new RenderTexture((int)rect.width, (int)rect.height, 0, RenderTextureFormat.ARGB32);
m_HistogramTexture.hideFlags = HideFlags.HideAndDontSave;
}
m_HistogramMaterial.SetBuffer("_Histogram", m_HistogramBuffer);
m_HistogramMaterial.SetVector("_Size", new Vector2(m_HistogramTexture.width, m_HistogramTexture.height));
m_HistogramMaterial.SetColor("_ColorR", redCurveColor);
m_HistogramMaterial.SetColor("_ColorG", greenCurveColor);
m_HistogramMaterial.SetColor("_ColorB", blueCurveColor);
m_HistogramMaterial.SetColor("_ColorL", masterCurveColor);
m_HistogramMaterial.SetInt("_Channel", (int)mode);
Graphics.Blit(m_HistogramTexture, m_HistogramTexture, m_HistogramMaterial, (mode == HistogramMode.RGB) ? 1 : 0);
}
public static class ColorWheel
{
// Constants
private const float PI_2 = Mathf.PI / 2f;
private const float PI2 = Mathf.PI * 2f;
// hue Wheel
private static Texture2D s_WheelTexture;
private static float s_LastDiameter;
private static GUIStyle s_CenteredStyle;
public static Color DoGUI(Rect area, string title, Color color, float diameter)
{
var labelrect = area;
labelrect.height = EditorGUIUtility.singleLineHeight;
if (s_CenteredStyle == null)
{
s_CenteredStyle = new GUIStyle(GUI.skin.GetStyle("Label"))
{
alignment = TextAnchor.UpperCenter
};
}
GUI.Label(labelrect, title, s_CenteredStyle);
// Figure out the wheel draw area
var wheelDrawArea = area;
wheelDrawArea.y += EditorGUIUtility.singleLineHeight;
wheelDrawArea.height = diameter;
if (wheelDrawArea.width > wheelDrawArea.height)
{
wheelDrawArea.x += (wheelDrawArea.width - wheelDrawArea.height) / 2.0f;
wheelDrawArea.width = area.height;
}
wheelDrawArea.width = wheelDrawArea.height;
var radius = diameter / 2.0f;
Vector3 hsv;
Color.RGBToHSV(color, out hsv.x, out hsv.y, out hsv.z);
// Retina/HDPI screens handling
wheelDrawArea.width /= pixelRatio;
wheelDrawArea.height /= pixelRatio;
float scaledRadius = radius / pixelRatio;
if (Event.current.type == EventType.Repaint)
{
if (!Mathf.Approximately(diameter, s_LastDiameter))
{
s_LastDiameter = diameter;
UpdateHueWheel((int)diameter);
}
// Wheel
GUI.DrawTexture(wheelDrawArea, s_WheelTexture);
// Thumb
Vector2 thumbPos = Vector2.zero;
float theta = hsv.x * PI2;
float len = hsv.y * scaledRadius;
thumbPos.x = Mathf.Cos(theta + PI_2);
thumbPos.y = Mathf.Sin(theta - PI_2);
thumbPos *= len;
Vector2 thumbSize = s_Styles.thumb2DSize;
Color oldColor = GUI.color;
GUI.color = Color.black;
Vector2 thumbSizeH = thumbSize / 2f;
Handles.color = Color.white;
Handles.DrawAAPolyLine(new Vector2(wheelDrawArea.x + scaledRadius + thumbSizeH.x, wheelDrawArea.y + scaledRadius + thumbSizeH.y), new Vector2(wheelDrawArea.x + scaledRadius + thumbPos.x, wheelDrawArea.y + scaledRadius + thumbPos.y));
s_Styles.thumb2D.Draw(new Rect(wheelDrawArea.x + scaledRadius + thumbPos.x - thumbSizeH.x, wheelDrawArea.y + scaledRadius + thumbPos.y - thumbSizeH.y, thumbSize.x, thumbSize.y), false, false, false, false);
GUI.color = oldColor;
}
hsv = GetInput(wheelDrawArea, hsv, scaledRadius);
var sliderDrawArea = wheelDrawArea;
sliderDrawArea.y = sliderDrawArea.yMax;
sliderDrawArea.height = EditorGUIUtility.singleLineHeight;
hsv.y = GUI.HorizontalSlider(sliderDrawArea, hsv.y, 1e-04f, 1f);
color = Color.HSVToRGB(hsv.x, hsv.y, hsv.z);
return color;
}
private static readonly int k_ThumbHash = "colorWheelThumb".GetHashCode();
private static Vector3 GetInput(Rect bounds, Vector3 hsv, float radius)
{
Event e = Event.current;
var id = GUIUtility.GetControlID(k_ThumbHash, FocusType.Passive, bounds);
Vector2 mousePos = e.mousePosition;
Vector2 relativePos = mousePos - new Vector2(bounds.x, bounds.y);
if (e.type == EventType.MouseDown && e.button == 0 && GUIUtility.hotControl == 0)
{
if (bounds.Contains(mousePos))
{
Vector2 center = new Vector2(bounds.x + radius, bounds.y + radius);
float dist = Vector2.Distance(center, mousePos);
if (dist <= radius)
{
e.Use();
GetWheelHueSaturation(relativePos.x, relativePos.y, radius, out hsv.x, out hsv.y);
GUIUtility.hotControl = id;
}
}
}
else if (e.type == EventType.MouseDrag && e.button == 0 && GUIUtility.hotControl == id)
{
Vector2 center = new Vector2(bounds.x + radius, bounds.y + radius);
float dist = Vector2.Distance(center, mousePos);
if (dist <= radius)
{
e.Use();
GetWheelHueSaturation(relativePos.x, relativePos.y, radius, out hsv.x, out hsv.y);
}
}
else if (e.type == EventType.MouseUp && e.button == 0 && GUIUtility.hotControl == id)
{
e.Use();
GUIUtility.hotControl = 0;
}
return hsv;
}
private static void GetWheelHueSaturation(float x, float y, float radius, out float hue, out float saturation)
{
float dx = (x - radius) / radius;
float dy = (y - radius) / radius;
float d = Mathf.Sqrt(dx * dx + dy * dy);
hue = Mathf.Atan2(dx, -dy);
hue = 1f - ((hue > 0) ? hue : PI2 + hue) / PI2;
saturation = Mathf.Clamp01(d);
}
private static void UpdateHueWheel(int diameter)
{
CleanTexture(s_WheelTexture);
s_WheelTexture = MakeTexture(diameter);
var radius = diameter / 2.0f;
Color[] pixels = s_WheelTexture.GetPixels();
for (int y = 0; y < diameter; y++)
{
for (int x = 0; x < diameter; x++)
{
int index = y * diameter + x;
float dx = (x - radius) / radius;
float dy = (y - radius) / radius;
float d = Mathf.Sqrt(dx * dx + dy * dy);
// Out of the wheel, early exit
if (d >= 1f)
{
pixels[index] = new Color(0f, 0f, 0f, 0f);
continue;
}
// red (0) on top, counter-clockwise (industry standard)
float saturation = d;
float hue = Mathf.Atan2(dx, dy);
hue = 1f - ((hue > 0) ? hue : PI2 + hue) / PI2;
Color color = Color.HSVToRGB(hue, saturation, 1f);
// Quick & dirty antialiasing
color.a = (saturation > 0.99) ? (1f - saturation) * 100f : 1f;
pixels[index] = color;
}
}
s_WheelTexture.SetPixels(pixels);
s_WheelTexture.Apply();
}
private static Texture2D MakeTexture(int dimension)
{
return new Texture2D(dimension, dimension, TextureFormat.ARGB32, false, true)
{
filterMode = FilterMode.Point,
wrapMode = TextureWrapMode.Clamp,
hideFlags = HideFlags.HideAndDontSave,
alphaIsTransparency = true
};
}
private static void CleanTexture(Texture2D texture)
{
if (texture != null)
DestroyImmediate(texture);
}
public static float GetColorWheelHeight(int renderSizePerWheel)
{
// wheel height + title label + alpha slider
return renderSizePerWheel + 2 * EditorGUIUtility.singleLineHeight;
}
}
}
}
| |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using System;
using System.Globalization;
using System.Linq;
using System.Management.Automation;
using AutoMapper;
using Microsoft.WindowsAzure.Commands.ServiceManagement.Properties;
using Microsoft.WindowsAzure.Commands.Utilities.Common;
namespace Microsoft.WindowsAzure.Commands.ServiceManagement.IaaS.Endpoints
{
using NSM = Management.Compute.Models;
using PVM = Model;
[Cmdlet(VerbsCommon.Set, "AzureLoadBalancedEndpoint", DefaultParameterSetName = SetAzureLoadBalancedEndpoint.DefaultProbeParameterSet), OutputType(typeof(ManagementOperationContext))]
public class SetAzureLoadBalancedEndpoint : IaaSDeploymentManagementCmdletBase
{
public const string DefaultProbeParameterSet = "DefaultProbe";
public const string TCPProbeParameterSet = "TCPProbe";
public const string HTTPProbeParameterSet = "HTTPProbe";
[Parameter(Mandatory = true, HelpMessage = "Load balancer set name.")]
[ValidateNotNullOrEmpty]
public string LBSetName { get; set; }
[Parameter(Mandatory = false, HelpMessage = "Endpoint protocol.")]
[ValidateSet("TCP", "UDP", IgnoreCase = true)]
public string Protocol { get; set; }
[Parameter(Mandatory = false, HelpMessage = "Private port.")]
public int LocalPort { get; set; }
[Parameter(Mandatory = false, HelpMessage = "Public port.")]
public int PublicPort { get; set; }
[Parameter(Mandatory = false, HelpMessage = "Enable Direct Server Return")]
public bool DirectServerReturn { get; set; }
[Parameter(Mandatory = false, HelpMessage = "ACLs to specify with the endpoint.")]
[ValidateNotNull]
public PVM.NetworkAclObject ACL { get; set; }
[Parameter(Mandatory = true, ParameterSetName = SetAzureLoadBalancedEndpoint.TCPProbeParameterSet, HelpMessage = "Should a TCP probe should be used.")]
public SwitchParameter ProbeProtocolTCP { get; set; }
[Parameter(Mandatory = true, ParameterSetName = SetAzureLoadBalancedEndpoint.HTTPProbeParameterSet, HelpMessage = "Should a HTTP probe should be used.")]
public SwitchParameter ProbeProtocolHTTP { get; set; }
[Parameter(Mandatory = true, ParameterSetName = SetAzureLoadBalancedEndpoint.HTTPProbeParameterSet, HelpMessage = "Relative path to the HTTP probe.")]
[ValidateNotNullOrEmpty]
public string ProbePath { get; set; }
[Parameter(Mandatory = false, ParameterSetName = SetAzureLoadBalancedEndpoint.TCPProbeParameterSet, HelpMessage = "Probe port.")]
[Parameter(Mandatory = false, ParameterSetName = SetAzureLoadBalancedEndpoint.HTTPProbeParameterSet, HelpMessage = "Probe port.")]
public int ProbePort { get; set; }
[Parameter(Mandatory = false, ParameterSetName = SetAzureLoadBalancedEndpoint.TCPProbeParameterSet, HelpMessage = "Probe interval in seconds.")]
[Parameter(Mandatory = false, ParameterSetName = SetAzureLoadBalancedEndpoint.HTTPProbeParameterSet, HelpMessage = "Probe interval in seconds.")]
public int ProbeIntervalInSeconds { get; set; }
[Parameter(Mandatory = false, ParameterSetName = SetAzureLoadBalancedEndpoint.TCPProbeParameterSet, HelpMessage = "Probe timeout in seconds.")]
[Parameter(Mandatory = false, ParameterSetName = SetAzureLoadBalancedEndpoint.HTTPProbeParameterSet, HelpMessage = "Probe timeout in seconds.")]
public int ProbeTimeoutInSeconds { get; set; }
[Parameter(Mandatory = false, HelpMessage = "Internal Load Balancer Name.")]
public string InternalLoadBalancerName { get; set; }
[Parameter(Mandatory = false, HelpMessage = "Idle Timeout.")]
[ValidateNotNullOrEmpty]
public int IdleTimeoutInMinutes { get; set; }
[Parameter(HelpMessage = "LoadBalancerDistribution.")]
[ValidateSet("sourceIP", "sourceIPProtocol", "none", IgnoreCase = true)]
[ValidateNotNullOrEmpty]
public string LoadBalancerDistribution { get; set; }
protected override void ExecuteCommand()
{
ServiceManagementProfile.Initialize();
base.ExecuteCommand();
if (string.IsNullOrEmpty(this.ServiceName) || this.CurrentDeploymentNewSM == null)
{
return;
}
var endpoint = this.GetEndpoint();
if(endpoint == null)
{
this.ThrowTerminatingError(
new ErrorRecord(
new InvalidOperationException(
string.Format(
CultureInfo.InvariantCulture,
Resources.EndpointsCannotBeFoundWithGivenLBSetName,
this.LBSetName)),
string.Empty,
ErrorCategory.InvalidData,
null));
}
this.UpdateEndpointProperties(endpoint);
var endpointList = new PVM.LoadBalancedEndpointList();
endpointList.Add(endpoint);
var endPointParams = new NSM.VirtualMachineUpdateLoadBalancedSetParameters
{
//TODO: AutoMapper doesn't seem to work for this conversion.
//LoadBalancedEndpoints = Mapper.Map<IList<VirtualMachineUpdateLoadBalancedSetParameters.InputEndpoint>>(endpointList)
LoadBalancedEndpoints = new int[1].Select(e => new NSM.VirtualMachineUpdateLoadBalancedSetParameters.InputEndpoint
{
EnableDirectServerReturn = endpoint.EnableDirectServerReturn,
LoadBalancedEndpointSetName = endpoint.LoadBalancedEndpointSetName,
LoadBalancerProbe = endpoint.LoadBalancerProbe == null ? null : new NSM.LoadBalancerProbe
{
IntervalInSeconds = endpoint.LoadBalancerProbe.IntervalInSeconds,
Path = endpoint.LoadBalancerProbe.Path,
Port = endpoint.LoadBalancerProbe.Port,
Protocol = (NSM.LoadBalancerProbeTransportProtocol)Enum.Parse(typeof(NSM.LoadBalancerProbeTransportProtocol), endpoint.LoadBalancerProbe.Protocol, true),
TimeoutInSeconds = endpoint.LoadBalancerProbe.TimeoutInSeconds
},
LocalPort = endpoint.LocalPort,
Name = endpoint.Name,
Port = endpoint.Port,
Protocol = endpoint.Protocol,
Rules = endpoint.EndpointAccessControlList == null ? null : endpoint.EndpointAccessControlList.Rules == null ? null : endpoint.EndpointAccessControlList.Rules.Select(r => new NSM.AccessControlListRule
{
Action = r.Action,
Description = r.Description,
Order = r.Order,
RemoteSubnet = r.RemoteSubnet
}).ToList(),
VirtualIPAddress = endpoint.Vip,
LoadBalancerName = this.InternalLoadBalancerName,
IdleTimeoutInMinutes = endpoint.IdleTimeoutInMinutes,
LoadBalancerDistribution = endpoint.LoadBalancerDistribution,
}).ToList()
};
this.ExecuteClientActionNewSM(
null,
this.CommandRuntime.ToString(),
() => this.ComputeClient.VirtualMachines.UpdateLoadBalancedEndpointSet(this.ServiceName, this.CurrentDeploymentNewSM.Name, endPointParams));
}
private PVM.InputEndpoint GetEndpoint()
{
var r = from role in this.CurrentDeploymentNewSM.Roles
// TODO: NetworkConfigurationSet's string value should be 'NetworkConfiguration' instead of 'NetworkConfigurationSet'
// https://github.com/WindowsAzure/azure-sdk-for-net-pr/issues/293
//from networkConfig in role.ConfigurationSets.Where(c => c.ConfigurationSetType == ConfigurationSetTypes.NetworkConfigurationSet)
from networkConfig in role.ConfigurationSets.Where(c => c.ConfigurationSetType == "NetworkConfiguration")
where networkConfig.InputEndpoints != null
from endpoint in networkConfig.InputEndpoints
where !string.IsNullOrEmpty(endpoint.LoadBalancedEndpointSetName)
&& endpoint.LoadBalancedEndpointSetName.Equals(this.LBSetName, StringComparison.InvariantCultureIgnoreCase)
select endpoint;
return Mapper.Map<NSM.InputEndpoint, PVM.InputEndpoint>(r.FirstOrDefault());
}
private void UpdateEndpointProperties(PVM.InputEndpoint endpoint)
{
if (this.ParameterSpecified("Protocol"))
{
endpoint.Protocol = this.Protocol;
}
if (this.ParameterSpecified("LocalPort"))
{
if (!this.ParameterSpecified("ProbePort")
&& endpoint.LoadBalancerProbe != null
&& endpoint.LocalPort == endpoint.LoadBalancerProbe.Port)
{
endpoint.LoadBalancerProbe.Port = this.LocalPort;
}
endpoint.LocalPort = this.LocalPort;
}
if (this.ParameterSpecified("PublicPort"))
{
endpoint.Port = this.PublicPort;
}
if (this.ParameterSpecified("IdleTimeoutInMinutes"))
{
endpoint.IdleTimeoutInMinutes = this.IdleTimeoutInMinutes;
}
if (this.ParameterSpecified("LoadBalancerDistribution"))
{
endpoint.LoadBalancerDistribution = this.LoadBalancerDistribution;
}
if (this.ParameterSpecified("DirectServerReturn"))
{
endpoint.EnableDirectServerReturn = this.DirectServerReturn;
}
if (this.ParameterSpecified("ACL"))
{
endpoint.EndpointAccessControlList = this.ACL;
}
if (this.ParameterSetName == SetAzureLoadBalancedEndpoint.HTTPProbeParameterSet
|| this.ParameterSetName == SetAzureLoadBalancedEndpoint.TCPProbeParameterSet)
{
if (endpoint.LoadBalancerProbe == null)
{
endpoint.LoadBalancerProbe = new PVM.LoadBalancerProbe();
if (!this.ParameterSpecified("ProbePort"))
{
endpoint.LoadBalancerProbe.Port = endpoint.LocalPort;
}
}
if (this.ParameterSpecified("ProbePort"))
{
endpoint.LoadBalancerProbe.Port = this.ProbePort;
}
if (this.ParameterSpecified("ProbeIntervalInSeconds"))
{
endpoint.LoadBalancerProbe.IntervalInSeconds = this.ProbeIntervalInSeconds;
}
if (this.ParameterSpecified("ProbeTimeoutInSeconds"))
{
endpoint.LoadBalancerProbe.TimeoutInSeconds = this.ProbeTimeoutInSeconds;
}
if (this.ParameterSetName == SetAzureLoadBalancedEndpoint.HTTPProbeParameterSet)
{
endpoint.LoadBalancerProbe.Protocol = "http";
endpoint.LoadBalancerProbe.Path = this.ProbePath;
}
if (this.ParameterSetName == SetAzureLoadBalancedEndpoint.TCPProbeParameterSet)
{
endpoint.LoadBalancerProbe.Protocol = "tcp";
endpoint.LoadBalancerProbe.Path = null;
}
}
}
private bool ParameterSpecified(string parameterName)
{
return this.MyInvocation.BoundParameters.ContainsKey(parameterName);
}
}
}
| |
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Extensions;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Effects;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Input;
using osu.Framework.Input.Bindings;
using osu.Framework.Input.Events;
using osu.Game.Database;
using osu.Game.Graphics;
using osu.Game.Graphics.Sprites;
using osu.Game.Graphics.UserInterface;
using osu.Game.Input;
using osu.Game.Input.Bindings;
using osu.Game.Localisation;
using osuTK;
using osuTK.Graphics;
using osuTK.Input;
namespace osu.Game.Overlays.Settings.Sections.Input
{
public class KeyBindingRow : Container, IFilterable
{
private readonly object action;
private readonly IEnumerable<RealmKeyBinding> bindings;
private const float transition_time = 150;
private const float height = 20;
private const float padding = 5;
private bool matchingFilter;
public bool MatchingFilter
{
get => matchingFilter;
set
{
matchingFilter = value;
this.FadeTo(!matchingFilter ? 0 : 1);
}
}
private Container content;
public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) =>
content.ReceivePositionalInputAt(screenSpacePos);
public bool FilteringActive { get; set; }
[Resolved]
private ReadableKeyCombinationProvider keyCombinationProvider { get; set; }
private OsuSpriteText text;
private FillFlowContainer cancelAndClearButtons;
private FillFlowContainer<KeyButton> buttons;
private Bindable<bool> isDefault { get; } = new BindableBool(true);
public IEnumerable<string> FilterTerms => bindings.Select(b => keyCombinationProvider.GetReadableString(b.KeyCombination)).Prepend(text.Text.ToString());
public KeyBindingRow(object action, List<RealmKeyBinding> bindings)
{
this.action = action;
this.bindings = bindings;
RelativeSizeAxes = Axes.X;
AutoSizeAxes = Axes.Y;
}
[Resolved]
private RealmAccess realm { get; set; }
[BackgroundDependencyLoader]
private void load(OverlayColourProvider colourProvider)
{
RelativeSizeAxes = Axes.X;
AutoSizeAxes = Axes.Y;
Padding = new MarginPadding { Right = SettingsPanel.CONTENT_MARGINS };
InternalChildren = new Drawable[]
{
new Container
{
RelativeSizeAxes = Axes.Y,
Width = SettingsPanel.CONTENT_MARGINS,
Child = new RestoreDefaultValueButton<bool>
{
Current = isDefault,
Action = RestoreDefaults,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
}
},
new Container
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Padding = new MarginPadding { Left = SettingsPanel.CONTENT_MARGINS },
Children = new Drawable[]
{
content = new Container
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Masking = true,
CornerRadius = padding,
EdgeEffect = new EdgeEffectParameters
{
Radius = 2,
Colour = colourProvider.Highlight1.Opacity(0),
Type = EdgeEffectType.Shadow,
Hollow = true,
},
Children = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = colourProvider.Background5,
},
text = new OsuSpriteText
{
Text = action.GetLocalisableDescription(),
Margin = new MarginPadding(1.5f * padding),
},
buttons = new FillFlowContainer<KeyButton>
{
AutoSizeAxes = Axes.Both,
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight
},
cancelAndClearButtons = new FillFlowContainer
{
AutoSizeAxes = Axes.Both,
Padding = new MarginPadding(padding) { Top = height + padding * 2 },
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
Alpha = 0,
Spacing = new Vector2(5),
Children = new Drawable[]
{
new CancelButton { Action = finalise },
new ClearButton { Action = clear },
},
},
new HoverClickSounds()
}
}
}
}
};
foreach (var b in bindings)
buttons.Add(new KeyButton(b));
updateIsDefaultValue();
}
public void RestoreDefaults()
{
int i = 0;
foreach (var d in Defaults)
{
var button = buttons[i++];
button.UpdateKeyCombination(d);
updateStoreFromButton(button);
}
isDefault.Value = true;
}
protected override bool OnHover(HoverEvent e)
{
content.FadeEdgeEffectTo(1, transition_time, Easing.OutQuint);
return base.OnHover(e);
}
protected override void OnHoverLost(HoverLostEvent e)
{
content.FadeEdgeEffectTo(0, transition_time, Easing.OutQuint);
base.OnHoverLost(e);
}
public override bool AcceptsFocus => bindTarget == null;
private KeyButton bindTarget;
public bool AllowMainMouseButtons;
public IEnumerable<KeyCombination> Defaults;
private bool isModifier(Key k) => k < Key.F1;
protected override bool OnClick(ClickEvent e) => true;
protected override bool OnMouseDown(MouseDownEvent e)
{
if (!HasFocus || !bindTarget.IsHovered)
return base.OnMouseDown(e);
if (!AllowMainMouseButtons)
{
switch (e.Button)
{
case MouseButton.Left:
case MouseButton.Right:
return true;
}
}
bindTarget.UpdateKeyCombination(KeyCombination.FromInputState(e.CurrentState));
return true;
}
protected override void OnMouseUp(MouseUpEvent e)
{
// don't do anything until the last button is released.
if (!HasFocus || e.HasAnyButtonPressed)
{
base.OnMouseUp(e);
return;
}
if (bindTarget.IsHovered)
finalise();
// prevent updating bind target before clear button's action
else if (!cancelAndClearButtons.Any(b => b.IsHovered))
updateBindTarget();
}
protected override bool OnScroll(ScrollEvent e)
{
if (HasFocus)
{
if (bindTarget.IsHovered)
{
bindTarget.UpdateKeyCombination(KeyCombination.FromInputState(e.CurrentState, e.ScrollDelta));
finalise();
return true;
}
}
return base.OnScroll(e);
}
protected override bool OnKeyDown(KeyDownEvent e)
{
if (!HasFocus)
return false;
bindTarget.UpdateKeyCombination(KeyCombination.FromInputState(e.CurrentState));
if (!isModifier(e.Key)) finalise();
return true;
}
protected override void OnKeyUp(KeyUpEvent e)
{
if (!HasFocus)
{
base.OnKeyUp(e);
return;
}
finalise();
}
protected override bool OnJoystickPress(JoystickPressEvent e)
{
if (!HasFocus)
return false;
bindTarget.UpdateKeyCombination(KeyCombination.FromInputState(e.CurrentState));
finalise();
return true;
}
protected override void OnJoystickRelease(JoystickReleaseEvent e)
{
if (!HasFocus)
{
base.OnJoystickRelease(e);
return;
}
finalise();
}
protected override bool OnMidiDown(MidiDownEvent e)
{
if (!HasFocus)
return false;
bindTarget.UpdateKeyCombination(KeyCombination.FromInputState(e.CurrentState));
finalise();
return true;
}
protected override void OnMidiUp(MidiUpEvent e)
{
if (!HasFocus)
{
base.OnMidiUp(e);
return;
}
finalise();
}
private void clear()
{
if (bindTarget == null)
return;
bindTarget.UpdateKeyCombination(InputKey.None);
finalise();
}
private void finalise()
{
if (bindTarget != null)
{
updateStoreFromButton(bindTarget);
updateIsDefaultValue();
bindTarget.IsBinding = false;
Schedule(() =>
{
// schedule to ensure we don't instantly get focus back on next OnMouseClick (see AcceptFocus impl.)
bindTarget = null;
});
}
if (HasFocus)
GetContainingInputManager().ChangeFocus(null);
cancelAndClearButtons.FadeOut(300, Easing.OutQuint);
cancelAndClearButtons.BypassAutoSizeAxes |= Axes.Y;
}
protected override void OnFocus(FocusEvent e)
{
content.AutoSizeDuration = 500;
content.AutoSizeEasing = Easing.OutQuint;
cancelAndClearButtons.FadeIn(300, Easing.OutQuint);
cancelAndClearButtons.BypassAutoSizeAxes &= ~Axes.Y;
updateBindTarget();
base.OnFocus(e);
}
protected override void OnFocusLost(FocusLostEvent e)
{
finalise();
base.OnFocusLost(e);
}
/// <summary>
/// Updates the bind target to the currently hovered key button or the first if clicked anywhere else.
/// </summary>
private void updateBindTarget()
{
if (bindTarget != null) bindTarget.IsBinding = false;
bindTarget = buttons.FirstOrDefault(b => b.IsHovered) ?? buttons.FirstOrDefault();
if (bindTarget != null) bindTarget.IsBinding = true;
}
private void updateStoreFromButton(KeyButton button)
{
realm.Run(r =>
{
var binding = r.Find<RealmKeyBinding>(((IHasGuidPrimaryKey)button.KeyBinding).ID);
r.Write(() => binding.KeyCombinationString = button.KeyBinding.KeyCombinationString);
});
}
private void updateIsDefaultValue()
{
isDefault.Value = bindings.Select(b => b.KeyCombination).SequenceEqual(Defaults);
}
private class CancelButton : TriangleButton
{
public CancelButton()
{
Text = CommonStrings.Cancel;
Size = new Vector2(80, 20);
}
}
public class ClearButton : DangerousTriangleButton
{
public ClearButton()
{
Text = CommonStrings.Clear;
Size = new Vector2(80, 20);
}
}
public class KeyButton : Container
{
public readonly RealmKeyBinding KeyBinding;
private readonly Box box;
public readonly OsuSpriteText Text;
[Resolved]
private OverlayColourProvider colourProvider { get; set; }
[Resolved]
private ReadableKeyCombinationProvider keyCombinationProvider { get; set; }
private bool isBinding;
public bool IsBinding
{
get => isBinding;
set
{
if (value == isBinding) return;
isBinding = value;
updateHoverState();
}
}
public KeyButton(RealmKeyBinding keyBinding)
{
if (keyBinding.IsManaged)
throw new ArgumentException("Key binding should not be attached as we make temporary changes", nameof(keyBinding));
KeyBinding = keyBinding;
Margin = new MarginPadding(padding);
Masking = true;
CornerRadius = padding;
Height = height;
AutoSizeAxes = Axes.X;
Children = new Drawable[]
{
new Container
{
AlwaysPresent = true,
Width = 80,
Height = height,
},
box = new Box
{
RelativeSizeAxes = Axes.Both,
},
Text = new OsuSpriteText
{
Font = OsuFont.Numeric.With(size: 10),
Margin = new MarginPadding(5),
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
},
new HoverSounds()
};
}
protected override void LoadComplete()
{
base.LoadComplete();
keyCombinationProvider.KeymapChanged += updateKeyCombinationText;
updateKeyCombinationText();
}
[BackgroundDependencyLoader]
private void load()
{
updateHoverState();
}
protected override bool OnHover(HoverEvent e)
{
updateHoverState();
return base.OnHover(e);
}
protected override void OnHoverLost(HoverLostEvent e)
{
updateHoverState();
base.OnHoverLost(e);
}
private void updateHoverState()
{
if (isBinding)
{
box.FadeColour(colourProvider.Light2, transition_time, Easing.OutQuint);
Text.FadeColour(Color4.Black, transition_time, Easing.OutQuint);
}
else
{
box.FadeColour(IsHovered ? colourProvider.Light4 : colourProvider.Background6, transition_time, Easing.OutQuint);
Text.FadeColour(IsHovered ? Color4.Black : Color4.White, transition_time, Easing.OutQuint);
}
}
public void UpdateKeyCombination(KeyCombination newCombination)
{
if (KeyBinding.RulesetName != null && !RealmKeyBindingStore.CheckValidForGameplay(newCombination))
return;
KeyBinding.KeyCombination = newCombination;
updateKeyCombinationText();
}
private void updateKeyCombinationText()
{
Scheduler.AddOnce(updateText);
void updateText() => Text.Text = keyCombinationProvider.GetReadableString(KeyBinding.KeyCombination);
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
if (keyCombinationProvider != null)
keyCombinationProvider.KeymapChanged -= updateKeyCombinationText;
}
}
}
}
| |
// 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.
#if UseSingularityPDB
///////////////////////////////////////////////////////////////////////////////
//
// Microsoft Research Singularity PDB Info Library
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// File: DumpMisc.cs
//
using System;
using System.Collections;
using System.IO;
using System.Text;
using Microsoft.Singularity.PdbInfo;
using Microsoft.Singularity.PdbInfo.CodeView;
using Microsoft.Singularity.PdbInfo.Features;
namespace Microsoft.Singularity.Applications
{
//////////////////////////////////////////////////////////////////////////
//
public class DumpMisc
{
public static void Dump(BitSet bits)
{
uint word;
for (int i = 0; bits.GetWord(i, out word); i++) {
Console.Write("{0:x8}", word);
}
}
public static void Dump(PdbFunction f, int indent)
{
string pad = new String(' ', indent);
Console.WriteLine(" {0}Func: [{1}] addr={2:x4}:{3:x8} len={4:x4} token={5:x8}",
pad,
f.name, f.segment, f.address, f.length, f.token);
if (f.metadata != null) {
Console.Write(" {0} Meta: [", pad);
for (int i = 0; i < f.metadata.Length; i++) {
Console.Write("{0:x2}", f.metadata[i]);
}
Console.WriteLine("]");
}
if (f.scopes != null) {
for (int i = 0; i < f.scopes.Length; i++) {
Dump(f.scopes[i], indent + 1);
}
}
if (f.lines != null) {
for (int i = 0; i < f.lines.Length; i++) {
Dump(f.lines[i], indent + 1);
}
}
}
public static void Dump(PdbScope s, int indent)
{
string pad = new String(' ', indent);
Console.WriteLine(" {0}Scope: addr={1:x4}:{2:x8} len={3:x4}",
pad, s.segment, s.address, s.length);
if (s.slots != null) {
for (int i = 0; i < s.slots.Length; i++) {
Dump(s.slots[i], indent + 1);
}
}
if (s.scopes != null) {
for (int i = 0; i < s.scopes.Length; i++) {
Dump(s.scopes[i], indent + 1);
}
}
}
public static void Dump(PdbSlot s, int indent)
{
string pad = new String(' ', indent);
Console.WriteLine(" {0}Slot: {1,2} [{2}] addr={3:x4}:{4:x8}",
pad, s.slot, s.name, s.segment, s.address);
}
public static void Dump(PdbSource s, int indent)
{
string pad = new String(' ', indent);
Console.WriteLine(" {0}[{1}] : {2}", pad, s.name, s.index);
}
public static void Dump(PdbLines s, int indent)
{
string pad = new String(' ', indent);
Console.WriteLine(" {0}[{1}]", pad, s.file.name);
for (int i = 0; i < s.lines.Length; i++) {
Dump(s.lines[i], indent + 1);
}
}
public static void Dump(PdbLine s, int indent)
{
string pad = new String(' ', indent);
if (s.line == 0xfeefee && s.colBegin == 0 && s.colEnd == 0) {
Console.WriteLine(" {0}off={1:x8} #---------",
pad, s.offset, s.line, s.colBegin);
}
else {
Console.WriteLine(" {0}off={1:x8} #{2,6},{3,2}",
pad, s.offset, s.line, s.colBegin);
}
}
public static void Dump(DbiSecCon s)
{
Console.WriteLine(" section={0}, offset={1}, size={2}, flags={3:x8}, mod={4}",
s.section,
s.offset,
s.size,
s.flags,
s.module);
Console.WriteLine(" data={0:x8}, reloc={1:x8}",
s.dataCrc,
s.relocCrc);
}
public static void Dump(DbiModuleInfo s)
{
Console.WriteLine(" stream={0,4}. {1,3} [{2}] {3}/{4}",
s.stream, s.section.module, s.moduleName,
s.cbSyms, s.cbLines);
#if VERBOSE
Console.WriteLine(" flags={0:x4}, sym={1}, lin={2}, c13={3}, files={4}",
s.stream,
s.flags,
s.cbSyms,
s.cbOldLines,
s.cbLines,
s.files);
Dump(section);
Console.WriteLine(" offsets={0:x8}, source={1}, compiler={2}",
s.offsets, s.niSource, s.niCompiler);
Console.WriteLine(" mod=[{0}]", s.moduleName);
Console.WriteLine(" obj=[{0}]", s.objectName);
#endif
}
public static void Dump(PdbFileHeader f)
{
Console.WriteLine("FileHeader({0}, size={1}, pages={2}, dir={3}.{4})",
f.Magic,
f.pageSize,
f.pagesUsed,
f.directoryRoot,
f.directorySize);
}
public static void Dump(DataStream d)
{
Console.Write("DataStream({0} bytes", d.Length);
for (int i = 0; i < d.Pages; i++) {
Console.Write(",{0}", d.GetPage(i));
}
Console.WriteLine(")");
}
static void DumpLine(byte[] bytes, int offset, int limit)
{
for (int j = 0; j < 16; j++) {
if (j % 4 == 0) {
Console.Write(" ");
}
if (offset + j < limit) {
Console.Write("{0:x2}", bytes[offset + j]);
}
else {
Console.Write(" ");
}
}
Console.Write(" ");
for (int j = 0; j < 16; j++) {
if (offset + j < limit) {
if (bytes[offset + j] >= ' ' && bytes[offset + j] < 127) {
Console.Write("{0}", unchecked((char)bytes[offset + j]));
}
else {
Console.Write(".");
}
}
else {
Console.Write(" ");
}
}
}
static void DumpLineExt(byte[] bytes, int offset, int limit)
{
DumpLine(bytes, offset, limit);
for (int j = offset; j < offset + 16; j += 4) {
if (j + 4 <= limit) {
int value = (int)((bytes[j + 0] & 0xFF) |
(bytes[j + 1] << 8) |
(bytes[j + 2] << 16) |
(bytes[j + 3] << 24));
if (value < -9999999 || value > 99999999) {
Console.Write(" .");
}
else {
Console.Write("{0,8}", value);
}
}
else {
Console.Write(" ");
}
}
}
public static void Dump(byte[] bytes, int offset, int limit)
{
for (int i = offset; i < limit; i += 16) {
Console.Write(" {0,10}:", i);
DumpLine(bytes, i, limit);
Console.WriteLine();
}
}
static void Dump(int label, byte[] bytes, int limit)
{
for (int i = 0; i < limit; i += 16) {
Console.Write(" {0,10}:", label + i);
DumpLine(bytes, i, limit);
Console.WriteLine();
}
}
static void DumpVerbose(DataStream stream, PdbReader reader)
{
byte[] bytes = new byte[reader.PageSize];
if (stream.Length <= 0) {
return;
}
int left = stream.Length;
int pos = 0;
for (int page = 0; left > 0; page++) {
int todo = bytes.Length;
if (todo > left) {
todo = left;
}
stream.Read(reader, pos, bytes, 0, todo);
for (int i = 0; i < todo; i += 16) {
Console.Write("{0,7}:", pos + i);
DumpLineExt(bytes, i, todo);
Console.WriteLine();
}
left -= todo;
pos += todo;
}
}
static void DumpPdbStream(BitAccess bits,
out int linkStream,
out int nameStream,
out int srchStream)
{
linkStream = 0;
nameStream = 0;
srchStream = 0;
int ver;
int sig;
int age;
Guid guid;
bits.ReadInt32(out ver); // 0..3 Version
bits.ReadInt32(out sig); // 4..7 Signature
bits.ReadInt32(out age); // 8..11 Age
bits.ReadGuid(out guid); // 12..27 GUID
// Read string buffer.
int buf;
bits.ReadInt32(out buf); // 28..31 Bytes of Strings
Console.WriteLine(" ** PDB ver={0,8} sig={1:x8} age={2} guid={3}",
ver, sig, age, guid);
int beg = bits.Position;
int nxt = bits.Position + buf;
bits.Position = nxt;
// Read map index.
int cnt; // n+0..3 hash size.
int max; // n+4..7 maximum ni.
bits.ReadInt32(out cnt);
bits.ReadInt32(out max);
Console.WriteLine(" cnt={0}, max={1}", cnt, max);
BitSet present = new BitSet(bits);
BitSet deleted = new BitSet(bits);
if (!deleted.IsEmpty) {
Console.Write(" deleted: ");
Dump(deleted);
Console.WriteLine();
}
int j = 0;
for (int i = 0; i < max; i++) {
if (present.IsSet(i)) {
int ns;
int ni;
bits.ReadInt32(out ns);
bits.ReadInt32(out ni);
string name;
int saved = bits.Position;
bits.Position = beg + ns;
bits.ReadCString(out name);
bits.Position = saved;
if (name == "/names") {
nameStream = ni;
}
else if (name == "/src/headerblock") {
srchStream = ni;
}
else if (name == "/LinkInfo") {
linkStream = ni;
}
Console.WriteLine(" {0,4}: [{1}]", ni, name);
j++;
}
}
if (j != cnt) {
throw new PdbDebugException("Count mismatch. ({0} != {1})", j, cnt);
}
// Read maxni.
int maxni;
bits.ReadInt32(out maxni);
Console.WriteLine(" maxni={0}", maxni);
}
internal static int Hash(byte[] bytes, int mod)
{
byte b0 = 0;
byte b1 = 0;
byte b2 = 0;
byte b3 = 0;
int i = 0;
// word
while (i + 4 <= bytes.Length) {
b0 ^= bytes[i + 0];
b1 ^= bytes[i + 1];
b2 ^= bytes[i + 2];
b3 ^= bytes[i + 3];
i += 4;
}
// odd half word
if (i + 2 <= bytes.Length) {
b0 ^= bytes[i + 0];
b1 ^= bytes[i + 1];
}
// odd byte
if (i < bytes.Length) {
b0 ^= bytes[i + 0];
}
// make case insensitive.
b0 |= 0x20;
b1 |= 0x20;
b2 |= 0x20;
b3 |= 0x20;
// put it together.
uint hash = (uint)((b0 & 0xFF) | (b1 << 8) | (b2 << 16) | (b3 << 24));
hash ^= (hash >> 11);
hash ^= (hash >> 16);
return (int)(hash % (uint)mod);
}
static void DumpNameStream(BitAccess bits)
{
uint sig;
int ver;
bits.ReadUInt32(out sig); // 0..3 Signature
bits.ReadInt32(out ver); // 4..7 Version
// Read (or skip) string buffer.
int buf;
bits.ReadInt32(out buf); // 8..11 Bytes of Strings
Console.Write(" ** NAM sig={0:x8} ver={1,4} cb={2,4}",
sig, ver, buf);
if (sig != 0xeffeeffe || ver != 1) {
throw new PdbDebugException("Unknown Name Stream version. "+
"(sig={0:x8}, ver={1})",
sig, ver);
}
#if true
int beg = bits.Position;
int nxt = bits.Position + buf;
bits.Position = nxt;
// Read hash table.
int siz;
bits.ReadInt32(out siz); // n+0..3 Number of hash buckets.
nxt = bits.Position;
Console.WriteLine(" siz={0,4}", siz);
for (int i = 0; i < siz; i++) {
int ni;
string name;
bits.ReadInt32(out ni);
if (ni != 0) {
int saved = bits.Position;
bits.Position = beg + ni;
bits.ReadCString(out name);
bits.Position = saved;
if (name.Length > 60) {
Console.WriteLine(" {0,6}: [{1}]+", ni, name.Substring(0,60));
}
else {
Console.WriteLine(" {0,6}: [{1}]", ni, name);
}
}
}
bits.Position = nxt;
// Read maxni.
int maxni;
bits.ReadInt32(out maxni);
Console.WriteLine(" maxni={0}", maxni);
#endif
}
static void DumpTpiStream(BitAccess bits,
out int tiHashStream,
out int tiHPadStream)
{
tiHashStream = 0;
tiHPadStream = 0;
// Read the header structure.
int ver;
int hdr;
int min;
int max;
int gprec;
bits.ReadInt32(out ver);
bits.ReadInt32(out hdr);
bits.ReadInt32(out min);
bits.ReadInt32(out max);
bits.ReadInt32(out gprec);
Console.WriteLine(" ** TPI ver={0}, hdr={1}, min={2}, max={3}, gprec={4}",
ver, hdr, min, max, gprec);
// Read the hash structure.
short stream;
short padStream;
int key;
int buckets;
int vals;
int pairs;
int adj;
bits.ReadInt16(out stream);
bits.ReadInt16(out padStream);
bits.ReadInt32(out key);
bits.ReadInt32(out buckets);
bits.ReadInt32(out vals);
bits.ReadInt32(out pairs);
bits.ReadInt32(out adj);
Console.WriteLine(" stream={0}, padstream={1}, key={2}, bux={3}, vals={4}, par={5}, adj={6}",
stream, padStream, key, buckets, vals, pairs, adj);
tiHashStream = stream;
tiHPadStream = padStream;
int u1;
int u2;
int u3;
bits.ReadInt32(out u1);
bits.ReadInt32(out u2);
bits.ReadInt32(out u3);
Console.WriteLine(" pos={0}, u1={1}, u2={2}, u3={3}",
bits.Position, u1, u2, u3);
#if true
int end = hdr + gprec;
while (bits.Position < end) {
ushort cbrec;
ushort leaf;
bits.ReadUInt16(out cbrec);
bits.ReadUInt16(out leaf);
Console.WriteLine(" [{0,4}] : {1}", cbrec, (LEAF)leaf);
Dump(bits.Buffer, bits.Position, bits.Position + cbrec - 2);
bits.Position += cbrec - 2;
// [GalenH]: Need to figure out what RECs are for.
}
#endif
}
static void DumpCvInfo(BitAccess bits, int begin, int limit)
{
int indent = 0;
string pad = "";
while (bits.Position < limit) {
ushort siz;
ushort rec;
bits.ReadUInt16(out siz);
int star = bits.Position;
int stop = bits.Position + siz;
#if false
Dump(bits.GetBuffer(), star, stop);
bits.Position = star;
#endif
bits.ReadUInt16(out rec);
SYM cv = (SYM)rec;
if (rec < 0x1000) {
if (cv != SYM.S_END &&
cv != SYM.S_OEM) {
throw new Exception("CV is unknown: " + rec);
}
}
switch (cv) {
case SYM.S_OEM: { // 0x0404
OemSymbol oem;
bits.ReadGuid(out oem.idOem);
bits.ReadUInt32(out oem.typind);
// public byte[] rgl; // user data, force 4-byte alignment
if (oem.idOem == PdbFunction.msilMetaData) {
Console.WriteLine(" {0}META: ", pad);
Dump(bits.Buffer, star + 22, stop);
break;
}
else {
Console.WriteLine(" {0}OEMS: guid={1} ti={2}",
pad, oem.idOem, oem.typind);
Dump(bits.Buffer, star + 22, stop);
}
break;
}
case SYM.S_OBJNAME: { // 0x1101
ObjNameSym obj;
bits.ReadUInt32(out obj.signature);
bits.ReadCString(out obj.name);
Console.WriteLine(" {0}OBJN: sig={1:x8} [{2}]",
pad, obj.signature, obj.name);
break;
}
case SYM.S_FRAMEPROC: { // 0x1012
FrameProcSym frame;
bits.ReadUInt32(out frame.cbFrame);
bits.ReadUInt32(out frame.cbPad);
bits.ReadUInt32(out frame.offPad);
bits.ReadUInt32(out frame.cbSaveRegs);
bits.ReadUInt32(out frame.offExHdlr);
bits.ReadUInt16(out frame.secExHdlr);
bits.ReadUInt32(out frame.flags);
Console.WriteLine(" {0}FRAM: size={1}, pad={2}+{3}, exc={4:x4}:{5:x8}, flags={6:x3}",
pad, frame.cbFrame, frame.cbPad, frame.offPad,
frame.offExHdlr, frame.secExHdlr,
frame.flags);
break;
}
case SYM.S_BLOCK32: { // 0x1103
BlockSym32 block;
bits.ReadUInt32(out block.parent);
bits.ReadUInt32(out block.end);
bits.ReadUInt32(out block.len);
bits.ReadUInt32(out block.off);
bits.ReadUInt16(out block.seg);
bits.ReadCString(out block.name);
Console.WriteLine(" {0}BLCK: par={1}, addr={2:x4}:{3:x8} len={4:x4} [{5}], end={6}",
pad, block.parent, block.seg, block.off,
block.len, block.name, block.end);
indent++;
pad = new String('.', indent);
break;
}
case SYM.S_COMPILE2: { // 0x1116
CompileSym com;
bits.ReadUInt32(out com.flags);
bits.ReadUInt16(out com.machine);
bits.ReadUInt16(out com.verFEMajor);
bits.ReadUInt16(out com.verFEMinor);
bits.ReadUInt16(out com.verFEBuild);
bits.ReadUInt16(out com.verMajor);
bits.ReadUInt16(out com.verMinor);
bits.ReadUInt16(out com.verBuild);
bits.ReadCString(out com.verSt);
Console.WriteLine(" {0}COMP: flg={1:x4} mach={2:x2} [{3}] {4}.{5}.{6}.{7}.{8}.{9}",
pad,
com.flags, com.machine, com.verSt,
com.verFEMajor, com.verFEMinor, com.verFEBuild,
com.verMajor, com.verMinor, com.verBuild);
break;
}
case SYM.S_BPREL32: { // 0x110b
BpRelSym32 bp;
bits.ReadInt32(out bp.off);
bits.ReadUInt32(out bp.typind);
bits.ReadCString(out bp.name);
Console.WriteLine(" {0}BPRL: ti={1:x8} [{2}] off={3,6}",
pad, bp.typind, bp.name, bp.off);
break;
}
case SYM.S_LPROC32: // 0x110f
case SYM.S_GPROC32: { // 0x1110
ProcSym32 proc;
bits.ReadUInt32(out proc.parent);
bits.ReadUInt32(out proc.end);
bits.ReadUInt32(out proc.next);
bits.ReadUInt32(out proc.len);
bits.ReadUInt32(out proc.dbgStart);
bits.ReadUInt32(out proc.dbgEnd);
bits.ReadUInt32(out proc.typind);
bits.ReadUInt32(out proc.off);
bits.ReadUInt16(out proc.seg);
bits.ReadUInt8(out proc.flags);
bits.ReadCString(out proc.name);
Console.WriteLine(" {0}PROC: ti={1,5} [{2}] addr={3:x4}:{4:x8} len={5} f={6:x4}, end={7}",
pad, proc.typind, proc.name,
proc.seg, proc.off, proc.len, proc.flags,
proc.end);
if (proc.parent != 0 || proc.next != 0) {
Console.WriteLine(" !!! Warning parent={0}, next={1}",
proc.parent, proc.next);
}
indent++;
pad = new String('.', indent);
break;
}
case SYM.S_MANSLOT: { // 0x1120
AttrSlotSym slot;
bits.ReadUInt32(out slot.index);
bits.ReadUInt32(out slot.typind);
bits.ReadUInt32(out slot.offCod);
bits.ReadUInt16(out slot.segCod);
bits.ReadUInt16(out slot.flags);
bits.ReadCString(out slot.name);
Console.WriteLine(" {0}SLOT: ti={1:x8} [{2}] slot={3} flg={4:x4}",
pad, slot.typind, slot.name, slot.index, slot.flags);
if (slot.segCod != 0 || slot.offCod != 0) {
Console.WriteLine(" !!! Warning: addr={0:x4}:{1:x8}",
slot.segCod, slot.offCod);
}
break;
}
case SYM.S_UNAMESPACE: { // 0x1124
UnamespaceSym ns;
bits.ReadCString(out ns.name);
Console.WriteLine(" {0}NAME: using [{1}]", pad, ns.name);
break;
}
case SYM.S_GMANPROC: // 0x112a
case SYM.S_LMANPROC: { // 0x112b
ManProcSym proc;
int offset = bits.Position;
bits.ReadUInt32(out proc.parent);
bits.ReadUInt32(out proc.end);
bits.ReadUInt32(out proc.next);
bits.ReadUInt32(out proc.len);
bits.ReadUInt32(out proc.dbgStart);
bits.ReadUInt32(out proc.dbgEnd);
bits.ReadUInt32(out proc.token);
bits.ReadUInt32(out proc.off);
bits.ReadUInt16(out proc.seg);
bits.ReadUInt8(out proc.flags);
bits.ReadUInt16(out proc.retReg);
bits.ReadCString(out proc.name);
Console.WriteLine(" {0}PROC: token={1:x8} [{2}] addr={3:x4}:{4:x8} len={5:x4} f={6:x4}, end={7}",
pad, proc.token, proc.name,
proc.seg, proc.off, proc.len, proc.flags, proc.end);
if (proc.parent != 0 || proc.next != 0) {
Console.WriteLine(" !!! Warning par={0}, pnext={1}",
proc.parent, proc.next);
}
if (proc.dbgStart != 0 || proc.dbgEnd != 0) {
Console.WriteLine(" !!! Warning DBG start={0}, end={1}",
proc.dbgStart, proc.dbgEnd);
}
indent++;
pad = new String('.', indent);
break;
}
case SYM.S_END: { // 0x0006
indent--;
pad = new String('.', indent);
Console.WriteLine(" {0}END {1}", pad, bits.Position - 4);
break;
}
case SYM.S_SECTION: { // 0x1136
SectionSym sect;
bits.ReadUInt16(out sect.isec);
bits.ReadUInt8(out sect.align);
bits.ReadUInt8(out sect.bReserved);
bits.ReadUInt32(out sect.rva);
bits.ReadUInt32(out sect.cb);
bits.ReadUInt32(out sect.characteristics);
bits.ReadCString(out sect.name);
Console.WriteLine(" {0}SECT: sec={1,4} align={2}, flags={3:x8} [{4}]",
pad, sect.isec, sect.align,
sect.characteristics, sect.name);
break;
}
case SYM.S_COFFGROUP: { // 0x1137
CoffGroupSym group;
bits.ReadUInt32(out group.cb);
bits.ReadUInt32(out group.characteristics);
bits.ReadUInt32(out group.off);
bits.ReadUInt16(out group.seg);
bits.ReadCString(out group.name);
Console.WriteLine(" {0}CGRP: flags={1:x8} [{2}] addr={3:x4}:{4:x8}",
pad, group.characteristics,
group.name, group.seg, group.off);
break;
}
case SYM.S_THUNK32: { // 0x1102
ThunkSym32 thunk;
bits.ReadUInt32(out thunk.parent);
bits.ReadUInt32(out thunk.end);
bits.ReadUInt32(out thunk.next);
bits.ReadUInt32(out thunk.off);
bits.ReadUInt16(out thunk.seg);
bits.ReadUInt16(out thunk.len);
bits.ReadUInt8(out thunk.ord);
bits.ReadCString(out thunk.name);
Console.WriteLine(" {0}THNK: addr={1:x4}:{2:x8} [{3}], end={4}",
pad, thunk.seg, thunk.off, thunk.name, thunk.end);
indent++;
pad = new String('.', indent);
break;
}
default: {
Console.WriteLine(" {0}{1}:", pad, cv);
Dump(bits.Buffer, star + 2, stop);
break;
}
}
bits.Position = stop;
}
if (indent != 0) {
throw new Exception("indent isn't 0.");
}
}
static void DumpSymbols(BitAccess bits, int begin, int limit)
{
// Dump the symbols.
Console.WriteLine(" Symbols:");
bits.Position = begin;
int sig;
bits.ReadInt32(out sig);
if (sig != 4) {
throw new Exception("Invalid signature.");
}
DumpCvInfo(bits, bits.Position, limit);
}
static void DumpLines(BitAccess bits,
int begin,
int limit)
{
uint lastAddr = 0;
// Read the files first
Console.WriteLine(" Lines:");
bits.Position = begin;
while (bits.Position < limit) {
int sig;
int siz;
bits.ReadInt32(out sig);
bits.ReadInt32(out siz);
int place = bits.Position;
int endSym = bits.Position + siz;
switch ((DEBUG_S_SUBSECTION)sig) {
case DEBUG_S_SUBSECTION.FILECHKSMS:
int beg = bits.Position;
while (bits.Position < endSym) {
CV_FileCheckSum chk;
int nif = bits.Position - beg;
bits.ReadUInt32(out chk.name);
bits.ReadUInt8(out chk.len);
bits.ReadUInt8(out chk.type);
int where = bits.Position;
bits.Position += chk.len;
bits.Align(4);
Console.WriteLine(" nif={0,4}, ni={1,5}, type={2:x2}, len={3}",
nif, chk.name, chk.type, chk.len);
Dump(bits.Buffer, where, where + chk.len);
}
bits.Position = endSym;
break;
case DEBUG_S_SUBSECTION.LINES:
bits.Position = endSym;
break;
default:
Console.WriteLine(" ??? {0}", (DEBUG_S_SUBSECTION)sig);
Dump(bits.Buffer, bits.Position, bits.Position + siz);
bits.Position = endSym;
break;
}
}
// Read the lines next.
bits.Position = begin;
while (bits.Position < limit) {
int sig;
int siz;
bits.ReadInt32(out sig);
bits.ReadInt32(out siz);
int endSym = bits.Position + siz;
switch ((DEBUG_S_SUBSECTION)sig) {
case DEBUG_S_SUBSECTION.LINES: {
CV_LineSection sec;
bits.ReadUInt32(out sec.off);
bits.ReadUInt16(out sec.sec);
bits.ReadUInt16(out sec.flags);
bits.ReadUInt32(out sec.cod);
Console.WriteLine(" addr={0:x4}:{1:x8}, flg={2:x4}, cod={3,8}",
sec.sec, sec.off, sec.flags, sec.cod);
if (sec.off < lastAddr) {
throw new PdbDebugException("address {0} follows {1}", sec.off, lastAddr);
}
else if (sec.off > lastAddr) {
lastAddr = sec.off;
}
while (bits.Position < endSym) {
CV_SourceFile file;
bits.ReadUInt32(out file.index);
bits.ReadUInt32(out file.count);
bits.ReadUInt32(out file.linsiz); // Size of payload.
Console.WriteLine(" nif={0,4}, cnt={1,4}",
file.index, file.count);
int plin = bits.Position;
int pcol = bits.Position + 8 * (int)file.count;
//Dump(bits.Buffer, bits.Position, bits.Position + file.linsiz);
for (int i = 0; i < file.count; i++) {
CV_Line line;
CV_Column column = new CV_Column();
bits.Position = plin + 8 * i;
bits.ReadUInt32(out line.offset);
bits.ReadUInt32(out line.flags);
uint delta = (line.flags & 0x7f000000) >> 24;
bool statement = ((line.flags & 0x80000000) == 0);
if ((sec.flags & 1) != 0) {
bits.Position = pcol + 4 * i;
bits.ReadUInt16(out column.offColumnStart);
bits.ReadUInt16(out column.offColumnEnd);
}
Console.WriteLine(" pc={0:x8} # {1,8}.{2,2}.{3,2}",
line.offset,
line.flags & 0xffffff,
column.offColumnStart,
column.offColumnEnd);
}
}
break;
}
}
bits.Position = endSym;
}
}
static void DumpDbiModule(BitAccess bits,
DbiModuleInfo info)
{
Console.WriteLine(" ** Module [{0}]", info.moduleName);
DumpSymbols(bits, 0, info.cbSyms);
DumpLines(bits,
info.cbSyms + info.cbOldLines,
info.cbSyms + info.cbOldLines + info.cbLines);
}
static void DumpDbiStream(BitAccess bits,
out int globalsStream,
out int publicsStream,
out int symbolsStream,
out DbiModuleInfo[] modules)
{
globalsStream = 0;
publicsStream = 0;
symbolsStream = 0;
DbiHeader dh = new DbiHeader(bits);
Console.WriteLine(" ** DBI sig={0}, ver={1}, age={2}, vers={3:x4}, "+
"pdb={4}, pdb2={5}",
dh.sig, dh.ver, dh.age, dh.vers, dh.pdbver, dh.pdbver2);
if (dh.sig != -1 || dh.ver != 19990903) {
throw new IOException("Unknown DBI Stream version");
}
Console.WriteLine(" mach={0:x4}, flags={1:x4}, globals={2}, publics={3}, symbols={4}",
dh.machine,
dh.flags,
dh.gssymStream,
dh.pssymStream,
dh.symrecStream);
Console.WriteLine(" gpmod={0}, seccon={1}, secmap={2}, filinf={3}, ",
dh.gpmodiSize,
dh.secconSize,
dh.secmapSize,
dh.filinfSize);
Console.WriteLine(" tsmap={0}, dbghdr={1}, ecinf={2}, mfc={3}",
dh.tsmapSize,
dh.dbghdrSize,
dh.ecinfoSize,
dh.mfcIndex);
Console.WriteLine(" sizes={0}",
bits.Position +
dh.gpmodiSize +
dh.secconSize +
dh.secmapSize +
dh.filinfSize +
dh.tsmapSize +
dh.dbghdrSize +
dh.ecinfoSize);
globalsStream = dh.gssymStream;
publicsStream = dh.pssymStream;
symbolsStream = dh.symrecStream;
// Read gpmod section.
ArrayList modList = new ArrayList();
int end = bits.Position + dh.gpmodiSize;
while (bits.Position < end) {
DbiModuleInfo mod = new DbiModuleInfo(bits, true);
Dump(mod);
modList.Add(mod);
}
if (bits.Position != end) {
throw new Exception("off!");
}
// Read seccon section.
end = bits.Position + dh.secconSize;
Console.WriteLine(" SecCon:");
Dump(bits.Buffer, bits.Position, end);
bits.Position = end;
// Read secmap section.
end = bits.Position + dh.secmapSize;
Console.WriteLine(" SecMap:");
Dump(bits.Buffer, bits.Position, end);
bits.Position = end;
// Read filinf section.
end = bits.Position + dh.filinfSize;
Console.WriteLine(" FilInf:");
Dump(bits.Buffer, bits.Position, end);
bits.Position = end;
// Read tsmap section.
end = bits.Position + dh.tsmapSize;
Console.WriteLine(" TSMap:");
Dump(bits.Buffer, bits.Position, end);
bits.Position = end;
// Read ecinfo section.
end = bits.Position + dh.ecinfoSize;
Console.WriteLine(" ECInfo:");
Dump(bits.Buffer, bits.Position, end);
DumpNameStream(bits);
bits.Position = end;
// Read dbghdr section.
end = bits.Position + dh.dbghdrSize;
Console.WriteLine(" DbgHdr:");
if (dh.dbghdrSize > 0) {
int beg = bits.Position;
Dump(bits.Buffer, bits.Position, end);
bits.Position = beg;
DbiDbgHdr ddh = new DbiDbgHdr(bits);
Console.WriteLine(" sechdr={0}, ridmap={1}",
ddh.snSectionHdr,
ddh.snTokenRidMap);
}
bits.Position = end;
if (modList.Count > 0) {
modules = (DbiModuleInfo[])modList.ToArray(typeof(DbiModuleInfo));
}
else {
modules = null;
}
}
static void DumpFile(Stream read, bool verbose)
{
BitAccess bits = new BitAccess(4096);
PdbFileHeader head = new PdbFileHeader(read, bits);
PdbReader reader = new PdbReader(read, head.pageSize);
MsfDirectory dir = new MsfDirectory(reader, head, bits);
Console.WriteLine(" PDB Processing[{0}]:", head.Magic);
Console.WriteLine(" cbPage: {0}, fmap: {1}, pages: {2}, dirs: {3}, streams: {4}",
head.pageSize,
head.freePageMap,
head.pagesUsed,
head.directoryRoot,
dir.streams.Length);
byte[] buffer = new byte[head.pageSize];
int linkStream = 0;
int nameStream = 0;
int srchStream = 0;
int tiHashStream = 0;
int tiHPadStream = 0;
int globalsStream = 0;
int publicsStream = 0;
int symbolsStream = 0;
DbiModuleInfo[] modules = null;
for (int i = 0; i < dir.streams.Length; i++) {
if (dir.streams[i].Length <= 0) {
Console.WriteLine("{0,4}:{1,7} bytes", i, dir.streams[i].Length);
}
else {
Console.Write("{0,4}:{1,7} bytes {2,5}:",
i,
dir.streams[i].Length,
dir.streams[i].GetPage(0));
int todo = 16;
if (todo > dir.streams[i].Length) {
todo = dir.streams[i].Length;
}
dir.streams[i].Read(reader, 0, buffer, 0, todo);
DumpLine(buffer, 0, todo);
Console.WriteLine();
DbiModuleInfo module = null;
if (modules != null) {
for (int m = 0; m < modules.Length; m++) {
if (modules[m].stream == i) {
module = modules[m];
break;
}
}
}
if (i == 1) { // <pdb>
dir.streams[i].Read(reader, bits);
DumpPdbStream(bits, out linkStream, out nameStream, out srchStream);
Console.WriteLine();
}
else if (i == 2) {
dir.streams[i].Read(reader, bits);
DumpTpiStream(bits, out tiHashStream, out tiHPadStream);
Console.WriteLine();
}
else if (i == 3) {
dir.streams[i].Read(reader, bits);
DumpDbiStream(bits,
out globalsStream,
out publicsStream,
out symbolsStream,
out modules);
Console.WriteLine();
}
else if (linkStream > 0 && i == linkStream) {
Console.WriteLine(" ** LNK");
if (verbose) {
DumpVerbose(dir.streams[i], reader);
}
Console.WriteLine();
}
else if (nameStream > 0 && i == nameStream) {
dir.streams[i].Read(reader, bits);
DumpNameStream(bits);
Console.WriteLine();
}
else if (srchStream > 0 && i == srchStream) {
Console.WriteLine(" ** SRC");
if (verbose) {
DumpVerbose(dir.streams[i], reader);
}
Console.WriteLine();
}
else if (tiHashStream > 0 && i == tiHashStream) {
Console.WriteLine(" ** TI#");
if (verbose) {
DumpVerbose(dir.streams[i], reader);
}
Console.WriteLine();
}
else if (tiHPadStream > 0 && i == tiHPadStream) {
Console.WriteLine(" ** TI#PAD");
if (verbose) {
DumpVerbose(dir.streams[i], reader);
}
Console.WriteLine();
}
else if (globalsStream > 0 && i == globalsStream) {
Console.WriteLine(" ** GLOBALS");
if (verbose) {
DumpVerbose(dir.streams[i], reader);
}
Console.WriteLine();
}
else if (publicsStream > 0 && i == publicsStream) {
Console.WriteLine(" ** PUBLICS");
if (verbose) {
DumpVerbose(dir.streams[i], reader);
}
Console.WriteLine();
}
else if (symbolsStream > 0 && i == symbolsStream) {
Console.WriteLine(" ** SYMBOLS");
if (verbose) {
dir.streams[i].Read(reader, bits);
DumpCvInfo(bits, 0, dir.streams[i].Length);
}
Console.WriteLine();
}
else if (module != null) {
dir.streams[i].Read(reader, bits);
DumpDbiModule(bits, module);
Console.WriteLine();
}
else if (verbose) {
DumpVerbose(dir.streams[i], reader);
Console.WriteLine();
}
}
if (i == 0) {
Console.WriteLine("+------------------------------------------------------------------------------");
}
}
}
static void CopyFile(Stream read, PdbWriter writer)
{
BitAccess bits = new BitAccess(4096);
// Read the header and directory from the old file.
// System.Diagnostics.Debugger.Break();
PdbFileHeader head = new PdbFileHeader(read, bits);
PdbReader reader = new PdbReader(read, head.pageSize);
MsfDirectory dir = new MsfDirectory(reader, head, bits);
byte[] buffer = new byte[head.pageSize];
// Copy the streams.
DataStream[] streams = new DataStream [dir.streams.Length];
for (int i = 0; i < dir.streams.Length; i++) {
streams[i] = new DataStream();
DataStream source = dir.streams[i];
if (source.Length <= 0) {
continue;
}
int left = source.Length;
int pos = 0;
for (int page = 0; left > 0; page++) {
int todo = buffer.Length;
if (todo > left) {
todo = left;
}
dir.streams[i].Read(reader, pos, buffer, 0, todo);
streams[i].Write(writer, buffer, todo);
left -= todo;
pos += todo;
}
}
writer.WriteMeta(streams, bits);
}
static void SplitStreams(Stream read, string split)
{
BitAccess bits = new BitAccess(4096);
// Read the header and directory from the old file.
// System.Diagnostics.Debugger.Break();
PdbFileHeader head = new PdbFileHeader(read, bits);
PdbReader reader = new PdbReader(read, head.pageSize);
MsfDirectory dir = new MsfDirectory(reader, head, bits);
byte[] buffer = new byte[head.pageSize];
// Copy the streams.
DataStream[] streams = new DataStream [dir.streams.Length];
for (int i = 0; i < dir.streams.Length; i++) {
streams[i] = new DataStream();
DataStream source = dir.streams[i];
if (source.Length <= 0) {
continue;
}
string name = String.Format("{0}.{1:d4}", split, i);
Console.WriteLine("{0,4}: --> {1}", i, name);
FileStream writer = new FileStream(name,
FileMode.Create,
FileAccess.Write);
int left = source.Length;
int pos = 0;
for (int page = 0; left > 0; page++) {
int todo = buffer.Length;
if (todo > left) {
todo = left;
}
dir.streams[i].Read(reader, pos, buffer, 0, todo);
writer.Write(buffer, 0, todo);
left -= todo;
pos += todo;
}
writer.Close();
}
}
private static void Usage()
{
Console.WriteLine("Usage:\n" +
" DumpMisc {options} [pdbs]\n" +
"Options:\n" +
" /a Dump all information.\n" +
" /o:dest Copy content into new file..\n" +
" /s Split file into streams.\n" +
" /v Verbose output.\n" +
"");
}
static int Main(string[] args)
{
bool good = false;
bool split = false;
bool verbose = false;
bool all = false;
FileStream dest = null;
if (args.Length == 0) {
Usage();
return 1;
}
for (int i = 0; i < args.Length; i++) {
string arg = args[i];
if (arg.Length >= 2 && (arg[0] == '-' || arg[0] == '/')) {
string name = null;
string value = null;
int n = arg.IndexOf(':');
if (n > -1) {
name = arg.Substring(1, n - 1).ToLower();
if (n < arg.Length + 1) {
value = arg.Substring(n + 1);
}
}
else {
name = arg.Substring(1).ToLower();
}
bool badArg = false;
switch (name) {
case "a":
case "all":
all = true;
break;
case "o":
case "out":
dest = new FileStream(value,
FileMode.Create,
FileAccess.Write);
break;
case "s":
case "split":
split = true;
break;
case "v":
case "verbose":
verbose = true;
break;
default :
badArg = true;
break;
}
if (badArg) {
Console.WriteLine("Malformed argument: \"{0}\"", arg);
Usage();
return 1;
}
}
else {
try {
string path = Path.GetDirectoryName(arg);
string match = Path.GetFileName(arg);
if (path == null || path == String.Empty) {
path = ".";
}
Console.WriteLine("[{0}] [{1}]", path, match);
String[] files = Directory.GetFiles(path, match);
if (files == null) {
Console.WriteLine("Could not find: {0}", arg);
return 2;
}
if (files != null) {
foreach (string file in files) {
try {
FileStream stream = new FileStream(file,
FileMode.Open,
FileAccess.Read);
if (split) {
SplitStreams(stream, file);
}
else if (dest != null) {
CopyFile(stream, new PdbWriter(dest, 2048));
}
else if (all) {
DumpFile(stream, verbose);
}
else {
Console.WriteLine("{0}:", file);
BitAccess bits = new BitAccess(512 * 1024);
PdbFunction[] funcs = PdbFile.LoadFunctions(stream,
bits,
true);
Console.WriteLine(" {0} functions", funcs.Length);
#if true
for (int f = 0; f < funcs.Length; f++) {
if (verbose) {
Dump(funcs[f], 0);
}
else {
Console.WriteLine(" {0:x4}:{1:x8} {2:x8} {3}",
funcs[f].segment,
funcs[f].address,
funcs[f].token,
funcs[f].name);
}
}
#endif
GC.Collect();
}
good = true;
}
catch (IOException e) {
Console.Error.WriteLine("{0}: I/O Failure: {1}",
file, e.Message);
good = false;
}
}
}
}
catch (IOException e) {
Console.Error.WriteLine("{0}: I/O Failure: {1}",
arg, e.Message);
good = false;
}
}
}
if (!good) {
return 1;
}
return 0;
}
}
}
#endif
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the ConLugarActividadGrupal class.
/// </summary>
[Serializable]
public partial class ConLugarActividadGrupalCollection : ActiveList<ConLugarActividadGrupal, ConLugarActividadGrupalCollection>
{
public ConLugarActividadGrupalCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>ConLugarActividadGrupalCollection</returns>
public ConLugarActividadGrupalCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
ConLugarActividadGrupal o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the CON_LugarActividadGrupal table.
/// </summary>
[Serializable]
public partial class ConLugarActividadGrupal : ActiveRecord<ConLugarActividadGrupal>, IActiveRecord
{
#region .ctors and Default Settings
public ConLugarActividadGrupal()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public ConLugarActividadGrupal(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public ConLugarActividadGrupal(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public ConLugarActividadGrupal(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("CON_LugarActividadGrupal", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdLugarActividadGrupal = new TableSchema.TableColumn(schema);
colvarIdLugarActividadGrupal.ColumnName = "idLugarActividadGrupal";
colvarIdLugarActividadGrupal.DataType = DbType.Int32;
colvarIdLugarActividadGrupal.MaxLength = 0;
colvarIdLugarActividadGrupal.AutoIncrement = true;
colvarIdLugarActividadGrupal.IsNullable = false;
colvarIdLugarActividadGrupal.IsPrimaryKey = true;
colvarIdLugarActividadGrupal.IsForeignKey = false;
colvarIdLugarActividadGrupal.IsReadOnly = false;
colvarIdLugarActividadGrupal.DefaultSetting = @"";
colvarIdLugarActividadGrupal.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdLugarActividadGrupal);
TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema);
colvarNombre.ColumnName = "nombre";
colvarNombre.DataType = DbType.AnsiString;
colvarNombre.MaxLength = 150;
colvarNombre.AutoIncrement = false;
colvarNombre.IsNullable = false;
colvarNombre.IsPrimaryKey = false;
colvarNombre.IsForeignKey = false;
colvarNombre.IsReadOnly = false;
colvarNombre.DefaultSetting = @"";
colvarNombre.ForeignKeyTableName = "";
schema.Columns.Add(colvarNombre);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("CON_LugarActividadGrupal",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdLugarActividadGrupal")]
[Bindable(true)]
public int IdLugarActividadGrupal
{
get { return GetColumnValue<int>(Columns.IdLugarActividadGrupal); }
set { SetColumnValue(Columns.IdLugarActividadGrupal, value); }
}
[XmlAttribute("Nombre")]
[Bindable(true)]
public string Nombre
{
get { return GetColumnValue<string>(Columns.Nombre); }
set { SetColumnValue(Columns.Nombre, value); }
}
#endregion
#region PrimaryKey Methods
protected override void SetPrimaryKey(object oValue)
{
base.SetPrimaryKey(oValue);
SetPKValues();
}
private DalSic.ConAgendaGrupalCollection colConAgendaGrupalRecords;
public DalSic.ConAgendaGrupalCollection ConAgendaGrupalRecords
{
get
{
if(colConAgendaGrupalRecords == null)
{
colConAgendaGrupalRecords = new DalSic.ConAgendaGrupalCollection().Where(ConAgendaGrupal.Columns.IdLugarActividadGrupal, IdLugarActividadGrupal).Load();
colConAgendaGrupalRecords.ListChanged += new ListChangedEventHandler(colConAgendaGrupalRecords_ListChanged);
}
return colConAgendaGrupalRecords;
}
set
{
colConAgendaGrupalRecords = value;
colConAgendaGrupalRecords.ListChanged += new ListChangedEventHandler(colConAgendaGrupalRecords_ListChanged);
}
}
void colConAgendaGrupalRecords_ListChanged(object sender, ListChangedEventArgs e)
{
if (e.ListChangedType == ListChangedType.ItemAdded)
{
// Set foreign key value
colConAgendaGrupalRecords[e.NewIndex].IdLugarActividadGrupal = IdLugarActividadGrupal;
}
}
#endregion
//no foreign key tables defined (0)
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(string varNombre)
{
ConLugarActividadGrupal item = new ConLugarActividadGrupal();
item.Nombre = varNombre;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdLugarActividadGrupal,string varNombre)
{
ConLugarActividadGrupal item = new ConLugarActividadGrupal();
item.IdLugarActividadGrupal = varIdLugarActividadGrupal;
item.Nombre = varNombre;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdLugarActividadGrupalColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn NombreColumn
{
get { return Schema.Columns[1]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdLugarActividadGrupal = @"idLugarActividadGrupal";
public static string Nombre = @"nombre";
}
#endregion
#region Update PK Collections
public void SetPKValues()
{
if (colConAgendaGrupalRecords != null)
{
foreach (DalSic.ConAgendaGrupal item in colConAgendaGrupalRecords)
{
if (item.IdLugarActividadGrupal != IdLugarActividadGrupal)
{
item.IdLugarActividadGrupal = IdLugarActividadGrupal;
}
}
}
}
#endregion
#region Deep Save
public void DeepSave()
{
Save();
if (colConAgendaGrupalRecords != null)
{
colConAgendaGrupalRecords.SaveAll();
}
}
#endregion
}
}
| |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System.Drawing;
using System.Drawing.Drawing2D;
namespace DotSpatial.Symbology.Forms
{
/// <summary>
/// SquareButton.
/// </summary>
public class SquareButton
{
#region Fields
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="SquareButton"/> class.
/// </summary>
public SquareButton()
{
ColorUpDark = SystemColors.ControlDark;
ColorUpLit = SystemColors.Control;
ColorDownDark = SystemColors.ControlDark;
ColorDownLit = SystemColors.ControlDark;
State = ButtonStates.None;
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the rectangular bounds for this button.
/// </summary>
public virtual RectangleF Bounds { get; set; }
/// <summary>
/// Gets or sets the color for this button control when it is pressed but is not
/// capturing the mouse.
/// </summary>
public Color ColorDownDark { get; set; }
/// <summary>
/// Gets or sets the primary color for this button control when it is pressed
/// and is capturing the mouse.
/// </summary>
public Color ColorDownLit { get; set; }
/// <summary>
/// Gets or sets the color for this button control when it is not pressed and is not
/// capturing the mouse.
/// </summary>
public Color ColorUpDark { get; set; }
/// <summary>
/// Gets or sets the color for this button control when it is not pressed, but is
/// currently capturing the mouse.
/// </summary>
public Color ColorUpLit { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this button is currently pressed.
/// </summary>
public bool IsDown
{
get
{
return State.IsPressed();
}
set
{
State = value ? State.Pressed() : State.Raised();
}
}
/// <summary>
/// Gets or sets a value indicating whether this button is currently lit.
/// </summary>
public bool IsLit
{
get
{
return State.IsLit();
}
set
{
State = value ? State.Lit() : State.Darkened();
}
}
/// <summary>
/// Gets or sets the state of the button, including whether it is pressed and whether
/// it is illuminated.
/// </summary>
public ButtonStates State { get; set; }
#endregion
#region Methods
/// <summary>
/// Instructs this button to draw itself.
/// </summary>
/// <param name="g">The graphics object used for drawing.</param>
/// <param name="clipRectangle">The clip rectangle.</param>
public void Draw(Graphics g, Rectangle clipRectangle)
{
OnDraw(g, clipRectangle);
}
/// <summary>
/// Gets the current color based on the current state.
/// </summary>
/// <returns>The current color.</returns>
public Color GetCurrentColor()
{
if (State.IsPressed())
{
return State.IsLit() ? ColorDownLit : ColorDownDark;
}
return State.IsLit() ? ColorUpLit : ColorUpDark;
}
/// <summary>
/// Updates the mouse location and return true if the state had to change.
/// </summary>
/// <param name="mouseLocation">Updates this button appropriately based on the specified mouse location.</param>
/// <returns>Boolean, true if a change was made.</returns>
public bool UpdateLight(Point mouseLocation)
{
PointF pt = new PointF(mouseLocation.X, mouseLocation.Y);
if (Bounds.Contains(pt))
{
if (State.IsLit() == false)
{
State = State.Lit();
return true;
}
}
else
{
if (State.IsLit())
{
State = State.Darkened();
return true;
}
}
return false;
}
/// <summary>
/// Updates the depressed nature of the button based on a mouse click in the specified location.
/// </summary>
/// <param name="mouseLocation">The location where the mouse was clicked.</param>
/// <returns>True, if the mouse was clicked inside the button.</returns>
public bool UpdatePressed(Point mouseLocation)
{
PointF pt = new PointF(mouseLocation.X, mouseLocation.Y);
if (Bounds.Contains(pt))
{
State = State.InverseDepression();
return true;
}
return false;
}
/// <summary>
/// Creates a Gradient Brush.
/// </summary>
/// <param name="color">The color.</param>
/// <param name="topLeft">The top left point.</param>
/// <param name="bottomRight">The bottom right point.</param>
/// <returns>A linear gradient brush.</returns>
protected static LinearGradientBrush CreateGradientBrush(Color color, PointF topLeft, PointF bottomRight)
{
float b = color.GetBrightness();
b += .3F;
if (b > 1F) b = 1F;
Color light = SymbologyGlobal.ColorFromHsl(color.GetHue(), color.GetSaturation(), b);
float d = color.GetBrightness();
d -= .3F;
if (d < 0F) d = 0F;
Color dark = SymbologyGlobal.ColorFromHsl(color.GetHue(), color.GetSaturation(), d);
return new LinearGradientBrush(topLeft, bottomRight, light, dark);
}
/// <summary>
/// Draws this square button. The graphics object should be in client coordinates.
/// </summary>
/// <param name="g">The graphics object used for drawing.</param>
/// <param name="clipRectangle">The clip rectangle.</param>
protected virtual void OnDraw(Graphics g, Rectangle clipRectangle)
{
Color baseColor = GetCurrentColor();
DrawFill(g, baseColor);
}
private void DrawBorders(Graphics g, Color baseColor)
{
Color light = baseColor.Lighter(.3F);
Color dark = baseColor.Darker(.3F);
Color topLeftColor = light;
Color bottomRightColor = dark;
if (State.IsPressed())
{
topLeftColor = dark;
bottomRightColor = light;
}
Pen topLeftPen = new Pen(topLeftColor);
Pen bottomRightPen = new Pen(bottomRightColor);
Pen middlePen = new Pen(baseColor);
float l = Bounds.Left;
float r = Bounds.Right;
float t = Bounds.Top;
float b = Bounds.Bottom;
// Straight line parts
g.DrawLine(topLeftPen, l + 1F, t, r - 1F, t);
g.DrawLine(bottomRightPen, l + 1F, b, r - 1F, b);
g.DrawLine(topLeftPen, l, t + 1F, l, b - 1F);
g.DrawLine(bottomRightPen, r, t + 1F, r, b - 1F);
// "rounded" corner lines
g.DrawLine(topLeftPen, l, t + 2F, l + 2F, t);
g.DrawLine(middlePen, r - 2F, t, r, t + 2F);
g.DrawLine(middlePen, l, b - 2F, l + 2F, b);
g.DrawLine(bottomRightPen, r, b - 2F, r - 2F, b);
topLeftPen.Dispose();
bottomRightPen.Dispose();
middlePen.Dispose();
}
private void DrawFill(Graphics g, Color baseColor)
{
PointF topLeft = new PointF(Bounds.X, Bounds.Y);
PointF bottomRight = new PointF(Bounds.Right, Bounds.Bottom);
RectangleF inner = RectangleF.Inflate(Bounds, -1F, -1F);
using (var br = State.IsPressed() ? CreateGradientBrush(baseColor, bottomRight, topLeft) : CreateGradientBrush(baseColor, topLeft, bottomRight))
{
g.FillRectangle(br, inner);
}
}
#endregion
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\Requests\EntityCollectionRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type GraphServiceUsersCollectionRequest.
/// </summary>
public partial class GraphServiceUsersCollectionRequest : BaseRequest, IGraphServiceUsersCollectionRequest
{
/// <summary>
/// Constructs a new GraphServiceUsersCollectionRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public GraphServiceUsersCollectionRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Adds the specified User to the collection via POST.
/// </summary>
/// <param name="user">The User to add.</param>
/// <returns>The created User.</returns>
public System.Threading.Tasks.Task<User> AddAsync(User user)
{
return this.AddAsync(user, CancellationToken.None);
}
/// <summary>
/// Adds the specified User to the collection via POST.
/// </summary>
/// <param name="user">The User to add.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created User.</returns>
public System.Threading.Tasks.Task<User> AddAsync(User user, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
return this.SendAsync<User>(user, cancellationToken);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <returns>The collection page.</returns>
public System.Threading.Tasks.Task<IGraphServiceUsersCollectionPage> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The collection page.</returns>
public async System.Threading.Tasks.Task<IGraphServiceUsersCollectionPage> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var response = await this.SendAsync<GraphServiceUsersCollectionResponse>(null, cancellationToken).ConfigureAwait(false);
if (response != null && response.Value != null && response.Value.CurrentPage != null)
{
if (response.AdditionalData != null)
{
object nextPageLink;
response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
response.Value.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
// Copy the additional data collection to the page itself so that information is not lost
response.Value.AdditionalData = response.AdditionalData;
}
return response.Value;
}
return null;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IGraphServiceUsersCollectionRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IGraphServiceUsersCollectionRequest Expand(Expression<Func<User, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IGraphServiceUsersCollectionRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IGraphServiceUsersCollectionRequest Select(Expression<Func<User, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Adds the specified top value to the request.
/// </summary>
/// <param name="value">The top value.</param>
/// <returns>The request object to send.</returns>
public IGraphServiceUsersCollectionRequest Top(int value)
{
this.QueryOptions.Add(new QueryOption("$top", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified filter value to the request.
/// </summary>
/// <param name="value">The filter value.</param>
/// <returns>The request object to send.</returns>
public IGraphServiceUsersCollectionRequest Filter(string value)
{
this.QueryOptions.Add(new QueryOption("$filter", value));
return this;
}
/// <summary>
/// Adds the specified skip value to the request.
/// </summary>
/// <param name="value">The skip value.</param>
/// <returns>The request object to send.</returns>
public IGraphServiceUsersCollectionRequest Skip(int value)
{
this.QueryOptions.Add(new QueryOption("$skip", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified orderby value to the request.
/// </summary>
/// <param name="value">The orderby value.</param>
/// <returns>The request object to send.</returns>
public IGraphServiceUsersCollectionRequest OrderBy(string value)
{
this.QueryOptions.Add(new QueryOption("$orderby", value));
return this;
}
}
}
| |
using System.Collections.Concurrent;
using Signum.Entities.Reflection;
namespace Signum.Entities;
/// <summary>
/// When used on a static class, auto-initializes its static fields of symbols or operations
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public sealed class AutoInitAttribute : Attribute
{
public static Exception ArgumentNullException(Type argumentType, string argumentName)
{
return new ArgumentNullException(argumentName, $"The argument '{argumentName}' of type '{argumentType.TypeName()}' is null. Are you missing an [AutoInit] attribute?");
}
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Enum | AttributeTargets.Property | AttributeTargets.Interface, AllowMultiple = false)]
public sealed class InTypeScriptAttribute : Attribute
{
bool? inTypeScript = null;
public bool? GetInTypeScript() => inTypeScript;
private InTypeScriptAttribute() { }
public InTypeScriptAttribute(bool inTypeScript)
{
this.inTypeScript = inTypeScript;
}
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class ImportInTypeScriptAttribute : Attribute
{
public Type Type { get; set; }
public string ForNamesace { get; set; }
public ImportInTypeScriptAttribute(Type type, string forNamespace)
{
this.Type = type;
this.ForNamesace = forNamespace;
}
}
[AttributeUsage(AttributeTargets.Class)]
public sealed class CleanTypeNameAttribute: Attribute
{
public string Name { get; private set; }
public CleanTypeNameAttribute(string name)
{
this.Name = name;
}
}
public static class EntityKindCache
{
static ConcurrentDictionary<Type, EntityKindAttribute> dictionary = new ConcurrentDictionary<Type, EntityKindAttribute>();
public static EntityKind GetEntityKind(Type type)
{
return GetAttribute(type).EntityKind;
}
public static EntityData GetEntityData(Type type)
{
return GetAttribute(type).EntityData;
}
public static bool RequiresSaveOperation(Type type)
{
return GetAttribute(type).RequiresSaveOperation;
}
public static bool IsLowPopulation(Type type)
{
return TryGetAttribute(type)?.IsLowPopulation ?? false;
}
public static EntityKindAttribute GetAttribute(Type type)
{
var attr = TryGetAttribute(type);
if (attr == null)
throw new InvalidOperationException("{0} does not define an EntityKindAttribute".FormatWith(type.TypeName()));
return attr;
}
public static EntityKindAttribute TryGetAttribute(Type type)
{
return dictionary.GetOrAdd(type, t =>
{
if (!t.IsIEntity())
throw new InvalidOperationException("{0} should be a non-abstrat Entity".FormatWith(type.TypeName()));
return t.GetCustomAttribute<EntityKindAttribute>(true)!;
});
}
public static void Override(Type type, EntityKindAttribute attr)
{
if (type == null)
throw new ArgumentNullException(nameof(attr));
if (attr == null)
throw new ArgumentNullException(nameof(attr));
dictionary.AddOrUpdate(type, attr, (t, _) => attr);
}
}
[AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = false)]
public sealed class EntityKindAttribute : Attribute
{
public EntityKind EntityKind { get; private set; }
public EntityData EntityData { get; private set; }
public bool IsLowPopulation { get; set; }
bool? overridenRequiresSaveOperation;
public bool RequiresSaveOperation
{
get { return overridenRequiresSaveOperation ?? CalculateRequiresSaveOperation(this.EntityKind) ; }
set
{
if (overridenRequiresSaveOperation != CalculateRequiresSaveOperation(this.EntityKind))
overridenRequiresSaveOperation = value;
}
}
public bool IsRequiresSaveOperationOverriden => overridenRequiresSaveOperation.HasValue;
public static bool CalculateRequiresSaveOperation(EntityKind entityKind)
{
switch (entityKind)
{
case EntityKind.SystemString: return false;
case EntityKind.System: return false;
case EntityKind.Relational: return true;
case EntityKind.String: return true;
case EntityKind.Shared: return true;
case EntityKind.Main: return true;
case EntityKind.Part: return false;
case EntityKind.SharedPart: return false;
default: throw new InvalidOperationException("Unexpeced entityKind");
}
}
public EntityKindAttribute(EntityKind entityKind, EntityData entityData)
{
this.EntityKind = entityKind;
this.EntityData = entityData;
}
}
public enum EntityKind
{
/// <summary>
/// Doesn't make sense to view it from other entity, since there's not to much to see. Not editable.
/// Not RequiresSaveOperation
/// ie: PermissionSymbol
/// </summary>
SystemString,
/// <summary>
/// Not editable.
/// Not RequiresSaveOperation
/// ie: ExceptionEntity
/// </summary>
System,
/// <summary>
/// An entity that connects two entitities to implement a N to N relationship in a symetric way (no MLists)
/// RequiresSaveOperation, not vieable, not creable (override on SearchControl)
/// ie: DiscountProductEntity
/// </summary>
Relational,
/// <summary>
/// Doesn't make sense to view it from other entity, since there's not to much to see.
/// RequiresSaveOperation
/// ie: CountryEntity
/// </summary>
String,
/// <summary>
/// Used and shared by other entities, can be created from other entity.
/// RequiresSaveOperation
/// ie: CustomerEntity (can create new while creating the order)
/// </summary>
Shared,
/// <summary>
/// Used and shared by other entities, but too big to create it from other entity.
/// RequiresSaveOperation
/// ie: OrderEntity
/// </summary>
Main,
/// <summary>
/// Entity that belongs to just one entity and should be saved together, but that can not be implemented as EmbeddedEntity (usually to enable polymorphisim)
/// Not RequiresSaveOperation
/// ie :ProductExtensionEntity
/// </summary>
Part,
/// <summary>
/// Entity that can be created on the fly and saved with the parent entity, but could also be shared with other entities to save space.
/// Not RequiresSaveOperation
/// ie: AddressEntity
/// </summary>
SharedPart,
}
public enum EntityData
{
/// <summary>
/// Entity created for business definition
/// By default ordered by id Ascending
/// ie: ProductEntity, OperationSymbol, PermissionSymbol, CountryEntity...
/// </summary>
Master,
/// <summary>
/// Entity created while the business is running
/// By default is ordered by id Descending
/// ie: OrderEntity, ExceptionEntity, OperationLogEntity...
/// </summary>
Transactional
}
| |
namespace android.os
{
[global::MonoJavaBridge.JavaClass()]
public partial class ParcelFileDescriptor : java.lang.Object, Parcelable
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected ParcelFileDescriptor(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
[global::MonoJavaBridge.JavaClass()]
public partial class AutoCloseInputStream : java.io.FileInputStream
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected AutoCloseInputStream(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public override void close()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.ParcelFileDescriptor.AutoCloseInputStream.staticClass, "close", "()V", ref global::android.os.ParcelFileDescriptor.AutoCloseInputStream._m0);
}
private static global::MonoJavaBridge.MethodId _m1;
public AutoCloseInputStream(android.os.ParcelFileDescriptor arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.os.ParcelFileDescriptor.AutoCloseInputStream._m1.native == global::System.IntPtr.Zero)
global::android.os.ParcelFileDescriptor.AutoCloseInputStream._m1 = @__env.GetMethodIDNoThrow(global::android.os.ParcelFileDescriptor.AutoCloseInputStream.staticClass, "<init>", "(Landroid/os/ParcelFileDescriptor;)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.os.ParcelFileDescriptor.AutoCloseInputStream.staticClass, global::android.os.ParcelFileDescriptor.AutoCloseInputStream._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
static AutoCloseInputStream()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.os.ParcelFileDescriptor.AutoCloseInputStream.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/os/ParcelFileDescriptor$AutoCloseInputStream"));
}
}
[global::MonoJavaBridge.JavaClass()]
public partial class AutoCloseOutputStream : java.io.FileOutputStream
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected AutoCloseOutputStream(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public override void close()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.ParcelFileDescriptor.AutoCloseOutputStream.staticClass, "close", "()V", ref global::android.os.ParcelFileDescriptor.AutoCloseOutputStream._m0);
}
private static global::MonoJavaBridge.MethodId _m1;
public AutoCloseOutputStream(android.os.ParcelFileDescriptor arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.os.ParcelFileDescriptor.AutoCloseOutputStream._m1.native == global::System.IntPtr.Zero)
global::android.os.ParcelFileDescriptor.AutoCloseOutputStream._m1 = @__env.GetMethodIDNoThrow(global::android.os.ParcelFileDescriptor.AutoCloseOutputStream.staticClass, "<init>", "(Landroid/os/ParcelFileDescriptor;)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.os.ParcelFileDescriptor.AutoCloseOutputStream.staticClass, global::android.os.ParcelFileDescriptor.AutoCloseOutputStream._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
static AutoCloseOutputStream()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.os.ParcelFileDescriptor.AutoCloseOutputStream.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/os/ParcelFileDescriptor$AutoCloseOutputStream"));
}
}
private static global::MonoJavaBridge.MethodId _m0;
protected override void finalize()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.ParcelFileDescriptor.staticClass, "finalize", "()V", ref global::android.os.ParcelFileDescriptor._m0);
}
private static global::MonoJavaBridge.MethodId _m1;
public override global::java.lang.String toString()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.os.ParcelFileDescriptor.staticClass, "toString", "()Ljava/lang/String;", ref global::android.os.ParcelFileDescriptor._m1) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m2;
public virtual void close()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.ParcelFileDescriptor.staticClass, "close", "()V", ref global::android.os.ParcelFileDescriptor._m2);
}
private static global::MonoJavaBridge.MethodId _m3;
public static global::android.os.ParcelFileDescriptor open(java.io.File arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.os.ParcelFileDescriptor._m3.native == global::System.IntPtr.Zero)
global::android.os.ParcelFileDescriptor._m3 = @__env.GetStaticMethodIDNoThrow(global::android.os.ParcelFileDescriptor.staticClass, "open", "(Ljava/io/File;I)Landroid/os/ParcelFileDescriptor;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.os.ParcelFileDescriptor.staticClass, global::android.os.ParcelFileDescriptor._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as android.os.ParcelFileDescriptor;
}
private static global::MonoJavaBridge.MethodId _m4;
public virtual void writeToParcel(android.os.Parcel arg0, int arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.ParcelFileDescriptor.staticClass, "writeToParcel", "(Landroid/os/Parcel;I)V", ref global::android.os.ParcelFileDescriptor._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m5;
public virtual int describeContents()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.os.ParcelFileDescriptor.staticClass, "describeContents", "()I", ref global::android.os.ParcelFileDescriptor._m5);
}
private static global::MonoJavaBridge.MethodId _m6;
public static global::android.os.ParcelFileDescriptor fromSocket(java.net.Socket arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.os.ParcelFileDescriptor._m6.native == global::System.IntPtr.Zero)
global::android.os.ParcelFileDescriptor._m6 = @__env.GetStaticMethodIDNoThrow(global::android.os.ParcelFileDescriptor.staticClass, "fromSocket", "(Ljava/net/Socket;)Landroid/os/ParcelFileDescriptor;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.os.ParcelFileDescriptor.staticClass, global::android.os.ParcelFileDescriptor._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.os.ParcelFileDescriptor;
}
public new global::java.io.FileDescriptor FileDescriptor
{
get
{
return getFileDescriptor();
}
}
private static global::MonoJavaBridge.MethodId _m7;
public virtual global::java.io.FileDescriptor getFileDescriptor()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.io.FileDescriptor>(this, global::android.os.ParcelFileDescriptor.staticClass, "getFileDescriptor", "()Ljava/io/FileDescriptor;", ref global::android.os.ParcelFileDescriptor._m7) as java.io.FileDescriptor;
}
public new long StatSize
{
get
{
return getStatSize();
}
}
private static global::MonoJavaBridge.MethodId _m8;
public virtual long getStatSize()
{
return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::android.os.ParcelFileDescriptor.staticClass, "getStatSize", "()J", ref global::android.os.ParcelFileDescriptor._m8);
}
private static global::MonoJavaBridge.MethodId _m9;
public ParcelFileDescriptor(android.os.ParcelFileDescriptor arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.os.ParcelFileDescriptor._m9.native == global::System.IntPtr.Zero)
global::android.os.ParcelFileDescriptor._m9 = @__env.GetMethodIDNoThrow(global::android.os.ParcelFileDescriptor.staticClass, "<init>", "(Landroid/os/ParcelFileDescriptor;)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.os.ParcelFileDescriptor.staticClass, global::android.os.ParcelFileDescriptor._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
public static int MODE_WORLD_READABLE
{
get
{
return 1;
}
}
public static int MODE_WORLD_WRITEABLE
{
get
{
return 2;
}
}
public static int MODE_READ_ONLY
{
get
{
return 268435456;
}
}
public static int MODE_WRITE_ONLY
{
get
{
return 536870912;
}
}
public static int MODE_READ_WRITE
{
get
{
return 805306368;
}
}
public static int MODE_CREATE
{
get
{
return 134217728;
}
}
public static int MODE_TRUNCATE
{
get
{
return 67108864;
}
}
public static int MODE_APPEND
{
get
{
return 33554432;
}
}
internal static global::MonoJavaBridge.FieldId _CREATOR4019;
public static global::android.os.Parcelable_Creator CREATOR
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.os.Parcelable_Creator>(@__env.GetStaticObjectField(global::android.os.ParcelFileDescriptor.staticClass, _CREATOR4019)) as android.os.Parcelable_Creator;
}
}
static ParcelFileDescriptor()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.os.ParcelFileDescriptor.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/os/ParcelFileDescriptor"));
global::android.os.ParcelFileDescriptor._CREATOR4019 = @__env.GetStaticFieldIDNoThrow(global::android.os.ParcelFileDescriptor.staticClass, "CREATOR", "Landroid/os/Parcelable$Creator;");
}
}
}
| |
// ===========================================================
// Copyright (C) 2014-2015 Kendar.org
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy,
// modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
// is furnished to do so, subject to the following conditions:
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
// BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
// OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ===========================================================
using System.Web;
using System;
using System.Collections;
using System.Web.Caching;
using System.Web.Routing;
using System.Threading;
using System.Text;
using System.IO;
using System.Collections.Specialized;
using Http.Shared.Contexts;
namespace Http.Contexts
{
public class DefaultHttpResponse : HttpResponseBase, IHttpResponse
{
public DefaultHttpResponse() { }
public object SourceObject { get { return _httpResponse; } }
private readonly HttpResponse _httpResponse;
public DefaultHttpResponse(HttpResponse httpResponse)
{
_httpResponse = httpResponse;
InitializeUnsettable();
}
public override void AddCacheItemDependency(String cacheKey)
{
_httpResponse.AddCacheItemDependency(cacheKey);
}
public override void AddCacheItemDependencies(ArrayList cacheKeys)
{
_httpResponse.AddCacheItemDependencies(cacheKeys);
}
public override void AddCacheItemDependencies(String[] cacheKeys)
{
_httpResponse.AddCacheItemDependencies(cacheKeys);
}
public override void AddCacheDependency(params CacheDependency[] dependencies)
{
_httpResponse.AddCacheDependency(dependencies);
}
public override void AddFileDependency(String filename)
{
_httpResponse.AddFileDependency(filename);
}
public override void AddFileDependencies(ArrayList filenames)
{
_httpResponse.AddFileDependencies(filenames);
}
public override void AddFileDependencies(String[] filenames)
{
_httpResponse.AddFileDependencies(filenames);
}
public override void AddHeader(String name, String value)
{
_httpResponse.AddHeader(name, value);
}
public override void AppendCookie(HttpCookie cookie)
{
_httpResponse.AppendCookie(cookie);
}
public override void AppendHeader(String name, String value)
{
_httpResponse.AppendHeader(name, value);
}
public override void AppendToLog(String param)
{
_httpResponse.AppendToLog(param);
}
public override String ApplyAppPathModifier(String virtualPath)
{
return _httpResponse.ApplyAppPathModifier(virtualPath);
}
public override IAsyncResult BeginFlush(AsyncCallback callback, Object state)
{
return _httpResponse.BeginFlush(callback, state);
}
public override void BinaryWrite(Byte[] buffer)
{
_httpResponse.BinaryWrite(buffer);
}
public override void Clear()
{
_httpResponse.Clear();
}
public override void ClearContent()
{
_httpResponse.ClearContent();
}
public override void ClearHeaders()
{
_httpResponse.ClearHeaders();
}
public override void Close()
{
_httpResponse.Close();
ContextsManager.OnClose();
}
public override void DisableKernelCache()
{
_httpResponse.DisableKernelCache();
}
public override void DisableUserCache()
{
_httpResponse.DisableUserCache();
}
public override void End()
{
_httpResponse.End();
}
public override void EndFlush(IAsyncResult asyncResult)
{
_httpResponse.EndFlush(asyncResult);
}
public override void Flush()
{
_httpResponse.Flush();
}
public override void Pics(String value)
{
_httpResponse.Pics(value);
}
public override void Redirect(String url)
{
_httpResponse.Redirect(url);
}
public override void Redirect(String url, Boolean endResponse)
{
_httpResponse.Redirect(url, endResponse);
}
public override void RedirectToRoute(Object routeValues)
{
_httpResponse.RedirectToRoute(routeValues);
}
public override void RedirectToRoute(String routeName)
{
_httpResponse.RedirectToRoute(routeName);
}
public override void RedirectToRoute(RouteValueDictionary routeValues)
{
_httpResponse.RedirectToRoute(routeValues);
}
public override void RedirectToRoute(String routeName, Object routeValues)
{
_httpResponse.RedirectToRoute(routeName, routeValues);
}
public override void RedirectToRoute(String routeName, RouteValueDictionary routeValues)
{
_httpResponse.RedirectToRoute(routeName, routeValues);
}
public override void RedirectToRoutePermanent(Object routeValues)
{
_httpResponse.RedirectToRoutePermanent(routeValues);
}
public override void RedirectToRoutePermanent(String routeName)
{
_httpResponse.RedirectToRoutePermanent(routeName);
}
public override void RedirectToRoutePermanent(RouteValueDictionary routeValues)
{
_httpResponse.RedirectToRoutePermanent(routeValues);
}
public override void RedirectToRoutePermanent(String routeName, Object routeValues)
{
_httpResponse.RedirectToRoutePermanent(routeName, routeValues);
}
public override void RedirectToRoutePermanent(String routeName, RouteValueDictionary routeValues)
{
_httpResponse.RedirectToRoutePermanent(routeName, routeValues);
}
public override void RedirectPermanent(String url)
{
_httpResponse.RedirectPermanent(url);
}
public override void RedirectPermanent(String url, Boolean endResponse)
{
_httpResponse.RedirectPermanent(url, endResponse);
}
public override void RemoveOutputCacheItem(String path)
{
//TODO Missing RemoveOutputCacheItem for HttpResponse
}
public override void RemoveOutputCacheItem(String path, String providerName)
{
//TODO Missing RemoveOutputCacheItem for HttpResponse
}
public override void SetCookie(HttpCookie cookie)
{
_httpResponse.SetCookie(cookie);
}
public override void TransmitFile(String filename)
{
_httpResponse.TransmitFile(filename);
}
public override void TransmitFile(String filename, Int64 offset, Int64 length)
{
_httpResponse.TransmitFile(filename, offset, length);
}
public override void Write(Char ch)
{
_httpResponse.Write(ch);
}
public override void Write(Char[] buffer, Int32 index, Int32 count)
{
_httpResponse.Write(buffer, index, count);
}
public override void Write(Object obj)
{
_httpResponse.Write(obj);
}
public override void Write(String s)
{
_httpResponse.Write(s);
}
public override void WriteFile(String filename)
{
_httpResponse.WriteFile(filename);
}
public override void WriteFile(String filename, Boolean readIntoMemory)
{
_httpResponse.WriteFile(filename, readIntoMemory);
}
public override void WriteFile(String filename, Int64 offset, Int64 size)
{
_httpResponse.WriteFile(filename, offset, size);
}
public override void WriteFile(IntPtr fileHandle, Int64 offset, Int64 size)
{
_httpResponse.WriteFile(fileHandle, offset, size);
}
public override void WriteSubstitution(HttpResponseSubstitutionCallback callback)
{
_httpResponse.WriteSubstitution(callback);
}
public override Boolean Buffer
{
set
{
_httpResponse.Buffer = value;
}
get
{
return _httpResponse.Buffer;
}
}
public override Boolean BufferOutput
{
set
{
_httpResponse.BufferOutput = value;
}
get
{
return _httpResponse.BufferOutput;
}
}
public override String CacheControl
{
set
{
_httpResponse.CacheControl = value;
}
get
{
return _httpResponse.CacheControl;
}
}
public override String Charset
{
set
{
_httpResponse.Charset = value;
}
get
{
return _httpResponse.Charset;
}
}
public override CancellationToken ClientDisconnectedToken { get { return _httpResponse.ClientDisconnectedToken; } }
public void SetClientDisconnectedToken(CancellationToken val)
{
}
public override Encoding ContentEncoding
{
set
{
_httpResponse.ContentEncoding = value;
}
get
{
return _httpResponse.ContentEncoding;
}
}
public override String ContentType
{
set
{
_httpResponse.ContentType = value;
}
get
{
return _httpResponse.ContentType;
}
}
public override HttpCookieCollection Cookies { get { return _httpResponse.Cookies; } }
public void SetCookies(HttpCookieCollection val)
{
}
public override Int32 Expires
{
set
{
_httpResponse.Expires = value;
}
get
{
return _httpResponse.Expires;
}
}
public override DateTime ExpiresAbsolute
{
set
{
_httpResponse.ExpiresAbsolute = value;
}
get
{
return _httpResponse.ExpiresAbsolute;
}
}
public override Stream Filter
{
set
{
_httpResponse.Filter = value;
}
get
{
return _httpResponse.Filter;
}
}
public override NameValueCollection Headers { get { return _httpResponse.Headers; } }
public void SetHeaders(NameValueCollection val)
{
}
public override Encoding HeaderEncoding
{
set
{
_httpResponse.HeaderEncoding = value;
}
get
{
return _httpResponse.HeaderEncoding;
}
}
public override Boolean IsClientConnected { get { return _httpResponse.IsClientConnected; } }
public void SetIsClientConnected(Boolean val)
{
}
public override Boolean IsRequestBeingRedirected { get { return _httpResponse.IsRequestBeingRedirected; } }
public void SetIsRequestBeingRedirected(Boolean val)
{
}
public override TextWriter Output
{
set
{
_httpResponse.Output = value;
}
get
{
return _httpResponse.Output;
}
}
public override Stream OutputStream { get { return _httpResponse.OutputStream; } }
public void SetOutputStream(Stream val)
{
}
public override String RedirectLocation
{
set
{
_httpResponse.RedirectLocation = value;
}
get
{
return _httpResponse.RedirectLocation;
}
}
public override String Status
{
set
{
_httpResponse.Status = value;
}
get
{
return _httpResponse.Status;
}
}
public override Int32 StatusCode
{
set
{
_httpResponse.StatusCode = value;
}
get
{
return _httpResponse.StatusCode;
}
}
public override String StatusDescription
{
set
{
_httpResponse.StatusDescription = value;
}
get
{
return _httpResponse.StatusDescription;
}
}
public override Int32 SubStatusCode
{
set
{
_httpResponse.SubStatusCode = value;
}
get
{
return _httpResponse.SubStatusCode;
}
}
public override Boolean SupportsAsyncFlush { get { return _httpResponse.SupportsAsyncFlush; } }
public void SetSupportsAsyncFlush(Boolean val)
{
}
public override Boolean SuppressContent
{
set
{
_httpResponse.SuppressContent = value;
}
get
{
return _httpResponse.SuppressContent;
}
}
public override Boolean SuppressFormsAuthenticationRedirect
{
set
{
_httpResponse.SuppressFormsAuthenticationRedirect = value;
}
get
{
return _httpResponse.SuppressFormsAuthenticationRedirect;
}
}
public override Boolean TrySkipIisCustomErrors
{
set
{
_httpResponse.TrySkipIisCustomErrors = value;
}
get
{
return _httpResponse.TrySkipIisCustomErrors;
}
}
public void InitializeUnsettable()
{
_cache = ConvertCache(_httpResponse.Cache);
}
// ReSharper disable once UnusedParameter.Local
private HttpCachePolicyBase ConvertCache(HttpCachePolicy cache)
{
return null;
}
private HttpCachePolicyBase _cache;
public override HttpCachePolicyBase Cache { get { return _cache; } }
public void SetCache(HttpCachePolicyBase val)
{
}
public void Close(byte[] data, bool willblock = true)
{
if (!willblock) _httpResponse.OutputStream.WriteAsync(data, 0, data.Length).ContinueWith(a => Close());
else { _httpResponse.OutputStream.Write(data, 0, data.Length); Close(); }
}
}
}
| |
using Foundation;
using ScnViewGestures.Plugin.Forms;
using ScnViewGestures.Plugin.Forms.iOS.Renderers;
using System;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
[assembly: ExportRenderer(typeof(ViewGestures), typeof(ViewGesturesRenderer))]
namespace ScnViewGestures.Plugin.Forms.iOS.Renderers
{
public class ViewGesturesRenderer : ViewRenderer
{
public new static void Init()
{
}
protected override void OnElementChanged(ElementChangedEventArgs<View> e)
{
base.OnElementChanged(e);
var viewGesture = (ViewGestures) e.NewElement;
var tapGestureRecognizer = new TapGestureRecognizer
{
OnTouchesBegan = (x, y) => viewGesture.OnTouchBegan(x, y),
OnTouchesEnded = (x, y) => viewGesture.OnTouchEnded(x, y),
OnTap = (x, y) => viewGesture.OnTap(x, y)
};
var longPressGestureRecognizer = new LongPressGestureRecognizer(() => viewGesture.OnLongTap())
{
OnTouchesBegan = (x, y) => viewGesture.OnTouchBegan(x, y),
OnTouchesEnded = (x, y) => viewGesture.OnTouchEnded(x, y)
};
#region SwipeGestureRecognizer
var swipeLeftGestureRecognizer = new SwipeGestureRecognizer(() => viewGesture.OnSwipeLeft())
{
Direction = UISwipeGestureRecognizerDirection.Left,
OnTouchesBegan = (x, y) => viewGesture.OnTouchBegan(x, y),
OnTouchesEnded = (x, y) => viewGesture.OnTouchEnded(x, y)
};
var swipeRightGestureRecognizer = new SwipeGestureRecognizer(() => viewGesture.OnSwipeRight())
{
Direction = UISwipeGestureRecognizerDirection.Right,
OnTouchesBegan = (x, y) => viewGesture.OnTouchBegan(x, y),
OnTouchesEnded = (x, y) => viewGesture.OnTouchEnded(x, y)
};
var swipeUpGestureRecognizer = new SwipeGestureRecognizer(() => viewGesture.OnSwipeUp())
{
Direction = UISwipeGestureRecognizerDirection.Up,
OnTouchesBegan = (x, y) => viewGesture.OnTouchBegan(x, y),
OnTouchesEnded = (x, y) => viewGesture.OnTouchEnded(x, y)
};
var swipeDownGestureRecognizer = new SwipeGestureRecognizer(() => viewGesture.OnSwipeDown())
{
Direction = UISwipeGestureRecognizerDirection.Down,
OnTouchesBegan = (x, y) => viewGesture.OnTouchBegan(x, y),
OnTouchesEnded = (x, y) => viewGesture.OnTouchEnded(x, y)
};
#endregion
#region DragGestureRecognizer
var dragGestureRecognizer = new DragGestureRecognizer
{
OnTouchesBegan = (x, y) => viewGesture.OnTouchBegan(x, y),
OnTouchesEnded = (x, y) => viewGesture.OnTouchEnded(x, y),
OnDrag = (x, y) => viewGesture.OnDrag(x, y)
};
if (viewGesture != null)
{
//from iOS Developer Library (Gesture Recognizers)
//...For your view to recognize both swipes and pans, you want the swipe gesture recognizer to analyze the touch event before the pan gesture recognizer does...
if ((viewGesture.SupportGestures & ViewGestures.GestureType.gtSwipeLeft) != 0)
dragGestureRecognizer.RequireGestureRecognizerToFail(swipeLeftGestureRecognizer);
if ((viewGesture.SupportGestures & ViewGestures.GestureType.gtSwipeRight) != 0)
dragGestureRecognizer.RequireGestureRecognizerToFail(swipeRightGestureRecognizer);
if ((viewGesture.SupportGestures & ViewGestures.GestureType.gtSwipeUp) != 0)
dragGestureRecognizer.RequireGestureRecognizerToFail(swipeUpGestureRecognizer);
if ((viewGesture.SupportGestures & ViewGestures.GestureType.gtSwipeDown) != 0)
dragGestureRecognizer.RequireGestureRecognizerToFail(swipeDownGestureRecognizer);
}
#endregion
if (e.NewElement == null)
{
RemoveGestureRecognizer(tapGestureRecognizer);
RemoveGestureRecognizer(longPressGestureRecognizer);
RemoveGestureRecognizer(swipeLeftGestureRecognizer);
RemoveGestureRecognizer(swipeRightGestureRecognizer);
RemoveGestureRecognizer(swipeUpGestureRecognizer);
RemoveGestureRecognizer(swipeDownGestureRecognizer);
RemoveGestureRecognizer(dragGestureRecognizer);
}
if (e.OldElement == null)
{
AddGestureRecognizer(tapGestureRecognizer);
AddGestureRecognizer(longPressGestureRecognizer);
AddGestureRecognizer(swipeLeftGestureRecognizer);
AddGestureRecognizer(swipeRightGestureRecognizer);
AddGestureRecognizer(swipeUpGestureRecognizer);
AddGestureRecognizer(swipeDownGestureRecognizer);
AddGestureRecognizer(dragGestureRecognizer);
}
}
private class TapGestureRecognizer : UITapGestureRecognizer
{
public override void TouchesBegan(NSSet touches, UIEvent evt)
{
base.TouchesBegan(touches, evt);
double positionX = -1;
double positionY = -1;
if (touches.AnyObject is UITouch touch)
{
positionX = touch.LocationInView(View).X;
positionY = touch.LocationInView(View).Y;
}
OnTouchesBegan?.Invoke(positionX, positionY);
}
public override void TouchesEnded(NSSet touches, UIEvent evt)
{
base.TouchesEnded(touches, evt);
double positionX = -1;
double positionY = -1;
if (OnTap != null && touches.AnyObject is UITouch touch)
{
positionX = touch.LocationInView(View).X;
positionY = touch.LocationInView(View).Y;
OnTap(positionX, positionY);
}
OnTouchesEnded?.Invoke(positionX, positionY);
}
public override void TouchesCancelled(NSSet touches, UIEvent evt)
{
base.TouchesCancelled(touches, evt);
OnTouchesEnded?.Invoke(-1, -1);
}
public Action<double, double> OnTap;
public Action<double, double> OnTouchesBegan;
public Action<double, double> OnTouchesEnded;
}
private class LongPressGestureRecognizer : UILongPressGestureRecognizer
{
public LongPressGestureRecognizer(Action action)
: base(action)
{
}
public override void TouchesBegan(NSSet touches, UIEvent evt)
{
base.TouchesBegan(touches, evt);
double positionX = -1;
double positionY = -1;
if (touches.AnyObject is UITouch touch)
{
positionX = touch.LocationInView(View).X;
positionY = touch.LocationInView(View).Y;
}
OnTouchesBegan?.Invoke(positionX, positionY);
}
public override void TouchesEnded(NSSet touches, UIEvent evt)
{
base.TouchesEnded(touches, evt);
double positionX = -1;
double positionY = -1;
if (touches.AnyObject is UITouch touch)
{
positionX = touch.LocationInView(View).X;
positionY = touch.LocationInView(View).Y;
}
OnTouchesEnded?.Invoke(positionX, positionY);
}
public override void TouchesCancelled(NSSet touches, UIEvent evt)
{
base.TouchesCancelled(touches, evt);
OnTouchesEnded?.Invoke(-1, -1);
}
public Action<double, double> OnTouchesBegan;
public Action<double, double> OnTouchesEnded;
}
private class SwipeGestureRecognizer : UISwipeGestureRecognizer
{
public SwipeGestureRecognizer(Action action)
: base(action)
{
}
public override void TouchesBegan(NSSet touches, UIEvent evt)
{
base.TouchesBegan(touches, evt);
double positionX = -1;
double positionY = -1;
if (touches.AnyObject is UITouch touch)
{
positionX = touch.LocationInView(View).X;
positionY = touch.LocationInView(View).Y;
}
OnTouchesBegan?.Invoke(positionX, positionY);
}
public override void TouchesEnded(NSSet touches, UIEvent evt)
{
base.TouchesEnded(touches, evt);
double positionX = -1;
double positionY = -1;
if (touches.AnyObject is UITouch touch)
{
positionX = touch.LocationInView(View).X;
positionY = touch.LocationInView(View).Y;
}
OnTouchesEnded?.Invoke(positionX, positionY);
}
public override void TouchesCancelled(NSSet touches, UIEvent evt)
{
base.TouchesCancelled(touches, evt);
OnTouchesEnded?.Invoke(-1, -1);
}
public Action<double, double> OnTouchesBegan;
public Action<double, double> OnTouchesEnded;
}
private class DragGestureRecognizer : UIPanGestureRecognizer
{
public override void TouchesBegan(NSSet touches, UIEvent evt)
{
base.TouchesBegan(touches, evt);
double positionX = -1;
double positionY = -1;
if (touches.AnyObject is UITouch touch)
{
positionX = touch.LocationInView(View).X;
positionY = touch.LocationInView(View).Y;
}
OnTouchesBegan?.Invoke(positionX, positionY);
}
public override void TouchesEnded(NSSet touches, UIEvent evt)
{
base.TouchesEnded(touches, evt);
double positionX = -1;
double positionY = -1;
if (touches.AnyObject is UITouch touch)
{
positionX = touch.LocationInView(View).X;
positionY = touch.LocationInView(View).Y;
}
OnTouchesEnded?.Invoke(positionX, positionY);
}
public override void TouchesMoved(NSSet touches, UIEvent evt)
{
base.TouchesMoved(touches, evt);
if (OnDrag != null && touches.AnyObject is UITouch touch)
{
var offsetX = touch.PreviousLocationInView(View).X - (double) touch.LocationInView(View).X;
var offsetY = touch.PreviousLocationInView(View).Y - (double) touch.LocationInView(View).Y;
OnDrag(-offsetX, -offsetY);
}
}
public override void TouchesCancelled(NSSet touches, UIEvent evt)
{
base.TouchesCancelled(touches, evt);
OnTouchesEnded?.Invoke(-1, -1);
}
public Action<double, double> OnTouchesBegan;
public Action<double, double> OnTouchesEnded;
public Action<double, double> OnDrag;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Text.Internal;
using System.Text.Unicode;
namespace System.Text.Encodings.Web
{
/// <summary>
/// Represents a filter which allows only certain Unicode code points through.
/// </summary>
public class TextEncoderSettings
{
private readonly AllowedCharactersBitmap _allowedCharactersBitmap;
/// <summary>
/// Instantiates an empty filter (allows no code points through by default).
/// </summary>
public TextEncoderSettings()
{
_allowedCharactersBitmap = AllowedCharactersBitmap.CreateNew();
}
/// <summary>
/// Instantiates the filter by cloning the allow list of another <see cref="TextEncoderSettings"/>.
/// </summary>
public TextEncoderSettings(TextEncoderSettings other)
{
if (other == null)
{
throw new ArgumentNullException(nameof(other));
}
_allowedCharactersBitmap = AllowedCharactersBitmap.CreateNew();
AllowCodePoints(other.GetAllowedCodePoints());
}
/// <summary>
/// Instantiates the filter where only the character ranges specified by <paramref name="allowedRanges"/>
/// are allowed by the filter.
/// </summary>
public TextEncoderSettings(params UnicodeRange[] allowedRanges)
{
if (allowedRanges == null)
{
throw new ArgumentNullException(nameof(allowedRanges));
}
_allowedCharactersBitmap = AllowedCharactersBitmap.CreateNew();
AllowRanges(allowedRanges);
}
/// <summary>
/// Allows the character specified by <paramref name="character"/> through the filter.
/// </summary>
public virtual void AllowCharacter(char character)
{
_allowedCharactersBitmap.AllowCharacter(character);
}
/// <summary>
/// Allows all characters specified by <paramref name="characters"/> through the filter.
/// </summary>
public virtual void AllowCharacters(params char[] characters)
{
if (characters == null)
{
throw new ArgumentNullException(nameof(characters));
}
for (int i = 0; i < characters.Length; i++)
{
_allowedCharactersBitmap.AllowCharacter(characters[i]);
}
}
/// <summary>
/// Allows all code points specified by <paramref name="codePoints"/>.
/// </summary>
public virtual void AllowCodePoints(IEnumerable<int> codePoints)
{
if (codePoints == null)
{
throw new ArgumentNullException(nameof(codePoints));
}
foreach (var allowedCodePoint in codePoints)
{
// If the code point can't be represented as a BMP character, skip it.
char codePointAsChar = (char)allowedCodePoint;
if (allowedCodePoint == codePointAsChar)
{
_allowedCharactersBitmap.AllowCharacter(codePointAsChar);
}
}
}
/// <summary>
/// Allows all characters specified by <paramref name="range"/> through the filter.
/// </summary>
public virtual void AllowRange(UnicodeRange range)
{
if (range == null)
{
throw new ArgumentNullException(nameof(range));
}
int firstCodePoint = range.FirstCodePoint;
int rangeSize = range.Length;
for (int i = 0; i < rangeSize; i++)
{
_allowedCharactersBitmap.AllowCharacter((char)(firstCodePoint + i));
}
}
/// <summary>
/// Allows all characters specified by <paramref name="ranges"/> through the filter.
/// </summary>
public virtual void AllowRanges(params UnicodeRange[] ranges)
{
if (ranges == null)
{
throw new ArgumentNullException(nameof(ranges));
}
for (int i = 0; i < ranges.Length; i++)
{
AllowRange(ranges[i]);
}
}
/// <summary>
/// Resets this settings object by disallowing all characters.
/// </summary>
public virtual void Clear()
{
_allowedCharactersBitmap.Clear();
}
/// <summary>
/// Disallows the character <paramref name="character"/> through the filter.
/// </summary>
public virtual void ForbidCharacter(char character)
{
_allowedCharactersBitmap.ForbidCharacter(character);
}
/// <summary>
/// Disallows all characters specified by <paramref name="characters"/> through the filter.
/// </summary>
public virtual void ForbidCharacters(params char[] characters)
{
if (characters == null)
{
throw new ArgumentNullException(nameof(characters));
}
for (int i = 0; i < characters.Length; i++)
{
_allowedCharactersBitmap.ForbidCharacter(characters[i]);
}
}
/// <summary>
/// Disallows all characters specified by <paramref name="range"/> through the filter.
/// </summary>
public virtual void ForbidRange(UnicodeRange range)
{
if (range == null)
{
throw new ArgumentNullException(nameof(range));
}
int firstCodePoint = range.FirstCodePoint;
int rangeSize = range.Length;
for (int i = 0; i < rangeSize; i++)
{
_allowedCharactersBitmap.ForbidCharacter((char)(firstCodePoint + i));
}
}
/// <summary>
/// Disallows all characters specified by <paramref name="ranges"/> through the filter.
/// </summary>
public virtual void ForbidRanges(params UnicodeRange[] ranges)
{
if (ranges == null)
{
throw new ArgumentNullException(nameof(ranges));
}
for (int i = 0; i < ranges.Length; i++)
{
ForbidRange(ranges[i]);
}
}
/// <summary>
/// Retrieves the bitmap of allowed characters from this settings object.
/// The returned bitmap is a clone of the original bitmap to avoid unintentional modification.
/// </summary>
internal AllowedCharactersBitmap GetAllowedCharacters()
{
return _allowedCharactersBitmap.Clone();
}
/// <summary>
/// Gets an enumeration of all allowed code points.
/// </summary>
public virtual IEnumerable<int> GetAllowedCodePoints()
{
for (int i = 0; i < 0x10000; i++)
{
if (_allowedCharactersBitmap.IsCharacterAllowed((char)i))
{
yield return i;
}
}
}
}
}
| |
#pragma warning disable 1634, 1691
namespace System.Workflow.ComponentModel.Design
{
using System;
using System.IO;
using System.Drawing;
using System.CodeDom;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Windows.Forms;
using System.ComponentModel;
using System.Globalization;
using System.Drawing.Design;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Windows.Forms.Design;
using System.ComponentModel.Design;
using System.Collections.Specialized;
using System.ComponentModel.Design.Serialization;
using System.Workflow.ComponentModel.Compiler;
using System.Workflow.ComponentModel.Serialization;
using System.Collections.ObjectModel;
using System.Reflection;
using System.Workflow.ComponentModel.Design;
using System.Runtime.Serialization.Formatters.Binary;
//
#region SequentialWorkflowRootDesigner Class
/// <summary>
/// Base class for root designer for workflow. It provides a consistent look and feel for all the roots.
/// The root designers associated with root activities have to be derived from SequentialWorkflowRootDesigner.
/// </summary>
[Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")]
public class SequentialWorkflowRootDesigner : SequentialActivityDesigner
{
#region Statics
private const int HeaderFooterSizeIncr = 8;
private static readonly Image HeaderImage = DR.GetImage(DR.StartWorkflow);
private static readonly Image FooterImage = DR.GetImage(DR.EndWorkflow);
private static readonly Size PageStripItemSize = new Size(24, 20);
private static readonly Size MinSize = new Size(240, 240);
#endregion
#region Fields
//NOTE: The callingDesigner member is only set when the workflow is called from another
//workflow, this is used to hookup the parent chain.
private WorkflowHeader header;
private WorkflowFooter footer;
#endregion
#region Properties
#region Public Properties
public override string Text
{
get
{
return String.Empty;
}
}
public override Image Image
{
get
{
return Header.Image; //smart tag glyph needs an image
}
}
protected override Rectangle ImageRectangle
{
get
{
return Rectangle.Empty; //we are using image rect from the header for that...
}
}
public override bool CanExpandCollapse
{
get
{
return false;
}
}
public override Size MinimumSize
{
get
{
Size minimumSize = base.MinimumSize;
minimumSize.Width = Math.Max(minimumSize.Width, SequentialWorkflowRootDesigner.MinSize.Width);
minimumSize.Height = Math.Max(minimumSize.Width, SequentialWorkflowRootDesigner.MinSize.Height);
if (IsRootDesigner && InvokingDesigner == null)
{
minimumSize.Width = Math.Max(minimumSize.Width, ParentView.ViewPortSize.Width - 2 * WorkflowRootLayout.Separator.Width);
minimumSize.Height = Math.Max(minimumSize.Height, ParentView.ViewPortSize.Height - 2 * WorkflowRootLayout.Separator.Height);
}
return minimumSize;
}
}
#endregion
#region Protected Properties
/// <summary>
/// Gets the header associated with SequentialWorkflowRootDesigner
/// </summary>
protected virtual SequentialWorkflowHeaderFooter Header
{
get
{
if (this.header == null)
this.header = new WorkflowHeader(this);
return this.header;
}
}
/// <summary>
/// Gets the footer associated with SequentialWorkflowRootDesigner
/// </summary>
protected virtual SequentialWorkflowHeaderFooter Footer
{
get
{
if (this.footer == null)
this.footer = new WorkflowFooter(this);
return this.footer;
}
}
protected override int TitleHeight
{
get
{
int titleHeight = base.TitleHeight;
if (Header != null)
titleHeight += Header.Bounds.Height;
return titleHeight;
}
}
protected override bool ShowSmartTag
{
get
{
if (Header != null && !String.IsNullOrEmpty(Header.Text) && this.Views.Count > 1)
return true;
else
return base.ShowSmartTag;
}
}
protected override Rectangle SmartTagRectangle
{
get
{
Rectangle smartTagRectangle = Rectangle.Empty;
if (Header != null)
{
smartTagRectangle = Header.ImageRectangle;
}
return smartTagRectangle;
}
}
protected override CompositeActivityDesigner InvokingDesigner
{
get
{
return base.InvokingDesigner;
}
set
{
base.InvokingDesigner = value;
}
}
protected internal override ActivityDesignerGlyphCollection Glyphs
{
get
{
ActivityDesignerGlyphCollection glyphs = new ActivityDesignerGlyphCollection(base.Glyphs);
if (InvokingDesigner != null)
glyphs.Add(LockedActivityGlyph.Default);
return glyphs;
}
}
#endregion
#region Private Properties
internal override WorkflowLayout SupportedLayout
{
get
{
return new WorkflowRootLayout(Activity.Site);
}
}
private int OptimalHeight
{
get
{
CompositeDesignerTheme designerTheme = DesignerTheme as CompositeDesignerTheme;
if (designerTheme == null)
return 0;
//Calculate the size based on child size
int optimalHeight = 0;
if (ContainedDesigners.Count == 0)
{
optimalHeight += designerTheme.ConnectorSize.Height; //Add the height of first connector
optimalHeight += HelpTextSize.Height;
optimalHeight += designerTheme.ConnectorSize.Height; //Add the height of last connector
}
else
{
ActivityDesigner activeDesigner = ActiveDesigner;
if (activeDesigner == this)
optimalHeight += designerTheme.ConnectorSize.Height;
AmbientTheme ambientTheme = WorkflowTheme.CurrentTheme.AmbientTheme;
foreach (ActivityDesigner activityDesigner in ContainedDesigners)
{
Size childSize = activityDesigner.Size;
optimalHeight += childSize.Height;
if (activeDesigner == this)
optimalHeight += designerTheme.ConnectorSize.Height;
else
optimalHeight += 2 * ambientTheme.SelectionSize.Height;
}
}
return optimalHeight;
}
}
#endregion
#endregion
#region Methods
#region Public Methods
public override bool CanBeParentedTo(CompositeActivityDesigner parentActivityDesigner)
{
return false;
}
#endregion
#region Protected Methods
protected override ReadOnlyCollection<Point> GetInnerConnections(DesignerEdges edges)
{
List<Point> connectionPoints = new List<Point>(base.GetInnerConnections(edges));
if (connectionPoints.Count > 0 && Footer != null && (edges & DesignerEdges.Bottom) > 0)
connectionPoints[connectionPoints.Count - 1] = new Point(connectionPoints[connectionPoints.Count - 1].X, connectionPoints[connectionPoints.Count - 1].Y - Footer.Bounds.Height);
return connectionPoints.AsReadOnly();
}
protected override void OnSmartTagVisibilityChanged(bool visible)
{
base.OnSmartTagVisibilityChanged(visible);
if (Header != null && !Header.TextRectangle.IsEmpty)
Invalidate(Header.TextRectangle);
}
protected override Size OnLayoutSize(ActivityDesignerLayoutEventArgs e)
{
Size size = base.OnLayoutSize(e);
//Make sure that we set the minimum size
WorkflowFooter footer = Footer as WorkflowFooter;
if (footer != null)
size.Height += footer.ImageRectangle.Height + 2 * e.AmbientTheme.Margin.Height + footer.FooterBarRectangle.Size.Height;
if (Header != null)
Header.OnLayout(e);
if (Footer != null)
Footer.OnLayout(e);
return size;
}
protected override void OnPaint(ActivityDesignerPaintEventArgs e)
{
base.OnPaint(e);
CompositeDesignerTheme compositeDesignerTheme = e.DesignerTheme as CompositeDesignerTheme;
if (compositeDesignerTheme == null)
return;
//Draw the watermark at right bottom
Rectangle watermarkRectangle = Rectangle.Empty;
if (compositeDesignerTheme.WatermarkImage != null)
{
Rectangle bounds = Bounds;
bounds.Inflate(-e.AmbientTheme.Margin.Width, -e.AmbientTheme.Margin.Height);
watermarkRectangle = ActivityDesignerPaint.GetRectangleFromAlignment(compositeDesignerTheme.WatermarkAlignment, bounds, compositeDesignerTheme.WatermarkImage.Size);
}
//Here we go, draw header and footer rectangles
if (Header != null)
Header.OnPaint(e);
if (Footer != null)
Footer.OnPaint(e);
}
#endregion
#region Internal Methods
//this is for the workflow header/footer class
internal void InternalPerformLayout()
{
PerformLayout();
}
#endregion
#endregion
#region Nested Classes
#region Class WorkflowHeader
private sealed class WorkflowHeader : SequentialWorkflowHeaderFooter
{
public WorkflowHeader(SequentialWorkflowRootDesigner parent)
: base(parent, true)
{
Image = SequentialWorkflowRootDesigner.HeaderImage;
}
public override Rectangle Bounds
{
get
{
Rectangle bounds = base.Bounds;
Rectangle textRectangle = base.TextRectangle;
if (MinHeaderBarHeight > textRectangle.Height)
bounds.Height += (MinHeaderBarHeight - textRectangle.Height);
return bounds;
}
}
public override Rectangle TextRectangle
{
get
{
Rectangle textRectangle = base.TextRectangle;
if (MinHeaderBarHeight > textRectangle.Height)
textRectangle.Y += (MinHeaderBarHeight - textRectangle.Height) / 2;
return textRectangle;
}
}
public override Rectangle ImageRectangle
{
get
{
Rectangle imageRectangle = base.ImageRectangle;
if (Image != null)
{
ActivityDesignerTheme designerTheme = AssociatedDesigner.DesignerTheme;
imageRectangle.X -= SequentialWorkflowRootDesigner.HeaderFooterSizeIncr / 2;
imageRectangle.Y = HeaderBarRectangle.Bottom + WorkflowTheme.CurrentTheme.AmbientTheme.Margin.Height;
imageRectangle.Width += SequentialWorkflowRootDesigner.HeaderFooterSizeIncr;
imageRectangle.Height += SequentialWorkflowRootDesigner.HeaderFooterSizeIncr;
}
return imageRectangle;
}
}
public override void OnPaint(ActivityDesignerPaintEventArgs e)
{
if (e == null)
throw new ArgumentNullException("e");
Rectangle rectangle = HeaderBarRectangle;
Color color1 = Color.Empty;
Color color2 = Color.FromArgb(50, e.DesignerTheme.BorderColor);
using (Brush linearGradientBrush = new LinearGradientBrush(rectangle, color1, color2, LinearGradientMode.Vertical))
{
e.Graphics.FillRectangle(linearGradientBrush, rectangle);
e.Graphics.DrawLine(e.DesignerTheme.BorderPen, rectangle.Left, rectangle.Bottom, rectangle.Right, rectangle.Bottom);
}
base.OnPaint(e);
}
private Rectangle HeaderBarRectangle
{
get
{
Rectangle headerBarRectangle = new Rectangle();
headerBarRectangle.Location = AssociatedDesigner.Location;
headerBarRectangle.Width = AssociatedDesigner.Size.Width;
headerBarRectangle.Height = Math.Max(2 * WorkflowTheme.CurrentTheme.AmbientTheme.Margin.Height + base.textSize.Height, MinHeaderBarHeight);
return headerBarRectangle;
}
}
private int MinHeaderBarHeight
{
get
{
return 2 * WorkflowTheme.CurrentTheme.AmbientTheme.Margin.Height;
}
}
}
#endregion
#region Class WorkflowFooter
private sealed class WorkflowFooter : SequentialWorkflowHeaderFooter
{
public WorkflowFooter(SequentialWorkflowRootDesigner parent)
: base(parent, false)
{
Image = SequentialWorkflowRootDesigner.FooterImage;
}
public override Rectangle Bounds
{
get
{
Rectangle bounds = base.Bounds;
SequentialWorkflowRootDesigner rootDesigner = AssociatedDesigner as SequentialWorkflowRootDesigner;
bounds.Height = Math.Max(bounds.Height, rootDesigner.Size.Height - rootDesigner.TitleHeight - rootDesigner.OptimalHeight);
bounds.Y = rootDesigner.Location.Y + rootDesigner.TitleHeight + rootDesigner.OptimalHeight;
int minHeight = ImageRectangle.Height;
minHeight += (minHeight > 0) ? 2 * WorkflowTheme.CurrentTheme.AmbientTheme.Margin.Height : 0;
minHeight += MinFooterBarHeight;
bounds.Height = Math.Max(minHeight, bounds.Height);
return bounds;
}
}
public override Rectangle ImageRectangle
{
get
{
Rectangle imageRectangle = base.ImageRectangle;
if (Image != null)
{
SequentialWorkflowRootDesigner rootDesigner = AssociatedDesigner as SequentialWorkflowRootDesigner;
imageRectangle.X -= SequentialWorkflowRootDesigner.HeaderFooterSizeIncr / 2;
imageRectangle.Width += SequentialWorkflowRootDesigner.HeaderFooterSizeIncr;
imageRectangle.Height += SequentialWorkflowRootDesigner.HeaderFooterSizeIncr;
imageRectangle.Y = rootDesigner.Location.Y + rootDesigner.TitleHeight + rootDesigner.OptimalHeight;
imageRectangle.Y += WorkflowTheme.CurrentTheme.AmbientTheme.Margin.Height;
}
return imageRectangle;
}
}
public override void OnPaint(ActivityDesignerPaintEventArgs e)
{
if (e == null)
throw new ArgumentNullException("e");
Rectangle rectangle = FooterBarRectangle;
if (!FooterBarRectangle.IsEmpty)
{
Color color1 = Color.Empty;
Color color2 = Color.FromArgb(50, e.DesignerTheme.BorderColor);
using (Brush linearGradientBrush = new LinearGradientBrush(rectangle, color2, color1, LinearGradientMode.Vertical))
{
e.Graphics.FillRectangle(linearGradientBrush, rectangle);
e.Graphics.DrawLine(e.DesignerTheme.BorderPen, rectangle.Left, rectangle.Top, rectangle.Right, rectangle.Top);
}
}
base.OnPaint(e);
}
internal Rectangle FooterBarRectangle
{
get
{
return Rectangle.Empty;
}
}
private int MinFooterBarHeight
{
get
{
return 0;
}
}
}
#endregion
#endregion
}
#endregion
}
| |
using System;
using System.Runtime.Serialization;
namespace DotNetMatrix
{
#region Internal Maths utility
internal class Maths
{
/// <summary>
/// sqrt(a^2 + b^2) without under/overflow.
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
public static double Hypot(double a, double b)
{
double r;
if (Math.Abs(a) > Math.Abs(b))
{
r = b/a;
r = Math.Abs(a) * Math.Sqrt(1 + r * r);
}
else if (b != 0)
{
r = a/b;
r = Math.Abs(b) * Math.Sqrt(1 + r * r);
}
else
{
r = 0.0;
}
return r;
}
}
#endregion // Internal Maths utility
/// <summary>.NET GeneralMatrix class.
///
/// The .NET GeneralMatrix Class provides the fundamental operations of numerical
/// linear algebra. Various constructors create Matrices from two dimensional
/// arrays of double precision floating point numbers. Various "gets" and
/// "sets" provide access to submatrices and matrix elements. Several methods
/// implement basic matrix arithmetic, including matrix addition and
/// multiplication, matrix norms, and element-by-element array operations.
/// Methods for reading and printing matrices are also included. All the
/// operations in this version of the GeneralMatrix Class involve real matrices.
/// Complex matrices may be handled in a future version.
///
/// Five fundamental matrix decompositions, which consist of pairs or triples
/// of matrices, permutation vectors, and the like, produce results in five
/// decomposition classes. These decompositions are accessed by the GeneralMatrix
/// class to compute solutions of simultaneous linear equations, determinants,
/// inverses and other matrix functions. The five decompositions are:
/// <P><UL>
/// <LI>Cholesky Decomposition of symmetric, positive definite matrices.
/// <LI>LU Decomposition of rectangular matrices.
/// <LI>QR Decomposition of rectangular matrices.
/// <LI>Singular Value Decomposition of rectangular matrices.
/// <LI>Eigenvalue Decomposition of both symmetric and nonsymmetric square matrices.
/// </UL>
/// <DL>
/// <DT><B>Example of use:</B></DT>
/// <P>
/// <DD>Solve a linear system A x = b and compute the residual norm, ||b - A x||.
/// <P><PRE>
/// double[][] vals = {{1.,2.,3},{4.,5.,6.},{7.,8.,10.}};
/// GeneralMatrix A = new GeneralMatrix(vals);
/// GeneralMatrix b = GeneralMatrix.Random(3,1);
/// GeneralMatrix x = A.Solve(b);
/// GeneralMatrix r = A.Multiply(x).Subtract(b);
/// double rnorm = r.NormInf();
/// </PRE></DD>
/// </DL>
/// </summary>
/// <author>
/// The MathWorks, Inc. and the National Institute of Standards and Technology.
/// </author>
/// <version> 5 August 1998
/// </version>
[Serializable]
public class GeneralMatrix : System.ICloneable, System.Runtime.Serialization.ISerializable, System.IDisposable
{
#region Class variables
/// <summary>Array for internal storage of elements.
/// @serial internal array storage.
/// </summary>
private double[][] A;
/// <summary>Row and column dimensions.
/// @serial row dimension.
/// @serial column dimension.
/// </summary>
private int m, n;
#endregion // Class variables
#region Constructors
/// <summary>Construct an m-by-n matrix of zeros. </summary>
/// <param name="m"> Number of rows.
/// </param>
/// <param name="n"> Number of colums.
/// </param>
public GeneralMatrix(int m, int n)
{
this.m = m;
this.n = n;
A = new double[m][];
for (int i = 0; i < m; i++)
{
A[i] = new double[n];
}
}
/// <summary>Construct an m-by-n constant matrix.</summary>
/// <param name="m"> Number of rows.
/// </param>
/// <param name="n"> Number of colums.
/// </param>
/// <param name="s"> Fill the matrix with this scalar value.
/// </param>
public GeneralMatrix(int m, int n, double s)
{
this.m = m;
this.n = n;
A = new double[m][];
for (int i = 0; i < m; i++)
{
A[i] = new double[n];
}
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
A[i][j] = s;
}
}
}
/// <summary>Construct a matrix from a 2-D array.</summary>
/// <param name="A"> Two-dimensional array of doubles.
/// </param>
/// <exception cref="System.ArgumentException"> All rows must have the same length
/// </exception>
/// <seealso cref="Create">
/// </seealso>
public GeneralMatrix(double[][] A)
{
m = A.Length;
n = A[0].Length;
for (int i = 0; i < m; i++)
{
if (A[i].Length != n)
{
throw new System.ArgumentException("All rows must have the same length.");
}
}
this.A = A;
}
/// <summary>Construct a matrix quickly without checking arguments.</summary>
/// <param name="A"> Two-dimensional array of doubles.
/// </param>
/// <param name="m"> Number of rows.
/// </param>
/// <param name="n"> Number of colums.
/// </param>
public GeneralMatrix(double[][] A, int m, int n)
{
this.A = A;
this.m = m;
this.n = n;
}
/// <summary>Construct a matrix from a one-dimensional packed array</summary>
/// <param name="vals">One-dimensional array of doubles, packed by columns (ala Fortran).
/// </param>
/// <param name="m"> Number of rows.
/// </param>
/// <exception cref="System.ArgumentException"> Array length must be a multiple of m.
/// </exception>
public GeneralMatrix(double[] vals, int m)
{
this.m = m;
n = (m != 0?vals.Length / m:0);
if (m * n != vals.Length)
{
throw new System.ArgumentException("Array length must be a multiple of m.");
}
A = new double[m][];
for (int i = 0; i < m; i++)
{
A[i] = new double[n];
}
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
A[i][j] = vals[i + j * m];
}
}
}
#endregion // Constructors
#region Public Properties
/// <summary>Access the internal two-dimensional array.</summary>
/// <returns> Pointer to the two-dimensional array of matrix elements.
/// </returns>
virtual public double[][] Array
{
get
{
return A;
}
}
/// <summary>Copy the internal two-dimensional array.</summary>
/// <returns> Two-dimensional array copy of matrix elements.
/// </returns>
virtual public double[][] ArrayCopy
{
get
{
double[][] C = new double[m][];
for (int i = 0; i < m; i++)
{
C[i] = new double[n];
}
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
C[i][j] = A[i][j];
}
}
return C;
}
}
/// <summary>Make a one-dimensional column packed copy of the internal array.</summary>
/// <returns> Matrix elements packed in a one-dimensional array by columns.
/// </returns>
virtual public double[] ColumnPackedCopy
{
get
{
double[] vals = new double[m * n];
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
vals[i + j * m] = A[i][j];
}
}
return vals;
}
}
/// <summary>Make a one-dimensional row packed copy of the internal array.</summary>
/// <returns> Matrix elements packed in a one-dimensional array by rows.
/// </returns>
virtual public double[] RowPackedCopy
{
get
{
double[] vals = new double[m * n];
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
vals[i * n + j] = A[i][j];
}
}
return vals;
}
}
/// <summary>Get row dimension.</summary>
/// <returns> m, the number of rows.
/// </returns>
virtual public int RowDimension
{
get
{
return m;
}
}
/// <summary>Get column dimension.</summary>
/// <returns> n, the number of columns.
/// </returns>
virtual public int ColumnDimension
{
get
{
return n;
}
}
#endregion // Public Properties
#region Public Methods
/// <summary>Construct a matrix from a copy of a 2-D array.</summary>
/// <param name="A"> Two-dimensional array of doubles.
/// </param>
/// <exception cref="System.ArgumentException"> All rows must have the same length
/// </exception>
public static GeneralMatrix Create(double[][] A)
{
int m = A.Length;
int n = A[0].Length;
GeneralMatrix X = new GeneralMatrix(m, n);
double[][] C = X.Array;
for (int i = 0; i < m; i++)
{
if (A[i].Length != n)
{
throw new System.ArgumentException("All rows must have the same length.");
}
for (int j = 0; j < n; j++)
{
C[i][j] = A[i][j];
}
}
return X;
}
/// <summary>Make a deep copy of a matrix</summary>
public virtual GeneralMatrix Copy()
{
GeneralMatrix X = new GeneralMatrix(m, n);
double[][] C = X.Array;
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
C[i][j] = A[i][j];
}
}
return X;
}
/// <summary>Get a single element.</summary>
/// <param name="i"> Row index.
/// </param>
/// <param name="j"> Column index.
/// </param>
/// <returns> A(i,j)
/// </returns>
/// <exception cref="System.IndexOutOfRangeException">
/// </exception>
public virtual double GetElement(int i, int j)
{
return A[i][j];
}
/// <summary>Get a submatrix.</summary>
/// <param name="i0"> Initial row index
/// </param>
/// <param name="i1"> Final row index
/// </param>
/// <param name="j0"> Initial column index
/// </param>
/// <param name="j1"> Final column index
/// </param>
/// <returns> A(i0:i1,j0:j1)
/// </returns>
/// <exception cref="System.IndexOutOfRangeException"> Submatrix indices
/// </exception>
public virtual GeneralMatrix GetMatrix(int i0, int i1, int j0, int j1)
{
GeneralMatrix X = new GeneralMatrix(i1 - i0 + 1, j1 - j0 + 1);
double[][] B = X.Array;
try
{
for (int i = i0; i <= i1; i++)
{
for (int j = j0; j <= j1; j++)
{
B[i - i0][j - j0] = A[i][j];
}
}
}
catch (System.IndexOutOfRangeException e)
{
throw new System.IndexOutOfRangeException("Submatrix indices", e);
}
return X;
}
/// <summary>Get a submatrix.</summary>
/// <param name="r"> Array of row indices.
/// </param>
/// <param name="c"> Array of column indices.
/// </param>
/// <returns> A(r(:),c(:))
/// </returns>
/// <exception cref="System.IndexOutOfRangeException"> Submatrix indices
/// </exception>
public virtual GeneralMatrix GetMatrix(int[] r, int[] c)
{
GeneralMatrix X = new GeneralMatrix(r.Length, c.Length);
double[][] B = X.Array;
try
{
for (int i = 0; i < r.Length; i++)
{
for (int j = 0; j < c.Length; j++)
{
B[i][j] = A[r[i]][c[j]];
}
}
}
catch (System.IndexOutOfRangeException e)
{
throw new System.IndexOutOfRangeException("Submatrix indices", e);
}
return X;
}
/// <summary>Get a submatrix.</summary>
/// <param name="i0"> Initial row index
/// </param>
/// <param name="i1"> Final row index
/// </param>
/// <param name="c"> Array of column indices.
/// </param>
/// <returns> A(i0:i1,c(:))
/// </returns>
/// <exception cref="System.IndexOutOfRangeException"> Submatrix indices
/// </exception>
public virtual GeneralMatrix GetMatrix(int i0, int i1, int[] c)
{
GeneralMatrix X = new GeneralMatrix(i1 - i0 + 1, c.Length);
double[][] B = X.Array;
try
{
for (int i = i0; i <= i1; i++)
{
for (int j = 0; j < c.Length; j++)
{
B[i - i0][j] = A[i][c[j]];
}
}
}
catch (System.IndexOutOfRangeException e)
{
throw new System.IndexOutOfRangeException("Submatrix indices", e);
}
return X;
}
/// <summary>Get a submatrix.</summary>
/// <param name="r"> Array of row indices.
/// </param>
/// <param name="j0"> Initial column index
/// </param>
/// <param name="j1"> Final column index
/// </param>
/// <returns> A(r(:),j0:j1)
/// </returns>
/// <exception cref="System.IndexOutOfRangeException"> Submatrix indices
/// </exception>
public virtual GeneralMatrix GetMatrix(int[] r, int j0, int j1)
{
GeneralMatrix X = new GeneralMatrix(r.Length, j1 - j0 + 1);
double[][] B = X.Array;
try
{
for (int i = 0; i < r.Length; i++)
{
for (int j = j0; j <= j1; j++)
{
B[i][j - j0] = A[r[i]][j];
}
}
}
catch (System.IndexOutOfRangeException e)
{
throw new System.IndexOutOfRangeException("Submatrix indices", e);
}
return X;
}
/// <summary>Set a single element.</summary>
/// <param name="i"> Row index.
/// </param>
/// <param name="j"> Column index.
/// </param>
/// <param name="s"> A(i,j).
/// </param>
/// <exception cref="System.IndexOutOfRangeException">
/// </exception>
public virtual void SetElement(int i, int j, double s)
{
A[i][j] = s;
}
/// <summary>Set a submatrix.</summary>
/// <param name="i0"> Initial row index
/// </param>
/// <param name="i1"> Final row index
/// </param>
/// <param name="j0"> Initial column index
/// </param>
/// <param name="j1"> Final column index
/// </param>
/// <param name="X"> A(i0:i1,j0:j1)
/// </param>
/// <exception cref="System.IndexOutOfRangeException"> Submatrix indices
/// </exception>
public virtual void SetMatrix(int i0, int i1, int j0, int j1, GeneralMatrix X)
{
try
{
for (int i = i0; i <= i1; i++)
{
for (int j = j0; j <= j1; j++)
{
A[i][j] = X.GetElement(i - i0, j - j0);
}
}
}
catch (System.IndexOutOfRangeException e)
{
throw new System.IndexOutOfRangeException("Submatrix indices", e);
}
}
/// <summary>Set a submatrix.</summary>
/// <param name="r"> Array of row indices.
/// </param>
/// <param name="c"> Array of column indices.
/// </param>
/// <param name="X"> A(r(:),c(:))
/// </param>
/// <exception cref="System.IndexOutOfRangeException"> Submatrix indices
/// </exception>
public virtual void SetMatrix(int[] r, int[] c, GeneralMatrix X)
{
try
{
for (int i = 0; i < r.Length; i++)
{
for (int j = 0; j < c.Length; j++)
{
A[r[i]][c[j]] = X.GetElement(i, j);
}
}
}
catch (System.IndexOutOfRangeException e)
{
throw new System.IndexOutOfRangeException("Submatrix indices", e);
}
}
/// <summary>Set a submatrix.</summary>
/// <param name="r"> Array of row indices.
/// </param>
/// <param name="j0"> Initial column index
/// </param>
/// <param name="j1"> Final column index
/// </param>
/// <param name="X"> A(r(:),j0:j1)
/// </param>
/// <exception cref="System.IndexOutOfRangeException"> Submatrix indices
/// </exception>
public virtual void SetMatrix(int[] r, int j0, int j1, GeneralMatrix X)
{
try
{
for (int i = 0; i < r.Length; i++)
{
for (int j = j0; j <= j1; j++)
{
A[r[i]][j] = X.GetElement(i, j - j0);
}
}
}
catch (System.IndexOutOfRangeException e)
{
throw new System.IndexOutOfRangeException("Submatrix indices", e);
}
}
/// <summary>Set a submatrix.</summary>
/// <param name="i0"> Initial row index
/// </param>
/// <param name="i1"> Final row index
/// </param>
/// <param name="c"> Array of column indices.
/// </param>
/// <param name="X"> A(i0:i1,c(:))
/// </param>
/// <exception cref="System.IndexOutOfRangeException"> Submatrix indices
/// </exception>
public virtual void SetMatrix(int i0, int i1, int[] c, GeneralMatrix X)
{
try
{
for (int i = i0; i <= i1; i++)
{
for (int j = 0; j < c.Length; j++)
{
A[i][c[j]] = X.GetElement(i - i0, j);
}
}
}
catch (System.IndexOutOfRangeException e)
{
throw new System.IndexOutOfRangeException("Submatrix indices", e);
}
}
/// <summary>Matrix transpose.</summary>
/// <returns> A'
/// </returns>
public virtual GeneralMatrix Transpose()
{
GeneralMatrix X = new GeneralMatrix(n, m);
double[][] C = X.Array;
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
C[j][i] = A[i][j];
}
}
return X;
}
/// <summary>One norm</summary>
/// <returns> maximum column sum.
/// </returns>
public virtual double Norm1()
{
double f = 0;
for (int j = 0; j < n; j++)
{
double s = 0;
for (int i = 0; i < m; i++)
{
s += System.Math.Abs(A[i][j]);
}
f = System.Math.Max(f, s);
}
return f;
}
/// <summary>Two norm</summary>
/// <returns> maximum singular value.
/// </returns>
public virtual double Norm2()
{
return (new SingularValueDecomposition(this).Norm2());
}
/// <summary>Infinity norm</summary>
/// <returns> maximum row sum.
/// </returns>
public virtual double NormInf()
{
double f = 0;
for (int i = 0; i < m; i++)
{
double s = 0;
for (int j = 0; j < n; j++)
{
s += System.Math.Abs(A[i][j]);
}
f = System.Math.Max(f, s);
}
return f;
}
/// <summary>Frobenius norm</summary>
/// <returns> sqrt of sum of squares of all elements.
/// </returns>
public virtual double NormF()
{
double f = 0;
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
f = Maths.Hypot(f, A[i][j]);
}
}
return f;
}
/// <summary>Unary minus</summary>
/// <returns> -A
/// </returns>
public virtual GeneralMatrix UnaryMinus()
{
GeneralMatrix X = new GeneralMatrix(m, n);
double[][] C = X.Array;
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
C[i][j] = -A[i][j];
}
}
return X;
}
/// <summary>C = A + B</summary>
/// <param name="B"> another matrix
/// </param>
/// <returns> A + B
/// </returns>
public virtual GeneralMatrix Add(GeneralMatrix B)
{
CheckMatrixDimensions(B);
GeneralMatrix X = new GeneralMatrix(m, n);
double[][] C = X.Array;
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
C[i][j] = A[i][j] + B.A[i][j];
}
}
return X;
}
/// <summary>A = A + B</summary>
/// <param name="B"> another matrix
/// </param>
/// <returns> A + B
/// </returns>
public virtual GeneralMatrix AddEquals(GeneralMatrix B)
{
CheckMatrixDimensions(B);
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
A[i][j] = A[i][j] + B.A[i][j];
}
}
return this;
}
/// <summary>C = A - B</summary>
/// <param name="B"> another matrix
/// </param>
/// <returns> A - B
/// </returns>
public virtual GeneralMatrix Subtract(GeneralMatrix B)
{
CheckMatrixDimensions(B);
GeneralMatrix X = new GeneralMatrix(m, n);
double[][] C = X.Array;
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
C[i][j] = A[i][j] - B.A[i][j];
}
}
return X;
}
/// <summary>A = A - B</summary>
/// <param name="B"> another matrix
/// </param>
/// <returns> A - B
/// </returns>
public virtual GeneralMatrix SubtractEquals(GeneralMatrix B)
{
CheckMatrixDimensions(B);
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
A[i][j] = A[i][j] - B.A[i][j];
}
}
return this;
}
/// <summary>Element-by-element multiplication, C = A.*B</summary>
/// <param name="B"> another matrix
/// </param>
/// <returns> A.*B
/// </returns>
public virtual GeneralMatrix ArrayMultiply(GeneralMatrix B)
{
CheckMatrixDimensions(B);
GeneralMatrix X = new GeneralMatrix(m, n);
double[][] C = X.Array;
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
C[i][j] = A[i][j] * B.A[i][j];
}
}
return X;
}
/// <summary>Element-by-element multiplication in place, A = A.*B</summary>
/// <param name="B"> another matrix
/// </param>
/// <returns> A.*B
/// </returns>
public virtual GeneralMatrix ArrayMultiplyEquals(GeneralMatrix B)
{
CheckMatrixDimensions(B);
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
A[i][j] = A[i][j] * B.A[i][j];
}
}
return this;
}
/// <summary>Element-by-element right division, C = A./B</summary>
/// <param name="B"> another matrix
/// </param>
/// <returns> A./B
/// </returns>
public virtual GeneralMatrix ArrayRightDivide(GeneralMatrix B)
{
CheckMatrixDimensions(B);
GeneralMatrix X = new GeneralMatrix(m, n);
double[][] C = X.Array;
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
C[i][j] = A[i][j] / B.A[i][j];
}
}
return X;
}
/// <summary>Element-by-element right division in place, A = A./B</summary>
/// <param name="B"> another matrix
/// </param>
/// <returns> A./B
/// </returns>
public virtual GeneralMatrix ArrayRightDivideEquals(GeneralMatrix B)
{
CheckMatrixDimensions(B);
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
A[i][j] = A[i][j] / B.A[i][j];
}
}
return this;
}
/// <summary>Element-by-element left division, C = A.\B</summary>
/// <param name="B"> another matrix
/// </param>
/// <returns> A.\B
/// </returns>
public virtual GeneralMatrix ArrayLeftDivide(GeneralMatrix B)
{
CheckMatrixDimensions(B);
GeneralMatrix X = new GeneralMatrix(m, n);
double[][] C = X.Array;
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
C[i][j] = B.A[i][j] / A[i][j];
}
}
return X;
}
/// <summary>Element-by-element left division in place, A = A.\B</summary>
/// <param name="B"> another matrix
/// </param>
/// <returns> A.\B
/// </returns>
public virtual GeneralMatrix ArrayLeftDivideEquals(GeneralMatrix B)
{
CheckMatrixDimensions(B);
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
A[i][j] = B.A[i][j] / A[i][j];
}
}
return this;
}
/// <summary>Multiply a matrix by a scalar, C = s*A</summary>
/// <param name="s"> scalar
/// </param>
/// <returns> s*A
/// </returns>
public virtual GeneralMatrix Multiply(double s)
{
GeneralMatrix X = new GeneralMatrix(m, n);
double[][] C = X.Array;
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
C[i][j] = s * A[i][j];
}
}
return X;
}
/// <summary>Multiply a matrix by a scalar in place, A = s*A</summary>
/// <param name="s"> scalar
/// </param>
/// <returns> replace A by s*A
/// </returns>
public virtual GeneralMatrix MultiplyEquals(double s)
{
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
A[i][j] = s * A[i][j];
}
}
return this;
}
/// <summary>Linear algebraic matrix multiplication, A * B</summary>
/// <param name="B"> another matrix
/// </param>
/// <returns> Matrix product, A * B
/// </returns>
/// <exception cref="System.ArgumentException"> Matrix inner dimensions must agree.
/// </exception>
public virtual GeneralMatrix Multiply(GeneralMatrix B)
{
if (B.m != n)
{
throw new System.ArgumentException("GeneralMatrix inner dimensions must agree.");
}
GeneralMatrix X = new GeneralMatrix(m, B.n);
double[][] C = X.Array;
double[] Bcolj = new double[n];
for (int j = 0; j < B.n; j++)
{
for (int k = 0; k < n; k++)
{
Bcolj[k] = B.A[k][j];
}
for (int i = 0; i < m; i++)
{
double[] Arowi = A[i];
double s = 0;
for (int k = 0; k < n; k++)
{
s += Arowi[k] * Bcolj[k];
}
C[i][j] = s;
}
}
return X;
}
#region Operator Overloading
/// <summary>
/// Addition of matrices
/// </summary>
/// <param name="m1"></param>
/// <param name="m2"></param>
/// <returns></returns>
public static GeneralMatrix operator +(GeneralMatrix m1, GeneralMatrix m2)
{
return m1.Add(m2);
}
/// <summary>
/// Subtraction of matrices
/// </summary>
/// <param name="m1"></param>
/// <param name="m2"></param>
/// <returns></returns>
public static GeneralMatrix operator -(GeneralMatrix m1, GeneralMatrix m2)
{
return m1.Subtract(m2);
}
/// <summary>
/// Multiplication of matrices
/// </summary>
/// <param name="m1"></param>
/// <param name="m2"></param>
/// <returns></returns>
public static GeneralMatrix operator *(GeneralMatrix m1, GeneralMatrix m2)
{
return m1.Multiply(m2);
}
#endregion //Operator Overloading
/// <summary>LU Decomposition</summary>
/// <returns> LUDecomposition
/// </returns>
/// <seealso cref="LUDecomposition">
/// </seealso>
public virtual LUDecomposition LUD()
{
return new LUDecomposition(this);
}
/// <summary>QR Decomposition</summary>
/// <returns> QRDecomposition
/// </returns>
/// <seealso cref="QRDecomposition">
/// </seealso>
public virtual QRDecomposition QRD()
{
return new QRDecomposition(this);
}
/// <summary>Cholesky Decomposition</summary>
/// <returns> CholeskyDecomposition
/// </returns>
/// <seealso cref="CholeskyDecomposition">
/// </seealso>
public virtual CholeskyDecomposition chol()
{
return new CholeskyDecomposition(this);
}
/// <summary>Singular Value Decomposition</summary>
/// <returns> SingularValueDecomposition
/// </returns>
/// <seealso cref="SingularValueDecomposition">
/// </seealso>
public virtual SingularValueDecomposition SVD()
{
return new SingularValueDecomposition(this);
}
/// <summary>Eigenvalue Decomposition</summary>
/// <returns> EigenvalueDecomposition
/// </returns>
/// <seealso cref="EigenvalueDecomposition">
/// </seealso>
public virtual EigenvalueDecomposition Eigen()
{
return new EigenvalueDecomposition(this);
}
/// <summary>Solve A*X = B</summary>
/// <param name="B"> right hand side
/// </param>
/// <returns> solution if A is square, least squares solution otherwise
/// </returns>
public virtual GeneralMatrix Solve(GeneralMatrix B)
{
return (m == n ? (new LUDecomposition(this)).Solve(B):(new QRDecomposition(this)).Solve(B));
}
/// <summary>Solve X*A = B, which is also A'*X' = B'</summary>
/// <param name="B"> right hand side
/// </param>
/// <returns> solution if A is square, least squares solution otherwise.
/// </returns>
public virtual GeneralMatrix SolveTranspose(GeneralMatrix B)
{
return Transpose().Solve(B.Transpose());
}
/// <summary>Matrix inverse or pseudoinverse</summary>
/// <returns> inverse(A) if A is square, pseudoinverse otherwise.
/// </returns>
public virtual GeneralMatrix Inverse()
{
return Solve(Identity(m, m));
}
/// <summary>GeneralMatrix determinant</summary>
/// <returns> determinant
/// </returns>
public virtual double Determinant()
{
return new LUDecomposition(this).Determinant();
}
/// <summary>GeneralMatrix rank</summary>
/// <returns> effective numerical rank, obtained from SVD.
/// </returns>
public virtual int Rank()
{
return new SingularValueDecomposition(this).Rank();
}
/// <summary>Matrix condition (2 norm)</summary>
/// <returns> ratio of largest to smallest singular value.
/// </returns>
public virtual double Condition()
{
return new SingularValueDecomposition(this).Condition();
}
/// <summary>Matrix trace.</summary>
/// <returns> sum of the diagonal elements.
/// </returns>
public virtual double Trace()
{
double t = 0;
for (int i = 0; i < System.Math.Min(m, n); i++)
{
t += A[i][i];
}
return t;
}
/// <summary>Generate matrix with random elements</summary>
/// <param name="m"> Number of rows.
/// </param>
/// <param name="n"> Number of colums.
/// </param>
/// <returns> An m-by-n matrix with uniformly distributed random elements.
/// </returns>
public static GeneralMatrix Random(int m, int n)
{
System.Random random = new System.Random();
GeneralMatrix A = new GeneralMatrix(m, n);
double[][] X = A.Array;
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
X[i][j] = random.NextDouble();
}
}
return A;
}
/// <summary>Generate identity matrix</summary>
/// <param name="m"> Number of rows.
/// </param>
/// <param name="n"> Number of colums.
/// </param>
/// <returns> An m-by-n matrix with ones on the diagonal and zeros elsewhere.
/// </returns>
public static GeneralMatrix Identity(int m, int n)
{
GeneralMatrix A = new GeneralMatrix(m, n);
double[][] X = A.Array;
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
X[i][j] = (i == j ? 1.0 : 0.0);
}
}
return A;
}
#endregion // Public Methods
#region Private Methods
/// <summary>Check if size(A) == size(B) *</summary>
private void CheckMatrixDimensions(GeneralMatrix B)
{
if (B.m != m || B.n != n)
{
throw new System.ArgumentException("GeneralMatrix dimensions must agree.");
}
}
#endregion // Private Methods
#region Implement IDisposable
/// <summary>
/// Do not make this method virtual.
/// A derived class should not be able to override this method.
/// </summary>
public void Dispose()
{
Dispose(true);
}
/// <summary>
/// Dispose(bool disposing) executes in two distinct scenarios.
/// If disposing equals true, the method has been called directly
/// or indirectly by a user's code. Managed and unmanaged resources
/// can be disposed.
/// If disposing equals false, the method has been called by the
/// runtime from inside the finalizer and you should not reference
/// other objects. Only unmanaged resources can be disposed.
/// </summary>
/// <param name="disposing"></param>
private void Dispose(bool disposing)
{
// This object will be cleaned up by the Dispose method.
// Therefore, you should call GC.SupressFinalize to
// take this object off the finalization queue
// and prevent finalization code for this object
// from executing a second time.
if (disposing)
GC.SuppressFinalize(this);
}
/// <summary>
/// This destructor will run only if the Dispose method
/// does not get called.
/// It gives your base class the opportunity to finalize.
/// Do not provide destructors in types derived from this class.
/// </summary>
~GeneralMatrix()
{
// Do not re-create Dispose clean-up code here.
// Calling Dispose(false) is optimal in terms of
// readability and maintainability.
Dispose(false);
}
#endregion // Implement IDisposable
/// <summary>Clone the GeneralMatrix object.</summary>
public System.Object Clone()
{
return this.Copy();
}
/// <summary>
/// A method called when serializing this class
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.ServerManagement
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for GatewayOperations.
/// </summary>
public static partial class GatewayOperationsExtensions
{
/// <summary>
/// Creates or updates a ManagementService gateway.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum).
/// </param>
/// <param name='location'>
/// location of the resource
/// </param>
/// <param name='tags'>
/// resource tags
/// </param>
/// <param name='autoUpgrade'>
/// The autoUpgrade property gives the flexibility to gateway to auto upgrade
/// itself. If properties value not specified, then we assume autoUpgrade =
/// Off. Possible values include: 'On', 'Off'
/// </param>
public static GatewayResource Create(this IGatewayOperations operations, string resourceGroupName, string gatewayName, string location = default(string), object tags = default(object), AutoUpgrade? autoUpgrade = default(AutoUpgrade?))
{
return Task.Factory.StartNew(s => ((IGatewayOperations)s).CreateAsync(resourceGroupName, gatewayName, location, tags, autoUpgrade), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a ManagementService gateway.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum).
/// </param>
/// <param name='location'>
/// location of the resource
/// </param>
/// <param name='tags'>
/// resource tags
/// </param>
/// <param name='autoUpgrade'>
/// The autoUpgrade property gives the flexibility to gateway to auto upgrade
/// itself. If properties value not specified, then we assume autoUpgrade =
/// Off. Possible values include: 'On', 'Off'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<GatewayResource> CreateAsync(this IGatewayOperations operations, string resourceGroupName, string gatewayName, string location = default(string), object tags = default(object), AutoUpgrade? autoUpgrade = default(AutoUpgrade?), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateWithHttpMessagesAsync(resourceGroupName, gatewayName, location, tags, autoUpgrade, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates or updates a ManagementService gateway.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum).
/// </param>
/// <param name='location'>
/// location of the resource
/// </param>
/// <param name='tags'>
/// resource tags
/// </param>
/// <param name='autoUpgrade'>
/// The autoUpgrade property gives the flexibility to gateway to auto upgrade
/// itself. If properties value not specified, then we assume autoUpgrade =
/// Off. Possible values include: 'On', 'Off'
/// </param>
public static GatewayResource BeginCreate(this IGatewayOperations operations, string resourceGroupName, string gatewayName, string location = default(string), object tags = default(object), AutoUpgrade? autoUpgrade = default(AutoUpgrade?))
{
return Task.Factory.StartNew(s => ((IGatewayOperations)s).BeginCreateAsync(resourceGroupName, gatewayName, location, tags, autoUpgrade), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a ManagementService gateway.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum).
/// </param>
/// <param name='location'>
/// location of the resource
/// </param>
/// <param name='tags'>
/// resource tags
/// </param>
/// <param name='autoUpgrade'>
/// The autoUpgrade property gives the flexibility to gateway to auto upgrade
/// itself. If properties value not specified, then we assume autoUpgrade =
/// Off. Possible values include: 'On', 'Off'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<GatewayResource> BeginCreateAsync(this IGatewayOperations operations, string resourceGroupName, string gatewayName, string location = default(string), object tags = default(object), AutoUpgrade? autoUpgrade = default(AutoUpgrade?), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateWithHttpMessagesAsync(resourceGroupName, gatewayName, location, tags, autoUpgrade, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates a gateway belonging to a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum).
/// </param>
/// <param name='location'>
/// location of the resource
/// </param>
/// <param name='tags'>
/// resource tags
/// </param>
/// <param name='autoUpgrade'>
/// The autoUpgrade property gives the flexibility to gateway to auto upgrade
/// itself. If properties value not specified, then we assume autoUpgrade =
/// Off. Possible values include: 'On', 'Off'
/// </param>
public static GatewayResource Update(this IGatewayOperations operations, string resourceGroupName, string gatewayName, string location = default(string), object tags = default(object), AutoUpgrade? autoUpgrade = default(AutoUpgrade?))
{
return Task.Factory.StartNew(s => ((IGatewayOperations)s).UpdateAsync(resourceGroupName, gatewayName, location, tags, autoUpgrade), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Updates a gateway belonging to a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum).
/// </param>
/// <param name='location'>
/// location of the resource
/// </param>
/// <param name='tags'>
/// resource tags
/// </param>
/// <param name='autoUpgrade'>
/// The autoUpgrade property gives the flexibility to gateway to auto upgrade
/// itself. If properties value not specified, then we assume autoUpgrade =
/// Off. Possible values include: 'On', 'Off'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<GatewayResource> UpdateAsync(this IGatewayOperations operations, string resourceGroupName, string gatewayName, string location = default(string), object tags = default(object), AutoUpgrade? autoUpgrade = default(AutoUpgrade?), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, gatewayName, location, tags, autoUpgrade, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates a gateway belonging to a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum).
/// </param>
/// <param name='location'>
/// location of the resource
/// </param>
/// <param name='tags'>
/// resource tags
/// </param>
/// <param name='autoUpgrade'>
/// The autoUpgrade property gives the flexibility to gateway to auto upgrade
/// itself. If properties value not specified, then we assume autoUpgrade =
/// Off. Possible values include: 'On', 'Off'
/// </param>
public static GatewayResource BeginUpdate(this IGatewayOperations operations, string resourceGroupName, string gatewayName, string location = default(string), object tags = default(object), AutoUpgrade? autoUpgrade = default(AutoUpgrade?))
{
return Task.Factory.StartNew(s => ((IGatewayOperations)s).BeginUpdateAsync(resourceGroupName, gatewayName, location, tags, autoUpgrade), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Updates a gateway belonging to a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum).
/// </param>
/// <param name='location'>
/// location of the resource
/// </param>
/// <param name='tags'>
/// resource tags
/// </param>
/// <param name='autoUpgrade'>
/// The autoUpgrade property gives the flexibility to gateway to auto upgrade
/// itself. If properties value not specified, then we assume autoUpgrade =
/// Off. Possible values include: 'On', 'Off'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<GatewayResource> BeginUpdateAsync(this IGatewayOperations operations, string resourceGroupName, string gatewayName, string location = default(string), object tags = default(object), AutoUpgrade? autoUpgrade = default(AutoUpgrade?), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginUpdateWithHttpMessagesAsync(resourceGroupName, gatewayName, location, tags, autoUpgrade, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes a gateway from a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum).
/// </param>
public static void Delete(this IGatewayOperations operations, string resourceGroupName, string gatewayName)
{
Task.Factory.StartNew(s => ((IGatewayOperations)s).DeleteAsync(resourceGroupName, gatewayName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a gateway from a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum).
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IGatewayOperations operations, string resourceGroupName, string gatewayName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteWithHttpMessagesAsync(resourceGroupName, gatewayName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Returns a gateway
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum)
/// </param>
/// <param name='expand'>
/// Gets subscription credentials which uniquely identify Microsoft Azure
/// subscription. The subscription ID forms part of the URI for every service
/// call. Possible values include: 'status'
/// </param>
public static GatewayResource Get(this IGatewayOperations operations, string resourceGroupName, string gatewayName, GatewayExpandOption? expand = default(GatewayExpandOption?))
{
return Task.Factory.StartNew(s => ((IGatewayOperations)s).GetAsync(resourceGroupName, gatewayName, expand), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns a gateway
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum)
/// </param>
/// <param name='expand'>
/// Gets subscription credentials which uniquely identify Microsoft Azure
/// subscription. The subscription ID forms part of the URI for every service
/// call. Possible values include: 'status'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<GatewayResource> GetAsync(this IGatewayOperations operations, string resourceGroupName, string gatewayName, GatewayExpandOption? expand = default(GatewayExpandOption?), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, gatewayName, expand, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Returns gateways in a subscription
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<GatewayResource> List(this IGatewayOperations operations)
{
return Task.Factory.StartNew(s => ((IGatewayOperations)s).ListAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns gateways in a subscription
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<GatewayResource>> ListAsync(this IGatewayOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Returns gateways in a resource group
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
public static IPage<GatewayResource> ListForResourceGroup(this IGatewayOperations operations, string resourceGroupName)
{
return Task.Factory.StartNew(s => ((IGatewayOperations)s).ListForResourceGroupAsync(resourceGroupName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns gateways in a resource group
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<GatewayResource>> ListForResourceGroupAsync(this IGatewayOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListForResourceGroupWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Upgrade a gateway
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum).
/// </param>
public static void Upgrade(this IGatewayOperations operations, string resourceGroupName, string gatewayName)
{
Task.Factory.StartNew(s => ((IGatewayOperations)s).UpgradeAsync(resourceGroupName, gatewayName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Upgrade a gateway
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum).
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task UpgradeAsync(this IGatewayOperations operations, string resourceGroupName, string gatewayName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.UpgradeWithHttpMessagesAsync(resourceGroupName, gatewayName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Upgrade a gateway
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum).
/// </param>
public static void BeginUpgrade(this IGatewayOperations operations, string resourceGroupName, string gatewayName)
{
Task.Factory.StartNew(s => ((IGatewayOperations)s).BeginUpgradeAsync(resourceGroupName, gatewayName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Upgrade a gateway
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum).
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginUpgradeAsync(this IGatewayOperations operations, string resourceGroupName, string gatewayName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginUpgradeWithHttpMessagesAsync(resourceGroupName, gatewayName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Regenerate a gateway's profile
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum).
/// </param>
public static void RegenerateProfile(this IGatewayOperations operations, string resourceGroupName, string gatewayName)
{
Task.Factory.StartNew(s => ((IGatewayOperations)s).RegenerateProfileAsync(resourceGroupName, gatewayName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Regenerate a gateway's profile
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum).
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task RegenerateProfileAsync(this IGatewayOperations operations, string resourceGroupName, string gatewayName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.RegenerateProfileWithHttpMessagesAsync(resourceGroupName, gatewayName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Regenerate a gateway's profile
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum).
/// </param>
public static void BeginRegenerateProfile(this IGatewayOperations operations, string resourceGroupName, string gatewayName)
{
Task.Factory.StartNew(s => ((IGatewayOperations)s).BeginRegenerateProfileAsync(resourceGroupName, gatewayName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Regenerate a gateway's profile
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum).
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginRegenerateProfileAsync(this IGatewayOperations operations, string resourceGroupName, string gatewayName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginRegenerateProfileWithHttpMessagesAsync(resourceGroupName, gatewayName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets a gateway profile
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum).
/// </param>
public static GatewayProfile GetProfile(this IGatewayOperations operations, string resourceGroupName, string gatewayName)
{
return Task.Factory.StartNew(s => ((IGatewayOperations)s).GetProfileAsync(resourceGroupName, gatewayName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets a gateway profile
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum).
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<GatewayProfile> GetProfileAsync(this IGatewayOperations operations, string resourceGroupName, string gatewayName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetProfileWithHttpMessagesAsync(resourceGroupName, gatewayName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets a gateway profile
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum).
/// </param>
public static GatewayProfile BeginGetProfile(this IGatewayOperations operations, string resourceGroupName, string gatewayName)
{
return Task.Factory.StartNew(s => ((IGatewayOperations)s).BeginGetProfileAsync(resourceGroupName, gatewayName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets a gateway profile
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum).
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<GatewayProfile> BeginGetProfileAsync(this IGatewayOperations operations, string resourceGroupName, string gatewayName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginGetProfileWithHttpMessagesAsync(resourceGroupName, gatewayName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Returns gateways in a subscription
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<GatewayResource> ListNext(this IGatewayOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IGatewayOperations)s).ListNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns gateways in a subscription
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<GatewayResource>> ListNextAsync(this IGatewayOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Returns gateways in a resource group
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<GatewayResource> ListForResourceGroupNext(this IGatewayOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IGatewayOperations)s).ListForResourceGroupNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns gateways in a resource group
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<GatewayResource>> ListForResourceGroupNextAsync(this IGatewayOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListForResourceGroupNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.Tokens;
using Microsoft.SharePoint.Client;
using System;
using System.Net;
using System.Security.Principal;
using System.Web;
using System.Web.Configuration;
namespace ECM.RecordsManagementWeb
{
/// <summary>
/// Encapsulates all the information from SharePoint.
/// </summary>
public abstract class SharePointContext
{
public const string SPHostUrlKey = "SPHostUrl";
public const string SPAppWebUrlKey = "SPAppWebUrl";
public const string SPLanguageKey = "SPLanguage";
public const string SPClientTagKey = "SPClientTag";
public const string SPProductNumberKey = "SPProductNumber";
protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0);
private readonly Uri spHostUrl;
private readonly Uri spAppWebUrl;
private readonly string spLanguage;
private readonly string spClientTag;
private readonly string spProductNumber;
// <AccessTokenString, UtcExpiresOn>
protected Tuple<string, DateTime> userAccessTokenForSPHost;
protected Tuple<string, DateTime> userAccessTokenForSPAppWeb;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb;
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]);
Uri spHostUrl;
if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) &&
(spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps))
{
return spHostUrl;
}
return null;
}
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequest httpRequest)
{
return GetSPHostUrl(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// The SharePoint host url.
/// </summary>
public Uri SPHostUrl
{
get { return this.spHostUrl; }
}
/// <summary>
/// The SharePoint app web url.
/// </summary>
public Uri SPAppWebUrl
{
get { return this.spAppWebUrl; }
}
/// <summary>
/// The SharePoint language.
/// </summary>
public string SPLanguage
{
get { return this.spLanguage; }
}
/// <summary>
/// The SharePoint client tag.
/// </summary>
public string SPClientTag
{
get { return this.spClientTag; }
}
/// <summary>
/// The SharePoint product number.
/// </summary>
public string SPProductNumber
{
get { return this.spProductNumber; }
}
/// <summary>
/// The user access token for the SharePoint host.
/// </summary>
public abstract string UserAccessTokenForSPHost
{
get;
}
/// <summary>
/// The user access token for the SharePoint app web.
/// </summary>
public abstract string UserAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// The app only access token for the SharePoint host.
/// </summary>
public abstract string AppOnlyAccessTokenForSPHost
{
get;
}
/// <summary>
/// The app only access token for the SharePoint app web.
/// </summary>
public abstract string AppOnlyAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber)
{
if (spHostUrl == null)
{
throw new ArgumentNullException("spHostUrl");
}
if (string.IsNullOrEmpty(spLanguage))
{
throw new ArgumentNullException("spLanguage");
}
if (string.IsNullOrEmpty(spClientTag))
{
throw new ArgumentNullException("spClientTag");
}
if (string.IsNullOrEmpty(spProductNumber))
{
throw new ArgumentNullException("spProductNumber");
}
this.spHostUrl = spHostUrl;
this.spAppWebUrl = spAppWebUrl;
this.spLanguage = spLanguage;
this.spClientTag = spClientTag;
this.spProductNumber = spProductNumber;
}
/// <summary>
/// Creates a user ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost);
}
/// <summary>
/// Creates a user ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb);
}
/// <summary>
/// Creates app only ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost);
}
/// <summary>
/// Creates an app only ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb);
}
/// <summary>
/// Gets the database connection string from SharePoint for autohosted app.
/// </summary>
/// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns>
public string GetDatabaseConnectionString()
{
string dbConnectionString = null;
using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost())
{
if (clientContext != null)
{
var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext);
clientContext.ExecuteQuery();
dbConnectionString = result.Value;
}
}
if (dbConnectionString == null)
{
const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging";
var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey];
dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null;
}
return dbConnectionString;
}
/// <summary>
/// Determines if the specified access token is valid.
/// It considers an access token as not valid if it is null, or it has expired.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <returns>True if the access token is valid.</returns>
protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken)
{
return accessToken != null &&
!string.IsNullOrEmpty(accessToken.Item1) &&
accessToken.Item2 > DateTime.UtcNow;
}
/// <summary>
/// Creates a ClientContext with the specified SharePoint site url and the access token.
/// </summary>
/// <param name="spSiteUrl">The site url.</param>
/// <param name="accessToken">The access token.</param>
/// <returns>A ClientContext instance.</returns>
private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken)
{
if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken))
{
return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken);
}
return null;
}
}
/// <summary>
/// Redirection status.
/// </summary>
public enum RedirectionStatus
{
Ok,
ShouldRedirect,
CanNotRedirect
}
/// <summary>
/// Provides SharePointContext instances.
/// </summary>
public abstract class SharePointContextProvider
{
private static SharePointContextProvider current;
/// <summary>
/// The current SharePointContextProvider instance.
/// </summary>
public static SharePointContextProvider Current
{
get { return SharePointContextProvider.current; }
}
/// <summary>
/// Initializes the default SharePointContextProvider instance.
/// </summary>
static SharePointContextProvider()
{
if (!TokenHelper.IsHighTrustApp())
{
SharePointContextProvider.current = new SharePointAcsContextProvider();
}
else
{
SharePointContextProvider.current = new SharePointHighTrustContextProvider();
}
}
/// <summary>
/// Registers the specified SharePointContextProvider instance as current.
/// It should be called by Application_Start() in Global.asax.
/// </summary>
/// <param name="provider">The SharePointContextProvider to be set as current.</param>
public static void Register(SharePointContextProvider provider)
{
if (provider == null)
{
throw new ArgumentNullException("provider");
}
SharePointContextProvider.current = provider;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
redirectUrl = null;
if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null)
{
return RedirectionStatus.Ok;
}
const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint";
if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]))
{
return RedirectionStatus.CanNotRedirect;
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return RedirectionStatus.CanNotRedirect;
}
if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST"))
{
return RedirectionStatus.CanNotRedirect;
}
Uri requestUrl = httpContext.Request.Url;
var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query);
// Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string.
queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPLanguageKey);
queryNameValueCollection.Remove(SharePointContext.SPClientTagKey);
queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey);
// Adds SPHasRedirectedToSharePoint=1.
queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1");
UriBuilder returnUrlBuilder = new UriBuilder(requestUrl);
returnUrlBuilder.Query = queryNameValueCollection.ToString();
// Inserts StandardTokens.
const string StandardTokens = "{StandardTokens}";
string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri;
returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&");
// Constructs redirect url.
string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString));
redirectUrl = new Uri(redirectUrlString, UriKind.Absolute);
return RedirectionStatus.ShouldRedirect;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl)
{
return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
// SPHostUrl
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest);
if (spHostUrl == null)
{
return null;
}
// SPAppWebUrl
string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]);
Uri spAppWebUrl;
if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) ||
!(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps))
{
spAppWebUrl = null;
}
// SPLanguage
string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey];
if (string.IsNullOrEmpty(spLanguage))
{
return null;
}
// SPClientTag
string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey];
if (string.IsNullOrEmpty(spClientTag))
{
return null;
}
// SPProductNumber
string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey];
if (string.IsNullOrEmpty(spProductNumber))
{
return null;
}
return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequest httpRequest)
{
return CreateSharePointContext(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return null;
}
SharePointContext spContext = LoadSharePointContext(httpContext);
if (spContext == null || !ValidateSharePointContext(spContext, httpContext))
{
spContext = CreateSharePointContext(httpContext.Request);
if (spContext != null)
{
SaveSharePointContext(spContext, httpContext);
}
}
return spContext;
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContext httpContext)
{
return GetSharePointContext(new HttpContextWrapper(httpContext));
}
/// <summary>
/// Creates a SharePointContext instance.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest);
/// <summary>
/// Validates if the given SharePointContext can be used with the specified HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext.</param>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns>
protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
/// <summary>
/// Loads the SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns>
protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext);
/// <summary>
/// Saves the specified SharePointContext instance associated with the specified HTTP context.
/// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param>
/// <param name="httpContext">The HTTP context.</param>
protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
}
#region ACS
/// <summary>
/// Encapsulates all the information from SharePoint in ACS mode.
/// </summary>
public class SharePointAcsContext : SharePointContext
{
private readonly string contextToken;
private readonly SharePointContextToken contextTokenObj;
/// <summary>
/// The context token.
/// </summary>
public string ContextToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; }
}
/// <summary>
/// The context token's "CacheKey" claim.
/// </summary>
public string CacheKey
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; }
}
/// <summary>
/// The context token's "refreshtoken" claim.
/// </summary>
public string RefreshToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl)));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl)));
}
}
public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (string.IsNullOrEmpty(contextToken))
{
throw new ArgumentNullException("contextToken");
}
if (contextTokenObj == null)
{
throw new ArgumentNullException("contextTokenObj");
}
this.contextToken = contextToken;
this.contextTokenObj = contextTokenObj;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
try
{
OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler();
DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn;
if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn);
}
catch (WebException)
{
}
}
}
/// <summary>
/// Default provider for SharePointAcsContext.
/// </summary>
public class SharePointAcsContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
private const string SPCacheKeyKey = "SPCacheKey";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest);
if (string.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = null;
try
{
contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority);
}
catch (WebException)
{
return null;
}
catch (AudienceUriValidationFailedException)
{
return null;
}
return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request);
HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey];
string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null;
return spHostUrl == spAcsContext.SPHostUrl &&
!string.IsNullOrEmpty(spAcsContext.CacheKey) &&
spCacheKey == spAcsContext.CacheKey &&
!string.IsNullOrEmpty(spAcsContext.ContextToken) &&
(string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken);
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointAcsContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey)
{
Value = spAcsContext.CacheKey,
Secure = true,
HttpOnly = true
};
httpContext.Response.AppendCookie(spCacheKeyCookie);
}
httpContext.Session[SPContextKey] = spAcsContext;
}
}
#endregion ACS
#region HighTrust
/// <summary>
/// Encapsulates all the information from SharePoint in HighTrust mode.
/// </summary>
public class SharePointHighTrustContext : SharePointContext
{
private readonly WindowsIdentity logonUserIdentity;
/// <summary>
/// The Windows identity for the current user.
/// </summary>
public WindowsIdentity LogonUserIdentity
{
get { return this.logonUserIdentity; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null));
}
}
public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (logonUserIdentity == null)
{
throw new ArgumentNullException("logonUserIdentity");
}
this.logonUserIdentity = logonUserIdentity;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime);
if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn);
}
}
/// <summary>
/// Default provider for SharePointHighTrustContext.
/// </summary>
public class SharePointHighTrustContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity;
if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null)
{
return null;
}
return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext;
if (spHighTrustContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity;
return spHostUrl == spHighTrustContext.SPHostUrl &&
logonUserIdentity != null &&
logonUserIdentity.IsAuthenticated &&
!logonUserIdentity.IsGuest &&
logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User;
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointHighTrustContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext;
}
}
#endregion HighTrust
}
| |
using System;
using System.Threading;
using System.Threading.Tasks;
using Htc.Vita.Core.Log;
namespace Htc.Vita.Core.Auth
{
public static partial class OAuth2
{
public abstract partial class AuthorizationCodeClient
{
/// <summary>
/// Authorizes this instance.
/// </summary>
/// <returns>Task<AuthorizeResult>.</returns>
public Task<AuthorizeResult> AuthorizeAsync()
{
return AuthorizeAsync(CancellationToken.None);
}
/// <summary>
/// Authorizes this instance.
/// </summary>
/// <param name="cancellationToken">The cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <returns>A Task<AuthorizeResult> representing the asynchronous operation.</returns>
public async Task<AuthorizeResult> AuthorizeAsync(CancellationToken cancellationToken)
{
AuthorizeResult result = null;
try
{
result = await OnAuthorizeAsync(cancellationToken).ConfigureAwait(false);
}
catch (Exception e)
{
Logger.GetInstance(typeof(AuthorizationCodeClient)).Error(e.ToString());
}
return result ?? new AuthorizeResult();
}
/// <summary>
/// Introspects the token.
/// </summary>
/// <param name="token">The token.</param>
/// <returns>Task<IntrospectTokenResult>.</returns>
public Task<IntrospectTokenResult> IntrospectTokenAsync(ClientTokenInfo token)
{
return IntrospectTokenAsync(
token,
CancellationToken.None
);
}
/// <summary>
/// Introspects the token.
/// </summary>
/// <param name="token">The token.</param>
/// <param name="cancellationToken">The cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <returns>A Task<IntrospectTokenResult> representing the asynchronous operation.</returns>
public async Task<IntrospectTokenResult> IntrospectTokenAsync(
ClientTokenInfo token,
CancellationToken cancellationToken)
{
if (token == null || string.IsNullOrWhiteSpace(token.AccessToken))
{
return new IntrospectTokenResult
{
Status = IntrospectTokenStatus.InvalidToken
};
}
IntrospectTokenResult result = null;
try
{
result = await OnIntrospectTokenAsync(
token,
cancellationToken
).ConfigureAwait(false);
}
catch (Exception e)
{
Logger.GetInstance(typeof(AuthorizationCodeClient)).Error(e.ToString());
}
return result ?? new IntrospectTokenResult();
}
/// <summary>
/// Introspects the token.
/// </summary>
/// <param name="accessTokenString">The access token string.</param>
/// <returns>Task<IntrospectTokenResult>.</returns>
public Task<IntrospectTokenResult> IntrospectTokenAsync(string accessTokenString)
{
return IntrospectTokenAsync(
accessTokenString,
CancellationToken.None
);
}
/// <summary>
/// Introspects the token.
/// </summary>
/// <param name="accessTokenString">The access token string.</param>
/// <param name="cancellationToken">The cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <returns>Task<IntrospectTokenResult>.</returns>
public Task<IntrospectTokenResult> IntrospectTokenAsync(
string accessTokenString,
CancellationToken cancellationToken)
{
return IntrospectTokenAsync(
new ClientTokenInfo
{
AccessToken = accessTokenString
},
cancellationToken
);
}
/// <summary>
/// Redeems the token.
/// </summary>
/// <param name="authorizationCode">The authorization code.</param>
/// <returns>Task<RedeemTokenResult>.</returns>
public Task<RedeemTokenResult> RedeemTokenAsync(string authorizationCode)
{
return RedeemTokenAsync(
authorizationCode,
CancellationToken.None
);
}
/// <summary>
/// Redeems the token.
/// </summary>
/// <param name="authorizationCode">The authorization code.</param>
/// <param name="cancellationToken">The cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <returns>A Task<RedeemTokenResult> representing the asynchronous operation.</returns>
public async Task<RedeemTokenResult> RedeemTokenAsync(
string authorizationCode,
CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(authorizationCode))
{
return new RedeemTokenResult
{
Status = RedeemTokenStatus.InvalidAuthorizationCode
};
}
RedeemTokenResult result = null;
try
{
result = await OnRedeemTokenAsync(
authorizationCode,
cancellationToken
).ConfigureAwait(false);
}
catch (Exception e)
{
Logger.GetInstance(typeof(AuthorizationCodeClient)).Error(e.ToString());
}
return result ?? new RedeemTokenResult();
}
/// <summary>
/// Refreshes the token.
/// </summary>
/// <param name="token">The token.</param>
/// <returns>Task<RefreshTokenResult>.</returns>
public Task<RefreshTokenResult> RefreshTokenAsync(ClientTokenInfo token)
{
return RefreshTokenAsync(
token,
CancellationToken.None
);
}
/// <summary>
/// Refreshes the token.
/// </summary>
/// <param name="token">The token.</param>
/// <param name="cancellationToken">The cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <returns>A Task<RefreshTokenResult> representing the asynchronous operation.</returns>
public async Task<RefreshTokenResult> RefreshTokenAsync(
ClientTokenInfo token,
CancellationToken cancellationToken)
{
if (token == null || string.IsNullOrWhiteSpace(token.RefreshToken))
{
return new RefreshTokenResult
{
Status = RefreshTokenStatus.InvalidToken
};
}
RefreshTokenResult result = null;
try
{
result = await OnRefreshTokenAsync(
token,
cancellationToken
).ConfigureAwait(false);
}
catch (Exception e)
{
Logger.GetInstance(typeof(AuthorizationCodeClient)).Error(e.ToString());
}
return result ?? new RefreshTokenResult();
}
/// <summary>
/// Refreshes the token.
/// </summary>
/// <param name="refreshTokenString">The refresh token string.</param>
/// <returns>Task<RefreshTokenResult>.</returns>
public Task<RefreshTokenResult> RefreshTokenAsync(string refreshTokenString)
{
return RefreshTokenAsync(
refreshTokenString,
CancellationToken.None
);
}
/// <summary>
/// Refreshes the token.
/// </summary>
/// <param name="refreshTokenString">The refresh token string.</param>
/// <param name="cancellationToken">The cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <returns>Task<RefreshTokenResult>.</returns>
public Task<RefreshTokenResult> RefreshTokenAsync(
string refreshTokenString,
CancellationToken cancellationToken)
{
return RefreshTokenAsync(
new ClientTokenInfo
{
RefreshToken = refreshTokenString
},
cancellationToken
);
}
/// <summary>
/// Called when authorizing this instance.
/// </summary>
/// <param name="cancellationToken">The cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <returns>Task<AuthorizeResult>.</returns>
protected abstract Task<AuthorizeResult> OnAuthorizeAsync(CancellationToken cancellationToken);
/// <summary>
/// Called when introspecting token.
/// </summary>
/// <param name="token">The token.</param>
/// <param name="cancellationToken">The cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <returns>Task<IntrospectTokenResult>.</returns>
protected abstract Task<IntrospectTokenResult> OnIntrospectTokenAsync(
ClientTokenInfo token,
CancellationToken cancellationToken
);
/// <summary>
/// Called when redeeming token.
/// </summary>
/// <param name="authorizationCode">The authorization code.</param>
/// <param name="cancellationToken">The cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <returns>Task<RedeemTokenResult>.</returns>
protected abstract Task<RedeemTokenResult> OnRedeemTokenAsync(
string authorizationCode,
CancellationToken cancellationToken
);
/// <summary>
/// Called when refreshing token.
/// </summary>
/// <param name="token">The token.</param>
/// <param name="cancellationToken">The cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <returns>Task<RefreshTokenResult>.</returns>
protected abstract Task<RefreshTokenResult> OnRefreshTokenAsync(
ClientTokenInfo token,
CancellationToken cancellationToken
);
}
}
}
| |
/* $Id$
*
* Project: Swicli.Library - Two Way Interface for .NET and MONO to SWI-Prolog
* Author: Douglas R. Miles
* E-mail: [email protected]
* WWW: http://www.logicmoo.com
* Copyright (C): 2010-2012 LogicMOO Developement
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*********************************************************/
using System;
using System.Collections;
using System.Runtime.InteropServices;
#if USE_IKVM
/*
using ikvm.extensions;
using IKVM.Internal;
using ikvm.runtime;
using java.net;
using java.util;*/
//using jpl;
//using jpl;
using Hashtable = java.util.Hashtable;
using ClassLoader = java.lang.ClassLoader;
//using sun.reflect.misc;
//using Util = ikvm.runtime.Util;
using Exception = System.Exception;
//using JClass = java.lang.JClass;
using Type = System.Type;
#else
using System;
using JClass = System.Type;
#endif
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Reflection.Emit;
using PlTerm = SbsSW.SwiPlCs.PlTerm;
namespace Swicli.Library
{
}
namespace Swicli.Library
{
public partial class PrologCLR
{
static public bool ManagedHalt()
{
KillPrologThreads();
Environment.Exit(0);
return true;
}
static private Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
var domain = (AppDomain)sender;
foreach (var assembly in CopyOf(domain.GetAssemblies()))
{
if (assembly.FullName == args.Name)
return assembly;
if (assembly.ManifestModule.Name == args.Name)
return assembly;
}
foreach (Assembly assembly in CopyOf(AssembliesLoaded))
{
if (assembly.FullName == args.Name)
return assembly;
if (assembly.ManifestModule.Name == args.Name)
return assembly;
}
string assemblyName = args.Name;
int comma = assemblyName.IndexOf(",");
if (comma > 0)
{
assemblyName = assemblyName.Substring(0, comma);
}
return LoadAssemblyByFile(assemblyName);
}
public static Assembly LoadAssemblyByFile(string assemblyName)
{
if (File.Exists(assemblyName))
{
try
{
var fi = new FileInfo(assemblyName);
if (fi.Exists) return Assembly.LoadFile(fi.FullName);
}
catch (Exception)
{
throw;
}
}
IList<string> sp = CopyOf((IEnumerable<string>)AssemblySearchPaths);
foreach (var dir in new[] { AppDomain.CurrentDomain.BaseDirectory, new DirectoryInfo(".").FullName, Path.GetDirectoryName(typeof(PrologCLR).Assembly.CodeBase),Environment.CurrentDirectory })
{
if (!sp.Contains(dir)) sp.Add(dir);
}
string lastTested = "";
foreach (var s in CopyOf(AppDomain.CurrentDomain.GetAssemblies()))
{
try
{
if (s is AssemblyBuilder) continue;
string dir = Path.GetDirectoryName(s.CodeBase);
if (dir.StartsWith("file:\\"))
{
dir = dir.Substring(6);
}
if (dir.StartsWith("file://"))
{
dir = dir.Substring(7);
}
if (dir == lastTested) continue;
lastTested = dir;
if (!sp.Contains(dir)) sp.Add(dir);
}
catch (NotSupportedException)
{
// Reflected Assemblies do this
}
}
foreach (string pathname in sp)
{
var assemj = FindAssemblyByPath(assemblyName, pathname);
if (assemj != null) return assemj;
}
return null;
}
private static string NormalizePath(string dirname1)
{
string dirname = dirname1;
if (dirname.StartsWith("file:\\"))
{
dirname = dirname.Substring(6);
}
if (dirname.StartsWith("file://"))
{
dirname = dirname.Substring(7);
}
dirname = new FileInfo(dirname).FullName;
if (dirname != dirname1)
{
return dirname;
}
return dirname1;
}
private static readonly List<string> LoaderExtensionStrings = new List<string> { "dll", "exe", "jar", "lib", "dynlib", "class", "so" };
public static Assembly FindAssemblyByPath(string assemblyName, string dirname)
{
dirname = NormalizePath(dirname);
string filename = Path.Combine(dirname, assemblyName);
string loadfilename = filename;
bool tryexts = !File.Exists(loadfilename);
string filenameLower = filename.ToLower();
List<string> LoaderExtensions = new List<string>();
lock (LoaderExtensionStrings)
{
LoaderExtensions.AddRange(LoaderExtensionStrings);
}
foreach (string extension in LoaderExtensions)
{
if (filenameLower.EndsWith("." + extension))
{
tryexts = false;
break;
}
}
if (tryexts)
{
foreach (var s in LoaderExtensions)
{
string testfile = loadfilename + "." + s;
if (File.Exists(testfile))
{
loadfilename = testfile;
break;
}
}
}
if (File.Exists(loadfilename))
{
try
{
return Assembly.LoadFile(new FileInfo(loadfilename).FullName);
}
catch (Exception)
{
throw;
}
}
return null;
}
public static Assembly AssemblyLoad(string assemblyName)
{
Assembly assembly = null;
try
{
assembly = Assembly.Load(assemblyName);
}
catch (FileNotFoundException fnf)
{
if (fnf.FileName != assemblyName) throw fnf;
}
catch (Exception)
{
throw;
}
if (assembly != null) return assembly;
assembly = LoadAssemblyByFile(assemblyName);
if (assembly != null) return assembly;
return Assembly.LoadFrom(assemblyName);
}
public static List<string> AssemblySearchPaths = new List<string>();
public static List<Assembly> AssembliesLoaded = new List<Assembly>();
public static List<string> AssembliesLoading = new List<string>();
//public static List<Type> TypesLoaded = new List<Type>();
public static List<Type> TypesMethodsLoaded = new List<Type>();
public static List<Type> TypesLoading = new List<Type>();
public static bool ResolveAssembly(Assembly assembly)
{
string assemblyName = assembly.FullName;
lock (AssembliesLoaded)
{
if (AssembliesLoading.Contains(assemblyName))
{
return true;
}
AssembliesLoading.Add(assemblyName);
LoadReferencedAssemblies(assembly);
// push to the front
AssembliesLoaded.Remove(assembly);
AssembliesLoaded.Insert(0, assembly);
}
return true;
}
private static void LoadReferencedAssemblies(Assembly assembly)
{
foreach (var refed in assembly.GetReferencedAssemblies())
{
string assemblyName = refed.FullName;
try
{
Assembly assemblyLoad = Assembly.Load(refed);
ResolveAssembly(assemblyLoad);
continue;
}
catch (Exception e)
{
var top = Path.Combine(Path.GetDirectoryName(assembly.Location), refed.Name);
try
{
Assembly assemblyLoad = Assembly.LoadFrom(top + ".dll");
ResolveAssembly(assemblyLoad);
continue;
}
catch (Exception)
{
}
try
{
Assembly assemblyLoad = Assembly.LoadFrom(top + ".exe");
ResolveAssembly(assemblyLoad);
continue;
}
catch (Exception)
{
}
Embedded.Warn("LoadReferencedAssemblies:{0} caused {1}", assemblyName, e);
}
}
}
[PrologVisible]
public static void cliLoadAssemblyMethods(Assembly assembly, bool onlyAttributed, string requiredPrefix)
{
string assemblyName = assembly.FullName;
try
{
foreach (Type t in assembly.GetTypes())
{
try
{
AddForeignMethods(t, onlyAttributed, requiredPrefix);
}
catch (Exception te)
{
// Warn(e.Message);
}
}
}
catch (Exception e)
{
// get types problem
// Warn(e.Message);
}
}
/// <summary>
/// cliLoadAssembly('SwiPlCs.dll').
/// cliLoadAssembly('Cogbot.exe').
/// </summary>
/// <param name="term1"></param>
/// <returns></returns>
public static bool cliLoadAssembly(PlTerm term1)
{
PingThreadFactories();
try
{
return cliLoadAssemblyUncaught(term1);
}
catch (Exception e)
{
Embedded.Warn("cliLoadAssembly: {0} caused {1}", term1, e);
return false;
}
}
/// <summary>
/// ?- cliAddAssemblySearchPath('.').
/// </summary>
/// <param name="term1"></param>
/// <returns></returns>
public static bool cliAddAssemblySearchPath(PlTerm term1)
{
PingThreadFactories();
try
{
string name = AsString(term1);
AddAssemblySearchPath(name);
}
catch (Exception e)
{
Embedded.Warn("cliAddAssemblySearchPath: {0} caused {1}", term1, e);
return false;
}
return true;
}
public static bool AddAssemblySearchPath(String name)
{
lock (AssemblySearchPaths)
{
if (!AssemblySearchPaths.Contains(name))
{
AssemblySearchPaths.Add(name);
return true;
}
}
return false;
}
/// <summary>
/// cliRemoveAssemblySearchPath('.').
/// </summary>
/// <param name="term1"></param>
/// <returns></returns>
public static bool cliRemoveAssemblySearchPath(PlTerm term1)
{
PingThreadFactories();
try
{
string name = AsString(term1);
lock (AssemblySearchPaths)
{
AssemblySearchPaths.Remove(name);
}
}
catch (Exception e)
{
Embedded.Warn("cliRemoveAssemblySearchPath: {0} caused {1}", term1, e);
return false;
}
return true;
}
private static string AsString(PlTerm term1)
{
if (term1.IsVar)
{
Embedded.Warn("AsString IsVar {0}", term1);
return null;
}
if (IsTaggedObject(term1))
{
var obj = GetInstance(term1);
if (obj != null) return "" + obj;
}
if (term1.IsCompound) return term1.Name;
if (term1.IsString) return (string)term1;
if (term1.IsAtomOrNil) return term1.Name;
return (string)term1;
}
public static bool cliLoadAssemblyUncaught(PlTerm term1)
{
try
{
if (term1.IsVar)
{
Embedded.Warn("cliLoadAssembly IsVar {0}", term1);
return false;
}
if (IsTaggedObject(term1))
{
var assemblyOrType = GetInstance(term1);
if (assemblyOrType is Assembly)
{
return ResolveAssembly((Assembly)assemblyOrType);
}
if (assemblyOrType is Type)
{
return ResolveAssembly(((Type)assemblyOrType).Assembly);
}
return Embedded.Warn("Cannot get assembly from {0} for {1}", assemblyOrType, term1);
}
string name = term1.Name;
Assembly assembly = null;
try
{
assembly = AssemblyLoad(name);
if (assembly != null) return ResolveAssembly(assembly);
}
catch (Exception e)
{
//Warn("Load: " + name + " caused " + e);
}
var fi = new FileInfo(name);
if (fi.Exists)
{
string fiFullName = fi.FullName;
try
{
assembly = Assembly.LoadFile(fiFullName);
if (assembly != null) return ResolveAssembly(assembly);
}
catch (Exception e)
{
Embedded.Warn("LoadFile: {0} caused {1}", fiFullName, e);
}
}
try
{
if (assembly == null) assembly = Assembly.LoadWithPartialName(name);
}
catch (Exception e)
{
Embedded.Warn("LoadWithPartialName: {0} caused {1}", name, e);
}
if (assembly == null) return Embedded.Warn("Cannot get assembly from {0} for {1}", name, term1);
return ResolveAssembly(assembly);
}
catch (Exception exception)
{
throw ToPlException(exception);
}
return true;
}
public static IList<T> CopyOf<T>(List<T> list)
{
if (list == null) return new List<T>();
lock (list)
{
return list.ToArray();
}
}
public static IEnumerable<object> CopyOf<T>(ICollection list)
{
var copy = new List<object>();
if (list == null) return copy;
lock (list)
{
foreach (var o in copy)
{
copy.Add(o);
}
}
return copy;
}
public static IList<T> CopyOf<T>(IEnumerable<T> list)
{
var copy = new List<T>();
if (list == null) return copy;
lock (list)
{
copy.AddRange(list);
}
return copy;
}
public static IDictionary<K, V> CopyOf<K, V>(IDictionary<K, V> list)
{
var copy = new Dictionary<K, V>();
if (list == null) return copy;
lock (list)
{
foreach (var kv in list)
{
copy.Add(kv.Key, kv.Value);
}
}
return copy;
}
internal static bool BP()
{
return false;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace IncidentCS
{
public class GeoRandomizer : IGeoRandomizer
{
private static IRandomWheel<string> countryWheel;
private static IRandomWheel<string> stateWheel;
private static IRandomWheel<string> cityWheel;
private static string[] countries;
private static string[] streetSuffixes;
private static string[] shortStreetSuffixes;
private string base32alphabet = "0123456789bcdefghjkmnpqrstuvwxyz";
public virtual string Address
{
get
{
return string.Format("{0} {1}", Incident.Primitive.IntegerBetween(5, 2000), Street).Capitalize();
}
}
public virtual string FullAddress
{
get
{
return string.Format("{0} {1}, {2} {3}, {4}",
Incident.Primitive.IntegerBetween(5, 2000), Street, ZIP, City, Country).Capitalize();
}
}
public virtual string Street
{
get
{
if (streetSuffixes == null)
{
streetSuffixes = "StreetSuffixes.txt".LinesFromResource().ToArray();
shortStreetSuffixes = "ShortStreetSuffixes.txt".LinesFromResource().ToArray();
}
string name = Incident.Primitive.DoubleUnit < 0.75
? Incident.Text.Word
: string.Format("{0} {1}", Incident.Text.Word, Incident.Text.Word);
string suffix = Incident.Primitive.Boolean
? streetSuffixes.ChooseAtRandom()
: shortStreetSuffixes.ChooseAtRandom();
return string.Format("{0} {1}", name, suffix).Capitalize();
}
}
public virtual string ZIP
{
get
{
return Incident.Primitive.IntegerBetween(10000, 100000).ToString();
}
}
public virtual string PostalCode
{
get
{
return Incident.Primitive.IntegerBetween(1000, 100000).ToString();
}
}
public virtual string City
{
get
{
if (cityWheel == null)
{
cityWheel = Incident.Utils.CreateWheel(new Dictionary<String, double>()
{
{ "{0}", 10 },
{ "City of {0}", 4 },
{ "{0}ville", 3 },
{ "New {0}", 1 },
{ "{0} Town", 1 },
{ "District of {0}", 1 },
{ "Old {0}", 1 },
});
}
string name = Incident.Primitive.DoubleUnit < 0.75
? Incident.Text.Word
: string.Format("{0} {1}", Incident.Text.Word, Incident.Text.Word);
return string.Format(cityWheel.RandomElement, name).Capitalize();
}
}
public virtual string State
{
get
{
if (stateWheel == null)
{
stateWheel = Incident.Utils.CreateWheel(new Dictionary<String, double>()
{
{ "{0}", 5 },
{ "{0}ia", 5 },
{ "{0} State", 2 },
{ "State of {0}", 2 },
{ "West {0}", 1 },
{ "South {0}", 1 },
{ "North {0}", 1 },
{ "East {0}", 1 },
});
}
return string.Format(stateWheel.RandomElement, Incident.Text.Word).Capitalize();
}
}
public virtual string Country
{
get
{
if (countries == null)
countries = "Countries.txt".LinesFromResource().ToArray();
return countries.ChooseAtRandom();
}
}
public virtual string ImaginaryCountry
{
get
{
if (countryWheel == null)
{
countryWheel = Incident.Utils.CreateWheel(new Dictionary<String, double>()
{
{ "{0}", 5 },
{ "{0}ia", 5 },
{ "{0} Republic", 4 },
{ "Republic of {0}", 4 },
{ "Land of {0}", 4 },
{ "{0} Islands", 4 },
{ "Democratic Republic of {0}", 4 },
{ "{0} Federation", 3 },
{ "State of {0}", 3 },
{ "{0}stan", 2 },
{ "West {0}", 2 },
{ "South {0}", 2 },
{ "North {0}", 2 },
{ "East {0}", 2 },
{ "{0} Territory", 2 },
{ "United States of {0}", 1 },
});
}
return string.Format(countryWheel.RandomElement, Incident.Text.Word).Capitalize();
}
}
public virtual double Altitude
{
get
{
return CustomAltitude(5);
}
}
public virtual double CustomAltitude(int precision)
{
return Math.Round(Incident.Primitive.DoubleBetween(0, 8848), precision);
}
public virtual double Depth
{
get
{
return CustomDepth(5);
}
}
public virtual double CustomDepth(int precision)
{
return Math.Round(-1 * Incident.Primitive.DoubleBetween(0, 11034), precision);
}
public virtual double Latitude
{
get
{
return CustomLatitude(5);
}
}
public virtual double CustomLatitude(int precision)
{
return Math.Round(Incident.Primitive.DoubleBetween(-90, 90), precision);
}
public virtual double Longitude
{
get
{
return CustomLongitude(5);
}
}
public virtual double CustomLongitude(int precision)
{
return Math.Round(Incident.Primitive.DoubleBetween(-180, 180), precision);
}
public virtual string Coordinates
{
get
{
return CustomCoordinates(5);
}
}
public virtual string CustomCoordinates(int precision)
{
return string.Format("{0}, {1}", CustomLatitude(precision), CustomLongitude(precision));
}
public virtual string GeoHash
{
get
{
int precision = Incident.Primitive.IntegerBetween(5, 10);
return Enumerable.Range(0, precision)
.Select(_ => base32alphabet.ChooseAtRandom())
.StringJoin();
}
}
}
}
| |
namespace SandcastleBuilder.Gui
{
partial class NewFromOtherFormatDlg
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if(disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.txtProjectFile = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.btnSelectProject = new System.Windows.Forms.Button();
this.txtNewProjectFolder = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.btnSelectNewFolder = new System.Windows.Forms.Button();
this.btnConvert = new System.Windows.Forms.Button();
this.btnCancel = new System.Windows.Forms.Button();
this.statusBarTextProvider1 = new SandcastleBuilder.Utils.Controls.StatusBarTextProvider(this.components);
this.cboProjectFormat = new System.Windows.Forms.ComboBox();
this.toolTip1 = new System.Windows.Forms.ToolTip(this.components);
this.epErrors = new System.Windows.Forms.ErrorProvider(this.components);
this.label3 = new System.Windows.Forms.Label();
this.btnHelp = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.epErrors)).BeginInit();
this.SuspendLayout();
//
// txtProjectFile
//
this.txtProjectFile.Location = new System.Drawing.Point(218, 42);
this.txtProjectFile.Name = "txtProjectFile";
this.txtProjectFile.Size = new System.Drawing.Size(452, 22);
this.statusBarTextProvider1.SetStatusBarText(this.txtProjectFile, "Project to Convert: Specify the project file to convert");
this.txtProjectFile.TabIndex = 3;
//
// label1
//
this.label1.Location = new System.Drawing.Point(71, 42);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(141, 23);
this.label1.TabIndex = 2;
this.label1.Text = "&Project to Convert";
this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// btnSelectProject
//
this.btnSelectProject.Location = new System.Drawing.Point(671, 41);
this.btnSelectProject.Name = "btnSelectProject";
this.btnSelectProject.Size = new System.Drawing.Size(32, 25);
this.statusBarTextProvider1.SetStatusBarText(this.btnSelectProject, "Browse: Browse for the project to convert");
this.btnSelectProject.TabIndex = 4;
this.btnSelectProject.Text = "...";
this.toolTip1.SetToolTip(this.btnSelectProject, "Select project to convert");
this.btnSelectProject.UseVisualStyleBackColor = true;
this.btnSelectProject.Click += new System.EventHandler(this.btnSelectProject_Click);
//
// txtNewProjectFolder
//
this.txtNewProjectFolder.Location = new System.Drawing.Point(218, 72);
this.txtNewProjectFolder.Name = "txtNewProjectFolder";
this.txtNewProjectFolder.Size = new System.Drawing.Size(452, 22);
this.statusBarTextProvider1.SetStatusBarText(this.txtNewProjectFolder, "New Project Location: Specify the folder to use for the new project");
this.txtNewProjectFolder.TabIndex = 6;
//
// label2
//
this.label2.Location = new System.Drawing.Point(13, 72);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(199, 23);
this.label2.TabIndex = 5;
this.label2.Text = "&Location of New Project File";
this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// btnSelectNewFolder
//
this.btnSelectNewFolder.Location = new System.Drawing.Point(671, 71);
this.btnSelectNewFolder.Name = "btnSelectNewFolder";
this.btnSelectNewFolder.Size = new System.Drawing.Size(32, 25);
this.statusBarTextProvider1.SetStatusBarText(this.btnSelectNewFolder, "Browse: Browse for the new folder location");
this.btnSelectNewFolder.TabIndex = 7;
this.btnSelectNewFolder.Text = "...";
this.toolTip1.SetToolTip(this.btnSelectNewFolder, "Select folder for the converted project files");
this.btnSelectNewFolder.UseVisualStyleBackColor = true;
this.btnSelectNewFolder.Click += new System.EventHandler(this.btnSelectNewFolder_Click);
//
// btnConvert
//
this.btnConvert.Location = new System.Drawing.Point(12, 114);
this.btnConvert.Name = "btnConvert";
this.btnConvert.Size = new System.Drawing.Size(88, 32);
this.statusBarTextProvider1.SetStatusBarText(this.btnConvert, "Convert: Convert the project to the new format");
this.btnConvert.TabIndex = 8;
this.btnConvert.Text = "&Convert";
this.toolTip1.SetToolTip(this.btnConvert, "Convert the project");
this.btnConvert.UseVisualStyleBackColor = true;
this.btnConvert.Click += new System.EventHandler(this.btnConvert_Click);
//
// btnCancel
//
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnCancel.Location = new System.Drawing.Point(634, 114);
this.btnCancel.Name = "btnCancel";
this.btnCancel.Size = new System.Drawing.Size(88, 32);
this.statusBarTextProvider1.SetStatusBarText(this.btnCancel, "Cancel: Close without converting the project");
this.btnCancel.TabIndex = 10;
this.btnCancel.Text = "Cancel";
this.toolTip1.SetToolTip(this.btnCancel, "Close without converting");
this.btnCancel.UseVisualStyleBackColor = true;
this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
//
// cboProjectFormat
//
this.cboProjectFormat.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cboProjectFormat.FormattingEnabled = true;
this.cboProjectFormat.Items.AddRange(new object[] {
"SHFB 1.7.0.0 or earlier",
"NDoc 1.x",
"DocProject 1.x",
"Stephan Smetsers SandcastleGUI 1.x",
"Microsoft Sandcastle Example GUI"});
this.cboProjectFormat.Location = new System.Drawing.Point(218, 12);
this.cboProjectFormat.Name = "cboProjectFormat";
this.cboProjectFormat.Size = new System.Drawing.Size(274, 24);
this.statusBarTextProvider1.SetStatusBarText(this.cboProjectFormat, "Project Format: Select the format of the project to convert");
this.cboProjectFormat.TabIndex = 1;
//
// epErrors
//
this.epErrors.ContainerControl = this;
//
// label3
//
this.label3.Location = new System.Drawing.Point(71, 13);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(141, 23);
this.label3.TabIndex = 0;
this.label3.Text = "Project &Format";
this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// btnHelp
//
this.btnHelp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnHelp.Location = new System.Drawing.Point(540, 114);
this.btnHelp.Name = "btnHelp";
this.btnHelp.Size = new System.Drawing.Size(88, 32);
this.statusBarTextProvider1.SetStatusBarText(this.btnHelp, "Help: View help for this form");
this.btnHelp.TabIndex = 9;
this.btnHelp.Text = "&Help";
this.toolTip1.SetToolTip(this.btnHelp, "View help for this form");
this.btnHelp.UseVisualStyleBackColor = true;
this.btnHelp.Click += new System.EventHandler(this.btnHelp_Click);
//
// NewFromOtherFormatDlg
//
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Inherit;
this.CancelButton = this.btnCancel;
this.ClientSize = new System.Drawing.Size(734, 158);
this.Controls.Add(this.btnHelp);
this.Controls.Add(this.cboProjectFormat);
this.Controls.Add(this.label3);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.btnConvert);
this.Controls.Add(this.txtNewProjectFolder);
this.Controls.Add(this.label2);
this.Controls.Add(this.btnSelectNewFolder);
this.Controls.Add(this.txtProjectFile);
this.Controls.Add(this.label1);
this.Controls.Add(this.btnSelectProject);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "NewFromOtherFormatDlg";
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Create New Project From Other Format";
((System.ComponentModel.ISupportInitialize)(this.epErrors)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TextBox txtProjectFile;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button btnSelectProject;
private System.Windows.Forms.TextBox txtNewProjectFolder;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Button btnSelectNewFolder;
private System.Windows.Forms.Button btnConvert;
private System.Windows.Forms.Button btnCancel;
private SandcastleBuilder.Utils.Controls.StatusBarTextProvider statusBarTextProvider1;
private System.Windows.Forms.ToolTip toolTip1;
private System.Windows.Forms.ErrorProvider epErrors;
private System.Windows.Forms.ComboBox cboProjectFormat;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Button btnHelp;
}
}
| |
using System;
using System.Globalization;
using Umbraco.Core;
using Umbraco.Core.Models;
using UmbracoSettings = Umbraco.Core.Configuration.UmbracoSettings;
using Umbraco.Web.Configuration;
using umbraco;
using umbraco.cms.businesslogic.web;
namespace Umbraco.Web.Routing
{
/// <summary>
/// Represents a request for one specified Umbraco IPublishedContent to be rendered
/// by one specified template, using one specified Culture and RenderingEngine.
/// </summary>
public class PublishedContentRequest
{
private bool _readonly;
/// <summary>
/// Triggers once the published content request has been prepared, but before it is processed.
/// </summary>
/// <remarks>When the event triggers, preparation is done ie domain, culture, document, template,
/// rendering engine, etc. have been setup. It is then possible to change anything, before
/// the request is actually processed and rendered by Umbraco.</remarks>
public static event EventHandler<EventArgs> Prepared;
// the engine that does all the processing
// because in order to keep things clean and separated,
// the content request is just a data holder
private readonly PublishedContentRequestEngine _engine;
/// <summary>
/// Initializes a new instance of the <see cref="PublishedContentRequest"/> class with a specific Uri and routing context.
/// </summary>
/// <param name="uri">The request <c>Uri</c>.</param>
/// <param name="routingContext">A routing context.</param>
internal PublishedContentRequest(Uri uri, RoutingContext routingContext)
{
if (uri == null) throw new ArgumentNullException("uri");
if (routingContext == null) throw new ArgumentNullException("routingContext");
Uri = uri;
RoutingContext = routingContext;
_engine = new PublishedContentRequestEngine(this);
RenderingEngine = RenderingEngine.Unknown;
}
/// <summary>
/// Gets the engine associated to the request.
/// </summary>
internal PublishedContentRequestEngine Engine { get { return _engine; } }
/// <summary>
/// Prepares the request.
/// </summary>
internal void Prepare()
{
_engine.PrepareRequest();
}
/// <summary>
/// Updates the request when there is no template to render the content.
/// </summary>
internal void UpdateOnMissingTemplate()
{
var __readonly = _readonly;
_readonly = false;
_engine.UpdateRequestOnMissingTemplate();
_readonly = __readonly;
}
/// <summary>
/// Triggers the Prepared event.
/// </summary>
internal void OnPrepared()
{
if (Prepared != null)
Prepared(this, EventArgs.Empty);
if (!HasPublishedContent)
Is404 = true; // safety
_readonly = true;
}
/// <summary>
/// Gets or sets the cleaned up Uri used for routing.
/// </summary>
/// <remarks>The cleaned up Uri has no virtual directory, no trailing slash, no .aspx extension, etc.</remarks>
public Uri Uri { get; private set; }
private void EnsureWriteable()
{
if (_readonly)
throw new InvalidOperationException("Cannot modify a PublishedContentRequest once it is read-only.");
}
#region PublishedContent
/// <summary>
/// The requested IPublishedContent, if any, else <c>null</c>.
/// </summary>
private IPublishedContent _publishedContent;
/// <summary>
/// The initial requested IPublishedContent, if any, else <c>null</c>.
/// </summary>
/// <remarks>The initial requested content is the content that was found by the finders,
/// before anything such as 404, redirect... took place.</remarks>
private IPublishedContent _initialPublishedContent;
/// <summary>
/// Gets or sets the requested content.
/// </summary>
/// <remarks>Setting the requested content clears <c>Template</c>.</remarks>
public IPublishedContent PublishedContent
{
get { return _publishedContent; }
set
{
EnsureWriteable();
_publishedContent = value;
IsInternalRedirectPublishedContent = false;
TemplateModel = null;
}
}
/// <summary>
/// Sets the requested content, following an internal redirect.
/// </summary>
/// <param name="content">The requested content.</param>
/// <remarks>Depending on <c>UmbracoSettings.InternalRedirectPreservesTemplate</c>, will
/// preserve or reset the template, if any.</remarks>
public void SetInternalRedirectPublishedContent(IPublishedContent content)
{
EnsureWriteable();
// unless a template has been set already by the finder,
// template should be null at that point.
// IsInternalRedirect if IsInitial, or already IsInternalRedirect
var isInternalRedirect = IsInitialPublishedContent || IsInternalRedirectPublishedContent;
// redirecting to self
if (content.Id == PublishedContent.Id) // neither can be null
{
// no need to set PublishedContent, we're done
IsInternalRedirectPublishedContent = isInternalRedirect;
return;
}
// else
// save
var template = _template;
var renderingEngine = RenderingEngine;
// set published content - this resets the template, and sets IsInternalRedirect to false
PublishedContent = content;
IsInternalRedirectPublishedContent = isInternalRedirect;
// must restore the template if it's an internal redirect & the config option is set
if (isInternalRedirect && UmbracoSettings.For<WebRouting>().InternalRedirectPreservesTemplate)
{
// restore
_template = template;
RenderingEngine = renderingEngine;
}
}
/// <summary>
/// Gets the initial requested content.
/// </summary>
/// <remarks>The initial requested content is the content that was found by the finders,
/// before anything such as 404, redirect... took place.</remarks>
public IPublishedContent InitialPublishedContent { get { return _initialPublishedContent; } }
/// <summary>
/// Gets value indicating whether the current published content is the initial one.
/// </summary>
public bool IsInitialPublishedContent
{
get
{
return _initialPublishedContent != null && _initialPublishedContent == _publishedContent;
}
}
/// <summary>
/// Indicates that the current PublishedContent is the initial one.
/// </summary>
public void SetIsInitialPublishedContent()
{
EnsureWriteable();
// note: it can very well be null if the initial content was not found
_initialPublishedContent = _publishedContent;
IsInternalRedirectPublishedContent = false;
}
/// <summary>
/// Gets or sets a value indicating whether the current published content has been obtained
/// from the initial published content following internal redirections exclusively.
/// </summary>
/// <remarks>Used by PublishedContentRequestEngine.FindTemplate() to figure out whether to
/// apply the internal redirect or not, when content is not the initial content.</remarks>
public bool IsInternalRedirectPublishedContent { get; private set; }
/// <summary>
/// Gets a value indicating whether the content request has a content.
/// </summary>
public bool HasPublishedContent
{
get { return PublishedContent != null; }
}
#endregion
#region Template
/// <summary>
/// The template model, if any, else <c>null</c>.
/// </summary>
private ITemplate _template;
/// <summary>
/// Gets or sets the template model to use to display the requested content.
/// </summary>
internal ITemplate TemplateModel
{
get
{
return _template;
}
set
{
_template = value;
RenderingEngine = RenderingEngine.Unknown; // reset
if (_template != null)
RenderingEngine = _engine.FindTemplateRenderingEngine(_template.Alias);
}
}
/// <summary>
/// Gets the alias of the template to use to display the requested content.
/// </summary>
public string TemplateAlias
{
get
{
return _template == null ? null : _template.Alias;
}
}
/// <summary>
/// Tries to set the template to use to display the requested content.
/// </summary>
/// <param name="alias">The alias of the template.</param>
/// <returns>A value indicating whether a valid template with the specified alias was found.</returns>
/// <remarks>
/// <para>Successfully setting the template does refresh <c>RenderingEngine</c>.</para>
/// <para>If setting the template fails, then the previous template (if any) remains in place.</para>
/// </remarks>
public bool TrySetTemplate(string alias)
{
EnsureWriteable();
if (string.IsNullOrWhiteSpace(alias))
{
TemplateModel = null;
return true;
}
// NOTE - can we stil get it with whitespaces in it due to old legacy bugs?
alias = alias.Replace(" ", "");
var model = ApplicationContext.Current.Services.FileService.GetTemplate(alias);
if (model == null)
return false;
TemplateModel = model;
return true;
}
/// <summary>
/// Sets the template to use to display the requested content.
/// </summary>
/// <param name="template">The template.</param>
/// <remarks>Setting the template does refresh <c>RenderingEngine</c>.</remarks>
public void SetTemplate(ITemplate template)
{
EnsureWriteable();
TemplateModel = template;
}
/// <summary>
/// Gets a value indicating whether the content request has a template.
/// </summary>
public bool HasTemplate
{
get { return _template != null; }
}
#endregion
#region Domain and Culture
/// <summary>
/// Gets or sets the content request's domain.
/// </summary>
public Domain Domain { get; internal set; }
/// <summary>
/// Gets or sets the content request's domain Uri.
/// </summary>
/// <remarks>The <c>Domain</c> may contain "example.com" whereas the <c>Uri</c> will be fully qualified eg "http://example.com/".</remarks>
public Uri DomainUri { get; internal set; }
/// <summary>
/// Gets a value indicating whether the content request has a domain.
/// </summary>
public bool HasDomain
{
get { return Domain != null; }
}
private CultureInfo _culture;
/// <summary>
/// Gets or sets the content request's culture.
/// </summary>
public CultureInfo Culture
{
get { return _culture; }
set
{
EnsureWriteable();
_culture = value;
}
}
// note: do we want to have an ordered list of alternate cultures,
// to allow for fallbacks when doing dictionnary lookup and such?
#endregion
#region Rendering
/// <summary>
/// Gets or sets whether the rendering engine is MVC or WebForms.
/// </summary>
public RenderingEngine RenderingEngine { get; internal set; }
#endregion
/// <summary>
/// Gets or sets the current RoutingContext.
/// </summary>
public RoutingContext RoutingContext { get; private set; }
/// <summary>
/// The "umbraco page" object.
/// </summary>
private page _umbracoPage;
/// <summary>
/// Gets or sets the "umbraco page" object.
/// </summary>
/// <remarks>
/// This value is only used for legacy/webforms code.
/// </remarks>
internal page UmbracoPage
{
get
{
if (_umbracoPage == null)
throw new InvalidOperationException("The UmbracoPage object has not been initialized yet.");
return _umbracoPage;
}
set { _umbracoPage = value; }
}
#region Status
/// <summary>
/// Gets or sets a value indicating whether the requested content could not be found.
/// </summary>
/// <remarks>This is set in the <c>PublishedContentRequestBuilder</c>.</remarks>
public bool Is404 { get; internal set; }
/// <summary>
/// Indicates that the requested content could not be found.
/// </summary>
/// <remarks>This is for public access, in custom content finders or <c>Prepared</c> event handlers,
/// where we want to allow developers to indicate a request is 404 but not to cancel it.</remarks>
public void SetIs404()
{
EnsureWriteable();
Is404 = true;
}
/// <summary>
/// Gets a value indicating whether the content request triggers a redirect (permanent or not).
/// </summary>
public bool IsRedirect { get { return !string.IsNullOrWhiteSpace(RedirectUrl); } }
/// <summary>
/// Gets or sets a value indicating whether the redirect is permanent.
/// </summary>
public bool IsRedirectPermanent { get; private set; }
/// <summary>
/// Gets or sets the url to redirect to, when the content request triggers a redirect.
/// </summary>
public string RedirectUrl { get; private set; }
/// <summary>
/// Indicates that the content request should trigger a redirect (302).
/// </summary>
/// <param name="url">The url to redirect to.</param>
/// <remarks>Does not actually perform a redirect, only registers that the response should
/// redirect. Redirect will or will not take place in due time.</remarks>
public void SetRedirect(string url)
{
EnsureWriteable();
RedirectUrl = url;
IsRedirectPermanent = false;
}
/// <summary>
/// Indicates that the content request should trigger a permanent redirect (301).
/// </summary>
/// <param name="url">The url to redirect to.</param>
/// <remarks>Does not actually perform a redirect, only registers that the response should
/// redirect. Redirect will or will not take place in due time.</remarks>
public void SetRedirectPermanent(string url)
{
EnsureWriteable();
RedirectUrl = url;
IsRedirectPermanent = true;
}
/// <summary>
/// Indicates that the content requet should trigger a redirect, with a specified status code.
/// </summary>
/// <param name="url">The url to redirect to.</param>
/// <param name="status">The status code (300-308).</param>
/// <remarks>Does not actually perform a redirect, only registers that the response should
/// redirect. Redirect will or will not take place in due time.</remarks>
public void SetRedirect(string url, int status)
{
EnsureWriteable();
if (status < 300 || status > 308)
throw new ArgumentOutOfRangeException("status", "Valid redirection status codes 300-308.");
RedirectUrl = url;
IsRedirectPermanent = (status == 301 || status == 308);
if (status != 301 && status != 302) // default redirect statuses
ResponseStatusCode = status;
}
/// <summary>
/// Gets or sets the content request http response status code.
/// </summary>
/// <remarks>Does not actually set the http response status code, only registers that the response
/// should use the specified code. The code will or will not be used, in due time.</remarks>
public int ResponseStatusCode { get; private set; }
/// <summary>
/// Gets or sets the content request http response status description.
/// </summary>
/// <remarks>Does not actually set the http response status description, only registers that the response
/// should use the specified description. The description will or will not be used, in due time.</remarks>
public string ResponseStatusDescription { get; private set; }
/// <summary>
/// Sets the http response status code, along with an optional associated description.
/// </summary>
/// <param name="code">The http status code.</param>
/// <param name="description">The description.</param>
/// <remarks>Does not actually set the http response status code and description, only registers that
/// the response should use the specified code and description. The code and description will or will
/// not be used, in due time.</remarks>
public void SetResponseStatus(int code, string description = null)
{
EnsureWriteable();
// .Status is deprecated
// .SubStatusCode is IIS 7+ internal, ignore
ResponseStatusCode = code;
ResponseStatusDescription = description;
}
#endregion
}
}
| |
// Visual Studio Shared Project
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.Designer.Interfaces;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TextManager.Interop;
using ErrorHandler = Microsoft.VisualStudio.ErrorHandler;
using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
using VSConstants = Microsoft.VisualStudio.VSConstants;
namespace Microsoft.VisualStudioTools.Project {
/// <summary>
/// Common factory for creating our editor
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable")]
public abstract class CommonEditorFactory : IVsEditorFactory {
private Package _package;
private ServiceProvider _serviceProvider;
private readonly bool _promptEncodingOnLoad;
public CommonEditorFactory(Package package) {
_package = package;
}
public CommonEditorFactory(Package package, bool promptEncodingOnLoad) {
_package = package;
_promptEncodingOnLoad = promptEncodingOnLoad;
}
#region IVsEditorFactory Members
public virtual int SetSite(Microsoft.VisualStudio.OLE.Interop.IServiceProvider psp) {
_serviceProvider = new ServiceProvider(psp);
return VSConstants.S_OK;
}
public virtual object GetService(Type serviceType) {
return _serviceProvider.GetService(serviceType);
}
// This method is called by the Environment (inside IVsUIShellOpenDocument::
// OpenStandardEditor and OpenSpecificEditor) to map a LOGICAL view to a
// PHYSICAL view. A LOGICAL view identifies the purpose of the view that is
// desired (e.g. a view appropriate for Debugging [LOGVIEWID_Debugging], or a
// view appropriate for text view manipulation as by navigating to a find
// result [LOGVIEWID_TextView]). A PHYSICAL view identifies an actual type
// of view implementation that an IVsEditorFactory can create.
//
// NOTE: Physical views are identified by a string of your choice with the
// one constraint that the default/primary physical view for an editor
// *MUST* use a NULL string as its physical view name (*pbstrPhysicalView = NULL).
//
// NOTE: It is essential that the implementation of MapLogicalView properly
// validates that the LogicalView desired is actually supported by the editor.
// If an unsupported LogicalView is requested then E_NOTIMPL must be returned.
//
// NOTE: The special Logical Views supported by an Editor Factory must also
// be registered in the local registry hive. LOGVIEWID_Primary is implicitly
// supported by all editor types and does not need to be registered.
// For example, an editor that supports a ViewCode/ViewDesigner scenario
// might register something like the following:
// HKLM\Software\Microsoft\VisualStudio\9.0\Editors\
// {...guidEditor...}\
// LogicalViews\
// {...LOGVIEWID_TextView...} = s ''
// {...LOGVIEWID_Code...} = s ''
// {...LOGVIEWID_Debugging...} = s ''
// {...LOGVIEWID_Designer...} = s 'Form'
//
public virtual int MapLogicalView(ref Guid logicalView, out string physicalView) {
// initialize out parameter
physicalView = null;
bool isSupportedView = false;
// Determine the physical view
if (VSConstants.LOGVIEWID_Primary == logicalView ||
VSConstants.LOGVIEWID_Debugging == logicalView ||
VSConstants.LOGVIEWID_Code == logicalView ||
VSConstants.LOGVIEWID_TextView == logicalView) {
// primary view uses NULL as pbstrPhysicalView
isSupportedView = true;
} else if (VSConstants.LOGVIEWID_Designer == logicalView) {
physicalView = "Design";
isSupportedView = true;
}
if (isSupportedView)
return VSConstants.S_OK;
else {
// E_NOTIMPL must be returned for any unrecognized rguidLogicalView values
return VSConstants.E_NOTIMPL;
}
}
public virtual int Close() {
return VSConstants.S_OK;
}
/// <summary>
///
/// </summary>
/// <param name="grfCreateDoc"></param>
/// <param name="pszMkDocument"></param>
/// <param name="pszPhysicalView"></param>
/// <param name="pvHier"></param>
/// <param name="itemid"></param>
/// <param name="punkDocDataExisting"></param>
/// <param name="ppunkDocView"></param>
/// <param name="ppunkDocData"></param>
/// <param name="pbstrEditorCaption"></param>
/// <param name="pguidCmdUI"></param>
/// <param name="pgrfCDW"></param>
/// <returns></returns>
public virtual int CreateEditorInstance(
uint createEditorFlags,
string documentMoniker,
string physicalView,
IVsHierarchy hierarchy,
uint itemid,
System.IntPtr docDataExisting,
out System.IntPtr docView,
out System.IntPtr docData,
out string editorCaption,
out Guid commandUIGuid,
out int createDocumentWindowFlags) {
// Initialize output parameters
docView = IntPtr.Zero;
docData = IntPtr.Zero;
commandUIGuid = Guid.Empty;
createDocumentWindowFlags = 0;
editorCaption = null;
// Validate inputs
if ((createEditorFlags & (VSConstants.CEF_OPENFILE | VSConstants.CEF_SILENT)) == 0) {
return VSConstants.E_INVALIDARG;
}
if (_promptEncodingOnLoad && docDataExisting != IntPtr.Zero) {
return VSConstants.VS_E_INCOMPATIBLEDOCDATA;
}
// Get a text buffer
IVsTextLines textLines = GetTextBuffer(docDataExisting);
// Assign docData IntPtr to either existing docData or the new text buffer
if (docDataExisting != IntPtr.Zero) {
docData = docDataExisting;
Marshal.AddRef(docData);
} else {
docData = Marshal.GetIUnknownForObject(textLines);
}
try {
docView = CreateDocumentView(documentMoniker, physicalView, hierarchy, itemid, textLines, out editorCaption, out commandUIGuid);
} finally {
if (docView == IntPtr.Zero) {
if (docDataExisting != docData && docData != IntPtr.Zero) {
// Cleanup the instance of the docData that we have addref'ed
Marshal.Release(docData);
docData = IntPtr.Zero;
}
}
}
return VSConstants.S_OK;
}
#endregion
#region Helper methods
private IVsTextLines GetTextBuffer(System.IntPtr docDataExisting) {
IVsTextLines textLines;
if (docDataExisting == IntPtr.Zero) {
// Create a new IVsTextLines buffer.
Type textLinesType = typeof(IVsTextLines);
Guid riid = textLinesType.GUID;
Guid clsid = typeof(VsTextBufferClass).GUID;
textLines = _package.CreateInstance(ref clsid, ref riid, textLinesType) as IVsTextLines;
// set the buffer's site
((IObjectWithSite)textLines).SetSite(_serviceProvider.GetService(typeof(IOleServiceProvider)));
} else {
// Use the existing text buffer
Object dataObject = Marshal.GetObjectForIUnknown(docDataExisting);
textLines = dataObject as IVsTextLines;
if (textLines == null) {
// Try get the text buffer from textbuffer provider
IVsTextBufferProvider textBufferProvider = dataObject as IVsTextBufferProvider;
if (textBufferProvider != null) {
textBufferProvider.GetTextBuffer(out textLines);
}
}
if (textLines == null) {
// Unknown docData type then, so we have to force VS to close the other editor.
ErrorHandler.ThrowOnFailure((int)VSConstants.VS_E_INCOMPATIBLEDOCDATA);
}
}
return textLines;
}
private IntPtr CreateDocumentView(string documentMoniker, string physicalView, IVsHierarchy hierarchy, uint itemid, IVsTextLines textLines, out string editorCaption, out Guid cmdUI) {
//Init out params
editorCaption = string.Empty;
cmdUI = Guid.Empty;
if (string.IsNullOrEmpty(physicalView)) {
// create code window as default physical view
return CreateCodeView(documentMoniker, textLines, ref editorCaption, ref cmdUI);
} else if (string.Compare(physicalView, "design", StringComparison.OrdinalIgnoreCase) == 0) {
// Create Form view
return CreateFormView(hierarchy, itemid, textLines, ref editorCaption, ref cmdUI);
}
// We couldn't create the view
// Return special error code so VS can try another editor factory.
ErrorHandler.ThrowOnFailure((int)VSConstants.VS_E_UNSUPPORTEDFORMAT);
return IntPtr.Zero;
}
private IntPtr CreateFormView(IVsHierarchy hierarchy, uint itemid, IVsTextLines textLines, ref string editorCaption, ref Guid cmdUI) {
// Request the Designer Service
IVSMDDesignerService designerService = (IVSMDDesignerService)GetService(typeof(IVSMDDesignerService));
// Create loader for the designer
IVSMDDesignerLoader designerLoader = (IVSMDDesignerLoader)designerService.CreateDesignerLoader("Microsoft.VisualStudio.Designer.Serialization.VSDesignerLoader");
bool loaderInitalized = false;
try {
IOleServiceProvider provider = _serviceProvider.GetService(typeof(IOleServiceProvider)) as IOleServiceProvider;
// Initialize designer loader
designerLoader.Initialize(provider, hierarchy, (int)itemid, textLines);
loaderInitalized = true;
// Create the designer
IVSMDDesigner designer = designerService.CreateDesigner(provider, designerLoader);
// Get editor caption
editorCaption = designerLoader.GetEditorCaption((int)READONLYSTATUS.ROSTATUS_Unknown);
// Get view from designer
object docView = designer.View;
// Get command guid from designer
cmdUI = designer.CommandGuid;
return Marshal.GetIUnknownForObject(docView);
} catch {
// The designer loader may have created a reference to the shell or the text buffer.
// In case we fail to create the designer we should manually dispose the loader
// in order to release the references to the shell and the textbuffer
if (loaderInitalized) {
designerLoader.Dispose();
}
throw;
}
}
protected virtual IntPtr CreateCodeView(string documentMoniker, IVsTextLines textLines, ref string editorCaption, ref Guid cmdUI) {
Type codeWindowType = typeof(IVsCodeWindow);
Guid riid = codeWindowType.GUID;
Guid clsid = typeof(VsCodeWindowClass).GUID;
IVsCodeWindow window = (IVsCodeWindow)_package.CreateInstance(ref clsid, ref riid, codeWindowType);
ErrorHandler.ThrowOnFailure(window.SetBuffer(textLines));
ErrorHandler.ThrowOnFailure(window.SetBaseEditorCaption(null));
ErrorHandler.ThrowOnFailure(window.GetEditorCaption(READONLYSTATUS.ROSTATUS_Unknown, out editorCaption));
IVsUserData userData = textLines as IVsUserData;
if (userData != null) {
if (_promptEncodingOnLoad) {
var guid = VSConstants.VsTextBufferUserDataGuid.VsBufferEncodingPromptOnLoad_guid;
userData.SetData(ref guid, (uint)1);
}
}
InitializeLanguageService(textLines);
cmdUI = VSConstants.GUID_TextEditorFactory;
return Marshal.GetIUnknownForObject(window);
}
/// <summary>
/// Initializes the language service for the given file. This allows files with different
/// extensions to be opened by the editor type and get correct highlighting and intellisense
/// controllers.
///
/// New in 1.1
/// </summary>
protected virtual void InitializeLanguageService(IVsTextLines textLines) {
}
#endregion
protected void InitializeLanguageService(IVsTextLines textLines, Guid langSid) {
IVsUserData userData = textLines as IVsUserData;
if (userData != null) {
if (langSid != Guid.Empty) {
Guid vsCoreSid = new Guid("{8239bec4-ee87-11d0-8c98-00c04fc2ab22}");
Guid currentSid;
ErrorHandler.ThrowOnFailure(textLines.GetLanguageServiceID(out currentSid));
// If the language service is set to the default SID, then
// set it to our language
if (currentSid == vsCoreSid) {
ErrorHandler.ThrowOnFailure(textLines.SetLanguageServiceID(ref langSid));
} else if (currentSid != langSid) {
// Some other language service has it, so return VS_E_INCOMPATIBLEDOCDATA
throw new COMException("Incompatible doc data", VSConstants.VS_E_INCOMPATIBLEDOCDATA);
}
Guid bufferDetectLang = VSConstants.VsTextBufferUserDataGuid.VsBufferDetectLangSID_guid;
ErrorHandler.ThrowOnFailure(userData.SetData(ref bufferDetectLang, false));
}
}
}
}
}
| |
#region License
//
// Copyright (c) 2007-2009, Sean Chambers <[email protected]>
//
// 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 System.Linq;
using System.Text;
using FluentMigrator.Expressions;
using FluentMigrator.Runner.Extensions;
using FluentMigrator.Runner.Generators.Generic;
namespace FluentMigrator.Runner.Generators.SqlServer
{
public class SqlServer2000Generator : GenericGenerator
{
public SqlServer2000Generator()
: base(new SqlServerColumn(new SqlServer2000TypeMap()), new SqlServerQuoter(), new EmptyDescriptionGenerator())
{
}
protected SqlServer2000Generator(IColumn column, IDescriptionGenerator descriptionGenerator)
: base(column, new SqlServerQuoter(), descriptionGenerator)
{
}
public override string RenameTable { get { return "sp_rename '{0}', '{1}'"; } }
public override string RenameColumn { get { return "sp_rename '{0}.{1}', '{2}'"; } }
public override string DropIndex { get { return "DROP INDEX {1}.{0}"; } }
public override string AddColumn { get { return "ALTER TABLE {0} ADD {1}"; } }
public virtual string IdentityInsert { get { return "SET IDENTITY_INSERT {0} {1}"; } }
public override string CreateConstraint { get { return "ALTER TABLE {0} ADD CONSTRAINT {1} {2}{3} ({4})"; } }
//Not need for the nonclusted keyword as it is the default mode
public override string GetClusterTypeString(CreateIndexExpression column)
{
return column.Index.IsClustered ? "CLUSTERED " : string.Empty;
}
protected virtual string GetConstraintClusteringString(CreateConstraintExpression constraint)
{
object indexType;
if (!constraint.Constraint.AdditionalFeatures.TryGetValue(
SqlServerExtensions.ConstraintType, out indexType)) return string.Empty;
return (indexType.Equals(SqlServerConstraintType.Clustered)) ? " CLUSTERED" : " NONCLUSTERED";
}
public override string Generate(CreateConstraintExpression expression)
{
var constraintType = (expression.Constraint.IsPrimaryKeyConstraint) ? "PRIMARY KEY" : "UNIQUE";
var constraintClustering = GetConstraintClusteringString(expression);
string columns = String.Join(", ", expression.Constraint.Columns.Select(x => Quoter.QuoteColumnName(x)).ToArray());
return string.Format(CreateConstraint, Quoter.QuoteTableName(expression.Constraint.TableName),
Quoter.Quote(expression.Constraint.ConstraintName),
constraintType,
constraintClustering,
columns);
}
public override string Generate(RenameTableExpression expression)
{
return String.Format(RenameTable, Quoter.QuoteTableName(Quoter.QuoteCommand(expression.OldName)), Quoter.QuoteCommand(expression.NewName));
}
public override string Generate(RenameColumnExpression expression)
{
return String.Format(RenameColumn, Quoter.QuoteTableName(expression.TableName), Quoter.QuoteColumnName(Quoter.QuoteCommand(expression.OldName)), Quoter.QuoteCommand(expression.NewName));
}
public override string Generate(DeleteColumnExpression expression)
{
// before we drop a column, we have to drop any default value constraints in SQL Server
var builder = new StringBuilder();
foreach (string column in expression.ColumnNames)
{
if (expression.ColumnNames.First() != column) builder.AppendLine("GO");
BuildDelete(expression, column, builder);
}
return builder.ToString();
}
protected virtual void BuildDelete(DeleteColumnExpression expression, string columnName, StringBuilder builder)
{
builder.AppendLine(Generate(new DeleteDefaultConstraintExpression {
ColumnName = columnName,
SchemaName = expression.SchemaName,
TableName = expression.TableName
}));
builder.AppendLine();
builder.AppendLine(String.Format("-- now we can finally drop column" + Environment.NewLine + "ALTER TABLE {0} DROP COLUMN {1};",
Quoter.QuoteTableName(expression.TableName),
Quoter.QuoteColumnName(columnName)));
}
public override string Generate(AlterDefaultConstraintExpression expression)
{
// before we alter a default constraint on a column, we have to drop any default value constraints in SQL Server
var builder = new StringBuilder();
builder.AppendLine(Generate(new DeleteDefaultConstraintExpression
{
ColumnName = expression.ColumnName,
SchemaName = expression.SchemaName,
TableName = expression.TableName
}));
builder.AppendLine();
builder.Append(String.Format("-- create alter table command to create new default constraint as string and run it" + Environment.NewLine +"ALTER TABLE {0} WITH NOCHECK ADD CONSTRAINT {3} DEFAULT({2}) FOR {1};",
Quoter.QuoteTableName(expression.TableName),
Quoter.QuoteColumnName(expression.ColumnName),
Quoter.QuoteValue(expression.DefaultValue),
Quoter.QuoteConstraintName(SqlServerColumn.GetDefaultConstraintName(expression.TableName, expression.ColumnName))));
return builder.ToString();
}
public override string Generate(InsertDataExpression expression)
{
if (IsUsingIdentityInsert(expression))
{
return string.Format("{0}; {1}; {2}",
string.Format(IdentityInsert, Quoter.QuoteTableName(expression.TableName), "ON"),
base.Generate(expression),
string.Format(IdentityInsert, Quoter.QuoteTableName(expression.TableName), "OFF"));
}
return base.Generate(expression);
}
protected static bool IsUsingIdentityInsert(InsertDataExpression expression)
{
if (expression.AdditionalFeatures.ContainsKey(SqlServerExtensions.IdentityInsert))
{
return (bool)expression.AdditionalFeatures[SqlServerExtensions.IdentityInsert];
}
return false;
}
public override string Generate(CreateSequenceExpression expression)
{
return compatabilityMode.HandleCompatabilty("Sequences are not supported in SqlServer2000");
}
public override string Generate(DeleteSequenceExpression expression)
{
return compatabilityMode.HandleCompatabilty("Sequences are not supported in SqlServer2000");
}
public override string Generate(DeleteDefaultConstraintExpression expression)
{
string sql =
"DECLARE @default sysname, @sql nvarchar(4000);" + Environment.NewLine + Environment.NewLine +
"-- get name of default constraint" + Environment.NewLine +
"SELECT @default = name" + Environment.NewLine +
"FROM sys.default_constraints" + Environment.NewLine +
"WHERE parent_object_id = object_id('{0}')" + Environment.NewLine +
"AND type = 'D'" + Environment.NewLine +
"AND parent_column_id = (" + Environment.NewLine +
"SELECT column_id" + Environment.NewLine +
"FROM sys.columns" + Environment.NewLine +
"WHERE object_id = object_id('{0}')" + Environment.NewLine +
"AND name = '{1}'" + Environment.NewLine +
");" + Environment.NewLine + Environment.NewLine +
"-- create alter table command to drop constraint as string and run it" + Environment.NewLine +
"SET @sql = N'ALTER TABLE {0} DROP CONSTRAINT ' + @default;" + Environment.NewLine +
"EXEC sp_executesql @sql;";
return String.Format(sql, Quoter.QuoteTableName(expression.TableName), expression.ColumnName);
}
public override bool IsAdditionalFeatureSupported(string feature)
{
return _supportedAdditionalFeatures.Any(x => x == feature);
}
private readonly IEnumerable<string> _supportedAdditionalFeatures = new List<string>
{
SqlServerExtensions.IdentityInsert,
SqlServerExtensions.IdentitySeed,
SqlServerExtensions.IdentityIncrement,
SqlServerExtensions.ConstraintType
};
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Dynamic.Utils;
using System.Reflection;
namespace System.Linq.Expressions
{
/// <summary>
/// Represents accessing a field or property.
/// </summary>
[DebuggerTypeProxy(typeof(Expression.MemberExpressionProxy))]
public class MemberExpression : Expression
{
private readonly Expression _expression;
/// <summary>
/// Gets the field or property to be accessed.
/// </summary>
public MemberInfo Member
{
get { return GetMember(); }
}
/// <summary>
/// Gets the containing object of the field or property.
/// </summary>
public Expression Expression
{
get { return _expression; }
}
// param order: factories args in order, then other args
internal MemberExpression(Expression expression)
{
_expression = expression;
}
internal static PropertyExpression Make(Expression expression, PropertyInfo property)
{
Debug.Assert(property != null);
return new PropertyExpression(expression, property);
}
internal static FieldExpression Make(Expression expression, FieldInfo field)
{
Debug.Assert(field != null);
return new FieldExpression(expression, field);
}
internal static MemberExpression Make(Expression expression, MemberInfo member)
{
FieldInfo fi = member as FieldInfo;
return fi == null ? (MemberExpression)Make(expression, (PropertyInfo)member) : Make(expression, fi);
}
/// <summary>
/// Returns the node type of this <see cref="Expression" />. (Inherited from <see cref="Expression" />.)
/// </summary>
/// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns>
public sealed override ExpressionType NodeType
{
get { return ExpressionType.MemberAccess; }
}
[ExcludeFromCodeCoverage] // Unreachable
internal virtual MemberInfo GetMember()
{
throw ContractUtils.Unreachable;
}
/// <summary>
/// Dispatches to the specific visit method for this node type.
/// </summary>
protected internal override Expression Accept(ExpressionVisitor visitor)
{
return visitor.VisitMember(this);
}
/// <summary>
/// Creates a new expression that is like this one, but using the
/// supplied children. If all of the children are the same, it will
/// return this expression.
/// </summary>
/// <param name="expression">The <see cref="Expression" /> property of the result.</param>
/// <returns>This expression if no children changed, or an expression with the updated children.</returns>
public MemberExpression Update(Expression expression)
{
if (expression == Expression)
{
return this;
}
return Expression.MakeMemberAccess(expression, Member);
}
}
internal class FieldExpression : MemberExpression
{
private readonly FieldInfo _field;
public FieldExpression(Expression expression, FieldInfo member)
: base(expression)
{
_field = member;
}
internal override MemberInfo GetMember()
{
return _field;
}
public sealed override Type Type
{
get { return _field.FieldType; }
}
}
internal class PropertyExpression : MemberExpression
{
private readonly PropertyInfo _property;
public PropertyExpression(Expression expression, PropertyInfo member)
: base(expression)
{
_property = member;
}
internal override MemberInfo GetMember()
{
return _property;
}
public sealed override Type Type
{
get { return _property.PropertyType; }
}
}
public partial class Expression
{
#region Field
/// <summary>
/// Creates a <see cref="MemberExpression"/> accessing a field.
/// </summary>
/// <param name="expression">The containing object of the field. This can be null for static fields.</param>
/// <param name="field">The field to be accessed.</param>
/// <returns>The created <see cref="MemberExpression"/>.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
public static MemberExpression Field(Expression expression, FieldInfo field)
{
ContractUtils.RequiresNotNull(field, "field");
if (field.IsStatic)
{
if (expression != null) throw new ArgumentException(Strings.OnlyStaticFieldsHaveNullInstance, nameof(expression));
}
else
{
if (expression == null) throw new ArgumentException(Strings.OnlyStaticFieldsHaveNullInstance, nameof(field));
RequiresCanRead(expression, "expression");
if (!TypeUtils.AreReferenceAssignable(field.DeclaringType, expression.Type))
{
throw Error.FieldInfoNotDefinedForType(field.DeclaringType, field.Name, expression.Type);
}
}
return MemberExpression.Make(expression, field);
}
/// <summary>
/// Creates a <see cref="MemberExpression"/> accessing a field.
/// </summary>
/// <param name="expression">The containing object of the field. This can be null for static fields.</param>
/// <param name="fieldName">The field to be accessed.</param>
/// <returns>The created <see cref="MemberExpression"/>.</returns>
public static MemberExpression Field(Expression expression, string fieldName)
{
RequiresCanRead(expression, "expression");
// bind to public names first
FieldInfo fi = expression.Type.GetField(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy);
if (fi == null)
{
fi = expression.Type.GetField(fieldName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy);
}
if (fi == null)
{
throw Error.InstanceFieldNotDefinedForType(fieldName, expression.Type);
}
return Expression.Field(expression, fi);
}
/// <summary>
/// Creates a <see cref="MemberExpression"/> accessing a field.
/// </summary>
/// <param name="expression">The containing object of the field. This can be null for static fields.</param>
/// <param name="type">The <see cref="Type"/> containing the field.</param>
/// <param name="fieldName">The field to be accessed.</param>
/// <returns>The created <see cref="MemberExpression"/>.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
public static MemberExpression Field(Expression expression, Type type, string fieldName)
{
ContractUtils.RequiresNotNull(type, "type");
// bind to public names first
FieldInfo fi = type.GetField(fieldName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy);
if (fi == null)
{
fi = type.GetField(fieldName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy);
}
if (fi == null)
{
throw Error.FieldNotDefinedForType(fieldName, type);
}
return Expression.Field(expression, fi);
}
#endregion
#region Property
/// <summary>
/// Creates a <see cref="MemberExpression"/> accessing a property.
/// </summary>
/// <param name="expression">The containing object of the property. This can be null for static properties.</param>
/// <param name="propertyName">The property to be accessed.</param>
/// <returns>The created <see cref="MemberExpression"/>.</returns>
public static MemberExpression Property(Expression expression, string propertyName)
{
RequiresCanRead(expression, "expression");
ContractUtils.RequiresNotNull(propertyName, "propertyName");
// bind to public names first
PropertyInfo pi = expression.Type.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy);
if (pi == null)
{
pi = expression.Type.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy);
}
if (pi == null)
{
throw Error.InstancePropertyNotDefinedForType(propertyName, expression.Type);
}
return Property(expression, pi);
}
/// <summary>
/// Creates a <see cref="MemberExpression"/> accessing a property.
/// </summary>
/// <param name="expression">The containing object of the property. This can be null for static properties.</param>
/// <param name="type">The <see cref="Type"/> containing the property.</param>
/// <param name="propertyName">The property to be accessed.</param>
/// <returns>The created <see cref="MemberExpression"/>.</returns>
public static MemberExpression Property(Expression expression, Type type, string propertyName)
{
ContractUtils.RequiresNotNull(type, "type");
ContractUtils.RequiresNotNull(propertyName, "propertyName");
// bind to public names first
PropertyInfo pi = type.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy);
if (pi == null)
{
pi = type.GetProperty(propertyName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy);
}
if (pi == null)
{
throw Error.PropertyNotDefinedForType(propertyName, type);
}
return Property(expression, pi);
}
/// <summary>
/// Creates a <see cref="MemberExpression"/> accessing a property.
/// </summary>
/// <param name="expression">The containing object of the property. This can be null for static properties.</param>
/// <param name="property">The property to be accessed.</param>
/// <returns>The created <see cref="MemberExpression"/>.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
public static MemberExpression Property(Expression expression, PropertyInfo property)
{
ContractUtils.RequiresNotNull(property, "property");
MethodInfo mi = property.GetGetMethod(true);
if (mi == null)
{
mi = property.GetSetMethod(true);
if (mi == null)
{
throw Error.PropertyDoesNotHaveAccessor(property);
}
else if (mi.GetParametersCached().Length != 1)
{
throw Error.IncorrectNumberOfMethodCallArguments(mi);
}
}
else if (mi.GetParametersCached().Length != 0)
{
throw Error.IncorrectNumberOfMethodCallArguments(mi);
}
if (mi.IsStatic)
{
if (expression != null) throw new ArgumentException(Strings.OnlyStaticPropertiesHaveNullInstance, nameof(expression));
}
else
{
if (expression == null) throw new ArgumentException(Strings.OnlyStaticPropertiesHaveNullInstance, nameof(property));
RequiresCanRead(expression, "expression");
if (!TypeUtils.IsValidInstanceType(property, expression.Type))
{
throw Error.PropertyNotDefinedForType(property, expression.Type);
}
}
return MemberExpression.Make(expression, property);
}
/// <summary>
/// Creates a <see cref="MemberExpression"/> accessing a property.
/// </summary>
/// <param name="expression">The containing object of the property. This can be null for static properties.</param>
/// <param name="propertyAccessor">An accessor method of the property to be accessed.</param>
/// <returns>The created <see cref="MemberExpression"/>.</returns>
public static MemberExpression Property(Expression expression, MethodInfo propertyAccessor)
{
ContractUtils.RequiresNotNull(propertyAccessor, "propertyAccessor");
ValidateMethodInfo(propertyAccessor);
return Property(expression, GetProperty(propertyAccessor));
}
private static PropertyInfo GetProperty(MethodInfo mi)
{
Type type = mi.DeclaringType;
BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic;
flags |= (mi.IsStatic) ? BindingFlags.Static : BindingFlags.Instance;
var props = type.GetProperties(flags);
foreach (PropertyInfo pi in props)
{
if (pi.CanRead && CheckMethod(mi, pi.GetGetMethod(true)))
{
return pi;
}
if (pi.CanWrite && CheckMethod(mi, pi.GetSetMethod(true)))
{
return pi;
}
}
throw Error.MethodNotPropertyAccessor(mi.DeclaringType, mi.Name);
}
private static bool CheckMethod(MethodInfo method, MethodInfo propertyMethod)
{
if (method.Equals(propertyMethod))
{
return true;
}
// If the type is an interface then the handle for the method got by the compiler will not be the
// same as that returned by reflection.
// Check for this condition and try and get the method from reflection.
Type type = method.DeclaringType;
if (type.GetTypeInfo().IsInterface && method.Name == propertyMethod.Name && type.GetMethod(method.Name) == propertyMethod)
{
return true;
}
return false;
}
#endregion
/// <summary>
/// Creates a <see cref="MemberExpression"/> accessing a property or field.
/// </summary>
/// <param name="expression">The containing object of the member. This can be null for static members.</param>
/// <param name="propertyOrFieldName">The member to be accessed.</param>
/// <returns>The created <see cref="MemberExpression"/>.</returns>
public static MemberExpression PropertyOrField(Expression expression, string propertyOrFieldName)
{
RequiresCanRead(expression, "expression");
// bind to public names first
PropertyInfo pi = expression.Type.GetProperty(propertyOrFieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy);
if (pi != null)
return Property(expression, pi);
FieldInfo fi = expression.Type.GetField(propertyOrFieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy);
if (fi != null)
return Field(expression, fi);
pi = expression.Type.GetProperty(propertyOrFieldName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy);
if (pi != null)
return Property(expression, pi);
fi = expression.Type.GetField(propertyOrFieldName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy);
if (fi != null)
return Field(expression, fi);
throw Error.NotAMemberOfType(propertyOrFieldName, expression.Type);
}
/// <summary>
/// Creates a <see cref="MemberExpression"/> accessing a property or field.
/// </summary>
/// <param name="expression">The containing object of the member. This can be null for static members.</param>
/// <param name="member">The member to be accessed.</param>
/// <returns>The created <see cref="MemberExpression"/>.</returns>
public static MemberExpression MakeMemberAccess(Expression expression, MemberInfo member)
{
ContractUtils.RequiresNotNull(member, "member");
FieldInfo fi = member as FieldInfo;
if (fi != null)
{
return Expression.Field(expression, fi);
}
PropertyInfo pi = member as PropertyInfo;
if (pi != null)
{
return Expression.Property(expression, pi);
}
throw Error.MemberNotFieldOrProperty(member);
}
}
}
| |
/*---------------------------------------------------------------------------------------------
* 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.Text;
using System.Text.RegularExpressions;
using ConvertLinuxPerfFiles.Utility;
namespace ConvertLinuxPerfFiles.Model
{
// contains common methods used by the linuxoutfile[name] classes to get devices, metrics and/or headers.
class LinuxOutFileHelper
{
public List<string> GetDevices(int startingLine, List<string> fileContents, int deviceColumnNumber)
{
List<string> devices = new List<string>();
string emptyLinePattern = "^\\s*$";
string splitPattern = "\\s+";
Regex rgxEmptyLine = new Regex(emptyLinePattern);
Regex rgxSplitLine = new Regex(splitPattern);
// since the out files that have devices are block format and devices can be parsed in 1 block, we tell this method to only read the first block.
int blockCount = 1;
// we set the initial block count to 0
int block = 0;
// the starting line to start to parse the devices. passed in by the caller
int lineNumber = startingLine;
// loop through the first block
while (block < blockCount)
{
// check to make sure we are not on an empty line. then get loop through ad get devices
if (!rgxEmptyLine.IsMatch(fileContents[lineNumber]))
{
string[] thisLineValues = rgxSplitLine.Split(fileContents[lineNumber]);
devices.Add(thisLineValues[deviceColumnNumber]);
lineNumber++;
}
// if we hit an empty line, we know that we have reached the end of the block
else
{
block++;
}
}
return devices;
}
// common method to generate the header that gets written to the tsv file for perfmon
public string GetHeader(OutHeader outHeader)
{
string splitPattern = "\\s+";
Regex rgx = new Regex(splitPattern);
string[] outHeaderSplit = rgx.Split(outHeader.FileContents[outHeader.StartingRow]);
StringBuilder header = new StringBuilder();
header.Append('"' + "(PDH-TSV 4.0) (Pacific Daylight Time)(420)" + '"' + "\t");
// for the out files that have devices, we need to include the devices as part of the header
if (outHeader.Devices != null)
{
foreach (string device in outHeader.Devices)
{
for (int i = outHeader.StartingColumn; i < outHeaderSplit.Length - outHeader.TrimColumn; i++)
{
header.Append('"' + "\\\\" + ConfigValues.MachineName + "\\" + outHeader.ObjectName + "(" + device + ")\\" + outHeaderSplit[i] + '"' + "\t");
}
}
}
// some out files do not have devices, like mem free or mem swap. we look for devices count and if there are none, create header w/o devices
if (outHeader.Devices == null)
{
for (int i = outHeader.StartingColumn; i < outHeaderSplit.Length - outHeader.TrimColumn; i++)
{
header.Append('"' + "\\\\" + ConfigValues.MachineName + "\\" + outHeader.ObjectName + "\\" + outHeaderSplit[i] + '"' + "\t");
}
}
return header.ToString();
}
// since we need to get the metrics of swap and free memory, I am creating the get metric method in the common class.
public List<string> GetMemoryMetrics(List<string> fileContents)
{
// Progress progress = new Progress();
// progress.WriteTitle("Parsing Memory metrics",progressLine);
List<string> metrics = new List<string>();
string splitPattern = "\\s+";
string datePattern = "(\\d{2})\\/(\\d{2})\\/(\\d{4})";
Regex rgxSplitLine = new Regex(splitPattern);
int lastTimeStampHour = -1;
Regex rgxDate = new Regex(datePattern);
string metricDateMatch = rgxDate.Match(fileContents[0]).ToString();
for (int i = 3; i < fileContents.Count; i++)
{
// progress.WriteProgress(i, fileContents.Count,progressLine);
StringBuilder thisMetricSample = new StringBuilder();
string[] thisLineContents = rgxSplitLine.Split(fileContents[i]);
DateTime timeStamp = DateTime.Parse(metricDateMatch + " " + thisLineContents[0] + " " + thisLineContents[1]);
MetricTimeStamp metricTimeStamp = new DateTimeUtility().FormatMetricTimeStamp(timeStamp, lastTimeStampHour);
if (metricTimeStamp.IncrementDay) { metricDateMatch = DateTime.Parse(metricTimeStamp.FormattedTimeStamp).ToString("MM/dd/yyyy"); }
lastTimeStampHour = metricTimeStamp.LastTimeStampHour;
thisMetricSample.Append('"' + metricTimeStamp.FormattedTimeStamp + '"' + "\t");
for (int j = 2; j < thisLineContents.Length; j++)
{
thisMetricSample.Append('"' + thisLineContents[j] + '"' + "\t");
}
metrics.Add(thisMetricSample.ToString());
}
return metrics;
}
// this is the common get metric shared between network and mpstat. since both files are similar formats, we place the get metrics in the common helper class
public List<string> GetMetrics(List<string> devices, List<string> fileContents)
{
// Progress progress = new Progress();
// progress.WriteTitle("Parsing MPStat/Network metrics", progressLine);
List<string> metrics = new List<string>();
string emptyLinePattern = "^\\s*$";
string splitPattern = "\\s+";
string datePattern = "(\\d{2})\\/(\\d{2})\\/(\\d{4})";
Regex rgxEmptyLine = new Regex(emptyLinePattern);
Regex rgxSplitLine = new Regex(splitPattern);
Regex rgxDate = new Regex(datePattern);
int deviceCount = devices.Count;
int lastTimeStampHour = -1;
string metricDateMatch = rgxDate.Match(fileContents[0]).ToString();
// looping through each line in the contents of this out file
for (int i = 1; i < fileContents.Count;)
{
// progress.WriteProgress(i, fileContents.Count, progressLine);
StringBuilder thisMetricSample = new StringBuilder();
// this file is in a block format and we use empty lines to determin when to start parsing the next metric
if (rgxEmptyLine.IsMatch(fileContents[i]) && i < fileContents.Count - 1)
{
// advances to the line of the next metric
i = i + 2;
// grabbing timestamp information for this current metric. we also provide the logic to roll over to the next day since the linux metric collection does not do this for us.
string[] thisLineContents = rgxSplitLine.Split(fileContents[i]);
DateTime timeStamp = DateTime.Parse(metricDateMatch + " " + thisLineContents[0] + " " + thisLineContents[1]);
MetricTimeStamp metricTimeStamp = new DateTimeUtility().FormatMetricTimeStamp(timeStamp, lastTimeStampHour);
if (metricTimeStamp.IncrementDay) { metricDateMatch = DateTime.Parse(metricTimeStamp.FormattedTimeStamp).ToString("MM/dd/yyyy"); }
lastTimeStampHour = metricTimeStamp.LastTimeStampHour;
thisMetricSample.Append('"' + metricTimeStamp.FormattedTimeStamp + '"' + "\t");
}
// this is where the metric data gets parsed and added to the collection
for (int x = 1; x <= deviceCount; x++)
{
string[] thisLineContents = rgxSplitLine.Split(fileContents[i]);
// read the contents of the split line, start at column 3 and read each string until the end of the array.
for (int j = 3; j < thisLineContents.Length; j++)
{
thisMetricSample.Append('"' + thisLineContents[j] + '"' + "\t");
}
// the logic of incrementing the for loop for the file contents file is with in the for statement since we need to do some more complicated parsing.
i++;
}
metrics.Add(thisMetricSample.ToString());
}
return metrics;
}
}
// this is the object that we pass in to the GetHeader method in this helper class. this object contains instructions on where to start parsing data, data to parse and devices to include in the header.
class OutHeader
{
public OutHeader()
{
// setting the TrimColumn to a default of 0. In the case where we need to
// get columns from startcolumn to end, but need to ommit the last column.
// Like in the pidstat case. We don't want to get the last column "command"
TrimColumn = 0;
}
public int StartingColumn { get; set; }
public int TrimColumn { get; set; }
public int StartingRow { get; set; }
public List<string> FileContents { get; set; }
public List<string> Devices { get; set; }
public string ObjectName { get; set; }
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Alchemi.Core.Manager.Storage;
using Alchemi.Core;
using Alchemi.Console.DataForms;
namespace Alchemi.Console.PropertiesDialogs
{
public partial class GroupProperties : PropertiesForm
{
private bool UpdateNeeded = false;
private ConsoleNode console;
private GroupStorageView _Group;
public GroupProperties(ConsoleNode console)
{
InitializeComponent();
this.console = console;
}
#region Method - SetData
public void SetData(GroupStorageView group)
{
this._Group = group;
this.Text = _Group.GroupName + " Properties";
this.lbName.Text = _Group.GroupName;
GetMemberData();
GetPermissionData();
if (group.IsSystem)
{
btnAdd.Enabled = false;
btnRemove.Enabled = false;
btnAddPrm.Enabled = false;
btnRemovePrm.Enabled = false;
}
}
#endregion
#region Method - GetMemberData
private void GetMemberData()
{
lvMembers.Items.Clear();
try
{
UserStorageView[] users = console.Manager.Admon_GetGroupUsers(console.Credentials, _Group.GroupId);
//get the group this user belongs to.
foreach (UserStorageView user in users)
{
UserItem usrItem = new UserItem(user.Username);
usrItem.User = user;
usrItem.ImageIndex = 3;
lvMembers.Items.Add(usrItem);
}
}
catch (Exception ex)
{
if (ex is AuthorizationException)
{
MessageBox.Show("Access denied. You do not have adequate permissions for this operation.", "Authorization Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
MessageBox.Show("Could not get group membership details. Error: " + ex.Message, "Console Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
#endregion
#region Method - GetPermissionData
private void GetPermissionData()
{
lvPrm.Items.Clear();
try
{
//get the group this user belongs to.
PermissionStorageView[] permissions = console.Manager.Admon_GetGroupPermissions(console.Credentials, _Group);
foreach (PermissionStorageView permission in permissions)
{
PermissionItem prmItem = new PermissionItem(permission.PermissionName);
prmItem.Permission = new PermissionStorageView(permission.PermissionId, permission.PermissionName);
prmItem.ImageIndex = 12;
lvPrm.Items.Add(prmItem);
}
}
catch (Exception ex)
{
if (ex is AuthorizationException)
{
MessageBox.Show("Access denied. You do not have adequate permissions for this operation.", "Authorization Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
MessageBox.Show("Could not get group permissions. Error: " + ex.Message, "Console Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
#endregion
//add group members
private void btnAdd_Click(object sender, EventArgs e)
{
SearchForm srch = new SearchForm(this.console, SearchForm.SearchMode.User);
srch.ShowDialog(this);
//get list of users from the search form.
ListView.SelectedListViewItemCollection items = srch.lvMembers.SelectedItems;
//for now only one item can be included
if (items != null && items.Count > 0)
lvMembers.Items.Clear();
foreach (ListViewItem li in items)
{
UserItem user = new UserItem(li.Text);
user.ImageIndex = li.ImageIndex;
user.User = ((UserItem)li).User;
//this loop should go only once: since only one item can be selected.
lvMembers.Items.Add(user);
}
UpdateNeeded = UpdateNeeded || (lvMembers.Items != null && lvMembers.Items.Count > 0);
btnApply.Enabled = UpdateNeeded;
}
//need to hide this till multiple group-memberships are implemented.
private void btnRemove_Click(object sender, EventArgs e)
{
// TODO:
// bool removed = false;
// if (lvMembers.SelectedItems!=null)
// {
// foreach (ListViewItem li in lvMembers.SelectedItems)
// {
// if (console.Credentials.Username != li.Text)
// {
// li.Remove();
// }
// else
// {
// //for now, we can have only one group-membership, so we should enforce this.
// MessageBox.Show("Cannot remove self, from group-membership.", "Remove User", MessageBoxButtons.OK, MessageBoxIcon.Warning);
// }
// removed = true;
// }
// }
// lvMembers.Refresh();
//
// if (removed)
// {
// UpdateNeeded = true;
// btnApply.Enabled = UpdateNeeded;
// }
}
private void lvMembers_SelectedIndexChanged(object sender, EventArgs e)
{
btnRemove.Enabled = (lvMembers.SelectedItems != null && lvMembers.SelectedItems.Count > 0);
}
private void btnAddPrm_Click(object sender, EventArgs e)
{
SearchForm srch = new SearchForm(this.console, SearchForm.SearchMode.Permission);
srch.ShowDialog(this);
//get list of users from the search form.
ListView.SelectedListViewItemCollection items = srch.lvMembers.SelectedItems;
//for now only one item can be included
if (items != null && items.Count > 0)
lvPrm.Items.Clear();
foreach (ListViewItem li in items)
{
PermissionItem prm = new PermissionItem(li.Text);
prm.ImageIndex = li.ImageIndex;
prm.Permission = ((PermissionItem)li).Permission;
//this loop should go only once: since only one item can be selected.
lvPrm.Items.Add(prm);
}
UpdateNeeded = UpdateNeeded || (lvPrm.Items != null && lvPrm.Items.Count > 0);
btnApply.Enabled = UpdateNeeded;
}
private void btnRemovePrm_Click(object sender, EventArgs e)
{
// TODO remove permission from group
}
private void btnOK_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.Diagnostics;
using Test.Utilities;
using Xunit;
namespace System.Runtime.Analyzers.UnitTests
{
public class SpecifyCultureInfoTests : DiagnosticAnalyzerTestBase
{
protected override DiagnosticAnalyzer GetBasicDiagnosticAnalyzer()
{
return new SpecifyCultureInfoAnalyzer();
}
protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer()
{
return new SpecifyCultureInfoAnalyzer();
}
[Fact]
public void CA1304_PlainString_CSharp()
{
VerifyCSharp(@"
using System;
using System.Globalization;
public class CultureInfoTestClass0
{
public string SpecifyCultureInfo01()
{
return ""foo"".ToLower();
}
}",
GetCSharpResultAt(9, 16, SpecifyCultureInfoAnalyzer.Rule, "string.ToLower()", "CultureInfoTestClass0.SpecifyCultureInfo01()", "string.ToLower(CultureInfo)"));
}
[Fact]
public void CA1304_VariableStringInsideDifferentContainingSymbols_CSharp()
{
VerifyCSharp(@"
using System;
using System.Globalization;
public class CultureInfoTestClass1
{
public string LowercaseAString(string name)
{
return name.ToLower();
}
public string InsideALambda(string insideLambda)
{
Func<string> ddd = () =>
{
return insideLambda.ToLower();
};
return null;
}
public string PropertyWithALambda
{
get
{
Func<string> ddd = () =>
{
return ""InsideGetter"".ToLower();
};
return null;
}
}
}
",
GetCSharpResultAt(9, 16, SpecifyCultureInfoAnalyzer.Rule, "string.ToLower()", "CultureInfoTestClass1.LowercaseAString(string)", "string.ToLower(CultureInfo)"),
GetCSharpResultAt(16, 20, SpecifyCultureInfoAnalyzer.Rule, "string.ToLower()", "CultureInfoTestClass1.InsideALambda(string)", "string.ToLower(CultureInfo)"),
GetCSharpResultAt(28, 24, SpecifyCultureInfoAnalyzer.Rule, "string.ToLower()", "CultureInfoTestClass1.PropertyWithALambda.get", "string.ToLower(CultureInfo)"));
}
[Fact]
public void CA1304_MethodOverloadHasCultureInfoAsFirstArgument_CSharp()
{
VerifyCSharp(@"
using System;
using System.Globalization;
public class CultureInfoTestClass2
{
public static void Method()
{
MethodOverloadHasCultureInfoAsFirstArgument(""Foo"");
}
public static void MethodOverloadHasCultureInfoAsFirstArgument(string format)
{
MethodOverloadHasCultureInfoAsFirstArgument(CultureInfo.CurrentCulture, format);
}
public static void MethodOverloadHasCultureInfoAsFirstArgument(CultureInfo provider, string format)
{
Console.WriteLine(string.Format(provider, format));
}
}",
GetCSharpResultAt(9, 9, SpecifyCultureInfoAnalyzer.Rule, "CultureInfoTestClass2.MethodOverloadHasCultureInfoAsFirstArgument(string)", "CultureInfoTestClass2.Method()", "CultureInfoTestClass2.MethodOverloadHasCultureInfoAsFirstArgument(CultureInfo, string)"));
}
[Fact]
public void CA1304_MethodOverloadHasCultureInfoAsLastArgument_CSharp()
{
VerifyCSharp(@"
using System;
using System.Globalization;
public class CultureInfoTestClass2
{
public static void Method()
{
MethodOverloadHasCultureInfoAsLastArgument(""Foo"");
}
public static void MethodOverloadHasCultureInfoAsLastArgument(string format)
{
MethodOverloadHasCultureInfoAsLastArgument(format, CultureInfo.CurrentCulture);
}
public static void MethodOverloadHasCultureInfoAsLastArgument(string format, CultureInfo provider)
{
Console.WriteLine(string.Format(provider, format));
}
public static void MethodOverloadHasCultureInfoAsLastArgument(CultureInfo provider, string format)
{
Console.WriteLine(string.Format(provider, format));
}
}",
GetCSharpResultAt(9, 9, SpecifyCultureInfoAnalyzer.Rule, "CultureInfoTestClass2.MethodOverloadHasCultureInfoAsLastArgument(string)", "CultureInfoTestClass2.Method()", "CultureInfoTestClass2.MethodOverloadHasCultureInfoAsLastArgument(string, CultureInfo)"));
}
[Fact]
public void CA1304_MethodOverloadHasJustCultureInfo_CSharp()
{
VerifyCSharp(@"
using System;
using System.Globalization;
public class CultureInfoTestClass2
{
public static void Method()
{
MethodOverloadHasJustCultureInfo();
}
public static void MethodOverloadHasJustCultureInfo()
{
MethodOverloadHasJustCultureInfo(CultureInfo.CurrentCulture);
}
public static void MethodOverloadHasJustCultureInfo(CultureInfo provider)
{
Console.WriteLine(string.Format(provider, """"));
}
}",
GetCSharpResultAt(9, 9, SpecifyCultureInfoAnalyzer.Rule, "CultureInfoTestClass2.MethodOverloadHasJustCultureInfo()", "CultureInfoTestClass2.Method()", "CultureInfoTestClass2.MethodOverloadHasJustCultureInfo(CultureInfo)"));
}
[Fact]
public void CA1304_DoesNotRecommendObsoleteOverload_CSharp()
{
VerifyCSharp(@"
using System;
using System.Globalization;
public class CultureInfoTestClass2
{
public static void Method()
{
MethodOverloadHasJustCultureInfo();
}
public static void MethodOverloadHasJustCultureInfo()
{
MethodOverloadHasJustCultureInfo(CultureInfo.CurrentCulture);
}
[Obsolete]
public static void MethodOverloadHasJustCultureInfo(CultureInfo provider)
{
Console.WriteLine(string.Format(provider, """"));
}
}");
}
[Fact]
public void CA1304_TargetMethodIsGenericsAndNonGenerics_CSharp()
{
VerifyCSharp(@"
using System;
using System.Globalization;
public class CultureInfoTestClass2
{
public static void Method()
{
TargetMethodIsNonGenerics();
TargetMethodIsGenerics<int>(); // No Diagnostics
}
public static void TargetMethodIsNonGenerics()
{
}
public static void TargetMethodIsNonGenerics<T>(CultureInfo provider)
{
}
public static void TargetMethodIsGenerics<V>()
{
}
public static void TargetMethodIsGenerics(CultureInfo provider)
{
}
}",
GetCSharpResultAt(9, 9, SpecifyCultureInfoAnalyzer.Rule, "CultureInfoTestClass2.TargetMethodIsNonGenerics()", "CultureInfoTestClass2.Method()", "CultureInfoTestClass2.TargetMethodIsNonGenerics<T>(CultureInfo)"));
}
[Fact]
public void CA1304_MethodOverloadIncludeNonCandidates_CSharp()
{
VerifyCSharp(@"
using System;
using System.Globalization;
public class CultureInfoTestClass2
{
public static void Method()
{
MethodOverloadCount3();
}
public static void MethodOverloadCount3()
{
MethodOverloadCount3(CultureInfo.CurrentCulture);
}
public static void MethodOverloadCount3(CultureInfo provider)
{
Console.WriteLine(string.Format(provider, """"));
}
public static void MethodOverloadCount3(string b)
{
}
}",
GetCSharpResultAt(9, 9, SpecifyCultureInfoAnalyzer.Rule, "CultureInfoTestClass2.MethodOverloadCount3()", "CultureInfoTestClass2.Method()", "CultureInfoTestClass2.MethodOverloadCount3(CultureInfo)"));
}
[Fact]
public void CA1304_MethodOverloadWithJustCultureInfoAsExtraParameter_CSharp()
{
VerifyCSharp(@"
using System;
using System.Globalization;
public class CultureInfoTestClass2
{
public static void Method()
{
MethodOverloadWithJustCultureInfoAsExtraParameter(2, 3);
}
public static void MethodOverloadWithJustCultureInfoAsExtraParameter(int a, int b)
{
MethodOverloadWithJustCultureInfoAsExtraParameter(a, b, CultureInfo.CurrentCulture);
}
public static void MethodOverloadWithJustCultureInfoAsExtraParameter(int a, int b, CultureInfo provider)
{
Console.WriteLine(string.Format(provider, """"));
}
}",
GetCSharpResultAt(9, 9, SpecifyCultureInfoAnalyzer.Rule, "CultureInfoTestClass2.MethodOverloadWithJustCultureInfoAsExtraParameter(int, int)", "CultureInfoTestClass2.Method()", "CultureInfoTestClass2.MethodOverloadWithJustCultureInfoAsExtraParameter(int, int, CultureInfo)"));
}
[Fact]
public void CA1304_NoDiagnostics_CSharp()
{
VerifyCSharp(@"
using System;
using System.Globalization;
public class CultureInfoTestClass2
{
public static void Method()
{
// No Diag - Inherited CultureInfo
MethodOverloadHasInheritedCultureInfo(""Foo"");
// No Diag - Since the overload has more parameters apart from CultureInfo
MethodOverloadHasMoreThanCultureInfo(""Foo"");
// No Diag - Since the CultureInfo parameter is neither as the first parameter nor as the last parameter
MethodOverloadWithJustCultureInfoAsInbetweenParameter("""", """");
}
public static void MethodOverloadHasInheritedCultureInfo(string format)
{
MethodOverloadHasInheritedCultureInfo(new DerivedCultureInfo(""""), format);
}
public static void MethodOverloadHasInheritedCultureInfo(DerivedCultureInfo provider, string format)
{
Console.WriteLine(string.Format(provider, format));
}
public static void MethodOverloadHasMoreThanCultureInfo(string format)
{
MethodOverloadHasMoreThanCultureInfo(format, null, CultureInfo.CurrentCulture);
}
public static void MethodOverloadHasMoreThanCultureInfo(string format, string what, CultureInfo provider)
{
Console.WriteLine(string.Format(provider, format));
}
public static void MethodOverloadWithJustCultureInfoAsInbetweenParameter(string a, string b)
{
MethodOverloadWithJustCultureInfoAsInbetweenParameter(a, CultureInfo.CurrentCulture, b);
}
public static void MethodOverloadWithJustCultureInfoAsInbetweenParameter(string a, CultureInfo provider, string b)
{
Console.WriteLine(string.Format(provider, """"));
}
}
public class DerivedCultureInfo : CultureInfo
{
public DerivedCultureInfo(string name):
base(name)
{
}
}");
}
[Fact]
public void CA1304_PlainString_VisualBasic()
{
VerifyBasic(@"
Imports System
Imports System.Globalization
Public Class CultureInfoTestClass0
Public Function SpecifyCultureInfo01() As String
Return ""foo"".ToLower()
End Function
End Class",
GetBasicResultAt(7, 16, SpecifyCultureInfoAnalyzer.Rule, "String.ToLower()", "CultureInfoTestClass0.SpecifyCultureInfo01()", "String.ToLower(CultureInfo)"));
}
[Fact]
public void CA1304_VariableStringInsideDifferentContainingSymbols_VisualBasic()
{
VerifyBasic(@"
Imports System
Imports System.Globalization
Public Class CultureInfoTestClass1
Public Function LowercaseAString(name As String) As String
Return name.ToLower()
End Function
Public Function InsideALambda(insideLambda As String) As String
Dim ddd As Func(Of String) = Function()
Return insideLambda.ToLower()
End Function
Return Nothing
End Function
Public ReadOnly Property PropertyWithALambda() As String
Get
Dim ddd As Func(Of String) = Function()
Return ""InsideGetter"".ToLower()
End Function
Return Nothing
End Get
End Property
End Class",
GetBasicResultAt(7, 16, SpecifyCultureInfoAnalyzer.Rule, "String.ToLower()", "CultureInfoTestClass1.LowercaseAString(String)", "String.ToLower(CultureInfo)"),
GetBasicResultAt(12, 48, SpecifyCultureInfoAnalyzer.Rule, "String.ToLower()", "CultureInfoTestClass1.InsideALambda(String)", "String.ToLower(CultureInfo)"),
GetBasicResultAt(21, 52, SpecifyCultureInfoAnalyzer.Rule, "String.ToLower()", "CultureInfoTestClass1.PropertyWithALambda()", "String.ToLower(CultureInfo)"));
}
[Fact]
public void CA1304_MethodOverloadHasCultureInfoAsFirstArgument_VisualBasic()
{
VerifyBasic(@"
Imports System
Imports System.Globalization
Public Class CultureInfoTestClass2
Public Shared Sub Method()
MethodOverloadHasCultureInfoAsFirstArgument(""Foo"")
End Sub
Public Shared Sub MethodOverloadHasCultureInfoAsFirstArgument(format As String)
MethodOverloadHasCultureInfoAsFirstArgument(CultureInfo.CurrentCulture, format)
End Sub
Public Shared Sub MethodOverloadHasCultureInfoAsFirstArgument(provider As CultureInfo, format As String)
Console.WriteLine(String.Format(provider, format))
End Sub
End Class",
GetBasicResultAt(7, 9, SpecifyCultureInfoAnalyzer.Rule, "CultureInfoTestClass2.MethodOverloadHasCultureInfoAsFirstArgument(String)", "CultureInfoTestClass2.Method()", "CultureInfoTestClass2.MethodOverloadHasCultureInfoAsFirstArgument(CultureInfo, String)"));
}
[Fact]
public void CA1304_MethodOverloadHasCultureInfoAsLastArgument_VisualBasic()
{
VerifyBasic(@"
Imports System
Imports System.Globalization
Public Class CultureInfoTestClass2
Public Shared Sub Method()
MethodOverloadHasCultureInfoAsLastArgument(""Foo"")
End Sub
Public Shared Sub MethodOverloadHasCultureInfoAsLastArgument(format As String)
MethodOverloadHasCultureInfoAsLastArgument(format, CultureInfo.CurrentCulture)
End Sub
Public Shared Sub MethodOverloadHasCultureInfoAsLastArgument(format As String, provider As CultureInfo)
Console.WriteLine(String.Format(provider, format))
End Sub
Public Shared Sub MethodOverloadHasCultureInfoAsLastArgument(provider As CultureInfo, format As String)
Console.WriteLine(String.Format(provider, format))
End Sub
End Class",
GetBasicResultAt(7, 9, SpecifyCultureInfoAnalyzer.Rule, "CultureInfoTestClass2.MethodOverloadHasCultureInfoAsLastArgument(String)", "CultureInfoTestClass2.Method()", "CultureInfoTestClass2.MethodOverloadHasCultureInfoAsLastArgument(String, CultureInfo)"));
}
[Fact]
public void CA1304_MethodOverloadHasJustCultureInfo_VisualBasic()
{
VerifyBasic(@"
Imports System
Imports System.Globalization
Public Class CultureInfoTestClass2
Public Shared Sub Method()
MethodOverloadHasJustCultureInfo()
End Sub
Public Shared Sub MethodOverloadHasJustCultureInfo()
MethodOverloadHasJustCultureInfo(CultureInfo.CurrentCulture)
End Sub
Public Shared Sub MethodOverloadHasJustCultureInfo(provider As CultureInfo)
Console.WriteLine(String.Format(provider, """"))
End Sub
End Class",
GetBasicResultAt(7, 9, SpecifyCultureInfoAnalyzer.Rule, "CultureInfoTestClass2.MethodOverloadHasJustCultureInfo()", "CultureInfoTestClass2.Method()", "CultureInfoTestClass2.MethodOverloadHasJustCultureInfo(CultureInfo)"));
}
[Fact]
public void CA1304_MethodOverloadIncludeNonCandidates_VisualBasic()
{
VerifyBasic(@"
Imports System
Imports System.Globalization
Public Class CultureInfoTestClass2
Public Shared Sub Method()
MethodOverloadCount3()
End Sub
Public Shared Sub MethodOverloadCount3()
MethodOverloadCount3(CultureInfo.CurrentCulture)
End Sub
Public Shared Sub MethodOverloadCount3(provider As CultureInfo)
Console.WriteLine(String.Format(provider, """"))
End Sub
Public Shared Sub MethodOverloadCount3(b As String)
End Sub
End Class",
GetBasicResultAt(7, 9, SpecifyCultureInfoAnalyzer.Rule, "CultureInfoTestClass2.MethodOverloadCount3()", "CultureInfoTestClass2.Method()", "CultureInfoTestClass2.MethodOverloadCount3(CultureInfo)"));
}
[Fact]
public void CA1304_MethodOverloadWithJustCultureInfoAsExtraParameter_VisualBasic()
{
VerifyBasic(@"
Imports System
Imports System.Globalization
Public Class CultureInfoTestClass2
Public Shared Sub Method()
MethodOverloadWithJustCultureInfoAsExtraParameter(2, 3)
End Sub
Public Shared Sub MethodOverloadWithJustCultureInfoAsExtraParameter(a As Integer, b As Integer)
MethodOverloadWithJustCultureInfoAsExtraParameter(a, b, CultureInfo.CurrentCulture)
End Sub
Public Shared Sub MethodOverloadWithJustCultureInfoAsExtraParameter(a As Integer, b As Integer, provider As CultureInfo)
Console.WriteLine(String.Format(provider, """"))
End Sub
End Class",
GetBasicResultAt(7, 9, SpecifyCultureInfoAnalyzer.Rule, "CultureInfoTestClass2.MethodOverloadWithJustCultureInfoAsExtraParameter(Integer, Integer)", "CultureInfoTestClass2.Method()", "CultureInfoTestClass2.MethodOverloadWithJustCultureInfoAsExtraParameter(Integer, Integer, CultureInfo)"));
}
[Fact]
public void CA1304_NoDiagnostics_VisualBasic()
{
VerifyBasic(@"
Imports System
Imports System.Globalization
Public Class CultureInfoTestClass2
Public Shared Sub Method()
' No Diag - Inherited CultureInfo
MethodOverloadHasInheritedCultureInfo(""Foo"")
' No Diag - There are more parameters apart from CultureInfo
MethodOverloadHasMoreThanCultureInfo(""Foo"")
' No Diag - The CultureInfo parameter is neither the first parameter nor the last parameter
MethodOverloadWithJustCultureInfoAsInbetweenParameter("""", """")
End Sub
Public Shared Sub MethodOverloadHasInheritedCultureInfo(format As String)
MethodOverloadHasInheritedCultureInfo(New DerivedCultureInfo(""""), format)
End Sub
Public Shared Sub MethodOverloadHasInheritedCultureInfo(provider As DerivedCultureInfo, format As String)
Console.WriteLine(String.Format(provider, format))
End Sub
Public Shared Sub MethodOverloadHasMoreThanCultureInfo(format As String)
MethodOverloadHasMoreThanCultureInfo(format, Nothing, CultureInfo.CurrentCulture)
End Sub
Public Shared Sub MethodOverloadHasMoreThanCultureInfo(format As String, what As String, provider As CultureInfo)
Console.WriteLine(String.Format(provider, format))
End Sub
Public Shared Sub MethodOverloadWithJustCultureInfoAsInbetweenParameter(a As String, b As String)
MethodOverloadWithJustCultureInfoAsInbetweenParameter(a, CultureInfo.CurrentCulture, b)
End Sub
Public Shared Sub MethodOverloadWithJustCultureInfoAsInbetweenParameter(a As String, provider As CultureInfo, b As String)
Console.WriteLine(String.Format(provider, """"))
End Sub
End Class
Public Class DerivedCultureInfo
Inherits CultureInfo
Public Sub New(name As String)
MyBase.New(name)
End Sub
End Class");
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace Authenticated.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
private const int DefaultCollectionSize = 3;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using Attribute = Lucene.Net.Util.Attribute;
using AttributeSource = Lucene.Net.Util.AttributeSource;
namespace Lucene.Net.Analysis
{
/// <summary> This TokenFilter provides the ability to set aside attribute states
/// that have already been analyzed. This is useful in situations where multiple fields share
/// many common analysis steps and then go their separate ways.
/// <p/>
/// It is also useful for doing things like entity extraction or proper noun analysis as
/// part of the analysis workflow and saving off those tokens for use in another field.
///
/// <code>
/// TeeSinkTokenFilter source1 = new TeeSinkTokenFilter(new WhitespaceTokenizer(reader1));
/// TeeSinkTokenFilter.SinkTokenStream sink1 = source1.newSinkTokenStream();
/// TeeSinkTokenFilter.SinkTokenStream sink2 = source1.newSinkTokenStream();
/// TeeSinkTokenFilter source2 = new TeeSinkTokenFilter(new WhitespaceTokenizer(reader2));
/// source2.addSinkTokenStream(sink1);
/// source2.addSinkTokenStream(sink2);
/// TokenStream final1 = new LowerCaseFilter(source1);
/// TokenStream final2 = source2;
/// TokenStream final3 = new EntityDetect(sink1);
/// TokenStream final4 = new URLDetect(sink2);
/// d.add(new Field("f1", final1));
/// d.add(new Field("f2", final2));
/// d.add(new Field("f3", final3));
/// d.add(new Field("f4", final4));
/// </code>
/// In this example, <c>sink1</c> and <c>sink2</c> will both get tokens from both
/// <c>reader1</c> and <c>reader2</c> after whitespace tokenizer
/// and now we can further wrap any of these in extra analysis, and more "sources" can be inserted if desired.
/// It is important, that tees are consumed before sinks (in the above example, the field names must be
/// less the sink's field names). If you are not sure, which stream is consumed first, you can simply
/// add another sink and then pass all tokens to the sinks at once using <see cref="ConsumeAllTokens" />.
/// This TokenFilter is exhausted after this. In the above example, change
/// the example above to:
/// <code>
/// ...
/// TokenStream final1 = new LowerCaseFilter(source1.newSinkTokenStream());
/// TokenStream final2 = source2.newSinkTokenStream();
/// sink1.consumeAllTokens();
/// sink2.consumeAllTokens();
/// ...
/// </code>
/// In this case, the fields can be added in any order, because the sources are not used anymore and all sinks are ready.
/// <p/>Note, the EntityDetect and URLDetect TokenStreams are for the example and do not currently exist in Lucene.
/// </summary>
public sealed class TeeSinkTokenFilter:TokenFilter
{
public class AnonymousClassSinkFilter:SinkFilter
{
public override bool Accept(AttributeSource source)
{
return true;
}
}
private readonly LinkedList<WeakReference> sinks = new LinkedList<WeakReference>();
/// <summary> Instantiates a new TeeSinkTokenFilter.</summary>
public TeeSinkTokenFilter(TokenStream input):base(input)
{
}
/// <summary> Returns a new <see cref="SinkTokenStream" /> that receives all tokens consumed by this stream.</summary>
public SinkTokenStream NewSinkTokenStream()
{
return NewSinkTokenStream(ACCEPT_ALL_FILTER);
}
/// <summary> Returns a new <see cref="SinkTokenStream" /> that receives all tokens consumed by this stream
/// that pass the supplied filter.
/// </summary>
/// <seealso cref="SinkFilter">
/// </seealso>
public SinkTokenStream NewSinkTokenStream(SinkFilter filter)
{
var sink = new SinkTokenStream(this.CloneAttributes(), filter);
sinks.AddLast(new WeakReference(sink));
return sink;
}
/// <summary> Adds a <see cref="SinkTokenStream" /> created by another <c>TeeSinkTokenFilter</c>
/// to this one. The supplied stream will also receive all consumed tokens.
/// This method can be used to pass tokens from two different tees to one sink.
/// </summary>
public void AddSinkTokenStream(SinkTokenStream sink)
{
// check that sink has correct factory
if (!this.Factory.Equals(sink.Factory))
{
throw new System.ArgumentException("The supplied sink is not compatible to this tee");
}
// add eventually missing attribute impls to the existing sink
foreach (var impl in this.CloneAttributes().GetAttributeImplsIterator())
{
sink.AddAttributeImpl(impl);
}
sinks.AddLast(new WeakReference(sink));
}
/// <summary> <c>TeeSinkTokenFilter</c> passes all tokens to the added sinks
/// when itself is consumed. To be sure, that all tokens from the input
/// stream are passed to the sinks, you can call this methods.
/// This instance is exhausted after this, but all sinks are instant available.
/// </summary>
public void ConsumeAllTokens()
{
while (IncrementToken())
{
}
}
public override bool IncrementToken()
{
if (input.IncrementToken())
{
// capture state lazily - maybe no SinkFilter accepts this state
State state = null;
foreach(WeakReference wr in sinks)
{
var sink = (SinkTokenStream)wr.Target;
if (sink != null)
{
if (sink.Accept(this))
{
if (state == null)
{
state = this.CaptureState();
}
sink.AddState(state);
}
}
}
return true;
}
return false;
}
public override void End()
{
base.End();
State finalState = CaptureState();
foreach(WeakReference wr in sinks)
{
var sink = (SinkTokenStream)wr.Target;
if (sink != null)
{
sink.SetFinalState(finalState);
}
}
}
/// <summary> A filter that decides which <see cref="AttributeSource" /> states to store in the sink.</summary>
public abstract class SinkFilter
{
/// <summary> Returns true, iff the current state of the passed-in <see cref="AttributeSource" /> shall be stored
/// in the sink.
/// </summary>
public abstract bool Accept(AttributeSource source);
/// <summary> Called by <see cref="SinkTokenStream.Reset()" />. This method does nothing by default
/// and can optionally be overridden.
/// </summary>
public virtual void Reset()
{
// nothing to do; can be overridden
}
}
public sealed class SinkTokenStream : TokenStream
{
private readonly LinkedList<State> cachedStates = new LinkedList<State>();
private State finalState;
private IEnumerator<AttributeSource.State> it = null;
private readonly SinkFilter filter;
internal SinkTokenStream(AttributeSource source, SinkFilter filter)
: base(source)
{
this.filter = filter;
}
internal /*private*/ bool Accept(AttributeSource source)
{
return filter.Accept(source);
}
internal /*private*/ void AddState(AttributeSource.State state)
{
if (it != null)
{
throw new System.SystemException("The tee must be consumed before sinks are consumed.");
}
cachedStates.AddLast(state);
}
internal /*private*/ void SetFinalState(AttributeSource.State finalState)
{
this.finalState = finalState;
}
public override bool IncrementToken()
{
// lazy init the iterator
if (it == null)
{
it = cachedStates.GetEnumerator();
}
if (!it.MoveNext())
{
return false;
}
State state = it.Current;
RestoreState(state);
return true;
}
public override void End()
{
if (finalState != null)
{
RestoreState(finalState);
}
}
public override void Reset()
{
it = cachedStates.GetEnumerator();
}
protected override void Dispose(bool disposing)
{
// Do nothing.
}
}
private static readonly SinkFilter ACCEPT_ALL_FILTER;
static TeeSinkTokenFilter()
{
ACCEPT_ALL_FILTER = new AnonymousClassSinkFilter();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using SIL.Reporting;
namespace SIL.i18n
{
public class StringCatalog
{
private Dictionary<string, string> _catalog;
private static StringCatalog _singleton;
private static Font _font;
private static bool _inInternationalizationTestMode;
/// <summary>
/// Construct with no actual string file
/// </summary>
public StringCatalog(): this(String.Empty, 9)
{
}
/// <summary>
/// Construct with no actual string file
/// </summary>
public StringCatalog(string labelFontName, float labelFontSizeInPoints)
{
Init();
SetupUIFont(labelFontName, labelFontSizeInPoints );
}
private enum State
{
InMsgId,
InMsgStr,
Reset
} ;
public StringCatalog(string pathToPoFile, string labelFontName, float labelFontSizeInPoints)
{
Init();
_inInternationalizationTestMode = pathToPoFile == "test";
if (!_inInternationalizationTestMode)
{
using (var reader = File.OpenText(pathToPoFile))
{
string id = "";
string message = "";
string line = reader.ReadLine();
var state = State.Reset;
while (line != null)
{
switch (state)
{
case State.Reset:
if (line.StartsWith("msgid"))
{
state = State.InMsgId;
id = GetStringBetweenQuotes(line);
}
break;
case State.InMsgId:
if (line.StartsWith("msgstr"))
{
state = State.InMsgStr;
message = GetStringBetweenQuotes(line);
}
else if (line.StartsWith("\""))
{
id += GetStringBetweenQuotes(line);
}
break;
case State.InMsgStr:
if (string.IsNullOrEmpty(line))
{
state = State.Reset;
if (!(string.IsNullOrEmpty(id) || string.IsNullOrEmpty(message) || _catalog.ContainsKey(id)))
{
_catalog.Add(id.Trim(), message.Trim());
}
id = "";
message = "";
}
else if (line.StartsWith("\""))
{
message += GetStringBetweenQuotes(line);
}
break;
}
line = reader.ReadLine();
}
if (!(string.IsNullOrEmpty(id) || string.IsNullOrEmpty(message) || _catalog.ContainsKey(id)))
{
_catalog.Add(id, message);
}
}
}
SetupUIFont(labelFontName, labelFontSizeInPoints);
}
private void SetupUIFont(string labelFontName, float labelFontSizeInPoints)
{
if (_inInternationalizationTestMode)
{
LabelFont = new Font(FontFamily.GenericSansSerif, 9);
return;
}
LabelFont = new Font(FontFamily.GenericSansSerif, (float) 8.25, FontStyle.Regular);
if(!String.IsNullOrEmpty(labelFontName ))
{
try
{
LabelFont = new Font(labelFontName, labelFontSizeInPoints, FontStyle.Regular);
}
catch (Exception)
{
ErrorReport.NotifyUserOfProblem(
"Could not find the requested UI font '{0}'. Will use a generic font instead.",
labelFontName);
}
}
}
public static string Get(string id)
{
return Get(id, String.Empty);
}
/// <summary>
/// Clients should use this rather than running string.Format themselves,
/// because this has error checking and a helpful message, should the number
/// of parameters be wrong.
/// </summary>
/// <param name="id"></param>
/// <param name="translationNotes">just for the string scanner's use</param>
/// <param name="args">arguments to the string, used in string.format</param>
/// <returns></returns>
public static string GetFormatted(string id, string translationNotes, params object[] args)
{
//todo: this doesn't notice if the catalog has too few arugment slots, e.g.
//if it says "blah" when it should say "blah{0}"
try
{
var s = Get(id, translationNotes);
try
{
s = String.Format(s, args);
return s;
}
catch(Exception e)
{
Reporting.ErrorReport.NotifyUserOfProblem(
"There was a problem localizing\r\n'{0}'\r\ninto this UI language... check number of parameters. The code expects there to be {1}. The current localized string is\r\n'{2}'.\r\nThe error was {3}", id, args.Length, s, e.Message);
return "!!"+s; // show it without the formatting
}
}
catch(Exception e)
{
return "Error localizing string '" + id + "' to this UI language";
}
}
public static string Get(string id, string translationNotes)
{
if (!String.IsNullOrEmpty(id) && id[0] == '~')
{
id = id.Substring(1);
}
if (_singleton == null) //todo: this should not be needed
{
return id;
}
if (_inInternationalizationTestMode)
{
return "*"+_singleton[id];
}
else
{
return _singleton[id];
}
}
private void Init()
{
_singleton = this;
_catalog = new Dictionary<string, string>();
}
private static string GetStringBetweenQuotes(string line)
{
int s = line.IndexOf('"');
int f = line.LastIndexOf('"');
return line.Substring(s + 1, f - (s + 1));
}
public string this[string id]
{
get
{
string translated = null;
if (_catalog.ContainsKey(id))
{
return _catalog[id];
}
//REVIEW: What's this about? It was id = id.Replace("&&", "&"); which was removing the && we need when it gets to the UI
var idWithSingleAmpersand =id.Replace("&&", "&");
if (_catalog.ContainsKey(idWithSingleAmpersand))
{
return _catalog[idWithSingleAmpersand];
}
return id;
}
}
public static Font LabelFont
{
get
{
if (_font == null)
{
_font = new Font(FontFamily.GenericSansSerif, 9);
}
return _font;
}
set
{
_font = value;
}
}
// Font resizing is deprecated - obsolete API DG 2011-12
public static Font ModifyFontForLocalization(Font incoming)
{
return incoming;
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="Framing.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using Akka.IO;
using Akka.Streams.Implementation.Stages;
using Akka.Streams.Stage;
using Akka.Util;
namespace Akka.Streams.Dsl
{
/// <summary>
/// TBD
/// </summary>
public static class Framing
{
/// <summary>
/// Creates a Flow that handles decoding a stream of unstructured byte chunks into a stream of frames where the
/// incoming chunk stream uses a specific byte-sequence to mark frame boundaries.
///
/// The decoded frames will not include the separator sequence.
///
/// If there are buffered bytes (an incomplete frame) when the input stream finishes and <paramref name="allowTruncation"/> is set to
/// false then this Flow will fail the stream reporting a truncated frame.
/// </summary>
/// <param name="delimiter">The byte sequence to be treated as the end of the frame.</param>
/// <param name="maximumFrameLength">The maximum length of allowed frames while decoding. If the maximum length is exceeded this Flow will fail the stream.</param>
/// <param name="allowTruncation">If false, then when the last frame being decoded contains no valid delimiter this Flow fails the stream instead of returning a truncated frame.</param>
/// <returns>TBD</returns>
public static Flow<ByteString, ByteString, NotUsed> Delimiter(ByteString delimiter, int maximumFrameLength,
bool allowTruncation = false)
{
return Flow.Create<ByteString>()
.Via(new DelimiterFramingStage(delimiter, maximumFrameLength, allowTruncation))
.Named("DelimiterFraming");
}
/// <summary>
/// Creates a Flow that decodes an incoming stream of unstructured byte chunks into a stream of frames, assuming that
/// incoming frames have a field that encodes their length.
///
/// If the input stream finishes before the last frame has been fully decoded this Flow will fail the stream reporting
/// a truncated frame.
/// </summary>
/// <param name="fieldLength">The length of the "Count" field in bytes</param>
/// <param name="maximumFramelength">The maximum length of allowed frames while decoding. If the maximum length is exceeded this Flow will fail the stream. This length *includes* the header (i.e the offset and the length of the size field)</param>
/// <param name="fieldOffset">The offset of the field from the beginning of the frame in bytes</param>
/// <param name="byteOrder">The <see cref="ByteOrder"/> to be used when decoding the field</param>
/// <exception cref="ArgumentException">TBD</exception>
/// <returns>TBD</returns>
public static Flow<ByteString, ByteString, NotUsed> LengthField(int fieldLength, int maximumFramelength,
int fieldOffset = 0, ByteOrder byteOrder = ByteOrder.LittleEndian)
{
if (fieldLength < 1 || fieldLength > 4)
throw new ArgumentException("Length field length must be 1,2,3 or 4");
return Flow.Create<ByteString>()
.Transform(() => new LengthFieldFramingStage(fieldLength, maximumFramelength, fieldOffset, byteOrder))
.Named("LengthFieldFraming");
}
/// <summary>
/// Returns a BidiFlow that implements a simple framing protocol. This is a convenience wrapper over <see cref="LengthField"/>
/// and simply attaches a length field header of four bytes (using big endian encoding) to outgoing messages, and decodes
/// such messages in the inbound direction. The decoded messages do not contain the header.
///
/// This BidiFlow is useful if a simple message framing protocol is needed (for example when TCP is used to send
/// individual messages) but no compatibility with existing protocols is necessary.
///
/// The encoded frames have the layout
/// {{{
/// [4 bytes length field, Big Endian][User Payload]
/// }}}
/// The length field encodes the length of the user payload excluding the header itself.
/// </summary>
/// <param name="maximumMessageLength">Maximum length of allowed messages. If sent or received messages exceed the configured limit this BidiFlow will fail the stream. The header attached by this BidiFlow are not included in this limit.</param>
/// <returns>TBD</returns>
public static BidiFlow<ByteString, ByteString, ByteString, ByteString, NotUsed> SimpleFramingProtocol(int maximumMessageLength)
{
return BidiFlow.FromFlowsMat(SimpleFramingProtocolEncoder(maximumMessageLength),
SimpleFramingProtocolDecoder(maximumMessageLength), Keep.Left);
}
/// <summary>
/// Protocol decoder that is used by <see cref="SimpleFramingProtocol"/>
/// </summary>
/// <param name="maximumMessageLength">TBD</param>
/// <returns>TBD</returns>
public static Flow<ByteString, ByteString, NotUsed> SimpleFramingProtocolDecoder(int maximumMessageLength)
{
return LengthField(4, maximumMessageLength + 4, 0, ByteOrder.BigEndian).Select(b => b.Drop(4));
}
/// <summary>
/// Protocol encoder that is used by <see cref="SimpleFramingProtocol"/>
/// </summary>
/// <param name="maximumMessageLength">TBD</param>
/// <returns>TBD</returns>
public static Flow<ByteString, ByteString, NotUsed> SimpleFramingProtocolEncoder(int maximumMessageLength)
{
return Flow.Create<ByteString>().Transform(() => new FramingDecoderStage(maximumMessageLength));
}
/// <summary>
/// TBD
/// </summary>
public class FramingException : Exception
{
/// <summary>
/// TBD
/// </summary>
/// <param name="message">TBD</param>
public FramingException(string message) : base(message)
{
}
}
private static readonly Func<ByteIterator, int, int> BigEndianDecoder = (byteString, length) =>
{
var count = length;
var decoded = 0;
while (count > 0)
{
decoded <<= 8;
decoded |= byteString.Next() & 0xFF;
count--;
}
return decoded;
};
private static readonly Func<ByteIterator, int, int> LittleEndianDecoder = (byteString, length) =>
{
var highestOcted = (length - 1) << 3;
var mask = (int) (1L << (length << 3)) - 1;
var count = length;
var decoded = 0;
while (count > 0)
{
// decoded >>>= 8 on the jvm
decoded = (int) ((uint) decoded >> 8);
decoded += (byteString.Next() & 0xFF) << highestOcted;
count--;
}
return decoded & mask;
};
private sealed class FramingDecoderStage : PushStage<ByteString, ByteString>
{
private readonly int _maximumMessageLength;
public FramingDecoderStage(int maximumMessageLength)
{
_maximumMessageLength = maximumMessageLength;
}
public override ISyncDirective OnPush(ByteString element, IContext<ByteString> context)
{
var messageSize = element.Count;
if (messageSize > _maximumMessageLength)
return context.Fail(new FramingException($"Maximum allowed message size is {_maximumMessageLength} but tried to send {messageSize} bytes"));
var header = ByteString.Create(new[]
{
Convert.ToByte((messageSize >> 24) & 0xFF),
Convert.ToByte((messageSize >> 16) & 0xFF),
Convert.ToByte((messageSize >> 8) & 0xFF),
Convert.ToByte(messageSize & 0xFF)
});
return context.Push(header + element);
}
}
private sealed class DelimiterFramingStage : GraphStage<FlowShape<ByteString, ByteString>>
{
#region Logic
private sealed class Logic : InAndOutGraphStageLogic
{
private readonly DelimiterFramingStage _stage;
private readonly byte _firstSeparatorByte;
private ByteString _buffer;
private int _nextPossibleMatch;
public Logic(DelimiterFramingStage stage) : base (stage.Shape)
{
_stage = stage;
_firstSeparatorByte = stage._separatorBytes.Head;
_buffer = ByteString.Empty;
SetHandler(stage.In, this);
SetHandler(stage.Out, this);
}
public override void OnPush()
{
_buffer += Grab(_stage.In);
DoParse();
}
public override void OnUpstreamFinish()
{
if (_buffer.IsEmpty)
CompleteStage();
else if (IsAvailable(_stage.Out))
DoParse();
// else swallow the termination and wait for pull
}
public override void OnPull() => DoParse();
private void TryPull()
{
if (IsClosed(_stage.In))
{
if (_stage._allowTruncation)
{
Push(_stage.Out, _buffer);
CompleteStage();
}
else
FailStage(
new FramingException(
"Stream finished but there was a truncated final frame in the buffer"));
}
else
Pull(_stage.In);
}
private void DoParse()
{
var possibleMatchPosition = -1;
for (var i = _nextPossibleMatch; i < _buffer.Count; i++)
{
if (_buffer[i] == _firstSeparatorByte)
{
possibleMatchPosition = i;
break;
}
}
if (possibleMatchPosition > _stage._maximumLineBytes)
FailStage(
new FramingException(
$"Read {_buffer.Count} bytes which is more than {_stage._maximumLineBytes} without seeing a line terminator"));
else if (possibleMatchPosition == -1)
{
if (_buffer.Count > _stage._maximumLineBytes)
FailStage(
new FramingException(
$"Read {_buffer.Count} bytes which is more than {_stage._maximumLineBytes} without seeing a line terminator"));
else
{
// No matching character, we need to accumulate more bytes into the buffer
_nextPossibleMatch = _buffer.Count;
TryPull();
}
}
else if (possibleMatchPosition + _stage._separatorBytes.Count > _buffer.Count)
{
// We have found a possible match (we found the first character of the terminator
// sequence) but we don't have yet enough bytes. We remember the position to
// retry from next time.
_nextPossibleMatch = possibleMatchPosition;
TryPull();
}
else if (Equals(_buffer.Slice(possibleMatchPosition, possibleMatchPosition + _stage._separatorBytes.Count), _stage._separatorBytes))
{
// Found a match
var parsedFrame = _buffer.Slice(0, possibleMatchPosition).Compact();
_buffer = _buffer.Drop(possibleMatchPosition + _stage._separatorBytes.Count).Compact();
_nextPossibleMatch = 0;
Push(_stage.Out, parsedFrame);
if (IsClosed(_stage.In) && _buffer.IsEmpty)
CompleteStage();
}
else
{
// possibleMatchPos was not actually a match
_nextPossibleMatch++;
DoParse();
}
}
}
#endregion
private readonly ByteString _separatorBytes;
private readonly int _maximumLineBytes;
private readonly bool _allowTruncation;
public DelimiterFramingStage(ByteString separatorBytes, int maximumLineBytes, bool allowTruncation)
{
_separatorBytes = separatorBytes;
_maximumLineBytes = maximumLineBytes;
_allowTruncation = allowTruncation;
Shape = new FlowShape<ByteString, ByteString>(In, Out);
}
private Inlet<ByteString> In = new Inlet<ByteString>("DelimiterFraming.in");
private Outlet<ByteString> Out = new Outlet<ByteString>("DelimiterFraming.in");
public override FlowShape<ByteString, ByteString> Shape { get; }
protected override Attributes InitialAttributes { get; } = DefaultAttributes.DelimiterFraming;
protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this);
public override string ToString() => "DelimiterFraming";
}
private sealed class LengthFieldFramingStage : PushPullStage<ByteString, ByteString>
{
private readonly int _lengthFieldLength;
private readonly int _maximumFramelength;
private readonly int _lengthFieldOffset;
private ByteString _buffer = ByteString.Empty;
private readonly int _minimumChunkSize;
private int _frameSize;
private readonly Func<ByteIterator, int, int> _intDecoder;
public LengthFieldFramingStage(int lengthFieldLength, int maximumFramelength, int lengthFieldOffset, ByteOrder byteOrder)
{
_lengthFieldLength = lengthFieldLength;
_maximumFramelength = maximumFramelength;
_lengthFieldOffset = lengthFieldOffset;
_minimumChunkSize = lengthFieldOffset + lengthFieldLength;
_frameSize = int.MaxValue;
_intDecoder = byteOrder == ByteOrder.BigEndian ? BigEndianDecoder : LittleEndianDecoder;
}
public override ISyncDirective OnPush(ByteString element, IContext<ByteString> context)
{
_buffer += element;
return DoParse(context);
}
public override ISyncDirective OnPull(IContext<ByteString> context) => DoParse(context);
public override ITerminationDirective OnUpstreamFinish(IContext<ByteString> context)
{
return _buffer.NonEmpty ? context.AbsorbTermination() : context.Finish();
}
public override void PostStop() => _buffer = null;
private ISyncDirective TryPull(IContext<ByteString> context)
{
if (context.IsFinishing)
return context.Fail(new FramingException("Stream finished but there was a truncated final frame in the buffer"));
return context.Pull();
}
private ISyncDirective DoParse(IContext<ByteString> context)
{
Func<IContext<ByteString>, ISyncDirective> emitFrame = ctx =>
{
var parsedFrame = _buffer.Take(_frameSize).Compact();
_buffer = _buffer.Drop(_frameSize);
_frameSize = int.MaxValue;
if (ctx.IsFinishing && _buffer.IsEmpty)
return ctx.PushAndFinish(parsedFrame);
return ctx.Push(parsedFrame);
};
var bufferSize = _buffer.Count;
if (bufferSize >= _frameSize)
return emitFrame(context);
if (bufferSize >= _minimumChunkSize)
{
var parsedLength = _intDecoder(_buffer.Iterator().Drop(_lengthFieldOffset), _lengthFieldLength);
_frameSize = parsedLength + _minimumChunkSize;
if (_frameSize > _maximumFramelength)
return context.Fail(new FramingException($"Maximum allowed frame size is {_maximumFramelength} but decoded frame header reported size {_frameSize}"));
if (bufferSize >= _frameSize)
return emitFrame(context);
return TryPull(context);
}
return TryPull(context);
}
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using Microsoft.Azure;
using Microsoft.Azure.Commands.Compute.Automation.Models;
using Microsoft.Azure.Management.Compute;
using Microsoft.Azure.Management.Compute.Models;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Reflection;
namespace Microsoft.Azure.Commands.Compute.Automation
{
public partial class InvokeAzureComputeMethodCmdlet : ComputeAutomationBaseCmdlet
{
protected object CreateContainerServiceCreateOrUpdateDynamicParameters()
{
dynamicParameters = new RuntimeDefinedParameterDictionary();
var pResourceGroupName = new RuntimeDefinedParameter();
pResourceGroupName.Name = "ResourceGroupName";
pResourceGroupName.ParameterType = typeof(string);
pResourceGroupName.Attributes.Add(new ParameterAttribute
{
ParameterSetName = "InvokeByDynamicParameters",
Position = 1,
Mandatory = true
});
pResourceGroupName.Attributes.Add(new AllowNullAttribute());
dynamicParameters.Add("ResourceGroupName", pResourceGroupName);
var pContainerServiceName = new RuntimeDefinedParameter();
pContainerServiceName.Name = "Name";
pContainerServiceName.ParameterType = typeof(string);
pContainerServiceName.Attributes.Add(new ParameterAttribute
{
ParameterSetName = "InvokeByDynamicParameters",
Position = 2,
Mandatory = true
});
pContainerServiceName.Attributes.Add(new AllowNullAttribute());
dynamicParameters.Add("Name", pContainerServiceName);
var pParameters = new RuntimeDefinedParameter();
pParameters.Name = "ContainerService";
pParameters.ParameterType = typeof(ContainerService);
pParameters.Attributes.Add(new ParameterAttribute
{
ParameterSetName = "InvokeByDynamicParameters",
Position = 3,
Mandatory = true
});
pParameters.Attributes.Add(new AllowNullAttribute());
dynamicParameters.Add("ContainerService", pParameters);
var pArgumentList = new RuntimeDefinedParameter();
pArgumentList.Name = "ArgumentList";
pArgumentList.ParameterType = typeof(object[]);
pArgumentList.Attributes.Add(new ParameterAttribute
{
ParameterSetName = "InvokeByStaticParameters",
Position = 4,
Mandatory = true
});
pArgumentList.Attributes.Add(new AllowNullAttribute());
dynamicParameters.Add("ArgumentList", pArgumentList);
return dynamicParameters;
}
protected void ExecuteContainerServiceCreateOrUpdateMethod(object[] invokeMethodInputParameters)
{
string resourceGroupName = (string)ParseParameter(invokeMethodInputParameters[0]);
string containerServiceName = (string)ParseParameter(invokeMethodInputParameters[1]);
ContainerService parameters = (ContainerService)ParseParameter(invokeMethodInputParameters[2]);
var result = ContainerServiceClient.CreateOrUpdate(resourceGroupName, containerServiceName, parameters);
WriteObject(result);
}
}
public partial class NewAzureComputeArgumentListCmdlet : ComputeAutomationBaseCmdlet
{
protected PSArgument[] CreateContainerServiceCreateOrUpdateParameters()
{
string resourceGroupName = string.Empty;
string containerServiceName = string.Empty;
ContainerService parameters = new ContainerService();
return ConvertFromObjectsToArguments(
new string[] { "ResourceGroupName", "ContainerServiceName", "Parameters" },
new object[] { resourceGroupName, containerServiceName, parameters });
}
}
[Cmdlet("New", "AzureRmContainerService", DefaultParameterSetName = "InvokeByDynamicParameters", SupportsShouldProcess = true)]
public partial class NewAzureRmContainerService : InvokeAzureComputeMethodCmdlet
{
public override string MethodName { get; set; }
protected override void ProcessRecord()
{
this.MethodName = "ContainerServiceCreateOrUpdate";
if (ShouldProcess(this.dynamicParameters["ResourceGroupName"].Value.ToString(), VerbsCommon.New))
{
base.ProcessRecord();
}
}
public override object GetDynamicParameters()
{
dynamicParameters = new RuntimeDefinedParameterDictionary();
var pResourceGroupName = new RuntimeDefinedParameter();
pResourceGroupName.Name = "ResourceGroupName";
pResourceGroupName.ParameterType = typeof(string);
pResourceGroupName.Attributes.Add(new ParameterAttribute
{
ParameterSetName = "InvokeByDynamicParameters",
Position = 1,
Mandatory = true,
ValueFromPipeline = false
});
pResourceGroupName.Attributes.Add(new AllowNullAttribute());
dynamicParameters.Add("ResourceGroupName", pResourceGroupName);
var pContainerServiceName = new RuntimeDefinedParameter();
pContainerServiceName.Name = "Name";
pContainerServiceName.ParameterType = typeof(string);
pContainerServiceName.Attributes.Add(new ParameterAttribute
{
ParameterSetName = "InvokeByDynamicParameters",
Position = 2,
Mandatory = true,
ValueFromPipeline = false
});
pContainerServiceName.Attributes.Add(new AllowNullAttribute());
dynamicParameters.Add("Name", pContainerServiceName);
var pParameters = new RuntimeDefinedParameter();
pParameters.Name = "ContainerService";
pParameters.ParameterType = typeof(ContainerService);
pParameters.Attributes.Add(new ParameterAttribute
{
ParameterSetName = "InvokeByDynamicParameters",
Position = 3,
Mandatory = true,
ValueFromPipeline = true
});
pParameters.Attributes.Add(new AllowNullAttribute());
dynamicParameters.Add("ContainerService", pParameters);
return dynamicParameters;
}
}
[Cmdlet("Update", "AzureRmContainerService", DefaultParameterSetName = "InvokeByDynamicParameters", SupportsShouldProcess = true)]
public partial class UpdateAzureRmContainerService : InvokeAzureComputeMethodCmdlet
{
public override string MethodName { get; set; }
protected override void ProcessRecord()
{
this.MethodName = "ContainerServiceCreateOrUpdate";
if (ShouldProcess(this.dynamicParameters["ResourceGroupName"].Value.ToString(), VerbsData.Update))
{
base.ProcessRecord();
}
}
public override object GetDynamicParameters()
{
dynamicParameters = new RuntimeDefinedParameterDictionary();
var pResourceGroupName = new RuntimeDefinedParameter();
pResourceGroupName.Name = "ResourceGroupName";
pResourceGroupName.ParameterType = typeof(string);
pResourceGroupName.Attributes.Add(new ParameterAttribute
{
ParameterSetName = "InvokeByDynamicParameters",
Position = 1,
Mandatory = true,
ValueFromPipeline = false
});
pResourceGroupName.Attributes.Add(new AllowNullAttribute());
dynamicParameters.Add("ResourceGroupName", pResourceGroupName);
var pContainerServiceName = new RuntimeDefinedParameter();
pContainerServiceName.Name = "Name";
pContainerServiceName.ParameterType = typeof(string);
pContainerServiceName.Attributes.Add(new ParameterAttribute
{
ParameterSetName = "InvokeByDynamicParameters",
Position = 2,
Mandatory = true,
ValueFromPipeline = false
});
pContainerServiceName.Attributes.Add(new AllowNullAttribute());
dynamicParameters.Add("Name", pContainerServiceName);
var pParameters = new RuntimeDefinedParameter();
pParameters.Name = "ContainerService";
pParameters.ParameterType = typeof(ContainerService);
pParameters.Attributes.Add(new ParameterAttribute
{
ParameterSetName = "InvokeByDynamicParameters",
Position = 3,
Mandatory = true,
ValueFromPipeline = true
});
pParameters.Attributes.Add(new AllowNullAttribute());
dynamicParameters.Add("ContainerService", pParameters);
return dynamicParameters;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using Internal.NativeFormat;
namespace Internal.TypeSystem
{
[Flags]
public enum MethodSignatureFlags
{
None = 0x0000,
// TODO: Generic, etc.
UnmanagedCallingConventionMask = 0x000F,
UnmanagedCallingConventionCdecl = 0x0001,
UnmanagedCallingConventionStdCall = 0x0002,
UnmanagedCallingConventionThisCall = 0x0003,
Static = 0x0010,
}
/// <summary>
/// Represents the parameter types, the return type, and flags of a method.
/// </summary>
public sealed partial class MethodSignature
{
internal MethodSignatureFlags _flags;
internal int _genericParameterCount;
internal TypeDesc _returnType;
internal TypeDesc[] _parameters;
public MethodSignature(MethodSignatureFlags flags, int genericParameterCount, TypeDesc returnType, TypeDesc[] parameters)
{
_flags = flags;
_genericParameterCount = genericParameterCount;
_returnType = returnType;
_parameters = parameters;
Debug.Assert(parameters != null, "Parameters must not be null");
}
public MethodSignatureFlags Flags
{
get
{
return _flags;
}
}
public bool IsStatic
{
get
{
return (_flags & MethodSignatureFlags.Static) != 0;
}
}
public int GenericParameterCount
{
get
{
return _genericParameterCount;
}
}
public TypeDesc ReturnType
{
get
{
return _returnType;
}
}
/// <summary>
/// Gets the parameter type at the specified index.
/// </summary>
[IndexerName("Parameter")]
public TypeDesc this[int index]
{
get
{
return _parameters[index];
}
}
/// <summary>
/// Gets the number of parameters of this method signature.
/// </summary>
public int Length
{
get
{
return _parameters.Length;
}
}
public bool Equals(MethodSignature otherSignature)
{
// TODO: Generics, etc.
if (this._flags != otherSignature._flags)
return false;
if (this._genericParameterCount != otherSignature._genericParameterCount)
return false;
if (this._returnType != otherSignature._returnType)
return false;
if (this._parameters.Length != otherSignature._parameters.Length)
return false;
for (int i = 0; i < this._parameters.Length; i++)
{
if (this._parameters[i] != otherSignature._parameters[i])
return false;
}
return true;
}
public override bool Equals(object obj)
{
return obj is MethodSignature && Equals((MethodSignature)obj);
}
public override int GetHashCode()
{
return TypeHashingAlgorithms.ComputeMethodSignatureHashCode(_returnType.GetHashCode(), _parameters);
}
}
/// <summary>
/// Helper structure for building method signatures by cloning an existing method signature.
/// </summary>
/// <remarks>
/// This can potentially avoid array allocation costs for allocating the parameter type list.
/// </remarks>
public struct MethodSignatureBuilder
{
private MethodSignature _template;
private MethodSignatureFlags _flags;
private int _genericParameterCount;
private TypeDesc _returnType;
private TypeDesc[] _parameters;
public MethodSignatureBuilder(MethodSignature template)
{
_template = template;
_flags = template._flags;
_genericParameterCount = template._genericParameterCount;
_returnType = template._returnType;
_parameters = template._parameters;
}
public MethodSignatureFlags Flags
{
set
{
_flags = value;
}
}
public TypeDesc ReturnType
{
set
{
_returnType = value;
}
}
[System.Runtime.CompilerServices.IndexerName("Parameter")]
public TypeDesc this[int index]
{
set
{
if (_parameters[index] == value)
return;
if (_template != null && _parameters == _template._parameters)
{
TypeDesc[] parameters = new TypeDesc[_parameters.Length];
for (int i = 0; i < parameters.Length; i++)
parameters[i] = _parameters[i];
_parameters = parameters;
}
_parameters[index] = value;
}
}
public int Length
{
set
{
_parameters = new TypeDesc[value];
_template = null;
}
}
public MethodSignature ToSignature()
{
if (_template == null ||
_flags != _template._flags ||
_genericParameterCount != _template._genericParameterCount ||
_returnType != _template._returnType ||
_parameters != _template._parameters)
{
_template = new MethodSignature(_flags, _genericParameterCount, _returnType, _parameters);
}
return _template;
}
}
/// <summary>
/// Represents the fundamental base type for all methods within the type system.
/// </summary>
public abstract partial class MethodDesc : TypeSystemEntity
{
public static readonly MethodDesc[] EmptyMethods = new MethodDesc[0];
private int _hashcode;
/// <summary>
/// Allows a performance optimization that skips the potentially expensive
/// construction of a hash code if a hash code has already been computed elsewhere.
/// Use to allow objects to have their hashcode computed
/// independently of the allocation of a MethodDesc object
/// For instance, compute the hashcode when looking up the object,
/// then when creating the object, pass in the hashcode directly.
/// The hashcode specified MUST exactly match the algorithm implemented
/// on this type normally.
/// </summary>
protected void SetHashCode(int hashcode)
{
_hashcode = hashcode;
Debug.Assert(hashcode == ComputeHashCode());
}
public sealed override int GetHashCode()
{
if (_hashcode != 0)
return _hashcode;
return AcquireHashCode();
}
private int AcquireHashCode()
{
_hashcode = ComputeHashCode();
return _hashcode;
}
/// <summary>
/// Compute HashCode. Should only be overriden by a MethodDesc that represents an instantiated method.
/// </summary>
protected virtual int ComputeHashCode()
{
return TypeHashingAlgorithms.ComputeMethodHashCode(OwningType.GetHashCode(), TypeHashingAlgorithms.ComputeNameHashCode(Name));
}
public override bool Equals(Object o)
{
// Its only valid to compare two MethodDescs in the same context
Debug.Assert(Object.ReferenceEquals(o, null) || !(o is MethodDesc) || Object.ReferenceEquals(((MethodDesc)o).Context, this.Context));
return Object.ReferenceEquals(this, o);
}
/// <summary>
/// Gets the type that owns this method. This will be a <see cref="DefType"/> or
/// an <see cref="ArrayType"/>.
/// </summary>
public abstract TypeDesc OwningType
{
get;
}
/// <summary>
/// Gets the signature of the method.
/// </summary>
public abstract MethodSignature Signature
{
get;
}
/// <summary>
/// Gets the generic instantiation information of this method.
/// For generic definitions, retrieves the generic parameters of the method.
/// For generic instantiation, retrieves the generic arguments of the method.
/// </summary>
public virtual Instantiation Instantiation
{
get
{
return Instantiation.Empty;
}
}
/// <summary>
/// Gets a value indicating whether this method has a generic instantiation.
/// This will be true for generic method instantiations and generic definitions.
/// </summary>
public bool HasInstantiation
{
get
{
return this.Instantiation.Length != 0;
}
}
/// <summary>
/// Gets a value indicating whether this method is an instance constructor.
/// </summary>
public bool IsConstructor
{
get
{
// TODO: Precise check
// TODO: Cache?
return this.Name == ".ctor";
}
}
/// <summary>
/// Gets a value indicating whether this is a public parameterless instance constructor
/// on a non-abstract type.
/// </summary>
public virtual bool IsDefaultConstructor
{
get
{
return OwningType.GetDefaultConstructor() == this;
}
}
/// <summary>
/// Gets a value indicating whether this method is a static constructor.
/// </summary>
public bool IsStaticConstructor
{
get
{
return this == this.OwningType.GetStaticConstructor();
}
}
/// <summary>
/// Gets the name of the method as specified in the metadata.
/// </summary>
public virtual string Name
{
get
{
return null;
}
}
/// <summary>
/// Gets a value indicating whether the method is virtual.
/// </summary>
public virtual bool IsVirtual
{
get
{
return false;
}
}
/// <summary>
/// Gets a value indicating whether this virtual method should not override any
/// virtual methods defined in any of the base classes.
/// </summary>
public virtual bool IsNewSlot
{
get
{
return false;
}
}
/// <summary>
/// Gets a value indicating whether this virtual method needs to be overriden
/// by all non-abstract classes deriving from the method's owning type.
/// </summary>
public virtual bool IsAbstract
{
get
{
return false;
}
}
/// <summary>
/// Gets a value indicating that this method cannot be overriden.
/// </summary>
public virtual bool IsFinal
{
get
{
return false;
}
}
public abstract bool HasCustomAttribute(string attributeNamespace, string attributeName);
/// <summary>
/// Retrieves the uninstantiated form of the method on the method's <see cref="OwningType"/>.
/// For generic methods, this strips method instantiation. For non-generic methods, returns 'this'.
/// To also strip instantiation of the owning type, use <see cref="GetTypicalMethodDefinition"/>.
/// </summary>
public virtual MethodDesc GetMethodDefinition()
{
return this;
}
/// <summary>
/// Gets a value indicating whether this is a method definition. This property
/// is true for non-generic methods and for uninstantiated generic methods.
/// </summary>
public bool IsMethodDefinition
{
get
{
return GetMethodDefinition() == this;
}
}
/// <summary>
/// Retrieves the generic definition of the method on the generic definition of the owning type.
/// To only uninstantiate the method without uninstantiating the owning type, use <see cref="GetMethodDefinition"/>.
/// </summary>
public virtual MethodDesc GetTypicalMethodDefinition()
{
return this;
}
/// <summary>
/// Gets a value indicating whether this is a typical definition. This property is true
/// if neither the owning type, nor the method are instantiated.
/// </summary>
public bool IsTypicalMethodDefinition
{
get
{
return GetTypicalMethodDefinition() == this;
}
}
/// <summary>
/// Gets a value indicating whether this is an uninstantiated generic method.
/// </summary>
public bool IsGenericMethodDefinition
{
get
{
return HasInstantiation && IsMethodDefinition;
}
}
public bool IsFinalizer
{
get
{
TypeDesc owningType = OwningType;
return owningType.HasFinalizer &&
(owningType.GetFinalizer() == this || owningType.IsObject && Name == "Finalize");
}
}
public virtual MethodDesc InstantiateSignature(Instantiation typeInstantiation, Instantiation methodInstantiation)
{
Instantiation instantiation = Instantiation;
TypeDesc[] clone = null;
for (int i = 0; i < instantiation.Length; i++)
{
TypeDesc uninst = instantiation[i];
TypeDesc inst = uninst.InstantiateSignature(typeInstantiation, methodInstantiation);
if (inst != uninst)
{
if (clone == null)
{
clone = new TypeDesc[instantiation.Length];
for (int j = 0; j < clone.Length; j++)
{
clone[j] = instantiation[j];
}
}
clone[i] = inst;
}
}
MethodDesc method = this;
TypeDesc owningType = method.OwningType;
TypeDesc instantiatedOwningType = owningType.InstantiateSignature(typeInstantiation, methodInstantiation);
if (owningType != instantiatedOwningType)
{
method = Context.GetMethodForInstantiatedType(method.GetTypicalMethodDefinition(), (InstantiatedType)instantiatedOwningType);
if (clone == null && instantiation.Length != 0)
return Context.GetInstantiatedMethod(method, instantiation);
}
return (clone == null) ? method : Context.GetInstantiatedMethod(method.GetMethodDefinition(), new Instantiation(clone));
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using System.Threading;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.Packets;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using BlockingLLSDQueue = OpenSim.Framework.BlockingQueue<OpenMetaverse.StructuredData.OSD>;
using Caps=OpenSim.Framework.Capabilities.Caps;
namespace OpenSim.Region.CoreModules.Framework.EventQueue
{
public struct QueueItem
{
public int id;
public OSDMap body;
}
public class EventQueueGetModule : IEventQueue, IRegionModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected Scene m_scene = null;
private IConfigSource m_gConfig;
bool enabledYN = false;
private Dictionary<UUID, int> m_ids = new Dictionary<UUID, int>();
private Dictionary<UUID, Queue<OSD>> queues = new Dictionary<UUID, Queue<OSD>>();
private Dictionary<UUID, UUID> m_QueueUUIDAvatarMapping = new Dictionary<UUID, UUID>();
private Dictionary<UUID, UUID> m_AvatarQueueUUIDMapping = new Dictionary<UUID, UUID>();
#region IRegionModule methods
public virtual void Initialise(Scene scene, IConfigSource config)
{
m_gConfig = config;
IConfig startupConfig = m_gConfig.Configs["Startup"];
ReadConfigAndPopulate(scene, startupConfig, "Startup");
if (enabledYN)
{
m_scene = scene;
scene.RegisterModuleInterface<IEventQueue>(this);
// Register fallback handler
// Why does EQG Fail on region crossings!
//scene.CommsManager.HttpServer.AddLLSDHandler("/CAPS/EQG/", EventQueueFallBack);
scene.EventManager.OnNewClient += OnNewClient;
// TODO: Leaving these open, or closing them when we
// become a child is incorrect. It messes up TP in a big
// way. CAPS/EQ need to be active as long as the UDP
// circuit is there.
scene.EventManager.OnClientClosed += ClientClosed;
scene.EventManager.OnMakeChildAgent += MakeChildAgent;
scene.EventManager.OnRegisterCaps += OnRegisterCaps;
}
else
{
m_gConfig = null;
}
}
private void ReadConfigAndPopulate(Scene scene, IConfig startupConfig, string p)
{
enabledYN = startupConfig.GetBoolean("EventQueue", true);
}
public void PostInitialise()
{
}
public virtual void Close()
{
}
public virtual string Name
{
get { return "EventQueueGetModule"; }
}
public bool IsSharedModule
{
get { return false; }
}
#endregion
/// <summary>
/// Always returns a valid queue
/// </summary>
/// <param name="agentId"></param>
/// <returns></returns>
private Queue<OSD> TryGetQueue(UUID agentId)
{
lock (queues)
{
if (!queues.ContainsKey(agentId))
{
m_log.DebugFormat(
"[EVENTQUEUE]: Adding new queue for agent {0} in region {1}",
agentId, m_scene.RegionInfo.RegionName);
queues[agentId] = new Queue<OSD>();
}
return queues[agentId];
}
}
/// <summary>
/// May return a null queue
/// </summary>
/// <param name="agentId"></param>
/// <returns></returns>
private Queue<OSD> GetQueue(UUID agentId)
{
lock (queues)
{
if (queues.ContainsKey(agentId))
{
return queues[agentId];
}
else
return null;
}
}
#region IEventQueue Members
public bool Enqueue(OSD ev, UUID avatarID)
{
//m_log.DebugFormat("[EVENTQUEUE]: Enqueuing event for {0} in region {1}", avatarID, m_scene.RegionInfo.RegionName);
try
{
Queue<OSD> queue = GetQueue(avatarID);
if (queue != null)
queue.Enqueue(ev);
}
catch(NullReferenceException e)
{
m_log.Error("[EVENTQUEUE] Caught exception: " + e);
return false;
}
return true;
}
#endregion
private void OnNewClient(IClientAPI client)
{
//client.OnLogout += ClientClosed;
}
// private void ClientClosed(IClientAPI client)
// {
// ClientClosed(client.AgentId);
// }
private void ClientClosed(UUID AgentID, Scene scene)
{
m_log.DebugFormat("[EVENTQUEUE]: Closed client {0} in region {1}", AgentID, m_scene.RegionInfo.RegionName);
int count = 0;
while (queues.ContainsKey(AgentID) && queues[AgentID].Count > 0 && count++ < 5)
{
Thread.Sleep(1000);
}
lock (queues)
{
queues.Remove(AgentID);
}
List<UUID> removeitems = new List<UUID>();
lock (m_AvatarQueueUUIDMapping)
{
foreach (UUID ky in m_AvatarQueueUUIDMapping.Keys)
{
if (ky == AgentID)
{
removeitems.Add(ky);
}
}
foreach (UUID ky in removeitems)
{
m_AvatarQueueUUIDMapping.Remove(ky);
MainServer.Instance.RemovePollServiceHTTPHandler("","/CAPS/EQG/" + ky.ToString() + "/");
}
}
UUID searchval = UUID.Zero;
removeitems.Clear();
lock (m_QueueUUIDAvatarMapping)
{
foreach (UUID ky in m_QueueUUIDAvatarMapping.Keys)
{
searchval = m_QueueUUIDAvatarMapping[ky];
if (searchval == AgentID)
{
removeitems.Add(ky);
}
}
foreach (UUID ky in removeitems)
m_QueueUUIDAvatarMapping.Remove(ky);
}
}
private void MakeChildAgent(ScenePresence avatar)
{
//m_log.DebugFormat("[EVENTQUEUE]: Make Child agent {0} in region {1}.", avatar.UUID, m_scene.RegionInfo.RegionName);
//lock (m_ids)
// {
//if (m_ids.ContainsKey(avatar.UUID))
//{
// close the event queue.
//m_ids[avatar.UUID] = -1;
//}
//}
}
public void OnRegisterCaps(UUID agentID, Caps caps)
{
// Register an event queue for the client
//m_log.DebugFormat(
// "[EVENTQUEUE]: OnRegisterCaps: agentID {0} caps {1} region {2}",
// agentID, caps, m_scene.RegionInfo.RegionName);
// Let's instantiate a Queue for this agent right now
TryGetQueue(agentID);
string capsBase = "/CAPS/EQG/";
UUID EventQueueGetUUID = UUID.Zero;
lock (m_AvatarQueueUUIDMapping)
{
// Reuse open queues. The client does!
if (m_AvatarQueueUUIDMapping.ContainsKey(agentID))
{
m_log.DebugFormat("[EVENTQUEUE]: Found Existing UUID!");
EventQueueGetUUID = m_AvatarQueueUUIDMapping[agentID];
}
else
{
EventQueueGetUUID = UUID.Random();
//m_log.DebugFormat("[EVENTQUEUE]: Using random UUID!");
}
}
lock (m_QueueUUIDAvatarMapping)
{
if (!m_QueueUUIDAvatarMapping.ContainsKey(EventQueueGetUUID))
m_QueueUUIDAvatarMapping.Add(EventQueueGetUUID, agentID);
}
lock (m_AvatarQueueUUIDMapping)
{
if (!m_AvatarQueueUUIDMapping.ContainsKey(agentID))
m_AvatarQueueUUIDMapping.Add(agentID, EventQueueGetUUID);
}
// Register this as a caps handler
caps.RegisterHandler("EventQueueGet",
new RestHTTPHandler("POST", capsBase + EventQueueGetUUID.ToString() + "/",
delegate(Hashtable m_dhttpMethod)
{
return ProcessQueue(m_dhttpMethod, agentID, caps);
}));
// This will persist this beyond the expiry of the caps handlers
MainServer.Instance.AddPollServiceHTTPHandler(
capsBase + EventQueueGetUUID.ToString() + "/", EventQueuePath2, new PollServiceEventArgs(HasEvents, GetEvents, NoEvents, agentID));
Random rnd = new Random(Environment.TickCount);
lock (m_ids)
{
if (!m_ids.ContainsKey(agentID))
m_ids.Add(agentID, rnd.Next(30000000));
}
}
public bool HasEvents(UUID agentID)
{
// Don't use this, because of race conditions at agent closing time
//Queue<OSD> queue = TryGetQueue(agentID);
Queue<OSD> queue = GetQueue(agentID);
if (queue != null)
lock (queue)
{
if (queue.Count > 0)
return true;
else
return false;
}
return false;
}
public Hashtable GetEvents(UUID pAgentId, string request)
{
Queue<OSD> queue = TryGetQueue(pAgentId);
OSD element;
lock (queue)
{
if (queue.Count == 0)
return NoEvents();
element = queue.Dequeue(); // 15s timeout
}
int thisID = 0;
lock (m_ids)
thisID = m_ids[pAgentId];
OSDArray array = new OSDArray();
if (element == null) // didn't have an event in 15s
{
// Send it a fake event to keep the client polling! It doesn't like 502s like the proxys say!
array.Add(EventQueueHelper.KeepAliveEvent());
m_log.DebugFormat("[EVENTQUEUE]: adding fake event for {0} in region {1}", pAgentId, m_scene.RegionInfo.RegionName);
}
else
{
array.Add(element);
lock (queue)
{
while (queue.Count > 0)
{
array.Add(queue.Dequeue());
thisID++;
}
}
}
OSDMap events = new OSDMap();
events.Add("events", array);
events.Add("id", new OSDInteger(thisID));
lock (m_ids)
{
m_ids[pAgentId] = thisID + 1;
}
Hashtable responsedata = new Hashtable();
responsedata["int_response_code"] = 200;
responsedata["content_type"] = "application/xml";
responsedata["keepalive"] = false;
responsedata["reusecontext"] = false;
responsedata["str_response_string"] = OSDParser.SerializeLLSDXmlString(events);
return responsedata;
//m_log.DebugFormat("[EVENTQUEUE]: sending response for {0} in region {1}: {2}", agentID, m_scene.RegionInfo.RegionName, responsedata["str_response_string"]);
}
public Hashtable NoEvents()
{
Hashtable responsedata = new Hashtable();
responsedata["int_response_code"] = 502;
responsedata["content_type"] = "text/plain";
responsedata["keepalive"] = false;
responsedata["reusecontext"] = false;
responsedata["str_response_string"] = "Upstream error: ";
responsedata["error_status_text"] = "Upstream error:";
responsedata["http_protocol_version"] = "HTTP/1.0";
return responsedata;
}
public Hashtable ProcessQueue(Hashtable request, UUID agentID, Caps caps)
{
// TODO: this has to be redone to not busy-wait (and block the thread),
// TODO: as soon as we have a non-blocking way to handle HTTP-requests.
// if (m_log.IsDebugEnabled)
// {
// String debug = "[EVENTQUEUE]: Got request for agent {0} in region {1} from thread {2}: [ ";
// foreach (object key in request.Keys)
// {
// debug += key.ToString() + "=" + request[key].ToString() + " ";
// }
// m_log.DebugFormat(debug + " ]", agentID, m_scene.RegionInfo.RegionName, System.Threading.Thread.CurrentThread.Name);
// }
Queue<OSD> queue = TryGetQueue(agentID);
OSD element = queue.Dequeue(); // 15s timeout
Hashtable responsedata = new Hashtable();
int thisID = 0;
lock (m_ids)
thisID = m_ids[agentID];
if (element == null)
{
//m_log.ErrorFormat("[EVENTQUEUE]: Nothing to process in " + m_scene.RegionInfo.RegionName);
if (thisID == -1) // close-request
{
m_log.ErrorFormat("[EVENTQUEUE]: 404 in " + m_scene.RegionInfo.RegionName);
responsedata["int_response_code"] = 404; //501; //410; //404;
responsedata["content_type"] = "text/plain";
responsedata["keepalive"] = false;
responsedata["str_response_string"] = "Closed EQG";
return responsedata;
}
responsedata["int_response_code"] = 502;
responsedata["content_type"] = "text/plain";
responsedata["keepalive"] = false;
responsedata["str_response_string"] = "Upstream error: ";
responsedata["error_status_text"] = "Upstream error:";
responsedata["http_protocol_version"] = "HTTP/1.0";
return responsedata;
}
OSDArray array = new OSDArray();
if (element == null) // didn't have an event in 15s
{
// Send it a fake event to keep the client polling! It doesn't like 502s like the proxys say!
array.Add(EventQueueHelper.KeepAliveEvent());
m_log.DebugFormat("[EVENTQUEUE]: adding fake event for {0} in region {1}", agentID, m_scene.RegionInfo.RegionName);
}
else
{
array.Add(element);
while (queue.Count > 0)
{
array.Add(queue.Dequeue());
thisID++;
}
}
OSDMap events = new OSDMap();
events.Add("events", array);
events.Add("id", new OSDInteger(thisID));
lock (m_ids)
{
m_ids[agentID] = thisID + 1;
}
responsedata["int_response_code"] = 200;
responsedata["content_type"] = "application/xml";
responsedata["keepalive"] = false;
responsedata["str_response_string"] = OSDParser.SerializeLLSDXmlString(events);
//m_log.DebugFormat("[EVENTQUEUE]: sending response for {0} in region {1}: {2}", agentID, m_scene.RegionInfo.RegionName, responsedata["str_response_string"]);
return responsedata;
}
public Hashtable EventQueuePath2(Hashtable request)
{
string capuuid = (string)request["uri"]; //path.Replace("/CAPS/EQG/","");
// pull off the last "/" in the path.
Hashtable responsedata = new Hashtable();
capuuid = capuuid.Substring(0, capuuid.Length - 1);
capuuid = capuuid.Replace("/CAPS/EQG/", "");
UUID AvatarID = UUID.Zero;
UUID capUUID = UUID.Zero;
// parse the path and search for the avatar with it registered
if (UUID.TryParse(capuuid, out capUUID))
{
lock (m_QueueUUIDAvatarMapping)
{
if (m_QueueUUIDAvatarMapping.ContainsKey(capUUID))
{
AvatarID = m_QueueUUIDAvatarMapping[capUUID];
}
}
if (AvatarID != UUID.Zero)
{
return ProcessQueue(request, AvatarID, m_scene.CapsModule.GetCapsHandlerForUser(AvatarID));
}
else
{
responsedata["int_response_code"] = 404;
responsedata["content_type"] = "text/plain";
responsedata["keepalive"] = false;
responsedata["str_response_string"] = "Not Found";
responsedata["error_status_text"] = "Not Found";
responsedata["http_protocol_version"] = "HTTP/1.0";
return responsedata;
// return 404
}
}
else
{
responsedata["int_response_code"] = 404;
responsedata["content_type"] = "text/plain";
responsedata["keepalive"] = false;
responsedata["str_response_string"] = "Not Found";
responsedata["error_status_text"] = "Not Found";
responsedata["http_protocol_version"] = "HTTP/1.0";
return responsedata;
// return 404
}
}
public OSD EventQueueFallBack(string path, OSD request, string endpoint)
{
// This is a fallback element to keep the client from loosing EventQueueGet
// Why does CAPS fail sometimes!?
m_log.Warn("[EVENTQUEUE]: In the Fallback handler! We lost the Queue in the rest handler!");
string capuuid = path.Replace("/CAPS/EQG/","");
capuuid = capuuid.Substring(0, capuuid.Length - 1);
// UUID AvatarID = UUID.Zero;
UUID capUUID = UUID.Zero;
if (UUID.TryParse(capuuid, out capUUID))
{
/* Don't remove this yet code cleaners!
* Still testing this!
*
lock (m_QueueUUIDAvatarMapping)
{
if (m_QueueUUIDAvatarMapping.ContainsKey(capUUID))
{
AvatarID = m_QueueUUIDAvatarMapping[capUUID];
}
}
if (AvatarID != UUID.Zero)
{
// Repair the CAP!
//OpenSim.Framework.Capabilities.Caps caps = m_scene.GetCapsHandlerForUser(AvatarID);
//string capsBase = "/CAPS/EQG/";
//caps.RegisterHandler("EventQueueGet",
//new RestHTTPHandler("POST", capsBase + capUUID.ToString() + "/",
//delegate(Hashtable m_dhttpMethod)
//{
// return ProcessQueue(m_dhttpMethod, AvatarID, caps);
//}));
// start new ID sequence.
Random rnd = new Random(System.Environment.TickCount);
lock (m_ids)
{
if (!m_ids.ContainsKey(AvatarID))
m_ids.Add(AvatarID, rnd.Next(30000000));
}
int thisID = 0;
lock (m_ids)
thisID = m_ids[AvatarID];
BlockingLLSDQueue queue = GetQueue(AvatarID);
OSDArray array = new OSDArray();
LLSD element = queue.Dequeue(15000); // 15s timeout
if (element == null)
{
array.Add(EventQueueHelper.KeepAliveEvent());
}
else
{
array.Add(element);
while (queue.Count() > 0)
{
array.Add(queue.Dequeue(1));
thisID++;
}
}
OSDMap events = new OSDMap();
events.Add("events", array);
events.Add("id", new LLSDInteger(thisID));
lock (m_ids)
{
m_ids[AvatarID] = thisID + 1;
}
return events;
}
else
{
return new LLSD();
}
*
*/
}
else
{
//return new LLSD();
}
return new OSDString("shutdown404!");
}
public void DisableSimulator(ulong handle, UUID avatarID)
{
OSD item = EventQueueHelper.DisableSimulator(handle);
Enqueue(item, avatarID);
}
public virtual void EnableSimulator(ulong handle, IPEndPoint endPoint, UUID avatarID)
{
OSD item = EventQueueHelper.EnableSimulator(handle, endPoint);
Enqueue(item, avatarID);
}
public virtual void EstablishAgentCommunication(UUID avatarID, IPEndPoint endPoint, string capsPath)
{
OSD item = EventQueueHelper.EstablishAgentCommunication(avatarID, endPoint.ToString(), capsPath);
Enqueue(item, avatarID);
}
public virtual void TeleportFinishEvent(ulong regionHandle, byte simAccess,
IPEndPoint regionExternalEndPoint,
uint locationID, uint flags, string capsURL,
UUID avatarID)
{
OSD item = EventQueueHelper.TeleportFinishEvent(regionHandle, simAccess, regionExternalEndPoint,
locationID, flags, capsURL, avatarID);
Enqueue(item, avatarID);
}
public virtual void CrossRegion(ulong handle, Vector3 pos, Vector3 lookAt,
IPEndPoint newRegionExternalEndPoint,
string capsURL, UUID avatarID, UUID sessionID)
{
OSD item = EventQueueHelper.CrossRegion(handle, pos, lookAt, newRegionExternalEndPoint,
capsURL, avatarID, sessionID);
Enqueue(item, avatarID);
}
public void ChatterboxInvitation(UUID sessionID, string sessionName,
UUID fromAgent, string message, UUID toAgent, string fromName, byte dialog,
uint timeStamp, bool offline, int parentEstateID, Vector3 position,
uint ttl, UUID transactionID, bool fromGroup, byte[] binaryBucket)
{
OSD item = EventQueueHelper.ChatterboxInvitation(sessionID, sessionName, fromAgent, message, toAgent, fromName, dialog,
timeStamp, offline, parentEstateID, position, ttl, transactionID,
fromGroup, binaryBucket);
Enqueue(item, toAgent);
//m_log.InfoFormat("########### eq ChatterboxInvitation #############\n{0}", item);
}
public void ChatterBoxSessionAgentListUpdates(UUID sessionID, UUID fromAgent, UUID toAgent, bool canVoiceChat,
bool isModerator, bool textMute)
{
OSD item = EventQueueHelper.ChatterBoxSessionAgentListUpdates(sessionID, fromAgent, canVoiceChat,
isModerator, textMute);
Enqueue(item, toAgent);
//m_log.InfoFormat("########### eq ChatterBoxSessionAgentListUpdates #############\n{0}", item);
}
public void ParcelProperties(ParcelPropertiesPacket parcelPropertiesPacket, UUID avatarID)
{
OSD item = EventQueueHelper.ParcelProperties(parcelPropertiesPacket);
Enqueue(item, avatarID);
}
public void GroupMembership(AgentGroupDataUpdatePacket groupUpdate, UUID avatarID)
{
OSD item = EventQueueHelper.GroupMembership(groupUpdate);
Enqueue(item, avatarID);
}
}
}
| |
// 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.
#if DEBUG
// Uncomment to enable runtime checks to help validate that NetEventSource isn't being misused
// in a way that will cause performance problems, e.g. unexpected boxing of value types.
//#define DEBUG_NETEVENTSOURCE_MISUSE
#endif
using System.Collections;
using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
#if NET46
using System.Security;
#endif
namespace System.Net
{
// Implementation:
// This partial file is meant to be consumed into each System.Net.* assembly that needs to log. Each such assembly also provides
// its own NetEventSource partial class that adds an appropriate [EventSource] attribute, giving it a unique name for that assembly.
// Those partials can then also add additional events if needed, starting numbering from the NextAvailableEventId defined by this partial.
// Usage:
// - Operations that may allocate (e.g. boxing a value type, using string interpolation, etc.) or that may have computations
// at call sites should guard access like:
// if (NetEventSource.IsEnabled) NetEventSource.Enter(this, refArg1, valueTypeArg2); // entering an instance method with a value type arg
// if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"Found certificate: {cert}"); // info logging with a formattable string
// - Operations that have zero allocations / measurable computations at call sites can use a simpler pattern, calling methods like:
// NetEventSource.Enter(this); // entering an instance method
// NetEventSource.Info(this, "literal string"); // arbitrary message with a literal string
// NetEventSource.Enter(this, refArg1, regArg2); // entering an instance method with two reference type arguments
// NetEventSource.Enter(null); // entering a static method
// NetEventSource.Enter(null, refArg1); // entering a static method with one reference type argument
// Debug.Asserts inside the logging methods will help to flag some misuse if the DEBUG_NETEVENTSOURCE_MISUSE compilation constant is defined.
// However, because it can be difficult by observation to understand all of the costs involved, guarding can be done everywhere.
// - NetEventSource.Fail calls typically do not need to be prefixed with an IsEnabled check, even if they allocate, as FailMessage
// should only be used in cases similar to Debug.Fail, where they are not expected to happen in retail builds, and thus extra costs
// don't matter.
// - Messages can be strings, formattable strings, or any other object. Objects (including those used in formattable strings) have special
// formatting applied, controlled by the Format method. Partial specializations can also override this formatting by implementing a partial
// method that takes an object and optionally provides a string representation of it, in case a particular library wants to customize further.
/// <summary>Provides logging facilities for System.Net libraries.</summary>
#if NET46
[SecuritySafeCritical]
#endif
internal sealed partial class NetEventSource : EventSource
{
/// <summary>The single event source instance to use for all logging.</summary>
public static readonly NetEventSource Log = new NetEventSource();
#region Metadata
public class Keywords
{
public const EventKeywords Default = (EventKeywords)0x0001;
public const EventKeywords Debug = (EventKeywords)0x0002;
public const EventKeywords EnterExit = (EventKeywords)0x0004;
}
private const string MissingMember = "(?)";
private const string NullInstance = "(null)";
private const string StaticMethodObject = "(static)";
private const string NoParameters = "";
private const int MaxDumpSize = 1024;
private const int EnterEventId = 1;
private const int ExitEventId = 2;
private const int AssociateEventId = 3;
private const int InfoEventId = 4;
private const int ErrorEventId = 5;
private const int CriticalFailureEventId = 6;
private const int DumpArrayEventId = 7;
private const int NextAvailableEventId = 8; // Update this value whenever new events are added. Derived types should base all events off of this to avoid conflicts.
#endregion
#region Events
#region Enter
/// <summary>Logs entrance to a method.</summary>
/// <param name="thisOrContextObject">`this`, or another object that serves to provide context for the operation.</param>
/// <param name="formattableString">A description of the entrance, including any arguments to the call.</param>
/// <param name="memberName">The calling member.</param>
[NonEvent]
public static void Enter(object thisOrContextObject, FormattableString formattableString = null, [CallerMemberName] string memberName = null)
{
DebugValidateArg(thisOrContextObject);
DebugValidateArg(formattableString);
if (IsEnabled) Log.Enter(IdOf(thisOrContextObject), memberName, formattableString != null ? Format(formattableString) : NoParameters);
}
/// <summary>Logs entrance to a method.</summary>
/// <param name="thisOrContextObject">`this`, or another object that serves to provide context for the operation.</param>
/// <param name="arg0">The object to log.</param>
/// <param name="memberName">The calling member.</param>
[NonEvent]
public static void Enter(object thisOrContextObject, object arg0, [CallerMemberName] string memberName = null)
{
DebugValidateArg(thisOrContextObject);
DebugValidateArg(arg0);
if (IsEnabled) Log.Enter(IdOf(thisOrContextObject), memberName, $"({Format(arg0)})");
}
/// <summary>Logs entrance to a method.</summary>
/// <param name="thisOrContextObject">`this`, or another object that serves to provide context for the operation.</param>
/// <param name="arg0">The first object to log.</param>
/// <param name="arg1">The second object to log.</param>
/// <param name="memberName">The calling member.</param>
[NonEvent]
public static void Enter(object thisOrContextObject, object arg0, object arg1, [CallerMemberName] string memberName = null)
{
DebugValidateArg(thisOrContextObject);
DebugValidateArg(arg0);
DebugValidateArg(arg1);
if (IsEnabled) Log.Enter(IdOf(thisOrContextObject), memberName, $"({Format(arg0)}, {Format(arg1)})");
}
/// <summary>Logs entrance to a method.</summary>
/// <param name="thisOrContextObject">`this`, or another object that serves to provide context for the operation.</param>
/// <param name="arg0">The first object to log.</param>
/// <param name="arg1">The second object to log.</param>
/// <param name="arg2">The third object to log.</param>
/// <param name="memberName">The calling member.</param>
[NonEvent]
public static void Enter(object thisOrContextObject, object arg0, object arg1, object arg2, [CallerMemberName] string memberName = null)
{
DebugValidateArg(thisOrContextObject);
DebugValidateArg(arg0);
DebugValidateArg(arg1);
DebugValidateArg(arg2);
if (IsEnabled) Log.Enter(IdOf(thisOrContextObject), memberName, $"({Format(arg0)}, {Format(arg1)}, {Format(arg2)})");
}
[Event(EnterEventId, Level = EventLevel.Informational, Keywords = Keywords.EnterExit)]
private void Enter(string thisOrContextObject, string memberName, string parameters) =>
WriteEvent(EnterEventId, thisOrContextObject, memberName ?? MissingMember, parameters);
#endregion
#region Exit
/// <summary>Logs exit from a method.</summary>
/// <param name="thisOrContextObject">`this`, or another object that serves to provide context for the operation.</param>
/// <param name="formattableString">A description of the exit operation, including any return values.</param>
/// <param name="memberName">The calling member.</param>
[NonEvent]
public static void Exit(object thisOrContextObject, FormattableString formattableString = null, [CallerMemberName] string memberName = null)
{
DebugValidateArg(thisOrContextObject);
DebugValidateArg(formattableString);
if (IsEnabled) Log.Exit(IdOf(thisOrContextObject), memberName, formattableString != null ? Format(formattableString) : NoParameters);
}
/// <summary>Logs exit from a method.</summary>
/// <param name="thisOrContextObject">`this`, or another object that serves to provide context for the operation.</param>
/// <param name="arg0">A return value from the member.</param>
/// <param name="memberName">The calling member.</param>
[NonEvent]
public static void Exit(object thisOrContextObject, object arg0, [CallerMemberName] string memberName = null)
{
DebugValidateArg(thisOrContextObject);
DebugValidateArg(arg0);
if (IsEnabled) Log.Exit(IdOf(thisOrContextObject), memberName, Format(arg0).ToString());
}
/// <summary>Logs exit from a method.</summary>
/// <param name="thisOrContextObject">`this`, or another object that serves to provide context for the operation.</param>
/// <param name="arg0">A return value from the member.</param>
/// <param name="arg1">A second return value from the member.</param>
/// <param name="memberName">The calling member.</param>
[NonEvent]
public static void Exit(object thisOrContextObject, object arg0, object arg1, [CallerMemberName] string memberName = null)
{
DebugValidateArg(thisOrContextObject);
DebugValidateArg(arg0);
DebugValidateArg(arg1);
if (IsEnabled) Log.Exit(IdOf(thisOrContextObject), memberName, $"{Format(arg0)}, {Format(arg1)}");
}
[Event(ExitEventId, Level = EventLevel.Informational, Keywords = Keywords.EnterExit)]
private void Exit(string thisOrContextObject, string memberName, string result) =>
WriteEvent(ExitEventId, thisOrContextObject, memberName ?? MissingMember, result);
#endregion
#region Info
/// <summary>Logs an information message.</summary>
/// <param name="thisOrContextObject">`this`, or another object that serves to provide context for the operation.</param>
/// <param name="formattableString">The message to be logged.</param>
/// <param name="memberName">The calling member.</param>
[NonEvent]
public static void Info(object thisOrContextObject, FormattableString formattableString = null, [CallerMemberName] string memberName = null)
{
DebugValidateArg(thisOrContextObject);
DebugValidateArg(formattableString);
if (IsEnabled) Log.Info(IdOf(thisOrContextObject), memberName, formattableString != null ? Format(formattableString) : NoParameters);
}
/// <summary>Logs an information message.</summary>
/// <param name="thisOrContextObject">`this`, or another object that serves to provide context for the operation.</param>
/// <param name="message">The message to be logged.</param>
/// <param name="memberName">The calling member.</param>
[NonEvent]
public static void Info(object thisOrContextObject, object message, [CallerMemberName] string memberName = null)
{
DebugValidateArg(thisOrContextObject);
DebugValidateArg(message);
if (IsEnabled) Log.Info(IdOf(thisOrContextObject), memberName, Format(message).ToString());
}
[Event(InfoEventId, Level = EventLevel.Informational, Keywords = Keywords.Default)]
private void Info(string thisOrContextObject, string memberName, string message) =>
WriteEvent(InfoEventId, thisOrContextObject, memberName ?? MissingMember, message);
#endregion
#region Error
/// <summary>Logs an error message.</summary>
/// <param name="thisOrContextObject">`this`, or another object that serves to provide context for the operation.</param>
/// <param name="formattableString">The message to be logged.</param>
/// <param name="memberName">The calling member.</param>
[NonEvent]
public static void Error(object thisOrContextObject, FormattableString formattableString, [CallerMemberName] string memberName = null)
{
DebugValidateArg(thisOrContextObject);
DebugValidateArg(formattableString);
if (IsEnabled) Log.ErrorMessage(IdOf(thisOrContextObject), memberName, Format(formattableString));
}
/// <summary>Logs an error message.</summary>
/// <param name="thisOrContextObject">`this`, or another object that serves to provide context for the operation.</param>
/// <param name="message">The message to be logged.</param>
/// <param name="memberName">The calling member.</param>
[NonEvent]
public static void Error(object thisOrContextObject, object message, [CallerMemberName] string memberName = null)
{
DebugValidateArg(thisOrContextObject);
DebugValidateArg(message);
if (IsEnabled) Log.ErrorMessage(IdOf(thisOrContextObject), memberName, Format(message).ToString());
}
[Event(ErrorEventId, Level = EventLevel.Warning, Keywords = Keywords.Default)]
private void ErrorMessage(string thisOrContextObject, string memberName, string message) =>
WriteEvent(InfoEventId, thisOrContextObject, memberName ?? MissingMember, message);
#endregion
#region Fail
/// <summary>Logs a fatal error and raises an assert.</summary>
/// <param name="thisOrContextObject">`this`, or another object that serves to provide context for the operation.</param>
/// <param name="formattableString">The message to be logged.</param>
/// <param name="memberName">The calling member.</param>
[NonEvent]
public static void Fail(object thisOrContextObject, FormattableString formattableString, [CallerMemberName] string memberName = null)
{
// Don't call DebugValidateArg on args, as we expect Fail to be used in assert/failure situations
// that should never happen in production, and thus we don't care about extra costs.
if (IsEnabled) Log.CriticalFailure(IdOf(thisOrContextObject), memberName, Format(formattableString));
Debug.Fail(Format(formattableString), $"{IdOf(thisOrContextObject)}.{memberName}");
}
/// <summary>Logs a fatal error and raises an assert.</summary>
/// <param name="thisOrContextObject">`this`, or another object that serves to provide context for the operation.</param>
/// <param name="message">The message to be logged.</param>
/// <param name="memberName">The calling member.</param>
[NonEvent]
public static void Fail(object thisOrContextObject, object message, [CallerMemberName] string memberName = null)
{
// Don't call DebugValidateArg on args, as we expect Fail to be used in assert/failure situations
// that should never happen in production, and thus we don't care about extra costs.
if (IsEnabled) Log.CriticalFailure(IdOf(thisOrContextObject), memberName, Format(message).ToString());
Debug.Fail(Format(message).ToString(), $"{IdOf(thisOrContextObject)}.{memberName}");
}
[Event(CriticalFailureEventId, Level = EventLevel.Critical, Keywords = Keywords.Debug)]
private void CriticalFailure(string thisOrContextObject, string memberName, string message) =>
WriteEvent(InfoEventId, thisOrContextObject, memberName ?? MissingMember, message);
#endregion
#region DumpBuffer
/// <summary>Logs the contents of a buffer.</summary>
/// <param name="thisOrContextObject">`this`, or another object that serves to provide context for the operation.</param>
/// <param name="buffer">The buffer to be logged.</param>
/// <param name="memberName">The calling member.</param>
[NonEvent]
public static void DumpBuffer(object thisOrContextObject, byte[] buffer, [CallerMemberName] string memberName = null)
{
DumpBuffer(thisOrContextObject, buffer, 0, buffer.Length, memberName);
}
/// <summary>Logs the contents of a buffer.</summary>
/// <param name="thisOrContextObject">`this`, or another object that serves to provide context for the operation.</param>
/// <param name="buffer">The buffer to be logged.</param>
/// <param name="offset">The starting offset from which to log.</param>
/// <param name="count">The number of bytes to log.</param>
/// <param name="memberName">The calling member.</param>
[NonEvent]
public static void DumpBuffer(object thisOrContextObject, byte[] buffer, int offset, int count, [CallerMemberName] string memberName = null)
{
if (IsEnabled)
{
if (offset < 0 || offset > buffer.Length - count)
{
Fail(thisOrContextObject, $"Invalid {nameof(DumpBuffer)} Args. Length={buffer.Length}, Offset={offset}, Count={count}", memberName);
return;
}
count = Math.Min(count, MaxDumpSize);
byte[] slice = buffer;
if (offset != 0 || count != buffer.Length)
{
slice = new byte[count];
Buffer.BlockCopy(buffer, offset, slice, 0, count);
}
Log.DumpBuffer(IdOf(thisOrContextObject), memberName, slice);
}
}
/// <summary>Logs the contents of a buffer.</summary>
/// <param name="thisOrContextObject">`this`, or another object that serves to provide context for the operation.</param>
/// <param name="bufferPtr">The starting location of the buffer to be logged.</param>
/// <param name="count">The number of bytes to log.</param>
/// <param name="memberName">The calling member.</param>
[NonEvent]
public static unsafe void DumpBuffer(object thisOrContextObject, IntPtr bufferPtr, int count, [CallerMemberName] string memberName = null)
{
Debug.Assert(bufferPtr != IntPtr.Zero);
Debug.Assert(count >= 0);
if (IsEnabled)
{
var buffer = new byte[Math.Min(count, MaxDumpSize)];
fixed (byte* targetPtr = buffer)
{
Buffer.MemoryCopy((byte*)bufferPtr, targetPtr, buffer.Length, buffer.Length);
}
Log.DumpBuffer(IdOf(thisOrContextObject), memberName, buffer);
}
}
[Event(DumpArrayEventId, Level = EventLevel.Verbose, Keywords = Keywords.Debug)]
private unsafe void DumpBuffer(string thisOrContextObject, string memberName, byte[] buffer) =>
WriteEvent(DumpArrayEventId, thisOrContextObject, memberName ?? MissingMember, buffer);
#endregion
#region Associate
/// <summary>Logs a relationship between two objects.</summary>
/// <param name="first">The first object.</param>
/// <param name="second">The second object.</param>
/// <param name="memberName">The calling member.</param>
[NonEvent]
public static void Associate(object first, object second, [CallerMemberName] string memberName = null)
{
DebugValidateArg(first);
DebugValidateArg(second);
if (IsEnabled) Log.Associate(IdOf(first), memberName, IdOf(first), IdOf(second));
}
/// <summary>Logs a relationship between two objects.</summary>
/// <param name="thisOrContextObject">`this`, or another object that serves to provide context for the operation.</param>
/// <param name="first">The first object.</param>
/// <param name="second">The second object.</param>
/// <param name="memberName">The calling member.</param>
[NonEvent]
public static void Associate(object thisOrContextObject, object first, object second, [CallerMemberName] string memberName = null)
{
DebugValidateArg(thisOrContextObject);
DebugValidateArg(first);
DebugValidateArg(second);
if (IsEnabled) Log.Associate(IdOf(thisOrContextObject), memberName, IdOf(first), IdOf(second));
}
[Event(AssociateEventId, Level = EventLevel.Informational, Keywords = Keywords.Default, Message = "[{2}]<-->[{3}]")]
private void Associate(string thisOrContextObject, string memberName, string first, string second) =>
WriteEvent(AssociateEventId, thisOrContextObject, memberName ?? MissingMember, first, second);
#endregion
#endregion
#region Helpers
[Conditional("DEBUG_NETEVENTSOURCE_MISUSE")]
private static void DebugValidateArg(object arg)
{
if (!IsEnabled)
{
Debug.Assert(!(arg is ValueType), $"Should not be passing value type {arg?.GetType()} to logging without IsEnabled check");
Debug.Assert(!(arg is FormattableString), $"Should not be formatting FormattableString \"{arg}\" if tracing isn't enabled");
}
}
[Conditional("DEBUG_NETEVENTSOURCE_MISUSE")]
private static void DebugValidateArg(FormattableString arg)
{
Debug.Assert(IsEnabled || arg == null, $"Should not be formatting FormattableString \"{arg}\" if tracing isn't enabled");
}
public static new bool IsEnabled => Log.IsEnabled();
[NonEvent]
public static string IdOf(object value) => value != null ? value.GetType().Name + "#" + GetHashCode(value) : NullInstance;
[NonEvent]
public static int GetHashCode(object value) => value?.GetHashCode() ?? 0;
[NonEvent]
public static object Format(object value)
{
// If it's null, return a known string for null values
if (value == null)
{
return NullInstance;
}
// Give another partial implementation a chance to provide its own string representation
string result = null;
AdditionalCustomizedToString(value, ref result);
if (result != null)
{
return result;
}
// Format arrays with their element type name and length
Array arr = value as Array;
if (arr != null)
{
return $"{arr.GetType().GetElementType()}[{((Array)value).Length}]";
}
// Format ICollections as the name and count
ICollection c = value as ICollection;
if (c != null)
{
return $"{c.GetType().Name}({c.Count})";
}
// Format SafeHandles as their type, hash code, and pointer value
SafeHandle handle = value as SafeHandle;
if (handle != null)
{
return $"{handle.GetType().Name}:{handle.GetHashCode()}(0x{handle.DangerousGetHandle():X})";
}
// Format IntPtrs as hex
if (value is IntPtr)
{
return $"0x{value:X}";
}
// If the string representation of the instance would just be its type name,
// use its id instead.
string toString = value.ToString();
if (toString == null || toString == value.GetType().FullName)
{
return IdOf(value);
}
// Otherwise, return the original object so that the caller does default formatting.
return value;
}
[NonEvent]
private static string Format(FormattableString s)
{
switch (s.ArgumentCount)
{
case 0: return s.Format;
case 1: return string.Format(s.Format, Format(s.GetArgument(0)));
case 2: return string.Format(s.Format, Format(s.GetArgument(0)), Format(s.GetArgument(1)));
case 3: return string.Format(s.Format, Format(s.GetArgument(0)), Format(s.GetArgument(1)), Format(s.GetArgument(2)));
default:
object[] args = s.GetArguments();
object[] formattedArgs = new object[args.Length];
for (int i = 0; i < args.Length; i++)
{
formattedArgs[i] = Format(args[i]);
}
return string.Format(s.Format, formattedArgs);
}
}
static partial void AdditionalCustomizedToString<T>(T value, ref string result);
#endregion
#region Custom WriteEvent overloads
[NonEvent]
private unsafe void WriteEvent(int eventId, int arg1, int arg2, string arg3, string arg4)
{
if (IsEnabled())
{
if (arg3 == null) arg3 = "";
if (arg4 == null) arg4 = "";
fixed (char* string3Bytes = arg3)
fixed (char* string4Bytes = arg4)
{
const int NumEventDatas = 4;
var descrs = stackalloc EventData[NumEventDatas];
descrs[0].DataPointer = (IntPtr)(&arg1);
descrs[0].Size = sizeof(int);
descrs[1].DataPointer = (IntPtr)(&arg2);
descrs[1].Size = sizeof(int);
descrs[2].DataPointer = (IntPtr)string3Bytes;
descrs[2].Size = ((arg3.Length + 1) * 2);
descrs[3].DataPointer = (IntPtr)string4Bytes;
descrs[3].Size = ((arg4.Length + 1) * 2);
WriteEventCore(eventId, NumEventDatas, descrs);
}
}
}
[NonEvent]
private unsafe void WriteEvent(int eventId, string arg1, string arg2, string arg3, string arg4)
{
if (IsEnabled())
{
if (arg1 == null) arg1 = "";
if (arg2 == null) arg2 = "";
if (arg3 == null) arg3 = "";
if (arg4 == null) arg4 = "";
fixed (char* string1Bytes = arg1)
fixed (char* string2Bytes = arg2)
fixed (char* string3Bytes = arg3)
fixed (char* string4Bytes = arg4)
{
const int NumEventDatas = 4;
var descrs = stackalloc EventData[NumEventDatas];
descrs[0].DataPointer = (IntPtr)string1Bytes;
descrs[0].Size = ((arg1.Length + 1) * 2);
descrs[1].DataPointer = (IntPtr)string2Bytes;
descrs[1].Size = ((arg2.Length + 1) * 2);
descrs[2].DataPointer = (IntPtr)string3Bytes;
descrs[2].Size = ((arg3.Length + 1) * 2);
descrs[3].DataPointer = (IntPtr)string4Bytes;
descrs[3].Size = ((arg4.Length + 1) * 2);
WriteEventCore(eventId, NumEventDatas, descrs);
}
}
}
[NonEvent]
private unsafe void WriteEvent(int eventId, string arg1, string arg2, byte[] arg3)
{
if (IsEnabled())
{
if (arg1 == null) arg1 = "";
if (arg2 == null) arg2 = "";
if (arg3 == null) arg3 = Array.Empty<byte>();
fixed (char* arg1Ptr = arg1)
fixed (char* arg2Ptr = arg2)
fixed (byte* arg3Ptr = arg3)
{
int bufferLength = arg3.Length;
const int NumEventDatas = 4;
var descrs = stackalloc EventData[NumEventDatas];
descrs[0].DataPointer = (IntPtr)arg1Ptr;
descrs[0].Size = (arg1.Length + 1) * sizeof(char);
descrs[1].DataPointer = (IntPtr)arg2Ptr;
descrs[1].Size = (arg2.Length + 1) * sizeof(char);
descrs[2].DataPointer = (IntPtr)(&bufferLength);
descrs[2].Size = 4;
descrs[3].DataPointer = (IntPtr)arg3Ptr;
descrs[3].Size = bufferLength;
WriteEventCore(eventId, NumEventDatas, descrs);
}
}
}
[NonEvent]
private unsafe void WriteEvent(int eventId, string arg1, int arg2, int arg3, int arg4)
{
if (IsEnabled())
{
if (arg1 == null) arg1 = "";
fixed (char* arg1Ptr = arg1)
{
const int NumEventDatas = 4;
var descrs = stackalloc EventData[NumEventDatas];
descrs[0].DataPointer = (IntPtr)(arg1Ptr);
descrs[0].Size = (arg1.Length + 1) * sizeof(char);
descrs[1].DataPointer = (IntPtr)(&arg2);
descrs[1].Size = sizeof(int);
descrs[2].DataPointer = (IntPtr)(&arg3);
descrs[2].Size = sizeof(int);
descrs[3].DataPointer = (IntPtr)(&arg4);
descrs[3].Size = sizeof(int);
WriteEventCore(eventId, NumEventDatas, descrs);
}
}
}
[NonEvent]
private unsafe void WriteEvent(int eventId, string arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, int arg8)
{
if (IsEnabled())
{
if (arg1 == null) arg1 = "";
fixed (char* arg1Ptr = arg1)
{
const int NumEventDatas = 8;
var descrs = stackalloc EventData[NumEventDatas];
descrs[0].DataPointer = (IntPtr)(arg1Ptr);
descrs[0].Size = (arg1.Length + 1) * sizeof(char);
descrs[1].DataPointer = (IntPtr)(&arg2);
descrs[1].Size = sizeof(int);
descrs[2].DataPointer = (IntPtr)(&arg3);
descrs[2].Size = sizeof(int);
descrs[3].DataPointer = (IntPtr)(&arg4);
descrs[3].Size = sizeof(int);
descrs[4].DataPointer = (IntPtr)(&arg5);
descrs[4].Size = sizeof(int);
descrs[5].DataPointer = (IntPtr)(&arg6);
descrs[5].Size = sizeof(int);
descrs[6].DataPointer = (IntPtr)(&arg7);
descrs[6].Size = sizeof(int);
descrs[7].DataPointer = (IntPtr)(&arg8);
descrs[7].Size = sizeof(int);
WriteEventCore(eventId, NumEventDatas, descrs);
}
}
}
[NonEvent]
private unsafe void WriteEvent(int eventId, string arg1, int arg2, string arg3)
{
if (IsEnabled())
{
if (arg1 == null) arg1 = "";
if (arg3 == null) arg3 = "";
fixed (char* arg1Ptr = arg1)
fixed (char* arg3Ptr = arg3)
{
const int NumEventDatas = 3;
var descrs = stackalloc EventData[NumEventDatas];
descrs[0].DataPointer = (IntPtr)(arg1Ptr);
descrs[0].Size = (arg1.Length + 1) * sizeof(char);
descrs[1].DataPointer = (IntPtr)(&arg2);
descrs[1].Size = sizeof(int);
descrs[2].DataPointer = (IntPtr)(arg3Ptr);
descrs[2].Size = (arg3.Length + 1) * sizeof(char);
WriteEventCore(eventId, NumEventDatas, descrs);
}
}
}
[NonEvent]
private unsafe void WriteEvent(int eventId, string arg1, string arg2, int arg3)
{
if (IsEnabled())
{
if (arg1 == null) arg1 = "";
if (arg2 == null) arg2 = "";
fixed (char* arg1Ptr = arg1)
fixed (char* arg2Ptr = arg2)
{
const int NumEventDatas = 3;
var descrs = stackalloc EventData[NumEventDatas];
descrs[0].DataPointer = (IntPtr)(arg1Ptr);
descrs[0].Size = (arg1.Length + 1) * sizeof(char);
descrs[1].DataPointer = (IntPtr)(arg2Ptr);
descrs[1].Size = (arg2.Length + 1) * sizeof(char);
descrs[2].DataPointer = (IntPtr)(&arg3);
descrs[2].Size = sizeof(int);
WriteEventCore(eventId, NumEventDatas, descrs);
}
}
}
[NonEvent]
private unsafe void WriteEvent(int eventId, string arg1, string arg2, string arg3, int arg4)
{
if (IsEnabled())
{
if (arg1 == null) arg1 = "";
if (arg2 == null) arg2 = "";
if (arg3 == null) arg3 = "";
fixed (char* arg1Ptr = arg1)
fixed (char* arg2Ptr = arg2)
fixed (char* arg3Ptr = arg3)
{
const int NumEventDatas = 4;
var descrs = stackalloc EventData[NumEventDatas];
descrs[0].DataPointer = (IntPtr)(arg1Ptr);
descrs[0].Size = (arg1.Length + 1) * sizeof(char);
descrs[1].DataPointer = (IntPtr)(arg2Ptr);
descrs[1].Size = (arg2.Length + 1) * sizeof(char);
descrs[2].DataPointer = (IntPtr)(arg3Ptr);
descrs[2].Size = (arg3.Length + 1) * sizeof(char);
descrs[3].DataPointer = (IntPtr)(&arg4);
descrs[3].Size = sizeof(int);
WriteEventCore(eventId, NumEventDatas, descrs);
}
}
}
#endregion
}
}
| |
/*
*
* (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.Globalization;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using AjaxPro;
using ASC.Core;
using ASC.ElasticSearch;
using ASC.Notify.Recipients;
using ASC.Web.Community.Modules.Wiki.Resources;
using ASC.Web.Community.Product;
using ASC.Web.Community.Search;
using ASC.Web.Community.Wiki.Common;
using ASC.Web.Core.Mobile;
using ASC.Web.Core.Users;
using ASC.Web.Core.Utility.Skins;
using ASC.Web.Studio.Core;
using ASC.Web.Studio.UserControls.Common.Comments;
using ASC.Web.Studio.Utility;
using ASC.Web.Studio.Utility.HtmlUtility;
using ASC.Web.UserControls.Wiki;
using ASC.Web.UserControls.Wiki.Data;
using ASC.Web.UserControls.Wiki.Handlers;
using ASC.Web.UserControls.Wiki.UC;
namespace ASC.Web.Community.Wiki
{
[AjaxNamespace("_Default")]
public partial class _Default : WikiBasePage, IContextInitializer
{
protected string WikiPageName { get; set; }
private bool _isEmptyPage;
protected int Version
{
get
{
int result;
if (Request["ver"] == null || !int.TryParse(Request["ver"], out result))
return 0;
return result;
}
}
protected bool m_IsCategory
{
get { return Action == ActionOnPage.CategoryView || Action == ActionOnPage.CategoryEdit; }
}
private string _categoryName;
protected string m_categoryName
{
get
{
if (_categoryName == null)
{
_categoryName = string.Empty;
if (m_IsCategory)
{
var str = PageNameUtil.Decode(WikiPage);
_categoryName = str.Substring(str.IndexOf(':') + 1).Trim();
}
}
return _categoryName;
}
}
protected string PrintPageName
{
get
{
var pageName = PageNameUtil.Decode(WikiPage);
if (string.IsNullOrEmpty(pageName))
{
pageName = WikiResource.MainWikiCaption;
}
return pageName;
}
}
protected string PrintPageNameEncoded
{
get { return HttpUtility.HtmlEncode(PrintPageName); }
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
wikiViewPage.TenantId = wikiViewFile.TenantId = wikiEditFile.TenantId = wikiEditPage.TenantId = TenantId;
}
private void CheckSpetialSymbols()
{
var spetialName = PrintPageName;
if (!spetialName.Contains(":"))
return;
var spetial = spetialName.Split(':')[0];
spetialName = spetialName.Split(':')[1];
/*if (spetial.Equals(ASC.Web.UserControls.Wiki.Resources.WikiResource.wikiCategoryKeyCaption, StringComparison.InvariantCultureIgnoreCase))
{
Response.RedirectLC(string.Format("ListPages.aspx?cat={0}", spetialName.Trim()), this);
}
else*/
if (spetial.Equals(UserControls.Wiki.Constants.WikiInternalKeyCaption, StringComparison.InvariantCultureIgnoreCase))
{
spetialName = spetialName.Trim();
var anchors = spetialName;
if (spetialName.Contains("#"))
{
spetialName = spetialName.Split('#')[0];
anchors = anchors.Remove(0, spetialName.Length).TrimStart('#');
}
else
{
anchors = string.Empty;
}
if (spetialName.Equals(UserControls.Wiki.Constants.WikiInternalIndexKey, StringComparison.InvariantCultureIgnoreCase))
{
Response.RedirectLC("ListPages.aspx", this);
}
else if (spetialName.Equals(UserControls.Wiki.Constants.WikiInternalCategoriesKey, StringComparison.InvariantCultureIgnoreCase))
{
Response.RedirectLC("ListCategories.aspx", this);
}
else if (spetialName.Equals(UserControls.Wiki.Constants.WikiInternalFilesKey, StringComparison.InvariantCultureIgnoreCase))
{
Response.RedirectLC("ListFiles.aspx", this);
}
else if (spetialName.Equals(UserControls.Wiki.Constants.WikiInternalHomeKey, StringComparison.InvariantCultureIgnoreCase))
{
if (string.IsNullOrEmpty(anchors))
{
Response.RedirectLC("Default.aspx", this);
}
else
{
Response.RedirectLC(string.Format(@"Default.aspx?page=#{0}", anchors), this);
}
}
else if (spetialName.Equals(UserControls.Wiki.Constants.WikiInternalNewPagesKey, StringComparison.InvariantCultureIgnoreCase))
{
Response.RedirectLC("ListPages.aspx?n=", this);
}
else if (spetialName.Equals(UserControls.Wiki.Constants.WikiInternalRecentlyKey, StringComparison.InvariantCultureIgnoreCase))
{
Response.RedirectLC("ListPages.aspx?f=", this);
}
else if (spetialName.Equals(UserControls.Wiki.Constants.WikiInternalHelpKey, StringComparison.InvariantCultureIgnoreCase))
{
if (string.IsNullOrEmpty(anchors))
{
Response.RedirectLC(string.Format(@"Default.aspx?page={0}", WikiUCResource.HelpPageCaption), this);
}
else
{
Response.RedirectLC(string.Format(@"Default.aspx?page={0}#{1}", WikiUCResource.HelpPageCaption, anchors), this);
}
}
}
}
protected void wikiEditPage_SetNewFCKMode(bool isWysiwygDefault)
{
WikiModuleSettings.SetIsWysiwygDefault(isWysiwygDefault);
}
protected string wikiEditPage_GetUserFriendlySizeFormat(long size)
{
return GetFileLengthToString(size);
}
protected void cmdDelete_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrEmpty(WikiPage) || IsFile) return;
var pageName = PageNameUtil.Decode(WikiPage);
var page = Wiki.GetPage(pageName);
CommunitySecurity.DemandPermissions(new WikiObjectsSecurityObject(page), Common.Constants.Action_RemovePage);
foreach (var cat in Wiki.GetCategoriesRemovedWithPage(pageName))
{
WikiNotifySource.Instance.GetSubscriptionProvider().UnSubscribe(Common.Constants.AddPageToCat, cat.CategoryName);
}
Wiki.RemoveCategories(pageName);
WikiNotifySource.Instance.GetSubscriptionProvider().UnSubscribe(Common.Constants.EditPage, pageName);
foreach (var comment in Wiki.GetComments(pageName))
{
CommonControlsConfigurer.FCKUploadsRemoveForItem("wiki_comments", comment.Id.ToString());
}
Wiki.RemovePage(pageName);
FactoryIndexer<WikiWrapper>.DeleteAsync(page);
Response.RedirectLC("Default.aspx", this);
}
catch (Exception err)
{
WikiMaster.PrintInfoMessage(err.Message, InfoType.Alert);
}
}
protected void Page_Load(object sender, EventArgs e)
{
WikiPageName = PrintPageName;
(Master as WikiMaster).GetDelUniqId += new WikiMaster.GetDelUniqIdHandle(_Default_GetDelUniqId);
Utility.RegisterTypeForAjax(typeof(_Default), Page);
RegisterInlineScript();
LoadViews();
if (IsPostBack) return;
if (IsFile)
{
Response.RedirectLC(string.Format(WikiSection.Section.ImageHangler.UrlFormat, WikiPage, TenantId), this);
}
pCredits.Visible = Action.Equals(ActionOnPage.View) || Action.Equals(ActionOnPage.CategoryView);
CheckSpetialSymbols();
wikiEditPage.mainPath = this.ResolveUrlLC("Default.aspx");
InitEditsLink();
var mainStudioCss = WebSkin.BaseCSSFileAbsoluteWebPath;
wikiEditPage.CanUploadFiles = CommunitySecurity.CheckPermissions(Common.Constants.Action_UploadFile);
wikiEditPage.MainCssFile = mainStudioCss;
if (Action == ActionOnPage.CategoryView)
{
BindPagesByCategory();
}
}
private void RegisterInlineScript()
{
var script = @"
window.scrollPreview = function() {
jq.scrollTo(jq('#_PrevContainer').position().top, { speed: 500 });
}
window.HidePreview = function() {
jq('#_PrevContainer').hide();
jq.scrollTo(jq('#edit_container').position().top, { speed: 500 });
}
window.WikiEditBtns = function() {
window.checkUnload=false;
LoadingBanner.showLoaderBtn('#actionWikiPage');
}
window.checkUnload=true;
window.checkUnloadFunc = function() {
return checkUnload;
}
window.panelEditBtnsID = '" + pEditButtons.ClientID + @"';
jq.dropdownToggle({
dropdownID: 'WikiActionsMenuPanel',
switcherSelector: '.WikiHeaderBlock .menu-small',
addLeft: -11,
showFunction: function (switcherObj, dropdownItem) {
jq('.WikiHeaderBlock .menu-small.active').removeClass('active');
if (dropdownItem.is(':hidden')) {
switcherObj.addClass('active');
}
},
hideFunction: function () {
jq('.WikiHeaderBlock .menu-small.active').removeClass('active');
}
});
if (jq('#WikiActionsMenuPanel .dropdown-content a').length == 0) {
jq('span.menu-small').hide();
}
jq('input[id$=txtPageName]').focus();";
if (Action == ActionOnPage.AddNew || Action == ActionOnPage.Edit)
script += "jq.confirmBeforeUnload(window.checkUnloadFunc);";
Page.RegisterInlineScript(script);
}
private IWikiObjectOwner _wikiObjOwner;
protected void InitPageActionPanel()
{
var sb = new StringBuilder();
var canEdit = false;
var canDelete = false;
var subscribed = false;
if (_wikiObjOwner != null)
{
var secObj = new WikiObjectsSecurityObject(_wikiObjOwner);
canEdit = CommunitySecurity.CheckPermissions(secObj, Common.Constants.Action_EditPage);
canDelete = CommunitySecurity.CheckPermissions(secObj, Common.Constants.Action_RemovePage) &&
!string.IsNullOrEmpty(_wikiObjOwner.GetObjectId().ToString());
}
if (SecurityContext.IsAuthenticated && (Action.Equals(ActionOnPage.CategoryView) || Action.Equals(ActionOnPage.View)))
{
var subscriptionProvider = WikiNotifySource.Instance.GetSubscriptionProvider();
var userList = new List<string>();
var IAmAsRecipient = (IDirectRecipient)WikiNotifySource.Instance.GetRecipientsProvider().GetRecipient(SecurityContext.CurrentAccount.ID.ToString());
if (IAmAsRecipient != null)
{
userList = new List<string>(
subscriptionProvider.GetSubscriptions(
Community.Wiki.Common.Constants.EditPage,
IAmAsRecipient)
);
}
var pageName = WikiPage ?? string.Empty;
subscribed = userList.Exists(s => string.Compare(s, pageName, StringComparison.InvariantCultureIgnoreCase) == 0 || (s == null && string.Empty.Equals(pageName)));
var SubscribeTopicLink = string.Format(CultureInfo.CurrentCulture, string.Format(CultureInfo.CurrentCulture,
"<a id=\"statusSubscribe\" class=\"follow-status " +
(subscribed ? "subscribed" : "unsubscribed") +
"\" title=\"{0}\" href=\"#\"></a>",
!subscribed ? WikiResource.NotifyOnEditPage : WikiResource.UnNotifyOnEditPage));
SubscribeLinkBlock.Text = SubscribeTopicLink;
}
var delURL = string.Format(@"javascript:if(confirm('{0}')) __doPostBack('{1}', '');", WikiResource.cfmDeletePage, _Default_GetDelUniqId());
sb.Append("<div id=\"WikiActionsMenuPanel\" class=\"studio-action-panel\">");
sb.Append("<ul class=\"dropdown-content\">");
sb.AppendFormat("<li><a class=\"dropdown-item\" href=\"{0}\">{1}</a></li>",
ActionHelper.GetViewPagePath(this.ResolveUrlLC("pagehistorylist.aspx"), WikiPage),
WikiResource.menu_ShowVersions);
sb.AppendFormat("<li><a class=\"dropdown-item\" href=\"javascript:window.print();\">{0}</a></li>", WikiResource.menu_PrintThePage);
if (canEdit)
sb.AppendFormat("<li><a class=\"dropdown-item\" href=\"{0}\">{1}</a></li>",
ActionHelper.GetEditPagePath(this.ResolveUrlLC("Default.aspx"), WikiPage),
WikiResource.menu_EditThePage);
if (canDelete)
sb.AppendFormat("<li><a class=\"dropdown-item\" href=\"{0}\">{1}</a></li>", delURL, WikiResource.menu_DeleteThePage);
sb.Append("</ul>");
sb.Append("</div>");
ActionPanel.Text = sb.ToString();
var script = String.Format("ASC.Community.Wiki.BindSubscribeEvent({0}, \"{1}\", \"{2}\", \"{3}\")",
subscribed.ToString().ToLower(CultureInfo.CurrentCulture),
HttpUtility.HtmlEncode((Page as WikiBasePage).WikiPage).EscapeString(),
WikiResource.NotifyOnEditPage,
WikiResource.UnNotifyOnEditPage
);
Page.RegisterInlineScript(script);
}
protected void InitCategoryActionPanel()
{
var sb = new StringBuilder();
sb.Append("<div id=\"WikiActionsMenuPanel\" class=\"studio-action-panel\">");
sb.Append("<ul class=\"dropdown-content\">");
sb.AppendFormat("<li><a class=\"dropdown-item\" href=\"{0}\">{1}</a></li>",
ActionHelper.GetEditPagePath(this.ResolveUrlLC("Default.aspx"), WikiPage),
WikiResource.cmdEdit);
sb.Append("</ul>");
sb.Append("</div>");
ActionPanel.Text = sb.ToString();
}
protected void wikiViewPage_WikiPageLoaded(bool isNew, IWikiObjectOwner owner)
{
_wikiObjOwner = owner;
wikiViewPage.CanEditPage = CommunitySecurity.CheckPermissions(new WikiObjectsSecurityObject(_wikiObjOwner), Common.Constants.Action_EditPage);
UpdateEditDeleteVisible(owner);
//WikiMaster.UpdateNavigationItems();
InitPageActionPanel();
}
protected void wikiEditPage_WikiPageLoaded(bool isNew, IWikiObjectOwner owner)
{
if (!isNew)
{
_wikiObjOwner = owner;
}
if ((isNew && !CommunitySecurity.CheckPermissions(Common.Constants.Action_AddPage))
||
(!isNew && !(CommunitySecurity.CheckPermissions(new WikiObjectsSecurityObject(owner), Common.Constants.Action_EditPage))))
{
Response.RedirectLC("Default.aspx", this);
}
}
protected void wikiEditPage_SaveNewCategoriesAdded(object sender, List<string> categories, string pageName)
{
//var authorId = SecurityContext.CurrentAccount.ID.ToString();
//foreach (var catName in categories)
//{
// WikiNotifyClient.SendNoticeAsync(
// authorId,
// Common.Constants.AddPageToCat,
// catName,
// null,
// GetListOfTagValForCategoryNotify(catName, pageName));
//}
}
private string _Default_GetDelUniqId()
{
return cmdDelete.UniqueID;
}
internal string GetCategoryName()
{
return m_categoryName;
}
protected void OnPageEmpty(object sender, EventArgs e)
{
var pageName = PageNameUtil.Decode(WikiPage);
wikiViewPage.Visible = false;
wikiEditPage.Visible = false;
wikiViewFile.Visible = false;
wikiEditFile.Visible = false;
pPageIsNotExists.Visible = true;
if (!(Action.Equals(ActionOnPage.CategoryView) || Action.Equals(ActionOnPage.CategoryEdit)))
{
if (IsFile)
{
txtPageEmptyLabel.Text = PrepereEmptyString(WikiResource.MainWikiFileIsNotExists, true, false);
}
else
{
if (Wiki.SearchPagesByName(pageName).Count > 0)
{
txtPageEmptyLabel.Text = PrepereEmptyString(WikiResource.MainWikiPageIsNotExists, false, true);
}
else
{
txtPageEmptyLabel.Text = PrepereEmptyString(WikiResource.MainWikiPageIsNotExists, false, false);
}
}
}
_isEmptyPage = true;
InitEditsLink();
//WikiMaster.UpdateNavigationItems();
}
private string PrepereEmptyString(string format, bool isFile, bool isSearchResultExists)
{
commentList.Visible = false;
var mainOptions = RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant;
var rxLinkCreatePlace = new Regex(@"{0([\s\S]+?)}", mainOptions);
var rxLinkSearchResult = new Regex(@"{1([\s\S]+?)}", mainOptions);
var rxSearchResultParth = new Regex(@"\[\[([\s\S]+?)\]\]", mainOptions);
var result = format;
foreach (Match match in rxLinkCreatePlace.Matches(format))
{
if (isFile)
{
if (CommunitySecurity.CheckPermissions(Common.Constants.Action_UploadFile))
{
result = result.Replace(match.Value, string.Format(@"<a href=""{0}"">{1}</a>", ActionHelper.GetEditFilePath(this.ResolveUrlLC("Default.aspx"), PageNameUtil.Decode(WikiPage)), match.Groups[1].Value));
}
}
else
{
if (CommunitySecurity.CheckPermissions(Common.Constants.Action_AddPage))
{
result = result.Replace(match.Value, string.Format(@"<a href=""{0}"">{1}</a>", ActionHelper.GetEditPagePath(this.ResolveUrlLC("Default.aspx"), PageNameUtil.Decode(WikiPage)), match.Groups[1].Value));
}
else
{
result = result.Replace(match.Value, match.Groups[1].Value);
}
}
}
if (isSearchResultExists && !isFile)
{
result = rxSearchResultParth.Replace(result, SearchResultParthMatchEvaluator);
foreach (Match match in rxLinkSearchResult.Matches(format))
{
result = result.Replace(match.Value, string.Format(@"<a href=""{0}"">{1}</a>", this.ResolveUrlLC(string.Format("Search.aspx?Search={0}&pn=", HttpUtility.UrlEncode(PageNameUtil.Decode(WikiPage)))), match.Groups[1].Value));
}
}
else
{
result = rxSearchResultParth.Replace(result, string.Empty);
}
return result;
}
private string SearchResultParthMatchEvaluator(Match match)
{
return match.Groups[1].Value;
}
private string GetAbsolutePath(string relative)
{
return string.Format(@"{0}://{1}{2}{3}",
Request.GetUrlRewriter().Scheme,
Request.GetUrlRewriter().Host,
(Request.GetUrlRewriter().Port != 80 ? string.Format(":{0}", Request.GetUrlRewriter().Port) : string.Empty),
this.ResolveUrlLC(relative));
}
private void LoadViews()
{
wikiEditPage.AlaxUploaderPath = GetAbsolutePath("~/js/uploader/ajaxupload.js");
wikiEditPage.JQPath = GetAbsolutePath("~/js/third-party/jquery/jquery.core.js");
wikiEditPage.CurrentUserId = SecurityContext.CurrentAccount.ID;
wikiViewPage.Visible = false;
wikiEditPage.Visible = false;
wikiViewFile.Visible = false;
wikiEditFile.Visible = false;
pPageIsNotExists.Visible = false;
pView.Visible = false;
PrintHeader.Visible = false;
phCategoryResult.Visible = Action == ActionOnPage.CategoryView;
var pageName = PrintPageName;
var _mobileVer = MobileDetector.IsMobile;
//fix for IE 10
var browser = HttpContext.Current.Request.Browser.Browser;
var userAgent = Context.Request.Headers["User-Agent"];
var regExp = new Regex("MSIE 10.0", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline);
var regExpIe11 = new Regex("(?=.*Trident.*rv:11.0).+", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline);
if (browser == "IE" && regExp.Match(userAgent).Success || regExpIe11.Match(userAgent).Success)
{
_mobileVer = true;
}
switch (Action)
{
case ActionOnPage.AddNew:
pageName = WikiResource.MainWikiAddNewPage;
wikiEditPage.IsWysiwygDefault = !_mobileVer && WikiModuleSettings.GetIsWysiwygDefault();
wikiEditPage.Visible = true;
wikiEditPage.IsNew = true;
WikiPageName = pageName;
break;
case ActionOnPage.AddNewFile:
pageName = WikiResource.MainWikiAddNewFile;
wikiEditFile.Visible = true;
WikiPageName = pageName;
break;
case ActionOnPage.Edit:
case ActionOnPage.CategoryEdit:
if (IsFile)
{
wikiEditFile.FileName = WikiPage;
wikiEditFile.Visible = true;
WikiPageName = WikiResource.MainWikiEditFile;
}
else
{
wikiEditPage.PageName = WikiPage;
wikiEditPage.IsWysiwygDefault = !_mobileVer && WikiModuleSettings.GetIsWysiwygDefault();
wikiEditPage.Visible = true;
if (m_IsCategory)
wikiEditPage.IsSpecialName = true;
WikiPageName = WikiResource.MainWikiEditPage;
}
break;
case ActionOnPage.View:
case ActionOnPage.CategoryView:
pView.Visible = true;
if (IsFile)
{
wikiViewFile.FileName = WikiPage;
wikiViewFile.Visible = true;
}
else
{
PrintHeader.Visible = true;
wikiViewPage.PageName = WikiPage;
wikiViewPage.Version = Version;
if (Version == 0)
{
if (m_IsCategory)
{
var name = HttpUtility.HtmlDecode(m_categoryName);
WikiPageName = string.Format(WikiResource.menu_ListPagesCatFormat, name);
}
}
else
{
if (m_IsCategory)
{
var name = HttpUtility.HtmlDecode(m_categoryName);
WikiPageName = string.Format(WikiResource.menu_ListPagesCatFormat, name);
}
WikiMaster.CurrentPageCaption = string.Format("{0}{1}", WikiResource.wikiVersionCaption, Version);
}
wikiViewPage.Visible = true;
}
InitCommentsView();
break;
}
if (SecurityContext.IsAuthenticated && (Action.Equals(ActionOnPage.CategoryView) || Action.Equals(ActionOnPage.View)))
{
var subscriptionProvider = WikiNotifySource.Instance.GetSubscriptionProvider();
var userList = new List<string>();
var IAmAsRecipient = (IDirectRecipient)WikiNotifySource.Instance.GetRecipientsProvider().GetRecipient(SecurityContext.CurrentAccount.ID.ToString());
if (IAmAsRecipient != null)
{
userList = new List<string>(
subscriptionProvider.GetSubscriptions(
Community.Wiki.Common.Constants.EditPage,
IAmAsRecipient)
);
}
pageName = WikiPage ?? string.Empty;
var subscribed = userList.Exists(s => string.Compare(s, pageName, StringComparison.InvariantCultureIgnoreCase) == 0 || (s == null && string.Empty.Equals(pageName)));
var SubscribeTopicLink = string.Format(CultureInfo.CurrentCulture, string.Format(CultureInfo.CurrentCulture,
"<a id=\"statusSubscribe\" class=\"follow-status " +
(subscribed ? "subscribed" : "unsubscribed") +
"\" title=\"{0}\" href=\"#\"></a>",
!subscribed ? WikiResource.NotifyOnEditPage : WikiResource.UnNotifyOnEditPage));
SubscribeLinkBlock.Text = SubscribeTopicLink;
}
}
protected void BindPagesByCategory()
{
if (Action != ActionOnPage.CategoryView || string.IsNullOrEmpty(m_categoryName))
return;
var result = Wiki.GetPages(m_categoryName);
result.RemoveAll(pemp => string.IsNullOrEmpty(pemp.PageName));
var letters = new List<string>(WikiResource.wikiCategoryAlfaList.Split(','));
var otherSymbol = string.Empty;
if (letters.Count > 0)
{
otherSymbol = letters[0];
letters.Remove(otherSymbol);
}
var dictList = new List<PageDictionary>();
foreach (var page in result)
{
var firstLetter = new string(page.PageName[0], 1);
if (!letters.Exists(lt => lt.Equals(firstLetter, StringComparison.InvariantCultureIgnoreCase)))
{
firstLetter = otherSymbol;
}
PageDictionary pageDic;
if (!dictList.Exists(dl => dl.HeadName.Equals(firstLetter, StringComparison.InvariantCultureIgnoreCase)))
{
pageDic = new PageDictionary { HeadName = firstLetter };
pageDic.Pages.Add(page);
dictList.Add(pageDic);
}
else
{
pageDic = dictList.Find(dl => dl.HeadName.Equals(firstLetter, StringComparison.InvariantCultureIgnoreCase));
pageDic.Pages.Add(page);
}
}
dictList.Sort(SortPageDict);
var countAll = dictList.Count * 3 + result.Count; //1 letter is like 2 links to category
var perColumn = (int)(Math.Round((decimal)countAll / 3));
var mainDictList = new List<List<PageDictionary>>();
int index = 0, lastIndex = 0, count = 0;
for (var i = 0; i < dictList.Count; i++)
{
var p = dictList[i];
count += 3;
count += p.Pages.Count;
index++;
if (count >= perColumn || i == dictList.Count - 1)
{
count = count - perColumn;
mainDictList.Add(dictList.GetRange(lastIndex, index - lastIndex));
lastIndex = index;
}
}
rptCategoryPageList.DataSource = mainDictList;
rptCategoryPageList.DataBind();
}
private int SortPageDict(PageDictionary cd1, PageDictionary cd2)
{
return cd1.HeadName.CompareTo(cd2.HeadName);
}
protected void On_PublishVersionInfo(object sender, VersionEventArgs e)
{
if (!e.UserID.Equals(Guid.Empty))
{
litAuthorInfo.Text = GetPageInfo(PageNameUtil.Decode(WikiPage), e.UserID, e.Date);
}
else
{
litAuthorInfo.Text = string.Empty;
}
hlVersionPage.Text = string.Format(WikiResource.cmdVersionTemplate, e.Version);
hlVersionPage.NavigateUrl = ActionHelper.GetViewPagePath(this.ResolveUrlLC("PageHistoryList.aspx"), PageNameUtil.Decode(WikiPage));
hlVersionPage.Visible = Action.Equals(ActionOnPage.View) || Action.Equals(ActionOnPage.CategoryView);
//litVersionSeparator.Visible = hlEditPage.Visible;
}
protected void cmdCancel_Click(object sender, EventArgs e)
{
if (!IsFile)
{
Response.RedirectLC(ActionHelper.GetViewPagePath(this.ResolveUrlLC("Default.aspx"), PageNameUtil.Decode(WikiPage)), this);
}
else
{
Response.RedirectLC(ActionHelper.GetViewFilePath(this.ResolveUrlLC("Default.aspx"), PageNameUtil.Decode(WikiPage)), this);
}
}
protected void cmdSave_Click(object sender, EventArgs e)
{
SaveResult result;
string pageName;
if (IsFile || Action.Equals(ActionOnPage.AddNewFile))
{
result = wikiEditFile.Save(SecurityContext.CurrentAccount.ID, out pageName);
}
else
{
result = wikiEditPage.Save(SecurityContext.CurrentAccount.ID, out pageName);
}
PrintResultBySave(result, pageName);
if (result == SaveResult.OkPageRename)
{
//Redirect
Response.RedirectLC(ActionHelper.GetViewPagePath(this.ResolveUrlLC("Default.aspx"), PageNameUtil.Decode(pageName)), this);
}
}
private void PrintInfoMessage(string info, InfoType type)
{
WikiMaster.PrintInfoMessage(info, type);
}
private void PrintResultBySave(SaveResult result, string pageName)
{
var infoType = InfoType.Info;
if (!result.Equals(SaveResult.Ok) && !result.Equals(SaveResult.NoChanges))
{
infoType = InfoType.Alert;
}
switch (result)
{
case SaveResult.SectionUpdate:
Response.RedirectLC(ActionHelper.GetViewPagePath(this.ResolveUrlLC("Default.aspx"), pageName), this);
break;
case SaveResult.OkPageRename:
case SaveResult.Ok:
PrintInfoMessage(WikiResource.msgSaveSucess, infoType);
if (Action.Equals(ActionOnPage.AddNew) || Action.Equals(ActionOnPage.Edit))
{
Response.RedirectLC(ActionHelper.GetViewPagePath(this.ResolveUrlLC("Default.aspx"), pageName), this);
}
else if (Action.Equals(ActionOnPage.AddNewFile))
{
Response.RedirectLC(ActionHelper.GetEditFilePath(this.ResolveUrlLC("Default.aspx"), pageName), this);
}
break;
case SaveResult.FileEmpty:
PrintInfoMessage(WikiResource.msgFileEmpty, infoType);
break;
case SaveResult.FileSizeExceeded:
PrintInfoMessage(FileSizeComment.GetFileSizeExceptionString(FileUploader.MaxUploadSize), infoType);
break;
case SaveResult.NoChanges:
PrintInfoMessage(WikiResource.msgNoChanges, infoType);
break;
case SaveResult.PageNameIsEmpty:
PrintInfoMessage(WikiResource.msgPageNameEmpty, infoType);
break;
case SaveResult.PageNameIsIncorrect:
PrintInfoMessage(WikiResource.msgPageNameIncorrect, infoType);
break;
case SaveResult.SamePageExists:
PrintInfoMessage(WikiResource.msgSamePageExists, infoType);
break;
case SaveResult.UserIdIsEmpty:
PrintInfoMessage(WikiResource.msgInternalError, infoType);
break;
case SaveResult.OldVersion:
PrintInfoMessage(WikiResource.msgOldVersion, infoType);
break;
case SaveResult.Error:
PrintInfoMessage(WikiResource.msgMarkupError, InfoType.Alert);
break;
case SaveResult.PageTextIsEmpty:
PrintInfoMessage(WikiResource.msgPageTextEmpty, infoType);
break;
}
}
private void InitEditsLink()
{
//hlEditPage.Text = WikiResource.cmdEdit;
cmdSave.Text = WikiResource.cmdPublish;
hlPreview.Text = WikiResource.cmdPreview;
hlPreview.Attributes["onclick"] = string.Format("{0}();return false;", wikiEditPage.GetShowPrevFunctionName());
//hlPreview.NavigateUrl = string.Format("javascript:{0}();", wikiEditPage.GetShowPrevFunctionName());
hlPreview.NavigateUrl = string.Format("javascript:void(0);");
cmdCancel.Text = WikiResource.cmdCancel;
cmdCancel.Attributes["name"] = wikiEditPage.WikiFckClientId;
cmdDelete.Text = WikiResource.cmdDelete;
cmdDelete.OnClientClick = string.Format("javascript:return confirm(\"{0}\");", WikiResource.cfmDeletePage);
hlPreview.Visible = Action.Equals(ActionOnPage.AddNew) || Action.Equals(ActionOnPage.Edit) || Action.Equals(ActionOnPage.CategoryEdit);
if (_isEmptyPage)
{
//hlEditPage.Visible = pEditButtons.Visible = false;
cmdDelete.Visible = false;
if (Action.Equals(ActionOnPage.CategoryView))
{
//hlEditPage.Visible = true;
InitCategoryActionPanel();
}
}
else
{
UpdateEditDeleteVisible(_wikiObjOwner);
}
litVersionSeparatorDel.Visible = cmdDelete.Visible;
}
private void UpdateEditDeleteVisible(IWikiObjectOwner obj)
{
var canDelete = false;
var editVisible = Action.Equals(ActionOnPage.View) || Action.Equals(ActionOnPage.CategoryView);
if (obj != null)
{
var secObj = new WikiObjectsSecurityObject(obj);
canDelete = CommunitySecurity.CheckPermissions(secObj, Common.Constants.Action_RemovePage) &&
!string.IsNullOrEmpty(obj.GetObjectId().ToString());
}
pEditButtons.Visible = !editVisible;
//hlEditPage.Visible = editVisible && canEdit;
if (Version > 0 && (Action.Equals(ActionOnPage.View) || Action.Equals(ActionOnPage.CategoryView)))
{
//hlEditPage.Visible = pEditButtons.Visible = false;
}
cmdDelete.Visible = editVisible && canDelete;
litVersionSeparatorDel.Visible = cmdDelete.Visible;
}
#region Comments Functions
private void InitCommentsView()
{
if (m_IsCategory) return;
int totalCount;
var pageName = PageNameUtil.Decode(WikiPage);
commentList.Visible = true;
commentList.Items = GetCommentsList(pageName, out totalCount);
ConfigureComments(commentList);
commentList.TotalCount = totalCount;
}
private IList<CommentInfo> GetCommentsList(string pageName, out int totalCount)
{
var comments = Wiki.GetComments(pageName);
totalCount = comments.Count;
return BuildCommentsList(comments);
}
private List<CommentInfo> BuildCommentsList(List<Comment> loaded)
{
return BuildCommentsList(loaded, Guid.Empty);
}
private List<CommentInfo> BuildCommentsList(List<Comment> loaded, Guid parentId)
{
var result = new List<CommentInfo>();
foreach (var comment in SelectChildLevel(parentId, loaded))
{
var info = GetCommentInfo(comment);
info.CommentList = BuildCommentsList(loaded, comment.Id);
result.Add(info);
}
return result;
}
private static List<Comment> SelectChildLevel(Guid forParentId, List<Comment> from)
{
return from.FindAll(comm => comm.ParentId == forParentId);
}
private static void ConfigureComments(CommentsList commentList)
{
CommonControlsConfigurer.CommentsConfigure(commentList);
commentList.BehaviorID = "_commentsWikiObj";
commentList.IsShowAddCommentBtn = CommunitySecurity.CheckPermissions(Common.Constants.Action_AddComment);
commentList.ModuleName = "wiki";
commentList.FckDomainName = "wiki_comments";
commentList.ObjectID = "wiki_page";
}
public CommentInfo GetCommentInfo(Comment comment)
{
var info = new CommentInfo
{
CommentID = comment.Id.ToString(),
UserID = comment.UserId,
TimeStamp = comment.Date,
TimeStampStr = comment.Date.Ago(),
IsRead = true,
Inactive = comment.Inactive,
CommentBody = HtmlUtility.GetFull(comment.Body),
UserFullName = DisplayUserSettings.GetFullUserName(comment.UserId),
UserProfileLink = CommonLinkUtility.GetUserProfile(comment.UserId),
UserAvatarPath = UserPhotoManager.GetBigPhotoURL(comment.UserId),
IsEditPermissions = CommunitySecurity.CheckPermissions(new WikiObjectsSecurityObject(comment), Common.Constants.Action_EditRemoveComment),
IsResponsePermissions = CommunitySecurity.CheckPermissions(Common.Constants.Action_AddComment),
UserPost = CoreContext.UserManager.GetUsers(comment.UserId).Title
};
return info;
}
#region Ajax functions for comments management
[AjaxMethod(HttpSessionStateRequirement.ReadWrite)]
public string ConvertWikiToHtml(string pageName, string wikiValue, string appRelativeCurrentExecutionFilePath,
string imageHandlerUrl)
{
return EditPage.ConvertWikiToHtml(pageName, wikiValue, appRelativeCurrentExecutionFilePath,
imageHandlerUrl, TenantId);
}
[AjaxMethod(HttpSessionStateRequirement.ReadWrite)]
public string ConvertWikiToHtmlWysiwyg(string pageName, string wikiValue, string appRelativeCurrentExecutionFilePath,
string imageHandlerUrl)
{
return EditPage.ConvertWikiToHtmlWysiwyg(pageName, wikiValue, appRelativeCurrentExecutionFilePath,
imageHandlerUrl, TenantId);
}
[AjaxMethod(HttpSessionStateRequirement.ReadWrite)]
public string CreateImageFromWiki(string pageName, string wikiValue, string appRelativeCurrentExecutionFilePath,
string imageHandlerUrl)
{
return EditPage.CreateImageFromWiki(pageName, wikiValue, appRelativeCurrentExecutionFilePath,
imageHandlerUrl, TenantId);
}
[AjaxMethod(HttpSessionStateRequirement.ReadWrite)]
public string UpdateTempImage(string fileName, string UserId, string tempFileName)
{
string outFileName;
EditFile.MoveContentFromTemp(new Guid(UserId), tempFileName, fileName, ConfigLocation, PageWikiSection, TenantId, HttpContext.Current, RootPath, out outFileName);
return outFileName;
}
[AjaxMethod(HttpSessionStateRequirement.ReadWrite)]
public void CancelUpdateImage(string UserId, string tempFileName)
{
EditFile.DeleteTempContent(tempFileName, ConfigLocation, PageWikiSection, TenantId, HttpContext.Current);
}
#endregion
#endregion
#region IContextInitializer Members
public void InitializeContext(HttpContext context)
{
_rootPath = context.Server.MapPath("~");
_wikiSection = WikiSection.Section;
}
#endregion
}
}
| |
namespace XenAdmin.Dialogs.HealthCheck
{
partial class HealthCheckSettingsDialog
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(HealthCheckSettingsDialog));
this.okButton = new System.Windows.Forms.Button();
this.cancelButton = new System.Windows.Forms.Button();
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.decentGroupBox2 = new XenAdmin.Controls.DecentGroupBox();
this.tableLayoutPanel4 = new System.Windows.Forms.TableLayoutPanel();
this.frequencyLabel = new System.Windows.Forms.Label();
this.frequencyNumericBox = new System.Windows.Forms.NumericUpDown();
this.weeksLabel = new System.Windows.Forms.Label();
this.dayOfweekLabel = new System.Windows.Forms.Label();
this.timeOfDayLabel = new System.Windows.Forms.Label();
this.timeOfDayComboBox = new System.Windows.Forms.ComboBox();
this.dayOfWeekComboBox = new System.Windows.Forms.ComboBox();
this.decentGroupBox1 = new XenAdmin.Controls.DecentGroupBox();
this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.textBoxMyCitrixPassword = new System.Windows.Forms.TextBox();
this.textBoxMyCitrixUsername = new System.Windows.Forms.TextBox();
this.existingAuthenticationRadioButton = new System.Windows.Forms.RadioButton();
this.newAuthenticationRadioButton = new System.Windows.Forms.RadioButton();
this.authRubricLinkLabel = new System.Windows.Forms.LinkLabel();
this.tableLayoutPanel5 = new System.Windows.Forms.TableLayoutPanel();
this.pictureBoxStatus = new System.Windows.Forms.PictureBox();
this.labelStatus = new System.Windows.Forms.Label();
this.rubricLabel = new System.Windows.Forms.Label();
this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel();
this.enrollmentCheckBox = new System.Windows.Forms.CheckBox();
this.decentGroupBoxXSCredentials = new XenAdmin.Controls.DecentGroupBox();
this.tableLayoutPanel3 = new System.Windows.Forms.TableLayoutPanel();
this.errorLabel = new System.Windows.Forms.Label();
this.testCredentialsStatusImage = new System.Windows.Forms.PictureBox();
this.label3 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.textboxXSPassword = new System.Windows.Forms.TextBox();
this.textboxXSUserName = new System.Windows.Forms.TextBox();
this.currentXsCredentialsRadioButton = new System.Windows.Forms.RadioButton();
this.newXsCredentialsRadioButton = new System.Windows.Forms.RadioButton();
this.testCredentialsButton = new System.Windows.Forms.Button();
this.PolicyStatementLinkLabel = new System.Windows.Forms.LinkLabel();
this.tableLayoutPanel1.SuspendLayout();
this.decentGroupBox2.SuspendLayout();
this.tableLayoutPanel4.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.frequencyNumericBox)).BeginInit();
this.decentGroupBox1.SuspendLayout();
this.tableLayoutPanel2.SuspendLayout();
this.tableLayoutPanel5.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxStatus)).BeginInit();
this.flowLayoutPanel1.SuspendLayout();
this.decentGroupBoxXSCredentials.SuspendLayout();
this.tableLayoutPanel3.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.testCredentialsStatusImage)).BeginInit();
this.SuspendLayout();
//
// okButton
//
resources.ApplyResources(this.okButton, "okButton");
this.okButton.Name = "okButton";
this.okButton.UseVisualStyleBackColor = true;
this.okButton.Click += new System.EventHandler(this.okButton_Click);
//
// cancelButton
//
resources.ApplyResources(this.cancelButton, "cancelButton");
this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.cancelButton.Name = "cancelButton";
this.cancelButton.UseVisualStyleBackColor = true;
this.cancelButton.Click += new System.EventHandler(this.cancelButton_Click);
//
// tableLayoutPanel1
//
resources.ApplyResources(this.tableLayoutPanel1, "tableLayoutPanel1");
this.tableLayoutPanel1.Controls.Add(this.decentGroupBox2, 0, 2);
this.tableLayoutPanel1.Controls.Add(this.decentGroupBox1, 0, 4);
this.tableLayoutPanel1.Controls.Add(this.rubricLabel, 0, 0);
this.tableLayoutPanel1.Controls.Add(this.flowLayoutPanel1, 0, 5);
this.tableLayoutPanel1.Controls.Add(this.enrollmentCheckBox, 0, 1);
this.tableLayoutPanel1.Controls.Add(this.decentGroupBoxXSCredentials, 0, 3);
this.tableLayoutPanel1.Controls.Add(this.PolicyStatementLinkLabel, 1, 1);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
//
// decentGroupBox2
//
resources.ApplyResources(this.decentGroupBox2, "decentGroupBox2");
this.tableLayoutPanel1.SetColumnSpan(this.decentGroupBox2, 2);
this.decentGroupBox2.Controls.Add(this.tableLayoutPanel4);
this.decentGroupBox2.Name = "decentGroupBox2";
this.decentGroupBox2.TabStop = false;
//
// tableLayoutPanel4
//
resources.ApplyResources(this.tableLayoutPanel4, "tableLayoutPanel4");
this.tableLayoutPanel4.Controls.Add(this.frequencyLabel, 0, 0);
this.tableLayoutPanel4.Controls.Add(this.frequencyNumericBox, 1, 0);
this.tableLayoutPanel4.Controls.Add(this.weeksLabel, 2, 0);
this.tableLayoutPanel4.Controls.Add(this.dayOfweekLabel, 0, 2);
this.tableLayoutPanel4.Controls.Add(this.timeOfDayLabel, 0, 1);
this.tableLayoutPanel4.Controls.Add(this.timeOfDayComboBox, 1, 1);
this.tableLayoutPanel4.Controls.Add(this.dayOfWeekComboBox, 1, 2);
this.tableLayoutPanel4.Name = "tableLayoutPanel4";
//
// frequencyLabel
//
resources.ApplyResources(this.frequencyLabel, "frequencyLabel");
this.frequencyLabel.Name = "frequencyLabel";
//
// frequencyNumericBox
//
resources.ApplyResources(this.frequencyNumericBox, "frequencyNumericBox");
this.frequencyNumericBox.Maximum = new decimal(new int[] {
52,
0,
0,
0});
this.frequencyNumericBox.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.frequencyNumericBox.Name = "frequencyNumericBox";
this.frequencyNumericBox.Value = new decimal(new int[] {
1,
0,
0,
0});
//
// weeksLabel
//
resources.ApplyResources(this.weeksLabel, "weeksLabel");
this.weeksLabel.Name = "weeksLabel";
//
// dayOfweekLabel
//
resources.ApplyResources(this.dayOfweekLabel, "dayOfweekLabel");
this.dayOfweekLabel.Name = "dayOfweekLabel";
//
// timeOfDayLabel
//
resources.ApplyResources(this.timeOfDayLabel, "timeOfDayLabel");
this.timeOfDayLabel.Name = "timeOfDayLabel";
//
// timeOfDayComboBox
//
this.tableLayoutPanel4.SetColumnSpan(this.timeOfDayComboBox, 2);
this.timeOfDayComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
resources.ApplyResources(this.timeOfDayComboBox, "timeOfDayComboBox");
this.timeOfDayComboBox.FormattingEnabled = true;
this.timeOfDayComboBox.Name = "timeOfDayComboBox";
//
// dayOfWeekComboBox
//
this.tableLayoutPanel4.SetColumnSpan(this.dayOfWeekComboBox, 2);
this.dayOfWeekComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
resources.ApplyResources(this.dayOfWeekComboBox, "dayOfWeekComboBox");
this.dayOfWeekComboBox.FormattingEnabled = true;
this.dayOfWeekComboBox.Name = "dayOfWeekComboBox";
//
// decentGroupBox1
//
resources.ApplyResources(this.decentGroupBox1, "decentGroupBox1");
this.tableLayoutPanel1.SetColumnSpan(this.decentGroupBox1, 2);
this.decentGroupBox1.Controls.Add(this.tableLayoutPanel2);
this.decentGroupBox1.Name = "decentGroupBox1";
this.decentGroupBox1.TabStop = false;
//
// tableLayoutPanel2
//
resources.ApplyResources(this.tableLayoutPanel2, "tableLayoutPanel2");
this.tableLayoutPanel2.Controls.Add(this.label1, 0, 3);
this.tableLayoutPanel2.Controls.Add(this.label2, 0, 4);
this.tableLayoutPanel2.Controls.Add(this.textBoxMyCitrixPassword, 1, 4);
this.tableLayoutPanel2.Controls.Add(this.textBoxMyCitrixUsername, 1, 3);
this.tableLayoutPanel2.Controls.Add(this.existingAuthenticationRadioButton, 0, 1);
this.tableLayoutPanel2.Controls.Add(this.newAuthenticationRadioButton, 0, 2);
this.tableLayoutPanel2.Controls.Add(this.authRubricLinkLabel, 0, 0);
this.tableLayoutPanel2.Controls.Add(this.tableLayoutPanel5, 1, 5);
this.tableLayoutPanel2.Name = "tableLayoutPanel2";
//
// label1
//
resources.ApplyResources(this.label1, "label1");
this.label1.Name = "label1";
//
// label2
//
resources.ApplyResources(this.label2, "label2");
this.label2.Name = "label2";
//
// textBoxMyCitrixPassword
//
resources.ApplyResources(this.textBoxMyCitrixPassword, "textBoxMyCitrixPassword");
this.textBoxMyCitrixPassword.Name = "textBoxMyCitrixPassword";
this.textBoxMyCitrixPassword.UseSystemPasswordChar = true;
this.textBoxMyCitrixPassword.TextChanged += new System.EventHandler(this.credentials_TextChanged);
//
// textBoxMyCitrixUsername
//
resources.ApplyResources(this.textBoxMyCitrixUsername, "textBoxMyCitrixUsername");
this.textBoxMyCitrixUsername.Name = "textBoxMyCitrixUsername";
this.textBoxMyCitrixUsername.TextChanged += new System.EventHandler(this.credentials_TextChanged);
//
// existingAuthenticationRadioButton
//
resources.ApplyResources(this.existingAuthenticationRadioButton, "existingAuthenticationRadioButton");
this.tableLayoutPanel2.SetColumnSpan(this.existingAuthenticationRadioButton, 2);
this.existingAuthenticationRadioButton.Name = "existingAuthenticationRadioButton";
this.existingAuthenticationRadioButton.TabStop = true;
this.existingAuthenticationRadioButton.UseVisualStyleBackColor = true;
this.existingAuthenticationRadioButton.CheckedChanged += new System.EventHandler(this.existingAuthenticationRadioButton_CheckedChanged);
//
// newAuthenticationRadioButton
//
resources.ApplyResources(this.newAuthenticationRadioButton, "newAuthenticationRadioButton");
this.tableLayoutPanel2.SetColumnSpan(this.newAuthenticationRadioButton, 2);
this.newAuthenticationRadioButton.Name = "newAuthenticationRadioButton";
this.newAuthenticationRadioButton.TabStop = true;
this.newAuthenticationRadioButton.UseVisualStyleBackColor = true;
this.newAuthenticationRadioButton.CheckedChanged += new System.EventHandler(this.newAuthenticationRadioButton_CheckedChanged);
//
// authRubricLinkLabel
//
resources.ApplyResources(this.authRubricLinkLabel, "authRubricLinkLabel");
this.tableLayoutPanel2.SetColumnSpan(this.authRubricLinkLabel, 2);
this.authRubricLinkLabel.Name = "authRubricLinkLabel";
this.authRubricLinkLabel.TabStop = true;
this.authRubricLinkLabel.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.authRubricLinkLabel_LinkClicked);
//
// tableLayoutPanel5
//
resources.ApplyResources(this.tableLayoutPanel5, "tableLayoutPanel5");
this.tableLayoutPanel5.Controls.Add(this.pictureBoxStatus, 0, 0);
this.tableLayoutPanel5.Controls.Add(this.labelStatus, 1, 0);
this.tableLayoutPanel5.Name = "tableLayoutPanel5";
//
// pictureBoxStatus
//
resources.ApplyResources(this.pictureBoxStatus, "pictureBoxStatus");
this.pictureBoxStatus.Name = "pictureBoxStatus";
this.pictureBoxStatus.TabStop = false;
//
// labelStatus
//
resources.ApplyResources(this.labelStatus, "labelStatus");
this.labelStatus.ForeColor = System.Drawing.SystemColors.ControlText;
this.labelStatus.Name = "labelStatus";
//
// rubricLabel
//
resources.ApplyResources(this.rubricLabel, "rubricLabel");
this.tableLayoutPanel1.SetColumnSpan(this.rubricLabel, 2);
this.rubricLabel.Name = "rubricLabel";
//
// flowLayoutPanel1
//
resources.ApplyResources(this.flowLayoutPanel1, "flowLayoutPanel1");
this.tableLayoutPanel1.SetColumnSpan(this.flowLayoutPanel1, 2);
this.flowLayoutPanel1.Controls.Add(this.cancelButton);
this.flowLayoutPanel1.Controls.Add(this.okButton);
this.flowLayoutPanel1.Name = "flowLayoutPanel1";
//
// enrollmentCheckBox
//
resources.ApplyResources(this.enrollmentCheckBox, "enrollmentCheckBox");
this.enrollmentCheckBox.Name = "enrollmentCheckBox";
this.enrollmentCheckBox.UseVisualStyleBackColor = true;
this.enrollmentCheckBox.CheckedChanged += new System.EventHandler(this.enrollmentCheckBox_CheckedChanged);
//
// decentGroupBoxXSCredentials
//
resources.ApplyResources(this.decentGroupBoxXSCredentials, "decentGroupBoxXSCredentials");
this.tableLayoutPanel1.SetColumnSpan(this.decentGroupBoxXSCredentials, 2);
this.decentGroupBoxXSCredentials.Controls.Add(this.tableLayoutPanel3);
this.decentGroupBoxXSCredentials.Name = "decentGroupBoxXSCredentials";
this.decentGroupBoxXSCredentials.TabStop = false;
//
// tableLayoutPanel3
//
resources.ApplyResources(this.tableLayoutPanel3, "tableLayoutPanel3");
this.tableLayoutPanel3.Controls.Add(this.errorLabel, 3, 5);
this.tableLayoutPanel3.Controls.Add(this.testCredentialsStatusImage, 2, 5);
this.tableLayoutPanel3.Controls.Add(this.label3, 0, 0);
this.tableLayoutPanel3.Controls.Add(this.label4, 0, 3);
this.tableLayoutPanel3.Controls.Add(this.label5, 0, 4);
this.tableLayoutPanel3.Controls.Add(this.textboxXSPassword, 1, 4);
this.tableLayoutPanel3.Controls.Add(this.textboxXSUserName, 1, 3);
this.tableLayoutPanel3.Controls.Add(this.currentXsCredentialsRadioButton, 0, 1);
this.tableLayoutPanel3.Controls.Add(this.newXsCredentialsRadioButton, 0, 2);
this.tableLayoutPanel3.Controls.Add(this.testCredentialsButton, 1, 5);
this.tableLayoutPanel3.Name = "tableLayoutPanel3";
//
// errorLabel
//
resources.ApplyResources(this.errorLabel, "errorLabel");
this.errorLabel.AutoEllipsis = true;
this.errorLabel.ForeColor = System.Drawing.Color.Red;
this.errorLabel.Name = "errorLabel";
//
// testCredentialsStatusImage
//
resources.ApplyResources(this.testCredentialsStatusImage, "testCredentialsStatusImage");
this.testCredentialsStatusImage.Name = "testCredentialsStatusImage";
this.testCredentialsStatusImage.TabStop = false;
//
// label3
//
resources.ApplyResources(this.label3, "label3");
this.tableLayoutPanel3.SetColumnSpan(this.label3, 4);
this.label3.Name = "label3";
//
// label4
//
resources.ApplyResources(this.label4, "label4");
this.label4.Name = "label4";
//
// label5
//
resources.ApplyResources(this.label5, "label5");
this.label5.Name = "label5";
//
// textboxXSPassword
//
this.tableLayoutPanel3.SetColumnSpan(this.textboxXSPassword, 3);
resources.ApplyResources(this.textboxXSPassword, "textboxXSPassword");
this.textboxXSPassword.Name = "textboxXSPassword";
this.textboxXSPassword.UseSystemPasswordChar = true;
this.textboxXSPassword.TextChanged += new System.EventHandler(this.xsCredentials_TextChanged);
//
// textboxXSUserName
//
this.tableLayoutPanel3.SetColumnSpan(this.textboxXSUserName, 3);
resources.ApplyResources(this.textboxXSUserName, "textboxXSUserName");
this.textboxXSUserName.Name = "textboxXSUserName";
this.textboxXSUserName.TextChanged += new System.EventHandler(this.xsCredentials_TextChanged);
//
// currentXsCredentialsRadioButton
//
resources.ApplyResources(this.currentXsCredentialsRadioButton, "currentXsCredentialsRadioButton");
this.currentXsCredentialsRadioButton.Checked = true;
this.tableLayoutPanel3.SetColumnSpan(this.currentXsCredentialsRadioButton, 4);
this.currentXsCredentialsRadioButton.Name = "currentXsCredentialsRadioButton";
this.currentXsCredentialsRadioButton.TabStop = true;
this.currentXsCredentialsRadioButton.UseVisualStyleBackColor = true;
//
// newXsCredentialsRadioButton
//
resources.ApplyResources(this.newXsCredentialsRadioButton, "newXsCredentialsRadioButton");
this.tableLayoutPanel3.SetColumnSpan(this.newXsCredentialsRadioButton, 4);
this.newXsCredentialsRadioButton.Name = "newXsCredentialsRadioButton";
this.newXsCredentialsRadioButton.TabStop = true;
this.newXsCredentialsRadioButton.UseVisualStyleBackColor = true;
this.newXsCredentialsRadioButton.CheckedChanged += new System.EventHandler(this.newXsCredentialsRadioButton_CheckedChanged);
//
// testCredentialsButton
//
resources.ApplyResources(this.testCredentialsButton, "testCredentialsButton");
this.testCredentialsButton.Name = "testCredentialsButton";
this.testCredentialsButton.UseVisualStyleBackColor = true;
this.testCredentialsButton.Click += new System.EventHandler(this.testCredentialsButton_Click);
//
// PolicyStatementLinkLabel
//
resources.ApplyResources(this.PolicyStatementLinkLabel, "PolicyStatementLinkLabel");
this.PolicyStatementLinkLabel.Name = "PolicyStatementLinkLabel";
this.PolicyStatementLinkLabel.TabStop = true;
this.PolicyStatementLinkLabel.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.PolicyStatementLinkLabel_LinkClicked);
//
// HealthCheckSettingsDialog
//
this.AcceptButton = this.okButton;
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.CancelButton = this.cancelButton;
this.Controls.Add(this.tableLayoutPanel1);
this.Name = "HealthCheckSettingsDialog";
this.tableLayoutPanel1.ResumeLayout(false);
this.tableLayoutPanel1.PerformLayout();
this.decentGroupBox2.ResumeLayout(false);
this.decentGroupBox2.PerformLayout();
this.tableLayoutPanel4.ResumeLayout(false);
this.tableLayoutPanel4.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.frequencyNumericBox)).EndInit();
this.decentGroupBox1.ResumeLayout(false);
this.decentGroupBox1.PerformLayout();
this.tableLayoutPanel2.ResumeLayout(false);
this.tableLayoutPanel2.PerformLayout();
this.tableLayoutPanel5.ResumeLayout(false);
this.tableLayoutPanel5.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxStatus)).EndInit();
this.flowLayoutPanel1.ResumeLayout(false);
this.flowLayoutPanel1.PerformLayout();
this.decentGroupBoxXSCredentials.ResumeLayout(false);
this.decentGroupBoxXSCredentials.PerformLayout();
this.tableLayoutPanel3.ResumeLayout(false);
this.tableLayoutPanel3.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.testCredentialsStatusImage)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private Controls.DecentGroupBox decentGroupBox2;
protected System.Windows.Forms.TableLayoutPanel tableLayoutPanel4;
private System.Windows.Forms.Label frequencyLabel;
private System.Windows.Forms.NumericUpDown frequencyNumericBox;
private System.Windows.Forms.Label weeksLabel;
private System.Windows.Forms.Label dayOfweekLabel;
private System.Windows.Forms.Label timeOfDayLabel;
private System.Windows.Forms.ComboBox timeOfDayComboBox;
private System.Windows.Forms.ComboBox dayOfWeekComboBox;
private Controls.DecentGroupBox decentGroupBox1;
protected System.Windows.Forms.TableLayoutPanel tableLayoutPanel2;
protected System.Windows.Forms.Label label1;
protected System.Windows.Forms.TextBox textBoxMyCitrixUsername;
private System.Windows.Forms.RadioButton existingAuthenticationRadioButton;
private System.Windows.Forms.RadioButton newAuthenticationRadioButton;
private System.Windows.Forms.LinkLabel PolicyStatementLinkLabel;
private System.Windows.Forms.Label rubricLabel;
private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1;
private System.Windows.Forms.Button cancelButton;
private System.Windows.Forms.Button okButton;
private System.Windows.Forms.CheckBox enrollmentCheckBox;
private Controls.DecentGroupBox decentGroupBoxXSCredentials;
protected System.Windows.Forms.TableLayoutPanel tableLayoutPanel3;
private System.Windows.Forms.Label label3;
protected System.Windows.Forms.Label label4;
protected System.Windows.Forms.Label label5;
protected System.Windows.Forms.TextBox textboxXSPassword;
protected System.Windows.Forms.TextBox textboxXSUserName;
private System.Windows.Forms.RadioButton currentXsCredentialsRadioButton;
private System.Windows.Forms.RadioButton newXsCredentialsRadioButton;
private System.Windows.Forms.Button testCredentialsButton;
private System.Windows.Forms.PictureBox testCredentialsStatusImage;
private System.Windows.Forms.Label errorLabel;
protected System.Windows.Forms.Label label2;
protected System.Windows.Forms.TextBox textBoxMyCitrixPassword;
private System.Windows.Forms.LinkLabel authRubricLinkLabel;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel5;
private System.Windows.Forms.PictureBox pictureBoxStatus;
private System.Windows.Forms.Label labelStatus;
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#if !UNIX
using System;
using System.Runtime.Serialization;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// Defines the base class for exceptions thrown by the
/// certificate provider when the specified item cannot be located.
/// </summary>
[Serializable]
public class CertificateProviderItemNotFoundException : SystemException
{
/// <summary>
/// Initializes a new instance of the CertificateProviderItemNotFoundException
/// class with the default message.
/// </summary>
public CertificateProviderItemNotFoundException() : base()
{
}
/// <summary>
/// Initializes a new instance of the CertificateProviderItemNotFoundException
/// class with the specified message.
/// </summary>
/// <param name="message">
/// The message to be included in the exception.
/// </param>
public CertificateProviderItemNotFoundException(string message) : base(message)
{
}
/// <summary>
/// Initializes a new instance of the CertificateProviderItemNotFoundException
/// class with the specified message, and inner exception.
/// </summary>
/// <param name="message">
/// The message to be included in the exception.
/// </param>
/// <param name="innerException">
/// The inner exception to be included in the exception.
/// </param>
public CertificateProviderItemNotFoundException(string message,
Exception innerException)
: base(message, innerException)
{
}
/// <summary>
/// Initializes a new instance of the CertificateProviderItemNotFoundException
/// class with the specified serialization information, and context.
/// </summary>
/// <param name="info">
/// The serialization information.
/// </param>
/// <param name="context">
/// The streaming context.
/// </param>
protected CertificateProviderItemNotFoundException(SerializationInfo info,
StreamingContext context)
: base(info, context)
{
}
/// <summary>
/// Initializes a new instance of the CertificateProviderItemNotFoundException
/// class with the specified inner exception.
/// </summary>
/// <param name="innerException">
/// The inner exception to be included in the exception.
/// </param>
internal CertificateProviderItemNotFoundException(Exception innerException)
: base(innerException.Message, innerException)
{
}
}
/// <summary>
/// Defines the exception thrown by the certificate provider
/// when the specified X509 certificate cannot be located.
/// </summary>
[Serializable]
public class CertificateNotFoundException
: CertificateProviderItemNotFoundException
{
/// <summary>
/// Initializes a new instance of the CertificateNotFoundException
/// class with the default message.
/// </summary>
public CertificateNotFoundException()
: base()
{
}
/// <summary>
/// Initializes a new instance of the CertificateNotFoundException
/// class with the specified message.
/// </summary>
/// <param name="message">
/// The message to be included in the exception.
/// </param>
public CertificateNotFoundException(string message)
: base(message)
{
}
/// <summary>
/// Initializes a new instance of the CertificateNotFoundException
/// class with the specified message, and inner exception.
/// </summary>
/// <param name="message">
/// The message to be included in the exception.
/// </param>
/// <param name="innerException">
/// The inner exception to be included in the exception.
/// </param>
public CertificateNotFoundException(string message,
Exception innerException)
: base(message, innerException)
{
}
/// <summary>
/// Initializes a new instance of the CertificateNotFoundException
/// class with the specified serialization information, and context.
/// </summary>
/// <param name="info">
/// The serialization information.
/// </param>
/// <param name="context">
/// The streaming context.
/// </param>
protected CertificateNotFoundException(SerializationInfo info,
StreamingContext context)
: base(info, context)
{
}
/// <summary>
/// Initializes a new instance of the CertificateNotFoundException
/// class with the specified inner exception.
/// </summary>
/// <param name="innerException">
/// The inner exception to be included in the exception.
/// </param>
internal CertificateNotFoundException(Exception innerException)
: base(innerException.Message, innerException)
{
}
}
/// <summary>
/// Defines the exception thrown by the certificate provider
/// when the specified X509 store cannot be located.
/// </summary>
[Serializable]
public class CertificateStoreNotFoundException
: CertificateProviderItemNotFoundException
{
/// <summary>
/// Initializes a new instance of the CertificateStoreNotFoundException
/// class with the default message.
/// </summary>
public CertificateStoreNotFoundException()
: base()
{
}
/// <summary>
/// Initializes a new instance of the CertificateStoreNotFoundException
/// class with the specified message.
/// </summary>
/// <param name="message">
/// The message to be included in the exception.
/// </param>
public CertificateStoreNotFoundException(string message)
: base(message)
{
}
/// <summary>
/// Initializes a new instance of the CertificateStoreNotFoundException
/// class with the specified message, and inner exception.
/// </summary>
/// <param name="message">
/// The message to be included in the exception.
/// </param>
/// <param name="innerException">
/// The inner exception to be included in the exception.
/// </param>
public CertificateStoreNotFoundException(string message,
Exception innerException)
: base(message, innerException)
{
}
/// <summary>
/// Initializes a new instance of the CertificateStoreNotFoundException
/// class with the specified serialization information, and context.
/// </summary>
/// <param name="info">
/// The serialization information.
/// </param>
/// <param name="context">
/// The streaming context.
/// </param>
protected CertificateStoreNotFoundException(SerializationInfo info,
StreamingContext context)
: base(info, context)
{
}
/// <summary>
/// Initializes a new instance of the CertificateStoreNotFoundException
/// class with the specified inner exception.
/// </summary>
/// <param name="innerException">
/// The inner exception to be included in the exception.
/// </param>
internal CertificateStoreNotFoundException(Exception innerException)
: base(innerException.Message, innerException)
{
}
}
/// <summary>
/// Defines the exception thrown by the certificate provider
/// when the specified X509 store location cannot be located.
/// </summary>
[Serializable]
public class CertificateStoreLocationNotFoundException
: CertificateProviderItemNotFoundException
{
/// <summary>
/// Initializes a new instance of the CertificateStoreLocationNotFoundException
/// class with the default message.
/// </summary>
public CertificateStoreLocationNotFoundException()
: base()
{
}
/// <summary>
/// Initializes a new instance of the CertificateStoreLocationNotFoundException
/// class with the specified message.
/// </summary>
/// <param name="message">
/// The message to be included in the exception.
/// </param>
public CertificateStoreLocationNotFoundException(string message)
: base(message)
{
}
/// <summary>
/// Initializes a new instance of the CertificateStoreLocationNotFoundException
/// class with the specified message, and inner exception.
/// </summary>
/// <param name="message">
/// The message to be included in the exception.
/// </param>
/// <param name="innerException">
/// The inner exception to be included in the exception.
/// </param>
public CertificateStoreLocationNotFoundException(string message,
Exception innerException)
: base(message, innerException)
{
}
/// <summary>
/// Initializes a new instance of the CertificateStoreLocationNotFoundException
/// class with the specified serialization information, and context.
/// </summary>
/// <param name="info">
/// The serialization information.
/// </param>
/// <param name="context">
/// The streaming context.
/// </param>
protected CertificateStoreLocationNotFoundException(SerializationInfo info,
StreamingContext context)
: base(info, context)
{
}
/// <summary>
/// Initializes a new instance of the CertificateStoreLocationNotFoundException
/// class with the specified inner exception.
/// </summary>
/// <param name="innerException">
/// The inner exception to be included in the exception.
/// </param>
internal CertificateStoreLocationNotFoundException(Exception innerException)
: base(innerException.Message, innerException)
{
}
}
}
#endif // !UNIX
| |
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Serialization;
using XposeCraft.Core.Faction;
using XposeCraft.Core.Faction.Buildings;
using XposeCraft.Core.Faction.Units;
using XposeCraft.Core.Grids;
using XposeCraft.GameInternal;
using XposeCraft.UI.MiniMap;
namespace XposeCraft.Core.Required
{
public class UnitSelection : MonoBehaviour
{
[FormerlySerializedAs("group")] public int FactionIndex;
public int maxUnitSelect = 50;
public int maxBuildingSelect = 50;
public int maxTotalSelect = 100;
public Texture selectTexture;
public Texture borderTexture;
public int borderSize = 3;
public Rect windowRect;
public LayerMask layer;
public LayerMask selection;
private List<UnitController> _unitList = new List<UnitController>();
public List<UnitController> UnitList
{
get { return _unitList; }
set { _unitList = value; }
}
private List<BuildingController> _buildingList = new List<BuildingController>();
public List<BuildingController> BuildingList
{
get { return _buildingList; }
set { _buildingList = value; }
}
int unitListLength;
int buildingListLength;
Vector2 startLoc;
Vector3 startLocV3;
Vector2 endLoc;
Vector3 endLocV3;
bool deselected;
// Hidden Info
//{
bool mouseDown;
bool largeSelect;
private bool _clickedOnMiniMap;
float disp = 0.5f;
Rect localWindow { get; set; }
public UGrid gridScript { get; set; }
public MiniMap map { get; set; }
public FactionManager FactionM { get; set; }
public List<GameObject> curSelected { get; set; }
public List<UnitController> curSelectedS { get; set; }
public List<GameObject> curBuildSelected { get; set; }
public List<BuildingController> curBuildSelectedS { get; set; }
public int curSelectedLength { get; set; }
public int curBuildSelectedLength { get; set; }
public GUIManager guiManager { get; set; }
public BuildingPlacement placement { get; set; }
//}
public void ResizeSelectionWindow(Vector2 ratio)
{
localWindow = new Rect(
windowRect.x * ratio.x,
windowRect.y * ratio.y,
windowRect.width * ratio.x,
windowRect.height * ratio.y
);
}
public void Start()
{
gridScript = GameObject.Find("UGrid").GetComponent<UGrid>();
FactionM = GameObject.Find("Faction Manager").GetComponent<FactionManager>();
placement = gameObject.GetComponent<BuildingPlacement>();
guiManager = gameObject.GetComponent<GUIManager>();
GameObject obj = GameObject.Find("MiniMap");
if (obj)
{
map = obj.GetComponent<MiniMap>();
}
//test = Camera.main.GetComponent<GUILayer>();
curSelected = new List<GameObject>();
curSelectedS = new List<UnitController>();
curBuildSelected = new List<GameObject>();
curBuildSelectedS = new List<BuildingController>();
}
public void Update()
{
if (Input.GetButton("LMB"))
{
if (!mouseDown && !guiManager.mouseOverGUI && !placement.place && !placement.placed)
{
_clickedOnMiniMap = map && map.localBounds.Contains(new Vector2(
Input.mousePosition.x, Screen.height - Input.mousePosition.y));
mouseDown = true;
startLoc = Input.mousePosition;
startLoc = WithinScreen(startLoc);
if (!_clickedOnMiniMap && !deselected)
{
Deselect();
}
}
else if (!_clickedOnMiniMap && mouseDown)
{
endLoc = Input.mousePosition;
endLoc = WithinScreen(endLoc);
if ((endLoc - startLoc).magnitude > disp)
{
largeSelect = true;
}
}
}
//Check if mouse has been released, if so and largeSelect is true then call Select for box location and reset the variables
if (Input.GetButtonUp("LMB"))
{
if (!_clickedOnMiniMap && largeSelect)
{
Select();
}
mouseDown = false;
largeSelect = false;
}
if (Input.GetButtonDown("RMB"))
{
RaycastHit hit;
if (map && map.localBounds.Contains(new Vector2(
Input.mousePosition.x, Screen.height - Input.mousePosition.y)))
{
Vector3 point = map.Determine3dLoc(100, new Vector2(
Input.mousePosition.x,
Screen.height - Input.mousePosition.y));
Physics.Raycast(point, Vector3.down, out hit, 10000);
}
else
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Physics.Raycast(ray, out hit, 10000, layer);
}
if (hit.collider)
{
SetTarget(hit.collider.gameObject, hit.point);
}
}
deselected = false;
}
public void SetTarget(GameObject obj, Vector3 loc)
{
SetTarget(curSelectedS, obj, loc);
}
public static void SetTarget(List<UnitController> units, GameObject obj, Vector3 loc)
{
string type; // = "None";
if (obj.CompareTag("Unit"))
{
type = "Unit";
}
else if (obj.CompareTag("Resource"))
{
type = "Resource";
}
else if (obj.CompareTag("Building"))
{
type = "Building";
}
else
{
type = "Location";
}
foreach (UnitController unit in units)
{
if (unit == null)
{
Log.e(typeof(UnitSelection), "UnitController with null value has attempted to set its target");
continue;
}
unit.SetTarget(obj, loc, type);
}
}
public void Select()
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(startLoc);
Physics.Raycast(ray, out hit, 10000, selection);
if (hit.collider)
{
startLocV3 = hit.point;
}
ray = Camera.main.ScreenPointToRay(endLoc);
Physics.Raycast(ray, out hit, 10000, selection);
if (hit.collider)
{
endLocV3 = hit.point;
}
SelectArea(startLocV3, endLocV3);
}
public void Deselect()
{
for (int x = 0; x < curSelectedLength; x++)
{
if (curSelected[x] == null)
{
curSelected.RemoveAt(x);
x--;
curSelectedLength--;
continue;
}
curSelectedS[x].Select(false);
}
for (int x = 0; x < curBuildSelectedLength; x++)
{
if (curBuildSelected[x] == null)
{
curBuildSelected.RemoveAt(x);
x--;
curBuildSelectedLength--;
continue;
}
curBuildSelected[x].GetComponent<BuildingController>().Select(false);
}
curSelected = new List<GameObject>();
curSelectedS = new List<UnitController>();
curSelectedLength = 0;
curBuildSelected = new List<GameObject>();
curBuildSelectedS = new List<BuildingController>();
curBuildSelectedLength = 0;
}
public void SelectArea(Vector3 startLocation, Vector3 endLocation)
{
var units = new List<GameObject>();
var buildings = new List<GameObject>();
SelectionFind(startLocation, endLocation, units, buildings, true);
for (int unitIndex = 0; unitIndex < units.Count; unitIndex++)
{
var unit = units[unitIndex];
curSelected.Add(unit);
var controller = unit.GetComponent<UnitController>();
controller.Select(true);
curSelectedS.Add(controller);
curSelectedLength++;
}
for (int buildingIndex = 0; buildingIndex < buildings.Count; buildingIndex++)
{
var building = buildings[buildingIndex];
curBuildSelected.Add(building);
var controller = building.GetComponent<BuildingController>();
controller.Select(true);
curBuildSelectedS.Add(controller);
curBuildSelectedLength++;
}
}
/// <summary>
/// Adds GameObjects representing units and buildings from the map within the rectangle size to the lists.
/// </summary>
/// <param name="startLocation">Start of rectangle for selection within the scene.</param>
/// <param name="endLocation">End of rectangle for selection within the scene.</param>
/// <param name="units">Output list for matched units.</param>
/// <param name="buildings">Output list for matched buildings.</param>
/// <param name="limit">True if this should respect UnitSelection's limit of selection amount.</param>
public void SelectionFind(
Vector3 startLocation, Vector3 endLocation, List<GameObject> units, List<GameObject> buildings, bool limit)
{
Rect selectionRect = MapRectangle(startLocation, endLocation);
int selectedAmount = 0;
for (int x = 0; x < unitListLength; x++)
{
if (_unitList[x] == null)
{
Debug.LogWarning("A unit was not safely removed from UnitSelection script");
_unitList.RemoveAt(x);
x--;
unitListLength--;
continue;
}
var unit = _unitList[x].gameObject;
if (!WithinRectangleBounds(unit, selectionRect) || limit && selectedAmount >= maxUnitSelect)
{
continue;
}
selectedAmount++;
units.Add(unit);
}
selectedAmount = 0;
for (int x = 0; x < buildingListLength; x++)
{
if (_buildingList[x] == null)
{
Debug.LogWarning("A building was not safely removed from UnitSelection script");
_buildingList.RemoveAt(x);
x--;
buildingListLength--;
continue;
}
var building = _buildingList[x].gameObject;
if (!WithinRectangleBounds(building, selectionRect) || limit && selectedAmount >= maxBuildingSelect)
{
continue;
}
buildings.Add(building);
selectedAmount++;
}
}
private static Rect MapRectangle(Vector3 startLocation, Vector3 endLocation)
{
Rect selectionRect = startLocation.x > endLocation.x
? new Rect(endLocation.x, 0, startLocation.x, 0)
: new Rect(startLocation.x, 0, endLocation.x, 0);
selectionRect = startLocation.z > endLocation.z
? new Rect(selectionRect.x, endLocation.z, selectionRect.width, startLocation.z)
: new Rect(selectionRect.x, startLocation.z, selectionRect.width, endLocation.z);
return selectionRect;
}
public static bool WithinRectangleBounds(GameObject unit, Rect rectangle)
{
return unit.transform.position.x > rectangle.x
&& unit.transform.position.x < rectangle.width
&& unit.transform.position.z > rectangle.y
&& unit.transform.position.z < rectangle.height;
}
public Vector2 WithinScreen(Vector2 loc)
{
if (loc.x < localWindow.x)
{
loc = new Vector2(localWindow.x, loc.y);
}
else if (loc.x > localWindow.x + localWindow.width)
{
loc = new Vector2(localWindow.x + localWindow.width, loc.y);
}
if (Screen.height - loc.y < localWindow.y)
{
loc = new Vector2(loc.x, Screen.height - localWindow.y);
}
else if (Screen.height - loc.y > localWindow.y + localWindow.height)
{
loc = new Vector2(loc.x, Screen.height - (localWindow.y + localWindow.height));
}
return loc;
}
public void OnGUI()
{
if (!largeSelect)
{
return;
}
Rect myRect = new Rect(0, 0, 0, 0);
myRect = startLoc.x > endLoc.x
? new Rect(endLoc.x, myRect.y, startLoc.x - endLoc.x, myRect.height)
: new Rect(startLoc.x, myRect.y, endLoc.x - startLoc.x, myRect.height);
myRect = startLoc.y > endLoc.y
? new Rect(myRect.x, Screen.height - startLoc.y, myRect.width, startLoc.y - endLoc.y)
: new Rect(myRect.x, Screen.height - endLoc.y, myRect.width, endLoc.y - startLoc.y);
if (selectTexture)
{
GUI.DrawTexture(myRect, selectTexture);
}
if (!borderTexture)
{
return;
}
GUI.DrawTexture(new Rect(myRect.x, myRect.y, myRect.width, borderSize), borderTexture);
GUI.DrawTexture(
new Rect(myRect.x, myRect.y + myRect.height - borderSize, myRect.width, borderSize),
borderTexture);
GUI.DrawTexture(new Rect(myRect.x, myRect.y, borderSize, myRect.height), borderTexture);
GUI.DrawTexture(
new Rect(myRect.x + myRect.width - borderSize, myRect.y, borderSize, myRect.height),
borderTexture);
}
public void Select(int i, string type)
{
if (type == "Unit")
{
for (int x = 0; x < curSelectedLength; x++)
{
curSelectedS[x].Select(false);
}
for (int x = 0; x < curBuildSelectedLength; x++)
{
curBuildSelectedS[x].Select(false);
}
curBuildSelected = new List<GameObject>();
curBuildSelectedS = new List<BuildingController>();
curBuildSelectedLength = 0;
GameObject obj = curSelected[i];
UnitController cont = curSelectedS[i];
curSelected = new List<GameObject>();
curSelectedS = new List<UnitController>();
curSelected.Add(obj);
curSelectedS.Add(cont);
curSelectedLength = 1;
obj.SendMessage("Select", true);
}
else
{
for (int x = 0; x < curSelectedLength; x++)
{
curSelectedS[x].Select(false);
}
for (int x = 0; x < curBuildSelectedLength; x++)
{
curBuildSelectedS[x].Select(false);
}
GameObject obj = curBuildSelected[i];
BuildingController cont = curBuildSelectedS[i];
curBuildSelected = new List<GameObject>();
curBuildSelectedS = new List<BuildingController>();
curBuildSelected.Add(obj);
curBuildSelectedS.Add(cont);
curBuildSelectedLength = 1;
curSelected = new List<GameObject>();
curSelectedS = new List<UnitController>();
curSelectedLength = 0;
cont.Select(true);
}
}
public void AddUnit(GameObject obj)
{
var unitController = obj.GetComponent<UnitController>();
if (unitController == null)
{
throw new Exception("Unit with a null controller has attempted to be registered");
}
if (unitController.FactionIndex == FactionIndex)
{
_unitList.Add(unitController);
unitListLength++;
}
}
public void RemoveUnit(GameObject obj)
{
for (int x = 0; x < unitListLength; x++)
{
if (_unitList[x].gameObject == obj)
{
_unitList.RemoveAt(x);
unitListLength--;
if (curSelected.Contains(obj))
{
var selectedIndex = curSelected.IndexOf(obj);
curSelected.RemoveAt(selectedIndex);
curSelectedS.RemoveAt(selectedIndex);
curSelectedLength--;
}
break;
}
}
}
public void AddSelectedUnit(GameObject obj)
{
Deselect();
deselected = true;
for (int x = 0; x < unitListLength; x++)
{
if (_unitList[x].gameObject == obj)
{
curSelected.Add(_unitList[x].gameObject);
curSelectedS.Add(_unitList[x].GetComponent<UnitController>());
curSelectedLength++;
curSelectedS[curSelectedLength - 1].Select(true);
break;
}
}
}
public void AddSelectedBuilding(GameObject obj)
{
Deselect();
deselected = true;
for (int x = 0; x < buildingListLength; x++)
{
if (_buildingList[x].gameObject == obj)
{
curBuildSelected.Add(_buildingList[x].gameObject);
curBuildSelectedS.Add(_buildingList[x].GetComponent<BuildingController>());
curBuildSelectedLength++;
_buildingList[x].GetComponent<BuildingController>().Select(true);
break;
}
}
}
public void AddBuilding(GameObject obj)
{
var buildingController = obj.GetComponent<BuildingController>();
if (buildingController == null)
{
throw new Exception("Building with a null controller has attempted to be registered");
}
_buildingList.Add(buildingController);
buildingListLength++;
}
public void RemoveBuilding(GameObject obj)
{
for (int x = 0; x < buildingListLength; x++)
{
if (_buildingList[x].gameObject == obj)
{
_buildingList.RemoveAt(x);
buildingListLength--;
if (curBuildSelected.Contains(obj))
{
var selectedIndex = curBuildSelected.IndexOf(obj);
curBuildSelected.RemoveAt(selectedIndex);
curBuildSelectedS.RemoveAt(selectedIndex);
curBuildSelectedLength--;
}
break;
}
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Runtime.CompilerServices;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using Xunit;
public class DirectoryInfo_GetDirectories
{
public static String s_strActiveBugNums = "";
public static String s_strClassMethod = "Directory.GetDirectories()";
public static String s_strTFName = "GetDirectories.cs";
public static String s_strTFPath = Directory.GetCurrentDirectory();
private static bool s_pass = true;
[Fact]
public static void runTest()
{
int iCountErrors = 0;
int iCountTestcases = 0;
String strLoc = "Loc_000oo";
String strValue = String.Empty;
try
{
///////////////////////// START TESTS ////////////////////////////
///////////////////////////////////////////////////////////////////
DirectoryInfo dir2;
String dirName = Path.GetRandomFileName();
DirectoryInfo[] dirArr;
if (Directory.Exists(dirName))
Directory.Delete(dirName, true);
// [] Should return zero length array for an empty directory
//-----------------------------------------------------------------
strLoc = "Loc_4y982";
dir2 = Directory.CreateDirectory(dirName);
dirArr = dir2.GetDirectories();
iCountTestcases++;
if (dirArr.Length != 0)
{
iCountErrors++;
printerr("Error_207v7! Incorrect number of directories returned");
}
//-----------------------------------------------------------------
// [] Create a directorystructure and get all the directories
//-----------------------------------------------------------------
strLoc = "Loc_2398c";
dir2.CreateSubdirectory("TestDir1");
dir2.CreateSubdirectory("TestDir2");
dir2.CreateSubdirectory("TestDir3");
new FileInfo(dir2.ToString() + "TestFile1");
new FileInfo(dir2.ToString() + "TestFile2");
iCountTestcases++;
dirArr = dir2.GetDirectories();
iCountTestcases++;
if (dirArr.Length != 3)
{
iCountErrors++;
printerr("Error_1yt75! Incorrect number of directories returned");
}
if (!Interop.IsWindows) // test is expecting sorted order as provided by Windows
{
Array.Sort(dirArr, Comparer<DirectoryInfo>.Create((left, right) => left.FullName.CompareTo(right.FullName)));
}
iCountTestcases++;
if (!dirArr[0].Name.Equals("TestDir1"))
{
iCountErrors++;
printerr("Error_3y775! Incorrect name==" + dirArr[0].Name);
}
iCountTestcases++;
if (!dirArr[1].Name.Equals("TestDir2"))
{
iCountErrors++;
printerr("Error_90885! Incorrect name==" + dirArr[1].Name);
}
iCountTestcases++;
if (!dirArr[2].Name.Equals("TestDir3"))
{
iCountErrors++;
printerr("Error_879by! Incorrect name==" + dirArr[2].Name);
}
Directory.Delete(Path.Combine(dirName, "TestDir3"));
Directory.Delete(Path.Combine(dirName, "TestDir2"));
dirArr = dir2.GetDirectories();
iCountTestcases++;
if (dirArr.Length != 1)
{
iCountErrors++;
printerr("Error_4y28x! Incorrect number of directories returned");
}
iCountTestcases++;
if (!dirArr[0].Name.Equals("TestDir1"))
{
iCountErrors++;
printerr("Error_0975b! Incorrect name==" + dirArr[0].Name);
}
//-----------------------------------------------------------------
if (Directory.Exists(dirName))
Directory.Delete(dirName, true);
//bug ####### - DirectoryInfo.GetDirectories() uses relative path and thus the current directory rather than the full directory passed on
//DirectoryInfos internally constructed
/**
For folders under the root DirectoryInfo everything is fine, but any subfolder of that turns into <workingdir>\foldername
So for example if my working dir is
C:\wd
And Im looking at a directory structure
C:\foo\bar\abc
If I do repro c:\foo
It prints out something like
C:\foo\bar
C:\wd\bar\abc
**/
if (Interop.IsWindows) // test expects that '/' is not root
{
//@TODO!! use ManageFileSystem utility
String rootTempDir = Path.DirectorySeparatorChar + "LaksTemp";
int dirSuffixNo = 0;
while (Directory.Exists(String.Format("{0}{1}", rootTempDir, dirSuffixNo++))) ;
rootTempDir = String.Format("{0}{1}", rootTempDir, (dirSuffixNo - 1));
String tempFullName = Path.Combine(rootTempDir, "laks1", "laks2");
Directory.CreateDirectory(tempFullName);
DirectoryInfo dir = new DirectoryInfo(rootTempDir);
AddFolders(dir);
Eval(s_directories.Count == 3, "Err_9347g! wrong count: {0}", s_directories.Count);
Eval(s_directories.Contains(Path.GetFullPath(rootTempDir)), "Err_3407tgs! PAth not found: {0}", Path.GetFullPath(rootTempDir));
Eval(s_directories.Contains(Path.Combine(Path.GetFullPath(rootTempDir), "laks1")), "Err_857sqi! PAth not found: {0}", Path.Combine(Path.GetFullPath(rootTempDir), "laks1"));
Eval(s_directories.Contains(Path.Combine(Path.GetFullPath(rootTempDir), Path.Combine("laks1", "laks2"))), "Err_356slh! PAth not found: {0}", Path.Combine(Path.GetFullPath(rootTempDir), "laks1", "laks2"));
Directory.Delete(rootTempDir, true);
}
if (!s_pass)
{
iCountErrors++;
printerr("Error_32947eg! Relative directories not working");
}
///////////////////////////////////////////////////////////////////
/////////////////////////// END TESTS /////////////////////////////
}
catch (Exception exc_general)
{
++iCountErrors;
Console.WriteLine("Error Err_8888yyy! strLoc==" + strLoc + ", exc_general==" + exc_general.ToString());
}
//// Finish Diagnostics
if (iCountErrors != 0)
{
Console.WriteLine("FAiL! " + s_strTFName + " ,iCountErrors==" + iCountErrors.ToString());
}
Assert.Equal(0, iCountErrors);
}
public static void printerr(String err, [CallerMemberName] string memberName = "", [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNumber = 0)
{
Console.WriteLine("ERROR: ({0}, {1}, {2}) {3}", memberName, filePath, lineNumber, err);
}
//Checks for error
private static bool Eval(bool expression, String msg, params Object[] values)
{
return Eval(expression, String.Format(msg, values));
}
private static bool Eval<T>(T actual, T expected, String errorMsg)
{
bool retValue = expected == null ? actual == null : expected.Equals(actual);
if (!retValue)
Eval(retValue, errorMsg +
" Expected:" + (null == expected ? "<null>" : expected.ToString()) +
" Actual:" + (null == actual ? "<null>" : actual.ToString()));
return retValue;
}
private static bool Eval(bool expression, String msg)
{
if (!expression)
{
s_pass = false;
Console.WriteLine(msg);
}
return expression;
}
private static List<String> s_directories = new List<String>();
public static void AddFolders(DirectoryInfo info)
{
s_directories.Add(info.FullName);
// Console.WriteLine("<{0}>", info.FullName);
foreach (DirectoryInfo i in info.GetDirectories())
{
AddFolders(i);
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Test.Utilities;
using Xunit;
namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.UnitTests
{
public class IdentifiersShouldNotContainUnderscoresTests : DiagnosticAnalyzerTestBase
{
protected override DiagnosticAnalyzer GetBasicDiagnosticAnalyzer()
{
return new IdentifiersShouldNotContainUnderscoresAnalyzer();
}
protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer()
{
return new IdentifiersShouldNotContainUnderscoresAnalyzer();
}
#region CSharp Tests
[Fact]
public void CA1707_ForAssembly_CSharp()
{
VerifyCSharp(@"
public class DoesNotMatter
{
}
",
testProjectName: "AssemblyNameHasUnderScore_",
expected: GetCA1707CSharpResultAt(line: 2, column: 1, symbolKind: SymbolKind.Assembly, identifierNames: "AssemblyNameHasUnderScore_"));
}
[Fact]
public void CA1707_ForAssembly_NoDiagnostics_CSharp()
{
VerifyCSharp(@"
public class DoesNotMatter
{
}
",
testProjectName: "AssemblyNameHasNoUnderScore");
}
[Fact]
public void CA1707_ForNamespace_CSharp()
{
VerifyCSharp(@"
namespace OuterNamespace
{
namespace HasUnderScore_
{
public class DoesNotMatter
{
}
}
}
namespace HasNoUnderScore
{
public class DoesNotMatter
{
}
}",
GetCA1707CSharpResultAt(line: 4, column: 15, symbolKind: SymbolKind.Namespace, identifierNames: "OuterNamespace.HasUnderScore_"));
}
[Fact]
public void CA1707_ForTypes_CSharp()
{
VerifyCSharp(@"
public class OuterType
{
public class UnderScoreInName_
{
}
private class UnderScoreInNameButPrivate_
{
}
}",
GetCA1707CSharpResultAt(line: 4, column: 18, symbolKind: SymbolKind.NamedType, identifierNames: "OuterType.UnderScoreInName_"));
}
[Fact]
public void CA1707_ForFields_CSharp()
{
VerifyCSharp(@"
public class DoesNotMatter
{
public const int ConstField_ = 5;
public static readonly int StaticReadOnlyField_ = 5;
// No diagnostics for the below
private string InstanceField_;
private static string StaticField_;
public string _field;
protected string Another_field;
}
public enum DoesNotMatterEnum
{
_EnumWithUnderscore,
_
}",
GetCA1707CSharpResultAt(line: 4, column: 26, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatter.ConstField_"),
GetCA1707CSharpResultAt(line: 5, column: 36, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatter.StaticReadOnlyField_"),
GetCA1707CSharpResultAt(line: 16, column: 5, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatterEnum._EnumWithUnderscore"),
GetCA1707CSharpResultAt(line: 17, column: 5, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatterEnum._"));
}
[Fact]
public void CA1707_ForMethods_CSharp()
{
VerifyCSharp(@"
public class DoesNotMatter
{
public void PublicM1_() { }
private void PrivateM2_() { } // No diagnostic
internal void InternalM3_() { } // No diagnostic
protected void ProtectedM4_() { }
}
public interface I1
{
void M_();
}
public class ImplementI1 : I1
{
public void M_() { } // No diagnostic
public virtual void M2_() { }
}
public class Derives : ImplementI1
{
public override void M2_() { } // No diagnostic
}",
GetCA1707CSharpResultAt(line: 4, column: 17, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatter.PublicM1_()"),
GetCA1707CSharpResultAt(line: 7, column: 20, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatter.ProtectedM4_()"),
GetCA1707CSharpResultAt(line: 12, column: 10, symbolKind: SymbolKind.Member, identifierNames: "I1.M_()"),
GetCA1707CSharpResultAt(line: 18, column: 25, symbolKind: SymbolKind.Member, identifierNames: "ImplementI1.M2_()"));
}
[Fact]
public void CA1707_ForProperties_CSharp()
{
VerifyCSharp(@"
public class DoesNotMatter
{
public int PublicP1_ { get; set; }
private int PrivateP2_ { get; set; } // No diagnostic
internal int InternalP3_ { get; set; } // No diagnostic
protected int ProtectedP4_ { get; set; }
}
public interface I1
{
int P_ { get; set; }
}
public class ImplementI1 : I1
{
public int P_ { get; set; } // No diagnostic
public virtual int P2_ { get; set; }
}
public class Derives : ImplementI1
{
public override int P2_ { get; set; } // No diagnostic
}",
GetCA1707CSharpResultAt(line: 4, column: 16, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatter.PublicP1_"),
GetCA1707CSharpResultAt(line: 7, column: 19, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatter.ProtectedP4_"),
GetCA1707CSharpResultAt(line: 12, column: 9, symbolKind: SymbolKind.Member, identifierNames: "I1.P_"),
GetCA1707CSharpResultAt(line: 18, column: 24, symbolKind: SymbolKind.Member, identifierNames: "ImplementI1.P2_"));
}
[Fact]
public void CA1707_ForEvents_CSharp()
{
VerifyCSharp(@"
using System;
public class DoesNotMatter
{
public event EventHandler PublicE1_;
private event EventHandler PrivateE2_; // No diagnostic
internal event EventHandler InternalE3_; // No diagnostic
protected event EventHandler ProtectedE4_;
}
public interface I1
{
event EventHandler E_;
}
public class ImplementI1 : I1
{
public event EventHandler E_;// No diagnostic
public virtual event EventHandler E2_;
}
public class Derives : ImplementI1
{
public override event EventHandler E2_; // No diagnostic
}",
GetCA1707CSharpResultAt(line: 6, column: 31, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatter.PublicE1_"),
GetCA1707CSharpResultAt(line: 9, column: 34, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatter.ProtectedE4_"),
GetCA1707CSharpResultAt(line: 14, column: 24, symbolKind: SymbolKind.Member, identifierNames: "I1.E_"),
GetCA1707CSharpResultAt(line: 20, column: 39, symbolKind: SymbolKind.Member, identifierNames: "ImplementI1.E2_"));
}
[Fact]
public void CA1707_ForDelegates_CSharp()
{
VerifyCSharp(@"
public delegate void Dele(int intPublic_, string stringPublic_);
internal delegate void Dele2(int intInternal_, string stringInternal_); // No diagnostics
public delegate T Del<T>(int t_);
",
GetCA1707CSharpResultAt(2, 31, SymbolKind.DelegateParameter, "Dele", "intPublic_"),
GetCA1707CSharpResultAt(2, 50, SymbolKind.DelegateParameter, "Dele", "stringPublic_"),
GetCA1707CSharpResultAt(4, 30, SymbolKind.DelegateParameter, "Del<T>", "t_"));
}
[Fact]
public void CA1707_ForMemberparameters_CSharp()
{
VerifyCSharp(@"
public class DoesNotMatter
{
public void PublicM1(int int_) { }
private void PrivateM2(int int_) { } // No diagnostic
internal void InternalM3(int int_) { } // No diagnostic
protected void ProtectedM4(int int_) { }
}
public interface I
{
void M(int int_);
}
public class implementI : I
{
public void M(int int_)
{
}
}
public abstract class Base
{
public virtual void M1(int int_)
{
}
public abstract void M2(int int_);
}
public class Der : Base
{
public override void M2(int int_)
{
throw new System.NotImplementedException();
}
public override void M1(int int_)
{
base.M1(int_);
}
}",
GetCA1707CSharpResultAt(4, 30, SymbolKind.MemberParameter, "DoesNotMatter.PublicM1(int)", "int_"),
GetCA1707CSharpResultAt(7, 36, SymbolKind.MemberParameter, "DoesNotMatter.ProtectedM4(int)", "int_"),
GetCA1707CSharpResultAt(12, 16, SymbolKind.MemberParameter, "I.M(int)", "int_"),
GetCA1707CSharpResultAt(24, 32, SymbolKind.MemberParameter, "Base.M1(int)", "int_"),
GetCA1707CSharpResultAt(28, 33, SymbolKind.MemberParameter, "Base.M2(int)", "int_"));
}
[Fact]
public void CA1707_ForTypeTypeParameters_CSharp()
{
VerifyCSharp(@"
public class DoesNotMatter<T_>
{
}
class NoDiag<U_>
{
}",
GetCA1707CSharpResultAt(2, 28, SymbolKind.TypeTypeParameter, "DoesNotMatter<T_>", "T_"));
}
[Fact]
public void CA1707_ForMemberTypeParameters_CSharp()
{
VerifyCSharp(@"
public class DoesNotMatter22
{
public void PublicM1<T1_>() { }
private void PrivateM2<U_>() { } // No diagnostic
internal void InternalM3<W_>() { } // No diagnostic
protected void ProtectedM4<D_>() { }
}
public interface I
{
void M<T_>();
}
public class implementI : I
{
public void M<U_>()
{
throw new System.NotImplementedException();
}
}
public abstract class Base
{
public virtual void M1<T_>()
{
}
public abstract void M2<U_>();
}
public class Der : Base
{
public override void M2<U_>()
{
throw new System.NotImplementedException();
}
public override void M1<T_>()
{
base.M1<T_>();
}
}",
GetCA1707CSharpResultAt(4, 26, SymbolKind.MethodTypeParameter, "DoesNotMatter22.PublicM1<T1_>()", "T1_"),
GetCA1707CSharpResultAt(7, 32, SymbolKind.MethodTypeParameter, "DoesNotMatter22.ProtectedM4<D_>()", "D_"),
GetCA1707CSharpResultAt(12, 12, SymbolKind.MethodTypeParameter, "I.M<T_>()", "T_"),
GetCA1707CSharpResultAt(25, 28, SymbolKind.MethodTypeParameter, "Base.M1<T_>()", "T_"),
GetCA1707CSharpResultAt(29, 29, SymbolKind.MethodTypeParameter, "Base.M2<U_>()", "U_"));
}
[Fact, WorkItem(947, "https://github.com/dotnet/roslyn-analyzers/issues/947")]
public void CA1707_ForOperators_CSharp()
{
VerifyCSharp(@"
public struct S
{
public static bool operator ==(S left, S right)
{
return left.Equals(right);
}
public static bool operator !=(S left, S right)
{
return !(left == right);
}
}
");
}
#endregion
#region Visual Basic Tests
[Fact]
public void CA1707_ForAssembly_VisualBasic()
{
VerifyBasic(@"
Public Class DoesNotMatter
End Class
",
testProjectName: "AssemblyNameHasUnderScore_",
expected: GetCA1707BasicResultAt(line: 2, column: 1, symbolKind: SymbolKind.Assembly, identifierNames: "AssemblyNameHasUnderScore_"));
}
[Fact]
public void CA1707_ForAssembly_NoDiagnostics_VisualBasic()
{
VerifyBasic(@"
Public Class DoesNotMatter
End Class
",
testProjectName: "AssemblyNameHasNoUnderScore");
}
[Fact]
public void CA1707_ForNamespace_VisualBasic()
{
VerifyBasic(@"
Namespace OuterNamespace
Namespace HasUnderScore_
Public Class DoesNotMatter
End Class
End Namespace
End Namespace
Namespace HasNoUnderScore
Public Class DoesNotMatter
End Class
End Namespace",
GetCA1707BasicResultAt(line: 3, column: 15, symbolKind: SymbolKind.Namespace, identifierNames: "OuterNamespace.HasUnderScore_"));
}
[Fact]
public void CA1707_ForTypes_VisualBasic()
{
VerifyBasic(@"
Public Class OuterType
Public Class UnderScoreInName_
End Class
Private Class UnderScoreInNameButPrivate_
End Class
End Class",
GetCA1707BasicResultAt(line: 3, column: 18, symbolKind: SymbolKind.NamedType, identifierNames: "OuterType.UnderScoreInName_"));
}
[Fact]
public void CA1707_ForFields_VisualBasic()
{
VerifyBasic(@"
Public Class DoesNotMatter
Public Const ConstField_ As Integer = 5
Public Shared ReadOnly SharedReadOnlyField_ As Integer = 5
' No diagnostics for the below
Private InstanceField_ As String
Private Shared StaticField_ As String
Public _field As String
Protected Another_field As String
End Class
Public Enum DoesNotMatterEnum
_EnumWithUnderscore
End Enum",
GetCA1707BasicResultAt(line: 3, column: 18, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatter.ConstField_"),
GetCA1707BasicResultAt(line: 4, column: 28, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatter.SharedReadOnlyField_"),
GetCA1707BasicResultAt(line: 14, column: 5, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatterEnum._EnumWithUnderscore"));
}
[Fact]
public void CA1707_ForMethods_VisualBasic()
{
VerifyBasic(@"
Public Class DoesNotMatter
Public Sub PublicM1_()
End Sub
' No diagnostic
Private Sub PrivateM2_()
End Sub
' No diagnostic
Friend Sub InternalM3_()
End Sub
Protected Sub ProtectedM4_()
End Sub
End Class
Public Interface I1
Sub M_()
End Interface
Public Class ImplementI1
Implements I1
Public Sub M_() Implements I1.M_
End Sub
' No diagnostic
Public Overridable Sub M2_()
End Sub
End Class
Public Class Derives
Inherits ImplementI1
' No diagnostic
Public Overrides Sub M2_()
End Sub
End Class",
GetCA1707BasicResultAt(line: 3, column: 16, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatter.PublicM1_()"),
GetCA1707BasicResultAt(line: 11, column: 19, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatter.ProtectedM4_()"),
GetCA1707BasicResultAt(line: 16, column: 9, symbolKind: SymbolKind.Member, identifierNames: "I1.M_()"),
GetCA1707BasicResultAt(line: 24, column: 28, symbolKind: SymbolKind.Member, identifierNames: "ImplementI1.M2_()"));
}
[Fact]
public void CA1707_ForProperties_VisualBasic()
{
VerifyBasic(@"
Public Class DoesNotMatter
Public Property PublicP1_() As Integer
Get
Return 0
End Get
Set
End Set
End Property
' No diagnostic
Private Property PrivateP2_() As Integer
Get
Return 0
End Get
Set
End Set
End Property
' No diagnostic
Friend Property InternalP3_() As Integer
Get
Return 0
End Get
Set
End Set
End Property
Protected Property ProtectedP4_() As Integer
Get
Return 0
End Get
Set
End Set
End Property
End Class
Public Interface I1
Property P_() As Integer
End Interface
Public Class ImplementI1
Implements I1
' No diagnostic
Public Property P_() As Integer Implements I1.P_
Get
Return 0
End Get
Set
End Set
End Property
Public Overridable Property P2_() As Integer
Get
Return 0
End Get
Set
End Set
End Property
End Class
Public Class Derives
Inherits ImplementI1
' No diagnostic
Public Overrides Property P2_() As Integer
Get
Return 0
End Get
Set
End Set
End Property
End Class",
GetCA1707BasicResultAt(line: 3, column: 21, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatter.PublicP1_"),
GetCA1707BasicResultAt(line: 26, column: 24, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatter.ProtectedP4_"),
GetCA1707BasicResultAt(line: 36, column: 14, symbolKind: SymbolKind.Member, identifierNames: "I1.P_"),
GetCA1707BasicResultAt(line: 49, column: 33, symbolKind: SymbolKind.Member, identifierNames: "ImplementI1.P2_"));
}
[Fact]
public void CA1707_ForEvents_VisualBasic()
{
VerifyBasic(@"
Public Class DoesNotMatter
Public Event PublicE1_ As System.EventHandler
Private Event PrivateE2_ As System.EventHandler
' No diagnostic
Friend Event InternalE3_ As System.EventHandler
' No diagnostic
Protected Event ProtectedE4_ As System.EventHandler
End Class
Public Interface I1
Event E_ As System.EventHandler
End Interface
Public Class ImplementI1
Implements I1
' No diagnostic
Public Event E_ As System.EventHandler Implements I1.E_
Public Event E2_ As System.EventHandler
End Class
Public Class Derives
Inherits ImplementI1
' No diagnostic
Public Shadows Event E2_ As System.EventHandler
End Class",
GetCA1707BasicResultAt(line: 3, column: 18, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatter.PublicE1_"),
GetCA1707BasicResultAt(line: 8, column: 21, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatter.ProtectedE4_"),
GetCA1707BasicResultAt(line: 12, column: 11, symbolKind: SymbolKind.Member, identifierNames: "I1.E_"),
GetCA1707BasicResultAt(line: 19, column: 18, symbolKind: SymbolKind.Member, identifierNames: "ImplementI1.E2_"),
GetCA1707BasicResultAt(line: 25, column: 26, symbolKind: SymbolKind.Member, identifierNames: "Derives.E2_"));
}
[Fact]
public void CA1707_ForDelegates_VisualBasic()
{
VerifyBasic(@"
Public Delegate Sub Dele(intPublic_ As Integer, stringPublic_ As String)
' No diagnostics
Friend Delegate Sub Dele2(intInternal_ As Integer, stringInternal_ As String)
Public Delegate Function Del(Of T)(t_ As Integer) As T
",
GetCA1707BasicResultAt(2, 26, SymbolKind.DelegateParameter, "Dele", "intPublic_"),
GetCA1707BasicResultAt(2, 49, SymbolKind.DelegateParameter, "Dele", "stringPublic_"),
GetCA1707BasicResultAt(5, 36, SymbolKind.DelegateParameter, "Del(Of T)", "t_"));
}
[Fact]
public void CA1707_ForMemberparameters_VisualBasic()
{
VerifyBasic(@"Public Class DoesNotMatter
Public Sub PublicM1(int_ As Integer)
End Sub
Private Sub PrivateM2(int_ As Integer)
End Sub
' No diagnostic
Friend Sub InternalM3(int_ As Integer)
End Sub
' No diagnostic
Protected Sub ProtectedM4(int_ As Integer)
End Sub
End Class
Public Interface I
Sub M(int_ As Integer)
End Interface
Public Class implementI
Implements I
Private Sub I_M(int_ As Integer) Implements I.M
End Sub
End Class
Public MustInherit Class Base
Public Overridable Sub M1(int_ As Integer)
End Sub
Public MustOverride Sub M2(int_ As Integer)
End Class
Public Class Der
Inherits Base
Public Overrides Sub M2(int_ As Integer)
Throw New System.NotImplementedException()
End Sub
Public Overrides Sub M1(int_ As Integer)
MyBase.M1(int_)
End Sub
End Class",
GetCA1707BasicResultAt(2, 25, SymbolKind.MemberParameter, "DoesNotMatter.PublicM1(Integer)", "int_"),
GetCA1707BasicResultAt(10, 31, SymbolKind.MemberParameter, "DoesNotMatter.ProtectedM4(Integer)", "int_"),
GetCA1707BasicResultAt(15, 11, SymbolKind.MemberParameter, "I.M(Integer)", "int_"),
GetCA1707BasicResultAt(25, 31, SymbolKind.MemberParameter, "Base.M1(Integer)", "int_"),
GetCA1707BasicResultAt(28, 32, SymbolKind.MemberParameter, "Base.M2(Integer)", "int_"));
}
[Fact]
public void CA1707_ForTypeTypeParameters_VisualBasic()
{
VerifyBasic(@"
Public Class DoesNotMatter(Of T_)
End Class
Class NoDiag(Of U_)
End Class",
GetCA1707BasicResultAt(2, 31, SymbolKind.TypeTypeParameter, "DoesNotMatter(Of T_)", "T_"));
}
[Fact]
public void CA1707_ForMemberTypeParameters_VisualBasic()
{
VerifyBasic(@"
Public Class DoesNotMatter22
Public Sub PublicM1(Of T1_)()
End Sub
Private Sub PrivateM2(Of U_)()
End Sub
Friend Sub InternalM3(Of W_)()
End Sub
Protected Sub ProtectedM4(Of D_)()
End Sub
End Class
Public Interface I
Sub M(Of T_)()
End Interface
Public Class implementI
Implements I
Public Sub M(Of U_)() Implements I.M
Throw New System.NotImplementedException()
End Sub
End Class
Public MustInherit Class Base
Public Overridable Sub M1(Of T_)()
End Sub
Public MustOverride Sub M2(Of U_)()
End Class
Public Class Der
Inherits Base
Public Overrides Sub M2(Of U_)()
Throw New System.NotImplementedException()
End Sub
Public Overrides Sub M1(Of T_)()
MyBase.M1(Of T_)()
End Sub
End Class",
GetCA1707BasicResultAt(3, 28, SymbolKind.MethodTypeParameter, "DoesNotMatter22.PublicM1(Of T1_)()", "T1_"),
GetCA1707BasicResultAt(9, 34, SymbolKind.MethodTypeParameter, "DoesNotMatter22.ProtectedM4(Of D_)()", "D_"),
GetCA1707BasicResultAt(14, 14, SymbolKind.MethodTypeParameter, "I.M(Of T_)()", "T_"),
GetCA1707BasicResultAt(25, 34, SymbolKind.MethodTypeParameter, "Base.M1(Of T_)()", "T_"),
GetCA1707BasicResultAt(28, 35, SymbolKind.MethodTypeParameter, "Base.M2(Of U_)()", "U_"));
}
[Fact, WorkItem(947, "https://github.com/dotnet/roslyn-analyzers/issues/947")]
public void CA1707_ForOperators_VisualBasic()
{
VerifyBasic(@"
Public Structure S
Public Shared Operator =(left As S, right As S) As Boolean
Return left.Equals(right)
End Operator
Public Shared Operator <>(left As S, right As S) As Boolean
Return Not (left = right)
End Operator
End Structure
");
}
#endregion
#region Helpers
private static DiagnosticResult GetCA1707CSharpResultAt(int line, int column, SymbolKind symbolKind, params string[] identifierNames)
{
return GetCA1707CSharpResultAt(line, column, GetApproriateMessage(symbolKind), identifierNames);
}
private static DiagnosticResult GetCA1707CSharpResultAt(int line, int column, string message, params string[] identifierName)
{
return GetCSharpResultAt(line, column, IdentifiersShouldNotContainUnderscoresAnalyzer.RuleId, string.Format(message, identifierName));
}
private void VerifyCSharp(string source, string testProjectName, params DiagnosticResult[] expected)
{
Verify(source, LanguageNames.CSharp, GetCSharpDiagnosticAnalyzer(), testProjectName, expected);
}
private static DiagnosticResult GetCA1707BasicResultAt(int line, int column, SymbolKind symbolKind, params string[] identifierNames)
{
return GetCA1707BasicResultAt(line, column, GetApproriateMessage(symbolKind), identifierNames);
}
private static DiagnosticResult GetCA1707BasicResultAt(int line, int column, string message, params string[] identifierName)
{
return GetBasicResultAt(line, column, IdentifiersShouldNotContainUnderscoresAnalyzer.RuleId, string.Format(message, identifierName));
}
private void VerifyBasic(string source, string testProjectName, params DiagnosticResult[] expected)
{
Verify(source, LanguageNames.VisualBasic, GetBasicDiagnosticAnalyzer(), testProjectName, expected);
}
private void Verify(string source, string language, DiagnosticAnalyzer analyzer, string testProjectName, DiagnosticResult[] expected)
{
var sources = new[] { source };
var diagnostics = GetSortedDiagnostics(sources.ToFileAndSource(), language, analyzer, addLanguageSpecificCodeAnalysisReference: true, projectName: testProjectName);
diagnostics.Verify(analyzer, expected);
}
private static string GetApproriateMessage(SymbolKind symbolKind)
{
switch (symbolKind)
{
case SymbolKind.Assembly:
return MicrosoftApiDesignGuidelinesAnalyzersResources.IdentifiersShouldNotContainUnderscoresMessageAssembly;
case SymbolKind.Namespace:
return MicrosoftApiDesignGuidelinesAnalyzersResources.IdentifiersShouldNotContainUnderscoresMessageNamespace;
case SymbolKind.NamedType:
return MicrosoftApiDesignGuidelinesAnalyzersResources.IdentifiersShouldNotContainUnderscoresMessageType;
case SymbolKind.Member:
return MicrosoftApiDesignGuidelinesAnalyzersResources.IdentifiersShouldNotContainUnderscoresMessageMember;
case SymbolKind.DelegateParameter:
return MicrosoftApiDesignGuidelinesAnalyzersResources.IdentifiersShouldNotContainUnderscoresMessageDelegateParameter;
case SymbolKind.MemberParameter:
return MicrosoftApiDesignGuidelinesAnalyzersResources.IdentifiersShouldNotContainUnderscoresMessageMemberParameter;
case SymbolKind.TypeTypeParameter:
return MicrosoftApiDesignGuidelinesAnalyzersResources.IdentifiersShouldNotContainUnderscoresMessageTypeTypeParameter;
case SymbolKind.MethodTypeParameter:
return MicrosoftApiDesignGuidelinesAnalyzersResources.IdentifiersShouldNotContainUnderscoresMessageMethodTypeParameter;
default:
throw new System.Exception("Unknown Symbol Kind");
}
}
private enum SymbolKind
{
Assembly,
Namespace,
NamedType,
Member,
DelegateParameter,
MemberParameter,
TypeTypeParameter,
MethodTypeParameter
}
#endregion
}
}
| |
using Umbraco.Core.Configuration;
using System;
using Umbraco.Core.Configuration.UmbracoSettings;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
using Umbraco.Core.Persistence.Repositories;
using Umbraco.Core.Persistence.SqlSyntax;
using Umbraco.Core.Persistence.UnitOfWork;
namespace Umbraco.Core.Persistence
{
/// <summary>
/// Used to instantiate each repository type
/// </summary>
public class RepositoryFactory
{
private readonly ILogger _logger;
private readonly ISqlSyntaxProvider _sqlSyntax;
private readonly CacheHelper _cacheHelper;
private readonly IUmbracoSettingsSection _settings;
#region Ctors
public RepositoryFactory(CacheHelper cacheHelper, ILogger logger, ISqlSyntaxProvider sqlSyntax, IUmbracoSettingsSection settings)
{
if (cacheHelper == null) throw new ArgumentNullException("cacheHelper");
if (logger == null) throw new ArgumentNullException("logger");
//if (sqlSyntax == null) throw new ArgumentNullException("sqlSyntax");
if (settings == null) throw new ArgumentNullException("settings");
_cacheHelper = cacheHelper;
_logger = logger;
_sqlSyntax = sqlSyntax;
_settings = settings;
}
[Obsolete("Use the ctor specifying all dependencies instead")]
public RepositoryFactory()
: this(ApplicationContext.Current.ApplicationCache, LoggerResolver.Current.Logger, SqlSyntaxContext.SqlSyntaxProvider, UmbracoConfig.For.UmbracoSettings())
{
}
[Obsolete("Use the ctor specifying all dependencies instead")]
public RepositoryFactory(CacheHelper cacheHelper)
: this(cacheHelper, LoggerResolver.Current.Logger, SqlSyntaxContext.SqlSyntaxProvider, UmbracoConfig.For.UmbracoSettings())
{
}
[Obsolete("Use the ctor specifying all dependencies instead, NOTE: disableAllCache has zero effect")]
public RepositoryFactory(bool disableAllCache, CacheHelper cacheHelper)
: this(cacheHelper, LoggerResolver.Current.Logger, SqlSyntaxContext.SqlSyntaxProvider, UmbracoConfig.For.UmbracoSettings())
{
if (cacheHelper == null) throw new ArgumentNullException("cacheHelper");
_cacheHelper = cacheHelper;
}
[Obsolete("Use the ctor specifying all dependencies instead")]
public RepositoryFactory(bool disableAllCache)
: this(disableAllCache ? CacheHelper.CreateDisabledCacheHelper() : ApplicationContext.Current.ApplicationCache, LoggerResolver.Current.Logger, SqlSyntaxContext.SqlSyntaxProvider, UmbracoConfig.For.UmbracoSettings())
{
}
#endregion
public virtual IExternalLoginRepository CreateExternalLoginRepository(IDatabaseUnitOfWork uow)
{
return new ExternalLoginRepository(uow,
_cacheHelper,
_logger, _sqlSyntax);
}
public virtual IPublicAccessRepository CreatePublicAccessRepository(IDatabaseUnitOfWork uow)
{
return new PublicAccessRepository(uow,
_cacheHelper,
_logger, _sqlSyntax);
}
public virtual ITaskRepository CreateTaskRepository(IDatabaseUnitOfWork uow)
{
return new TaskRepository(uow,
CacheHelper.CreateDisabledCacheHelper(), //never cache
_logger, _sqlSyntax);
}
public virtual IAuditRepository CreateAuditRepository(IDatabaseUnitOfWork uow)
{
return new AuditRepository(uow,
CacheHelper.CreateDisabledCacheHelper(), //never cache
_logger, _sqlSyntax);
}
public virtual ITagRepository CreateTagRepository(IDatabaseUnitOfWork uow)
{
return new TagRepository(
uow,
_cacheHelper, _logger, _sqlSyntax);
}
public virtual IContentRepository CreateContentRepository(IDatabaseUnitOfWork uow)
{
return new ContentRepository(
uow,
_cacheHelper,
_logger,
_sqlSyntax,
CreateContentTypeRepository(uow),
CreateTemplateRepository(uow),
CreateTagRepository(uow))
{
EnsureUniqueNaming = _settings.Content.EnsureUniqueNaming
};
}
public virtual IContentTypeRepository CreateContentTypeRepository(IDatabaseUnitOfWork uow)
{
return new ContentTypeRepository(
uow,
_cacheHelper,
_logger, _sqlSyntax,
CreateTemplateRepository(uow));
}
public virtual IDataTypeDefinitionRepository CreateDataTypeDefinitionRepository(IDatabaseUnitOfWork uow)
{
return new DataTypeDefinitionRepository(
uow,
_cacheHelper,
_cacheHelper,
_logger, _sqlSyntax,
CreateContentTypeRepository(uow));
}
public virtual IDictionaryRepository CreateDictionaryRepository(IDatabaseUnitOfWork uow)
{
return new DictionaryRepository(
uow,
_cacheHelper,
_logger,
_sqlSyntax,
CreateLanguageRepository(uow));
}
public virtual ILanguageRepository CreateLanguageRepository(IDatabaseUnitOfWork uow)
{
return new LanguageRepository(
uow,
_cacheHelper,
_logger, _sqlSyntax);
}
public virtual IMediaRepository CreateMediaRepository(IDatabaseUnitOfWork uow)
{
return new MediaRepository(
uow,
_cacheHelper,
_logger, _sqlSyntax,
CreateMediaTypeRepository(uow),
CreateTagRepository(uow)) { EnsureUniqueNaming = _settings.Content.EnsureUniqueNaming };
}
public virtual IMediaTypeRepository CreateMediaTypeRepository(IDatabaseUnitOfWork uow)
{
return new MediaTypeRepository(
uow,
_cacheHelper,
_logger, _sqlSyntax);
}
public virtual IRelationRepository CreateRelationRepository(IDatabaseUnitOfWork uow)
{
return new RelationRepository(
uow,
CacheHelper.CreateDisabledCacheHelper(), //never cache
_logger, _sqlSyntax,
CreateRelationTypeRepository(uow));
}
public virtual IRelationTypeRepository CreateRelationTypeRepository(IDatabaseUnitOfWork uow)
{
return new RelationTypeRepository(
uow,
CacheHelper.CreateDisabledCacheHelper(), //never cache
_logger, _sqlSyntax);
}
public virtual IScriptRepository CreateScriptRepository(IUnitOfWork uow)
{
return new ScriptRepository(uow, new PhysicalFileSystem(SystemDirectories.Scripts), _settings.Content);
}
internal virtual IPartialViewRepository CreatePartialViewRepository(IUnitOfWork uow)
{
return new PartialViewRepository(uow);
}
internal virtual IPartialViewRepository CreatePartialViewMacroRepository(IUnitOfWork uow)
{
return new PartialViewMacroRepository(uow);
}
public virtual IStylesheetRepository CreateStylesheetRepository(IUnitOfWork uow, IDatabaseUnitOfWork db)
{
return new StylesheetRepository(uow, new PhysicalFileSystem(SystemDirectories.Css));
}
public virtual ITemplateRepository CreateTemplateRepository(IDatabaseUnitOfWork uow)
{
return new TemplateRepository(uow,
_cacheHelper,
_logger, _sqlSyntax,
new PhysicalFileSystem(SystemDirectories.Masterpages),
new PhysicalFileSystem(SystemDirectories.MvcViews),
_settings.Templates);
}
public virtual IMigrationEntryRepository CreateMigrationEntryRepository(IDatabaseUnitOfWork uow)
{
return new MigrationEntryRepository(
uow,
CacheHelper.CreateDisabledCacheHelper(), //never cache
_logger, _sqlSyntax);
}
public virtual IServerRegistrationRepository CreateServerRegistrationRepository(IDatabaseUnitOfWork uow)
{
return new ServerRegistrationRepository(
uow,
CacheHelper.CreateDisabledCacheHelper(), //never cache
_logger, _sqlSyntax);
}
public virtual IUserTypeRepository CreateUserTypeRepository(IDatabaseUnitOfWork uow)
{
return new UserTypeRepository(
uow,
//There's not many user types but we query on users all the time so the result needs to be cached
_cacheHelper,
_logger, _sqlSyntax);
}
public virtual IUserRepository CreateUserRepository(IDatabaseUnitOfWork uow)
{
return new UserRepository(
uow,
//Need to cache users - we look up user information more than anything in the back office!
_cacheHelper,
_logger, _sqlSyntax,
CreateUserTypeRepository(uow));
}
internal virtual IMacroRepository CreateMacroRepository(IDatabaseUnitOfWork uow)
{
return new MacroRepository(uow,
_cacheHelper,
_logger, _sqlSyntax);
}
public virtual IMemberRepository CreateMemberRepository(IDatabaseUnitOfWork uow)
{
return new MemberRepository(
uow,
_cacheHelper,
_logger, _sqlSyntax,
CreateMemberTypeRepository(uow),
CreateMemberGroupRepository(uow),
CreateTagRepository(uow));
}
public virtual IMemberTypeRepository CreateMemberTypeRepository(IDatabaseUnitOfWork uow)
{
return new MemberTypeRepository(uow,
_cacheHelper,
_logger, _sqlSyntax);
}
public virtual IMemberGroupRepository CreateMemberGroupRepository(IDatabaseUnitOfWork uow)
{
return new MemberGroupRepository(uow,
_cacheHelper,
_logger, _sqlSyntax,
_cacheHelper);
}
public virtual IEntityRepository CreateEntityRepository(IDatabaseUnitOfWork uow)
{
return new EntityRepository(uow);
}
public IDomainRepository CreateDomainRepository(IDatabaseUnitOfWork uow)
{
return new DomainRepository(uow, _cacheHelper, _logger, _sqlSyntax, CreateContentRepository(uow), CreateLanguageRepository(uow));
}
public ITaskTypeRepository CreateTaskTypeRepository(IDatabaseUnitOfWork uow)
{
return new TaskTypeRepository(uow,
CacheHelper.CreateDisabledCacheHelper(), //never cache
_logger, _sqlSyntax);
}
}
}
| |
// 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.Threading.Tasks;
using System.Threading;
using System.Runtime.ExceptionServices;
using Xunit;
namespace System.Data.SqlClient.ManualTesting.Tests
{
public static class ConnectionPoolTest
{
private static readonly string _tcpConnStr = (new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr) { MultipleActiveResultSets = false }).ConnectionString;
private static readonly string _tcpMarsConnStr = (new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr) { MultipleActiveResultSets = true }).ConnectionString;
[Fact]
public static void ConnectionPool_NonMars()
{
RunDataTestForSingleConnString(_tcpConnStr);
}
[Fact]
public static void ConnectionPool_Mars()
{
RunDataTestForSingleConnString(_tcpMarsConnStr);
}
private static void RunDataTestForSingleConnString(string tcpConnectionString)
{
BasicConnectionPoolingTest(tcpConnectionString);
ClearAllPoolsTest(tcpConnectionString);
#if MANAGED_SNI && DEBUG
KillConnectionTest(tcpConnectionString);
#endif
ReclaimEmancipatedOnOpenTest(tcpConnectionString);
}
/// <summary>
/// Tests that using the same connection string results in the same pool\internal connection and a different string results in a different pool\internal connection
/// </summary>
/// <param name="connectionString"></param>
private static void BasicConnectionPoolingTest(string connectionString)
{
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
InternalConnectionWrapper internalConnection = new InternalConnectionWrapper(connection);
ConnectionPoolWrapper connectionPool = new ConnectionPoolWrapper(connection);
connection.Close();
SqlConnection connection2 = new SqlConnection(connectionString);
connection2.Open();
Assert.True(internalConnection.IsInternalConnectionOf(connection2), "New connection does not use same internal connection");
Assert.True(connectionPool.ContainsConnection(connection2), "New connection is in a different pool");
connection2.Close();
SqlConnection connection3 = new SqlConnection(connectionString + ";App=SqlConnectionPoolUnitTest;");
connection3.Open();
Assert.False(internalConnection.IsInternalConnectionOf(connection3), "Connection with different connection string uses same internal connection");
Assert.False(connectionPool.ContainsConnection(connection3), "Connection with different connection string uses same connection pool");
connection3.Close();
connectionPool.Cleanup();
SqlConnection connection4 = new SqlConnection(connectionString);
connection4.Open();
Assert.True(internalConnection.IsInternalConnectionOf(connection4), "New connection does not use same internal connection");
Assert.True(connectionPool.ContainsConnection(connection4), "New connection is in a different pool");
connection4.Close();
}
#if MANAGED_SNI && DEBUG
/// <summary>
/// Tests if killing the connection using the InternalConnectionWrapper is working
/// </summary>
/// <param name="connectionString"></param>
private static void KillConnectionTest(string connectionString)
{
InternalConnectionWrapper wrapper = null;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
wrapper = new InternalConnectionWrapper(connection);
using (SqlCommand command = new SqlCommand("SELECT 5;", connection))
{
DataTestUtility.AssertEqualsWithDescription(5, command.ExecuteScalar(), "Incorrect scalar result.");
}
wrapper.KillConnection();
}
using (SqlConnection connection2 = new SqlConnection(connectionString))
{
connection2.Open();
Assert.False(wrapper.IsInternalConnectionOf(connection2), "New connection has internal connection that was just killed");
using (SqlCommand command = new SqlCommand("SELECT 5;", connection2))
{
DataTestUtility.AssertEqualsWithDescription(5, command.ExecuteScalar(), "Incorrect scalar result.");
}
}
}
#endif
/// <summary>
/// Tests if clearing all of the pools does actually remove the pools
/// </summary>
/// <param name="connectionString"></param>
private static void ClearAllPoolsTest(string connectionString)
{
SqlConnection.ClearAllPools();
Assert.True(0 == ConnectionPoolWrapper.AllConnectionPools().Length, "Pools exist after clearing all pools");
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
ConnectionPoolWrapper pool = new ConnectionPoolWrapper(connection);
connection.Close();
ConnectionPoolWrapper[] allPools = ConnectionPoolWrapper.AllConnectionPools();
DataTestUtility.AssertEqualsWithDescription(1, allPools.Length, "Incorrect number of pools exist.");
Assert.True(allPools[0].Equals(pool), "Saved pool is not in the list of all pools");
DataTestUtility.AssertEqualsWithDescription(1, pool.ConnectionCount, "Saved pool has incorrect number of connections");
SqlConnection.ClearAllPools();
Assert.True(0 == ConnectionPoolWrapper.AllConnectionPools().Length, "Pools exist after clearing all pools");
DataTestUtility.AssertEqualsWithDescription(0, pool.ConnectionCount, "Saved pool has incorrect number of connections.");
}
/// <summary>
/// Checks if an 'emancipated' internal connection is reclaimed when a new connection is opened AND we hit max pool size
/// NOTE: 'emancipated' means that the internal connection's SqlConnection has fallen out of scope and has no references, but was not explicitly disposed\closed
/// </summary>
/// <param name="connectionString"></param>
private static void ReclaimEmancipatedOnOpenTest(string connectionString)
{
string newConnectionString = connectionString + ";Max Pool Size=1";
SqlConnection.ClearAllPools();
InternalConnectionWrapper internalConnection = CreateEmancipatedConnection(newConnectionString);
ConnectionPoolWrapper connectionPool = internalConnection.ConnectionPool;
GC.Collect();
GC.WaitForPendingFinalizers();
DataTestUtility.AssertEqualsWithDescription(1, connectionPool.ConnectionCount, "Wrong number of connections in the pool.");
DataTestUtility.AssertEqualsWithDescription(0, connectionPool.FreeConnectionCount, "Wrong number of free connections in the pool.");
using (SqlConnection connection = new SqlConnection(newConnectionString))
{
connection.Open();
Assert.True(internalConnection.IsInternalConnectionOf(connection), "Connection has wrong internal connection");
Assert.True(connectionPool.ContainsConnection(connection), "Connection is in wrong connection pool");
}
}
private static void ReplacementConnectionUsesSemaphoreTest(string connectionString)
{
string newConnectionString = (new SqlConnectionStringBuilder(connectionString) { MaxPoolSize = 2, ConnectTimeout = 5 }).ConnectionString;
SqlConnection.ClearAllPools();
SqlConnection liveConnection = new SqlConnection(newConnectionString);
SqlConnection deadConnection = new SqlConnection(newConnectionString);
liveConnection.Open();
deadConnection.Open();
InternalConnectionWrapper deadConnectionInternal = new InternalConnectionWrapper(deadConnection);
InternalConnectionWrapper liveConnectionInternal = new InternalConnectionWrapper(liveConnection);
deadConnectionInternal.KillConnection();
deadConnection.Close();
liveConnection.Close();
Task<InternalConnectionWrapper>[] tasks = new Task<InternalConnectionWrapper>[3];
Barrier syncBarrier = new Barrier(tasks.Length);
Func<InternalConnectionWrapper> taskFunction = (() => ReplacementConnectionUsesSemaphoreTask(newConnectionString, syncBarrier));
for (int i = 0; i < tasks.Length; i++)
{
tasks[i] = Task.Factory.StartNew<InternalConnectionWrapper>(taskFunction);
}
bool taskWithLiveConnection = false;
bool taskWithNewConnection = false;
bool taskWithCorrectException = false;
Task waitAllTask = Task.Factory.ContinueWhenAll(tasks, (completedTasks) =>
{
foreach (var item in completedTasks)
{
if (item.Status == TaskStatus.Faulted)
{
// One task should have a timeout exception
if ((!taskWithCorrectException) && (item.Exception.InnerException is InvalidOperationException) && (item.Exception.InnerException.Message.StartsWith(SystemDataResourceManager.Instance.ADP_PooledOpenTimeout)))
taskWithCorrectException = true;
else if (!taskWithCorrectException)
{
// Rethrow the unknown exception
ExceptionDispatchInfo exceptionInfo = ExceptionDispatchInfo.Capture(item.Exception);
exceptionInfo.Throw();
}
}
else if (item.Status == TaskStatus.RanToCompletion)
{
// One task should get the live connection
if (item.Result.Equals(liveConnectionInternal))
{
if (!taskWithLiveConnection)
taskWithLiveConnection = true;
}
else if (!item.Result.Equals(deadConnectionInternal) && !taskWithNewConnection)
taskWithNewConnection = true;
}
else
Console.WriteLine("ERROR: Task in unknown state: {0}", item.Status);
}
});
waitAllTask.Wait();
Assert.True(taskWithLiveConnection && taskWithNewConnection && taskWithCorrectException, string.Format("Tasks didn't finish as expected.\nTask with live connection: {0}\nTask with new connection: {1}\nTask with correct exception: {2}\n", taskWithLiveConnection, taskWithNewConnection, taskWithCorrectException));
}
private static InternalConnectionWrapper ReplacementConnectionUsesSemaphoreTask(string connectionString, Barrier syncBarrier)
{
InternalConnectionWrapper internalConnection = null;
using (SqlConnection connection = new SqlConnection(connectionString))
{
try
{
connection.Open();
internalConnection = new InternalConnectionWrapper(connection);
}
catch
{
syncBarrier.SignalAndWait();
throw;
}
syncBarrier.SignalAndWait();
}
return internalConnection;
}
private static InternalConnectionWrapper CreateEmancipatedConnection(string connectionString)
{
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
return new InternalConnectionWrapper(connection);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace System.Threading.Tasks.Dataflow.Tests
{
public class SimpleNetworkTests
{
const int Iterations = 1000;
[Fact]
public async Task TransformToAction()
{
var t = new TransformBlock<int, int>(i => i * 2);
int completedCount = 0;
int prev = -2;
var c = new ActionBlock<int>(i =>
{
completedCount++;
Assert.Equal(expected: i, actual: prev + 2);
prev = i;
});
t.LinkTo(c, new DataflowLinkOptions { PropagateCompletion = true });
t.PostRange(0, Iterations);
t.Complete();
await c.Completion;
Assert.True(completedCount == Iterations);
}
[Fact]
public async Task TransformThroughFilterToAction()
{
int completedCount = 0;
var t = new TransformBlock<int, int>(i => i);
var c = new ActionBlock<int>(i => completedCount++);
t.LinkTo(c, new DataflowLinkOptions { PropagateCompletion = true }, i => true);
t.PostRange(0, Iterations);
t.Complete();
await c.Completion;
Assert.Equal(expected: Iterations, actual: completedCount);
}
[Fact]
public async Task TransformThroughDiscardingFilterToAction()
{
int completedCount = 0;
var t = new TransformBlock<int, int>(i => i);
var c = new ActionBlock<int>(i => completedCount++);
t.LinkTo(c, new DataflowLinkOptions { PropagateCompletion = true }, i => i % 2 == 0);
t.LinkTo(DataflowBlock.NullTarget<int>());
t.PostRange(0, Iterations);
t.Complete();
await c.Completion;
Assert.Equal(expected: Iterations / 2, actual: completedCount);
}
[Fact]
public async Task TenTransformsToAction()
{
var first = new TransformBlock<int, int>(item => item);
TransformBlock<int, int> t = first;
for (int i = 0; i < 9; i++)
{
var next = new TransformBlock<int, int>(item => item);
t.LinkTo(next, new DataflowLinkOptions { PropagateCompletion = true });
t = next;
}
int completedCount = 0;
var last = new ActionBlock<int>(i => completedCount++);
t.LinkTo(last, new DataflowLinkOptions { PropagateCompletion = true });
first.PostRange(0, Iterations);
first.Complete();
await last.Completion;
Assert.Equal(expected: Iterations, actual: completedCount);
}
[Fact]
public async Task BatchGreedyToAction()
{
var b = new BatchBlock<int>(1);
int completedCount = 0;
var c = new ActionBlock<int[]>(i => completedCount++);
b.LinkTo(c, new DataflowLinkOptions { PropagateCompletion = true });
b.PostRange(0, Iterations);
b.Complete();
await c.Completion;
Assert.Equal(expected: Iterations / b.BatchSize, actual: completedCount);
}
[Fact]
public async Task WriteOnceToAction()
{
int completedCount = 0;
var c = new ActionBlock<int>(i => completedCount++);
var singleAssignments = Enumerable.Range(0, Iterations).Select(_ =>
{
var s = new WriteOnceBlock<int>(i => i);
s.LinkTo(c);
return s;
}).ToList();
var ignored = Task.WhenAll(singleAssignments.Select(s => s.Completion)).ContinueWith(
_ => c.Complete(), CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default);
foreach (var s in singleAssignments) s.Post(1);
await c.Completion;
Assert.Equal(expected: Iterations, actual: completedCount);
}
[Fact]
public async Task BatchedJoinToAction()
{
var b = new BatchedJoinBlock<int, int>(1);
int completedCount = 0;
var c = new ActionBlock<Tuple<IList<int>, IList<int>>>(i => completedCount++);
b.LinkTo(c, new DataflowLinkOptions { PropagateCompletion = true });
for (int i = 0; i < Iterations; i++)
{
if (i % 2 == 0) b.Target1.Post(i);
else b.Target2.Post(i);
}
b.Target1.Complete();
b.Target2.Complete();
await c.Completion;
Assert.Equal(expected: Iterations / b.BatchSize, actual: completedCount);
}
[Fact]
public async Task BufferBlocksToBatchNonGreedyToAction()
{
var inputs = Enumerable.Range(0, 1).Select(_ => new BufferBlock<int>()).ToList();
var b = new BatchBlock<int>(inputs.Count);
int completedCount = 0;
var c = new ActionBlock<int[]>(i => completedCount++);
foreach (var input in inputs) input.LinkTo(b);
var ignored = Task.WhenAll(inputs.Select(s => s.Completion)).ContinueWith(
_ => b.Complete(), CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default);
b.LinkTo(c, new DataflowLinkOptions { PropagateCompletion = true });
for (int i = 0; i < Iterations; i++)
{
inputs[i % inputs.Count].Post(i);
}
foreach (var input in inputs) input.Complete();
await c.Completion;
Assert.Equal(expected: Iterations / b.BatchSize, actual: completedCount);
}
[Fact]
public async Task BroadcastToActions()
{
var b = new BroadcastBlock<int>(i => i);
int completedCount = 0;
var tasks = Enumerable.Range(0, 1).Select(_ =>
{
var c = new ActionBlock<int>(i => Interlocked.Increment(ref completedCount));
b.LinkTo(c, new DataflowLinkOptions { PropagateCompletion = true });
return c.Completion;
}).ToArray();
var posts = Iterations / tasks.Length;
b.PostRange(0, posts);
b.Complete();
await Task.WhenAll(tasks);
Assert.Equal(expected: Iterations, actual: completedCount);
}
[Fact]
public async Task TransformManyEnumerableToAction()
{
var data = new[] { 1 };
var tm = new TransformManyBlock<int, int>(i => data);
int completedCount = 0;
var c = new ActionBlock<int>(i => completedCount++);
tm.LinkTo(c, new DataflowLinkOptions { PropagateCompletion = true });
tm.PostRange(0, Iterations);
tm.Complete();
await c.Completion;
Assert.Equal(expected: Iterations, actual: completedCount);
}
[Fact]
public async Task ActionPingPong()
{
var tcs = new TaskCompletionSource<bool>();
ActionBlock<int> c1 = null, c2 = null;
c1 = new ActionBlock<int>(i => c2.Post(i + 1));
c2 = new ActionBlock<int>(i => {
if (i >= Iterations) tcs.SetResult(true);
else c1.Post(i + 1);
});
c1.Post(0);
await tcs.Task;
}
[Fact]
public async Task TransformPingPong()
{
TransformBlock<int, int> t1 = null, t2 = null;
t1 = new TransformBlock<int, int>(i =>
{
if (i >= Iterations) t2.Complete();
return i + 1;
});
t2 = new TransformBlock<int, int>(i => i + 1);
t1.LinkTo(t2);
t2.LinkTo(t1);
t1.Post(0);
await t2.Completion;
}
[Fact]
public async Task BuffersToNonGreedyJoinToAction()
{
var b1 = new BufferBlock<string>();
var b2 = new BufferBlock<int>();
var j = new JoinBlock<string, int>(new GroupingDataflowBlockOptions { Greedy = false });
b1.LinkTo(j.Target1, new DataflowLinkOptions { PropagateCompletion = true });
b2.LinkTo(j.Target2, new DataflowLinkOptions { PropagateCompletion = true });
var a = new ActionBlock<Tuple<string, int>>(t => Assert.True((t.Item1 == t.Item2.ToString())));
j.LinkTo(a, new DataflowLinkOptions { PropagateCompletion = true });
for (int i = 0; i < Iterations; i++)
{
b1.Post(i.ToString());
b2.Post(i);
}
b1.Complete();
b2.Complete();
await a.Completion;
}
}
}
| |
/*
* Copyright (C) Sony Computer Entertainment America LLC.
* All Rights Reserved.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Sce.Atf.Adaptation;
using Sce.Sled.Project.Resources;
using Sce.Sled.Shared;
using Sce.Sled.Shared.Dom;
using Sce.Sled.Shared.Services;
using Sce.Sled.Shared.Utilities;
namespace Sce.Sled.Project
{
public static class SledProjectUtilities
{
/// <summary>
/// Open the project file and make sure the namespace is correct
/// </summary>
/// <param name="szAbsPath"></param>
public static void CleanupProjectFileNamespace(string szAbsPath)
{
if (!File.Exists(szAbsPath))
return;
if (SledUtil.IsFileReadOnly(szAbsPath))
return;
try
{
Encoding encoding;
string szFileContents;
using (Stream stream = new FileStream(szAbsPath, FileMode.Open, FileAccess.Read))
{
using (var reader = new StreamReader(stream, true))
{
// Store encoding & read contents
encoding = reader.CurrentEncoding;
szFileContents = reader.ReadToEnd();
}
}
if (!string.IsNullOrEmpty(szFileContents))
{
const string szOldXmlNs = "xmlns=\"lua\"";
const string szNewXmlNs = "xmlns=\"sled\"";
if (szFileContents.Contains(szOldXmlNs))
{
szFileContents = szFileContents.Replace(szOldXmlNs, szNewXmlNs);
using (Stream stream = new FileStream(szAbsPath, FileMode.Create, FileAccess.Write))
{
using (var writer = new StreamWriter(stream, encoding))
{
writer.Write(szFileContents);
}
}
}
}
}
catch (Exception ex)
{
SledOutDevice.OutLine(
SledMessageType.Error,
SledUtil.TransSub(Localization.SledProjectFilesErrorVerifyingNamespace, ex.Message, szAbsPath));
}
}
/// <summary>
/// Open the project file and remove any duplicates
/// </summary>
/// <param name="szAbsPath"></param>
public static void CleanupProjectFileDuplicates(string szAbsPath)
{
if (!File.Exists(szAbsPath))
return;
if (SledUtil.IsFileReadOnly(szAbsPath))
return;
try
{
var schemaLoader = SledServiceInstance.TryGet<SledSharedSchemaLoader>();
if (schemaLoader == null)
return;
var uri = new Uri(szAbsPath);
var reader = new SledSpfReader(schemaLoader);
var root = reader.Read(uri, false);
if (root == null)
return;
var lstProjFiles = new List<SledProjectFilesFileType>();
// Gather up all project files in the project
SledDomUtil.GatherAllAs(root, lstProjFiles);
if (lstProjFiles.Count <= 1)
return;
var uniquePaths = new Dictionary<string, SledProjectFilesFileType>(StringComparer.CurrentCultureIgnoreCase);
var lstDuplicates = new List<SledProjectFilesFileType>();
foreach (var projFile in lstProjFiles)
{
if (uniquePaths.ContainsKey(projFile.Path))
lstDuplicates.Add(projFile);
else
uniquePaths.Add(projFile.Path, projFile);
}
if (lstDuplicates.Count <= 0)
return;
foreach (var projFile in lstDuplicates)
projFile.DomNode.RemoveFromParent();
var writer = new SledSpfWriter(schemaLoader.TypeCollection);
// Write changes back to disk
writer.Write(root, uri, false);
}
catch (Exception ex)
{
SledOutDevice.OutLine(
SledMessageType.Error,
SledUtil.TransSub(Localization.SledProjectFilesErrorRemovingDuplicates, ex.Message, szAbsPath));
}
}
/// <summary>
/// Try and obtain project information from a project file on disk
/// </summary>
/// <param name="absPath"></param>
/// <param name="name"></param>
/// <param name="projectDir"></param>
/// <param name="assetDir"></param>
/// <param name="guid"></param>
/// <param name="files"></param>
/// <returns></returns>
public static bool TryGetProjectDetails(
string absPath,
out string name,
out string projectDir,
out string assetDir,
out Guid guid,
out List<string> files)
{
name = null;
projectDir = null;
assetDir = null;
guid = Guid.Empty;
files = null;
try
{
// ATF 3's DOM makes this so much easier now!
var schemaLoader =
SledServiceInstance.TryGet<SledSharedSchemaLoader>();
if (schemaLoader == null)
return false;
var uri = new Uri(absPath);
var reader =
new SledSpfReader(schemaLoader);
var root = reader.Read(uri, false);
if (root == null)
return false;
var project =
root.As<SledProjectFilesType>();
project.Uri = uri;
// Pull out project details
name = project.Name;
guid = project.Guid;
assetDir = project.AssetDirectory;
projectDir = Path.GetDirectoryName(absPath);
var lstProjFiles =
new List<SledProjectFilesFileType>();
SledDomUtil.GatherAllAs(root, lstProjFiles);
var assetDirTemp = assetDir;
files =
(from projFile in lstProjFiles
let absFilePath =
SledUtil.GetAbsolutePath(
projFile.Path,
assetDirTemp)
select absFilePath).ToList();
return true;
}
catch (Exception ex)
{
SledOutDevice.OutLine(
SledMessageType.Error,
"Exception encountered obtaining project " +
"details. Project file: \"{0}\". Exception: {1}",
absPath, ex.Message);
return false;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Verse;
using RimWorld;
using UnityEngine;
namespace Lincore.OmniLocator {
public class PawnColumnWorker_Watch : PawnColumnWorker {
public override void DoCell(Rect rect, Pawn pawn, PawnTable table) {
if (Widgets.ButtonInvisible(rect, false)) CameraJumper.TryJump(pawn);
var icon = Mouse.IsOver(rect) ? Global.WatchHoverIcon : Global.WatchIcon;
var tooltip = pawn.GetTooltip();
tooltip.text = "Click to look at this animal without closing the window.\n\n" + tooltip.text;
Utils.DrawIcon(rect, icon, tooltip);
}
public override int GetMaxWidth(PawnTable table) {
return GetOptimalWidth(table);
}
public override int GetMinWidth(PawnTable table) {
return Global.ICON_SIZE;
}
public override int GetOptimalWidth(PawnTable table) {
return Global.ICON_SIZE + 10;
}
}
public class PawnColumnWorker_Danger : PawnColumnWorker {
protected enum Danger {
Insectoid,
Manhunter,
Retaliation,
Taming,
Predator,
None
}
protected struct UiElem {
public readonly Texture2D Icon;
public readonly Func<Pawn, string> GetTooltip;
public UiElem(Texture2D icon, Func<Pawn, string> tooltip) {
Icon = icon;
GetTooltip = tooltip;
}
}
protected static Dictionary<Danger, UiElem> DangerUiElems = new Dictionary<Danger, UiElem> {
{Danger.None, new UiElem()},
{Danger.Insectoid, new UiElem(Global.InsectIcon, (_) => "Infestation")},
{Danger.Manhunter, new UiElem(Global.ManhunterIcon, (_) => "Manhunter") },
{Danger.Retaliation, new UiElem(Global.PredatorIcon,
(pawn) => "MessageAnimalsGoPsychoHunted".Translate(pawn.kindDef.label)) },
{Danger.Taming, new UiElem(Global.PredatorIcon,
(pawn) => "MessageAnimalManhuntsOnTameFailed".Translate(pawn.kindDef.label,
pawn.kindDef.RaceProps.manhunterOnTameFailChance.ToStringPercent("F2"))) },
{Danger.Predator, new UiElem(Global.Predator2Icon, (_) => "Predator") }
};
protected Danger GetDangerOf(Pawn pawn) {
var state = pawn.mindState.mentalStateHandler.CurStateDef;
if (state != null && state.IsAggro) {
return Danger.Manhunter;
}
if (pawn.Faction == Faction.OfInsects) {
return Danger.Insectoid;
}
var huntDesignation = Utils.GetDesignation(pawn, DesignationDefOf.Hunt);
var tameDesignation = Utils.GetDesignation(pawn, DesignationDefOf.Tame);
bool huntRisk = huntDesignation != null && pawn.RaceProps.manhunterOnDamageChance > Global.MIN_RETALIATION_CHANCE_ON_HUNT;
if (huntRisk) return Danger.Retaliation;
bool tameRisk = tameDesignation != null && pawn.RaceProps.manhunterOnTameFailChance > Global.MIN_RETALIATION_CHANCE_ON_TAME;
if (tameRisk) return Danger.Taming;
if (pawn.RaceProps.predator) return Danger.Predator;
return Danger.None;
}
public override void DoCell(Rect rect, Pawn pawn, PawnTable table) {
var center = rect.center;
rect = new Rect(rect.position, new Vector2(Global.ICON_SIZE, Global.ICON_SIZE));
rect.center = center;
var danger = GetDangerOf(pawn);
UiElem ui;
if (!DangerUiElems.TryGetValue(danger, out ui)) {
Log.ErrorOnce(string.Format("Unknown danger: {0}"), 9235423);
return;
}
var tooltip = ui.GetTooltip != null ? ui.GetTooltip(pawn) : "";
if (ui.Icon != null) Utils.DrawIcon(rect, ui.Icon, tooltip);
}
public override int GetMaxWidth(PawnTable table) {
return GetOptimalWidth(table);
}
public override int GetMinWidth(PawnTable table) {
return Global.ICON_SIZE;
}
public override int GetOptimalWidth(PawnTable table) {
return Global.ICON_SIZE + 10;
}
public override int Compare(Pawn a, Pawn b) {
return this.GetValueToCompare(a).CompareTo(this.GetValueToCompare(b));
}
private int GetValueToCompare(Pawn pawn) {
return -((int)GetDangerOf(pawn));
}
}
public class PawnColumnWorker_Tame : PawnColumnWorker_Checkbox {
protected override string GetTip(Pawn pawn) {
return "DesignatorTameDesc".Translate();
}
protected override bool GetValue(Pawn pawn) {
var designation = Utils.GetDesignation(pawn, DesignationDefOf.Tame);
return designation != null;
}
protected override void SetValue(Pawn pawn, bool value) {
if (value) {
Utils.AddDesignation(pawn, new Designation(pawn, DesignationDefOf.Tame));
var huntDesignation = Utils.GetDesignation(pawn, DesignationDefOf.Hunt);
if (huntDesignation != null) Utils.RemoveDesignation(pawn, huntDesignation);
if (pawn.RaceProps.manhunterOnTameFailChance > Global.MIN_RETALIATION_CHANCE_ON_TAME) {
Verse.Sound.SoundStarter.PlayOneShotOnCamera(SoundDefOf.MessageAlert);
}
} else {
var tameDesignation = Utils.GetDesignation(pawn, DesignationDefOf.Tame);
Utils.RemoveDesignation(pawn, tameDesignation);
}
}
public override int GetMaxWidth(PawnTable table) {
return GetOptimalWidth(table);
}
public override int GetMinWidth(PawnTable table) {
return Global.ICON_SIZE;
}
public override int GetOptimalWidth(PawnTable table) {
return Global.ICON_SIZE + 10;
}
}
public class PawnColumnWorker_Hunt : PawnColumnWorker_Checkbox {
protected override string GetTip(Pawn pawn) {
return "DesignatorHuntDesc".Translate();
}
protected override bool GetValue(Pawn pawn) {
var designation = Utils.GetDesignation(pawn, DesignationDefOf.Hunt);
return designation != null;
}
protected override void SetValue(Pawn pawn, bool value) {
if (value) {
Utils.AddDesignation(pawn, new Designation(pawn, DesignationDefOf.Hunt));
var tameDesignation = Utils.GetDesignation(pawn, DesignationDefOf.Tame);
if (tameDesignation != null) Utils.RemoveDesignation(pawn, tameDesignation);
if (pawn.RaceProps.manhunterOnDamageChance > Global.MIN_RETALIATION_CHANCE_ON_HUNT) {
Verse.Sound.SoundStarter.PlayOneShotOnCamera(SoundDefOf.MessageAlert);
}
} else {
var huntDesignation = Utils.GetDesignation(pawn, DesignationDefOf.Hunt);
Utils.RemoveDesignation(pawn, huntDesignation);
}
}
public override int GetMaxWidth(PawnTable table) {
return GetOptimalWidth(table);
}
public override int GetMinWidth(PawnTable table) {
return Global.ICON_SIZE;
}
public override int GetOptimalWidth(PawnTable table) {
return Global.ICON_SIZE + 10;
}
}
public class PawnColumnWorker_Medical : PawnColumnWorker {
protected string GetMedicalSummary(Pawn pawn) {
var hediffs = pawn.health.hediffSet.hediffs
.Where(h => !h.IsOld())
.Select(h => h.def.LabelCap)
.Distinct();
var c = hediffs.Count();
if (c == 0) return null;
return c == 1? hediffs.First() : hediffs.Aggregate((s1, s2) => s1 + ", " + s2);
}
public override void DoCell(Rect rect, Pawn pawn, PawnTable table) {
var str = GetMedicalSummary(pawn);
if (str != null) GUI.Label(rect, str);
}
public override int GetMinWidth(PawnTable table) {
return 100;
}
public override int GetOptimalWidth(PawnTable table) {
return 300;
}
public override int Compare(Pawn a, Pawn b) {
return (GetMedicalSummary(a) ?? "").CompareTo(GetMedicalSummary(b) ?? "");
}
}
public class PawnColumnWorker_InfoButton : PawnColumnWorker {
public override void DoCell(Rect rect, Pawn pawn, PawnTable table) {
Widgets.InfoCardButton(rect.x, rect.y, pawn);
}
public override int GetMaxWidth(PawnTable table) {
return GetOptimalWidth(table);
}
public override int GetMinWidth(PawnTable table) {
return Global.ICON_SIZE;
}
public override int GetOptimalWidth(PawnTable table) {
return Global.ICON_SIZE + 10;
}
}
}
| |
/*``The contents of this file are subject to the Erlang Public License,
* Version 1.1, (the "License"); you may not use this file except in
* compliance with the License. You should have received a copy of the
* Erlang Public License along with this software. If not, it can be
* retrieved via the world wide web at http://www.erlang.org/.
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
* the License for the specific language governing rights and limitations
* under the License.
*
* The Initial Developer of the Original Code is Ericsson Utvecklings AB.
* Portions created by Ericsson are Copyright 1999, Ericsson Utvecklings
* AB. All Rights Reserved.''
*
* Converted from Java to C# by Vlad Dumitrescu ([email protected])
*/
namespace Otp.Erlang
{
using System;
/*
* Provides a Java representation of Erlang atoms. Atoms can be
* created from strings whose length is not more than {@link
* #maxAtomLength maxAtomLength} characters.
**/
[Serializable]
public class Atom:Erlang.Object
{
/*The maximun allowed length of an atom, in characters */
public const int maxAtomLength = 0xff; // one byte length
private System.String atom;
/*
* Create an atom from the given string.
*
* @param atom the string to create the atom from.
*
* @exception java.lang.IllegalArgumentException if the string is
* empty ("") or contains more than {@link #maxAtomLength
* maxAtomLength} characters.
**/
public Atom(System.String atom)
{
if (atom == null || atom.Length < 1)
{
throw new System.ArgumentException("Atom must be non-empty");
}
if (atom.Length > maxAtomLength)
{
throw new System.ArgumentException("Atom may not exceed " + maxAtomLength + " characters");
}
this.atom = atom;
}
/*
* Create an atom from a stream containing an atom encoded in Erlang
* external format.
*
* @param buf the stream containing the encoded atom.
*
* @exception DecodeException if the buffer does not
* contain a valid external representation of an Erlang atom.
**/
public Atom(OtpInputStream buf)
{
this.atom = buf.read_atom();
}
/*
* Create an atom whose value is "true" or "false".
**/
public Atom(bool t)
{
this.atom = t.ToString();
}
/*
* Get the actual string contained in this object.
*
* @return the raw string contained in this object, without regard
* to Erlang quoting rules.
*
* @see #toString
**/
public virtual System.String atomValue()
{
return atom;
}
/*
* The boolean value of this atom.
*
* @return the value of this atom expressed as a boolean value. If
* the atom consists of the characters "true" (independent of case)
* the value will be true. For any other values, the value will be
* false.
*
**/
public virtual bool booleanValue()
{
return System.Boolean.Parse(atomValue());
}
/*
* Get the printname of the atom represented by this object. The
* difference between this method and {link #atomValue atomValue()}
* is that the printname is quoted and escaped where necessary,
* according to the Erlang rules for atom naming.
*
* @return the printname representation of this atom object.
*
* @see #atomValue
**/
public override System.String ToString()
{
if (atomNeedsQuoting(atom))
{
return "'" + escapeSpecialChars(atom) + "'";
}
else
{
return atom;
}
}
/*
* Determine if two atoms are equal.
*
* @param o the other object to compare to.
*
* @return true if the atoms are equal, false otherwise.
**/
public override bool Equals(System.Object o)
{
if (!(o is Erlang.Atom))
return false;
Erlang.Atom atom = (Erlang.Atom) o;
return this.atom.CompareTo(atom.atom) == 0;
}
public override int GetHashCode()
{
return 1;
}
/*
* Convert this atom to the equivalent Erlang external representation.
*
* @param buf an output stream to which the encoded atom should be
* written.
**/
public override void encode(OtpOutputStream buf)
{
buf.write_atom(this.atom);
}
/*the following four predicates are helpers for the toString() method */
private bool isErlangDigit(char c)
{
return (c >= '0' && c <= '9');
}
private bool isErlangUpper(char c)
{
return ((c >= 'A' && c <= 'Z') || (c == '_'));
}
private bool isErlangLower(char c)
{
return (c >= 'a' && c <= 'z');
}
private bool isErlangLetter(char c)
{
return (isErlangLower(c) || isErlangUpper(c));
}
// true if the atom should be displayed with quotation marks
private bool atomNeedsQuoting(System.String s)
{
char c;
if (s.Length == 0)
return true;
if (!isErlangLower(s[0]))
return true;
int len = s.Length;
for (int i = 1; i < len; i++)
{
c = s[i];
if (!isErlangLetter(c) && !isErlangDigit(c) && c != '@')
return true;
}
return false;
}
/*Get the atom string, with special characters escaped. Note that
* this function currently does not consider any characters above
* 127 to be printable.
*/
private System.String escapeSpecialChars(System.String s)
{
char c;
System.Text.StringBuilder so = new System.Text.StringBuilder();
int len = s.Length;
for (int i = 0; i < len; i++)
{
c = s[i];
/*note that some of these escape sequences are unique to
* Erlang, which is why the corresponding 'case' values use
* octal. The resulting string is, of course, in Erlang format.
*/
switch (c)
{
case '\b':
so.Append("\\b");
break;
case (char) (127):
so.Append("\\d");
break;
case (char) (27):
so.Append("\\e");
break;
case '\f':
so.Append("\\f");
break;
case '\n':
so.Append("\\n");
break;
case '\r':
so.Append("\\r");
break;
case '\t':
so.Append("\\t");
break;
case (char) (11):
so.Append("\\v");
break;
case '\\':
so.Append("\\\\");
break;
case '\'':
so.Append("\\'");
break;
case '\"':
so.Append("\\\"");
break;
default:
// some other character classes
if (c < 23)
{
// control chars show as "\^@", "\^A" etc
so.Append("\\^" + (char) (('A' - 1) + c));
}
else if (c > 126)
{
// 8-bit chars show as \345 \344 \366 etc
so.Append("\\" + System.Convert.ToString(c, 8));
}
else
{
// character is printable without modification!
so.Append(c);
}
break;
}
}
return new System.String(so.ToString().ToCharArray());
}
}
}
| |
// Copyright 2011 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Microsoft.Data.OData.Json
{
#region Namespaces
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Data.Edm;
using Microsoft.Data.OData.Metadata;
using o = Microsoft.Data.OData;
#endregion Namespaces
/// <summary>
/// OData JSON deserializer for properties and value types.
/// </summary>
internal class ODataJsonPropertyAndValueDeserializer : ODataJsonDeserializer
{
/// <summary>
/// The current recursion depth of values read by this deserializer, measured by the number of complex, collection, JSON object and JSON array values read so far.
/// </summary>
private int recursionDepth;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="jsonInputContext">The JSON input context to read from.</param>
internal ODataJsonPropertyAndValueDeserializer(ODataJsonInputContext jsonInputContext)
: base(jsonInputContext)
{
DebugUtils.CheckNoExternalCallers();
}
/// <summary>
/// This method creates an reads the property from the input and
/// returns an <see cref="ODataProperty"/> representing the read property.
/// </summary>
/// <param name="expectedPropertyTypeReference">The expected type reference of the property to read.</param>
/// <returns>An <see cref="ODataProperty"/> representing the read property.</returns>
internal ODataProperty ReadTopLevelProperty(IEdmTypeReference expectedPropertyTypeReference)
{
DebugUtils.CheckNoExternalCallers();
Debug.Assert(this.JsonReader.NodeType == JsonNodeType.None, "Pre-Condition: expected JsonNodeType.None, the reader must not have been used yet.");
Debug.Assert(
expectedPropertyTypeReference == null || !expectedPropertyTypeReference.IsODataEntityTypeKind(),
"If the expected type is specified it must not be an entity type.");
this.JsonReader.AssertNotBuffering();
if (!this.Model.IsUserModel())
{
throw new ODataException(o.Strings.ODataJsonPropertyAndValueDeserializer_TopLevelPropertyWithoutMetadata);
}
// Read the response wrapper "d" if expected.
this.ReadPayloadStart(false /*isReadingNestedPayload*/);
string propertyName = null;
object propertyValue = null;
// We have to support reading top-level complex values without the { "property": ... } wrapper for open properties
// in WCF DS Server backward compat mode. (Open property == property without expected type for us).
if (this.ShouldReadTopLevelPropertyValueWithoutPropertyWrapper(expectedPropertyTypeReference))
{
// We will report the value without property wrapper as a property with empty name (this is technically invalid, but it will only happen in WCF DS Server mode).
propertyName = string.Empty;
// Read the value directly
propertyValue = this.ReadNonEntityValue(
expectedPropertyTypeReference,
/*duplicatePropertyNamesChecker*/ null,
/*collectionValidator*/ null,
/*validateNullValue*/ true);
}
else
{
// Read the start of the object container around the property { "property": ... }
this.JsonReader.ReadStartObject();
// Read through all top-level properties, ignore the ones with reserved names (i.e., reserved
// characters in their name) and throw if we find none or more than one properties without reserved name.
bool foundProperty = false;
string foundPropertyName = null;
while (this.JsonReader.NodeType == JsonNodeType.Property)
{
// Read once - this should be the property
propertyName = this.JsonReader.ReadPropertyName();
if (!ValidationUtils.IsValidPropertyName(propertyName))
{
// We ignore properties with an invalid name since these are extension points for the future.
this.JsonReader.SkipValue();
}
else
{
if (foundProperty)
{
// There should be only one property in the top-level property wrapper that does not have a reserved name.
throw new ODataException(o.Strings.ODataJsonPropertyAndValueDeserializer_InvalidTopLevelPropertyPayload);
}
foundProperty = true;
foundPropertyName = propertyName;
// Now read the property value
propertyValue = this.ReadNonEntityValue(
expectedPropertyTypeReference,
/*duplicatePropertyNamesChecker*/ null,
/*collectionValidator*/ null,
/*validateNullValue*/ true);
}
}
if (!foundProperty)
{
// No property found; there should be exactly one property in the top-level property wrapper that does not have a reserved name.
throw new ODataException(o.Strings.ODataJsonPropertyAndValueDeserializer_InvalidTopLevelPropertyPayload);
}
Debug.Assert(foundPropertyName != null, "foundPropertyName != null");
propertyName = foundPropertyName;
// Read over the end object - note that this might be the last node in the input (in case there's no response wrapper)
this.JsonReader.Read();
}
// Read the end of the response wrapper "d" if expected.
this.ReadPayloadEnd(false /*isReadingNestedPayload*/);
Debug.Assert(this.JsonReader.NodeType == JsonNodeType.EndOfInput, "Post-Condition: expected JsonNodeType.EndOfInput");
this.JsonReader.AssertNotBuffering();
Debug.Assert(propertyName != null, "propertyName != null");
return new ODataProperty
{
Name = propertyName,
Value = propertyValue
};
}
/// <summary>
/// Reads an entry, complex or collection content in buffering mode until it finds the type name in the __metadata object
/// or hits the end of the object. If called for a primitive value, returns 'null' (since primitive types cannot have
/// type names in JSON)
/// </summary>
/// <returns>The type name as read from the __metadata object; null if none was found.</returns>
/// <remarks>
/// This method does not move the reader.
/// Pre-Condition: JsonNodeType.PrimitiveValue A primitive value
/// JsonNodeType.StartObject Any non-primitive value
/// Post-Condition: JsonNodeType.PrimitiveValue A primitive value
/// JsonNodeType.StartObject Any non-primitive value
/// </remarks>
internal string FindTypeNameInPayload()
{
DebugUtils.CheckNoExternalCallers();
Debug.Assert(
this.JsonReader.NodeType == JsonNodeType.PrimitiveValue ||
this.JsonReader.NodeType == JsonNodeType.StartObject,
"Pre-Condition: JsonNodeType.PrimitiveValue or JsonNodeType.StartObject");
this.JsonReader.AssertNotBuffering();
if (this.JsonReader.NodeType == JsonNodeType.PrimitiveValue)
{
// Primitive values don't have type names in JSON
return null;
}
// start buffering so we don't move the reader
this.JsonReader.StartBuffering();
// Read the start of the object
this.JsonReader.ReadStartObject();
string typeName = null;
// read through all the properties and find the __metadata one (if it exists)
while (this.JsonReader.NodeType == JsonNodeType.Property)
{
string propertyName = this.JsonReader.ReadPropertyName();
if (string.CompareOrdinal(propertyName, JsonConstants.ODataMetadataName) == 0)
{
// now extract the typename property (if present)
//
// NOTE we do strictly more work than absolutely necessary by calling this
// method here since it will read all of the metadata object and not just
// up to the typename; since we will come back and read the metadata object
// later it should not be an issue.
typeName = this.ReadTypeNameFromMetadataPropertyValue();
break;
}
else
{
// skip over the value of this property
this.JsonReader.SkipValue();
}
}
// stop buffering and reset the reader to its previous state
this.JsonReader.StopBuffering();
Debug.Assert(
this.JsonReader.NodeType == JsonNodeType.PrimitiveValue ||
this.JsonReader.NodeType == JsonNodeType.StartObject,
"Post-Condition: JsonNodeType.PrimitiveValue or JsonNodeType.StartObject");
return typeName;
}
/// <summary>
/// Reads a primitive value, complex value or collection.
/// </summary>
/// <param name="expectedValueTypeReference">The expected type reference of the property value.</param>
/// <param name="duplicatePropertyNamesChecker">The duplicate property names checker to use - if null the method should create a new one if necessary.</param>
/// <param name="collectionValidator">The collection validator instance if no expected item type has been specified; otherwise null.</param>
/// <param name="validateNullValue">true to validate null values; otherwise false.</param>
/// <returns>The value of the property read.</returns>
/// <remarks>
/// Pre-Condition: JsonNodeType.PrimitiveValue - the value of the property is a primitive value
/// JsonNodeType.StartObject - the value of the property is an object
/// JsonNodeType.StartArray - the value of the property is an array - method will fail in this case.
/// Post-Condition: almost anything - the node after the property value.
///
/// Returns the value of the property read, which can be one of:
/// - null
/// - primitive value
/// - <see cref="ODataComplexValue"/>
/// - <see cref="ODataCollectionValue"/>
/// </remarks>
internal object ReadNonEntityValue(
IEdmTypeReference expectedValueTypeReference,
DuplicatePropertyNamesChecker duplicatePropertyNamesChecker,
CollectionWithoutExpectedTypeValidator collectionValidator,
bool validateNullValue)
{
DebugUtils.CheckNoExternalCallers();
this.AssertRecursionDepthIsZero();
object nonEntityValue = this.ReadNonEntityValueImplementation(expectedValueTypeReference, duplicatePropertyNamesChecker, collectionValidator, validateNullValue);
this.AssertRecursionDepthIsZero();
return nonEntityValue;
}
/// <summary>
/// Reads the type name from the value of a __metadata property. All other properties in the __metadata property value are ignored.
/// </summary>
/// <returns>The type name found, or null if none was found.</returns>
/// <remarks>
/// This method can be used in buffering and non-buffering mode.
///
/// Pre-Condition: Fails if the current node is not a JsonNodeType.StartObject
/// Post-Condition: JsonNodeType.Property - the next property after the __metadata property value.
/// JsonNodeType.EndObject - if the __metadata property was the last property in the object.
/// </remarks>
internal string ReadTypeNameFromMetadataPropertyValue()
{
DebugUtils.CheckNoExternalCallers();
string typeName = null;
// The value of the __metadata property must be an object
if (this.JsonReader.NodeType != JsonNodeType.StartObject)
{
throw new ODataException(o.Strings.ODataJsonPropertyAndValueDeserializer_MetadataPropertyMustHaveObjectValue(this.JsonReader.NodeType));
}
this.JsonReader.ReadStartObject();
// Go over the properties and look for the type property.
ODataJsonReaderUtils.MetadataPropertyBitMask propertiesFoundBitField = 0;
while (this.JsonReader.NodeType == JsonNodeType.Property)
{
string propertyName = this.JsonReader.ReadPropertyName();
if (string.CompareOrdinal(JsonConstants.ODataMetadataTypeName, propertyName) == 0)
{
ODataJsonReaderUtils.VerifyMetadataPropertyNotFound(
ref propertiesFoundBitField,
ODataJsonReaderUtils.MetadataPropertyBitMask.Type,
JsonConstants.ODataMetadataTypeName);
object typeNameValue = this.JsonReader.ReadPrimitiveValue();
typeName = typeNameValue as string;
if (typeName == null)
{
throw new ODataException(o.Strings.ODataJsonPropertyAndValueDeserializer_InvalidTypeName(typeNameValue));
}
}
else
{
// Skip over the property value.
this.JsonReader.SkipValue();
}
}
Debug.Assert(this.JsonReader.NodeType == JsonNodeType.EndObject, "Only Property or EndObject can occur in Object scope.");
this.JsonReader.ReadEndObject();
Debug.Assert(
this.JsonReader.NodeType == JsonNodeType.Property || this.JsonReader.NodeType == JsonNodeType.EndObject,
"Post-Condition: expected JsonNodeType.Property or JsonNodeType.EndObject");
return typeName;
}
/// <summary>
/// Reads the json object value from the jsonReader
/// </summary>
/// <param name="jsonReader">Json reader to read payload from the wire.</param>
/// <returns>an instance of IDictionary containing the spatial value.</returns>
private IDictionary<string, object> ReadObjectValue(JsonReader jsonReader)
{
Debug.Assert(jsonReader != null, "jsonReader != null");
Debug.Assert(jsonReader.NodeType == JsonNodeType.StartObject, "jsonReader.NodeType == JsonNodeType.StartObject");
this.IncreaseRecursionDepth();
IDictionary<string, object> jsonValue = new Dictionary<string, object>(StringComparer.Ordinal);
jsonReader.ReadNext();
while (jsonReader.NodeType != JsonNodeType.EndObject)
{
// read the property name
string propertyName = jsonReader.ReadPropertyName();
// read the property value
object propertyValue = null;
switch (jsonReader.NodeType)
{
case JsonNodeType.PrimitiveValue:
propertyValue = jsonReader.ReadPrimitiveValue();
break;
case JsonNodeType.StartArray:
propertyValue = this.ReadArrayValue(jsonReader);
break;
case JsonNodeType.StartObject:
propertyValue = this.ReadObjectValue(jsonReader);
break;
default:
Debug.Assert(false, "We should never reach here - There should be matching end element");
return null;
}
jsonValue.Add(propertyName, propertyValue);
}
jsonReader.ReadEndObject();
this.DecreaseRecursionDepth();
return jsonValue;
}
/// <summary>
/// Read the json array from the reader.
/// </summary>
/// <param name="jsonReader">JsonReader instance.</param>
/// <returns>a list of json objects.</returns>
private IEnumerable<object> ReadArrayValue(JsonReader jsonReader)
{
Debug.Assert(jsonReader != null, "jsonReader != null");
Debug.Assert(jsonReader.NodeType == JsonNodeType.StartArray, "jsonReader.NodeType == JsonNodeType.StartArray");
this.IncreaseRecursionDepth();
List<object> array = new List<object>();
jsonReader.ReadNext();
while (jsonReader.NodeType != JsonNodeType.EndArray)
{
switch (jsonReader.NodeType)
{
case JsonNodeType.PrimitiveValue:
array.Add(jsonReader.ReadPrimitiveValue());
break;
case JsonNodeType.StartObject:
array.Add(this.ReadObjectValue(jsonReader));
break;
case JsonNodeType.StartArray:
array.Add(this.ReadArrayValue(jsonReader));
break;
default:
Debug.Assert(false, "We should never have got here - the valid states in array are primitive value or object");
return null;
}
}
jsonReader.ReadEndArray();
this.DecreaseRecursionDepth();
return array;
}
/// <summary>
/// Try and parse spatial type from the json payload.
/// </summary>
/// <param name="expectedValueTypeReference">Expected edm property type.</param>
/// <param name="validateNullValue">true to validate null values; otherwise false.</param>
/// <returns>An instance of the spatial type.</returns>
private System.Spatial.ISpatial ReadSpatialValue(IEdmPrimitiveTypeReference expectedValueTypeReference, bool validateNullValue)
{
Debug.Assert(expectedValueTypeReference != null, "expectedValueTypeReference != null");
Debug.Assert(expectedValueTypeReference.IsSpatial(), "TryParseSpatialType must be called only with spatial types");
// Note that we made sure that payload type detection will not return spatial for <V3 payloads
// So the only way we can get a spatial type reference is if it comes from the model,
// in which case we want to fail for <V3 payloads, since we can't report spatial values from such payloads.
ODataVersionChecker.CheckSpatialValue(this.Version);
// Spatial value can be either null constant or a JSON object
// If it's a null primitive value, report a null value.
if (this.TryReadNullValue(expectedValueTypeReference, validateNullValue))
{
return null;
}
System.Spatial.ISpatial spatialValue = null;
if (this.JsonReader.NodeType == JsonNodeType.StartObject)
{
IDictionary<string, object> jsonObject = this.ReadObjectValue(this.JsonReader);
System.Spatial.GeoJsonObjectFormatter jsonObjectFormatter =
System.Spatial.SpatialImplementation.CurrentImplementation.CreateGeoJsonObjectFormatter();
if (EdmLibraryExtensions.IsGeographyType(expectedValueTypeReference))
{
spatialValue = jsonObjectFormatter.Read<System.Spatial.Geography>(jsonObject);
}
else
{
spatialValue = jsonObjectFormatter.Read<System.Spatial.Geometry>(jsonObject);
}
}
if (spatialValue == null)
{
throw new ODataException(o.Strings.ODataJsonPropertyAndValueDeserializer_CannotReadSpatialPropertyValue);
}
return spatialValue;
}
/// <summary>
/// Reads a collection value.
/// </summary>
/// <param name="collectionValueTypeReference">The collection type reference of the value.</param>
/// <param name="payloadTypeName">The type name read from the payload.</param>
/// <param name="serializationTypeNameAnnotation">The serialization type name for the collection value (possibly null).</param>
/// <returns>The value of the collection.</returns>
/// <remarks>
/// Pre-Condition: Fails if the current node is not a JsonNodeType.StartObject
/// Post-Condition: almost anything - the node after the collection value (after the EndObject)
/// </remarks>
private ODataCollectionValue ReadCollectionValueImplementation(
IEdmCollectionTypeReference collectionValueTypeReference,
string payloadTypeName,
SerializationTypeNameAnnotation serializationTypeNameAnnotation)
{
DebugUtils.CheckNoExternalCallers();
Debug.Assert(
collectionValueTypeReference == null || collectionValueTypeReference.IsNonEntityODataCollectionTypeKind(),
"If the metadata is specified it must denote a Collection for this method to work.");
this.JsonReader.AssertNotBuffering();
ODataVersionChecker.CheckCollectionValue(this.Version);
this.IncreaseRecursionDepth();
// Read over the start object
this.JsonReader.ReadStartObject();
ODataCollectionValue collectionValue = new ODataCollectionValue();
collectionValue.TypeName = collectionValueTypeReference != null ? collectionValueTypeReference.ODataFullName() : payloadTypeName;
if (serializationTypeNameAnnotation != null)
{
collectionValue.SetAnnotation(serializationTypeNameAnnotation);
}
List<object> items = null;
bool metadataPropertyFound = false;
while (this.JsonReader.NodeType == JsonNodeType.Property)
{
string propertyName = this.JsonReader.ReadPropertyName();
if (string.CompareOrdinal(JsonConstants.ODataMetadataName, propertyName) == 0)
{
// __metadata property
if (metadataPropertyFound)
{
throw new ODataException(o.Strings.ODataJsonPropertyAndValueDeserializer_MultiplePropertiesInCollectionWrapper(JsonConstants.ODataMetadataName));
}
metadataPropertyFound = true;
// Note that we don't need to read the type name again, as we've already read it above in FindTypeNameInPayload.
// There's nothing else of interest in the __metadata for collections.
this.JsonReader.SkipValue();
}
else if (string.CompareOrdinal(JsonConstants.ODataResultsName, propertyName) == 0)
{
// results property
if (items != null)
{
throw new ODataException(o.Strings.ODataJsonPropertyAndValueDeserializer_MultiplePropertiesInCollectionWrapper(JsonConstants.ODataResultsName));
}
items = new List<object>();
this.JsonReader.ReadStartArray();
DuplicatePropertyNamesChecker duplicatePropertyNamesChecker = this.CreateDuplicatePropertyNamesChecker();
IEdmTypeReference itemType = null;
if (collectionValueTypeReference != null)
{
itemType = collectionValueTypeReference.CollectionDefinition().ElementType;
}
// NOTE: we do not support reading JSON without metadata right now so we always have an expected item type;
// The collection validator is always null.
CollectionWithoutExpectedTypeValidator collectionValidator = null;
while (this.JsonReader.NodeType != JsonNodeType.EndArray)
{
object itemValue = this.ReadNonEntityValueImplementation(
itemType,
duplicatePropertyNamesChecker,
collectionValidator,
/*validateNullValue*/ true);
// Validate the item (for example that it's not null)
ValidationUtils.ValidateCollectionItem(itemValue, false /* isStreamable */);
// Note that the ReadNonEntityValue already validated that the actual type of the value matches
// the expected type (the itemType).
items.Add(itemValue);
}
Debug.Assert(this.JsonReader.NodeType == JsonNodeType.EndArray, "The results value must end with an end array.");
this.JsonReader.ReadEndArray();
}
else
{
// Skip over any other property in the collection object
this.JsonReader.SkipValue();
}
}
Debug.Assert(this.JsonReader.NodeType == JsonNodeType.EndObject, "After all properties of Collection wrapper are read the EndObject node is expected.");
this.JsonReader.ReadEndObject();
if (items == null)
{
// We didn't find any results property. All collections must have the results property.
throw new ODataException(o.Strings.ODataJsonPropertyAndValueDeserializer_CollectionWithoutResults);
}
collectionValue.Items = new ReadOnlyEnumerable(items);
this.JsonReader.AssertNotBuffering();
this.DecreaseRecursionDepth();
return collectionValue;
}
/// <summary>
/// Reads a primitive value.
/// </summary>
/// <param name="expectedValueTypeReference">The expected type reference of the value.</param>
/// <param name="validateNullValue">true to validate null values; otherwise false.</param>
/// <returns>The value of the primitive value.</returns>
/// <remarks>
/// Pre-Condition: none - Fails if the current node is not a JsonNodeType.PrimitiveValue
/// Post-Condition: almost anything - the node after the primitive value.
/// </remarks>
private object ReadPrimitiveValueImplementation(IEdmPrimitiveTypeReference expectedValueTypeReference, bool validateNullValue)
{
this.JsonReader.AssertNotBuffering();
object result;
if (expectedValueTypeReference != null && expectedValueTypeReference.IsSpatial())
{
result = this.ReadSpatialValue(expectedValueTypeReference, validateNullValue);
}
else
{
result = this.JsonReader.ReadPrimitiveValue();
if (expectedValueTypeReference != null && !this.MessageReaderSettings.DisablePrimitiveTypeConversion)
{
result = ODataJsonReaderUtils.ConvertValue(result, expectedValueTypeReference, this.MessageReaderSettings, this.Version, validateNullValue);
}
}
this.JsonReader.AssertNotBuffering();
return result;
}
/// <summary>
/// Reads a complex value.
/// </summary>
/// <param name="complexValueTypeReference">The expected type reference of the value.</param>
/// <param name="payloadTypeName">The type name read from the payload.</param>
/// <param name="serializationTypeNameAnnotation">The serialization type name for the collection value (possibly null).</param>
/// <param name="duplicatePropertyNamesChecker">The duplicate property names checker to use - if null the method should create a new one if necessary.</param>
/// <returns>The value of the complex value.</returns>
/// <remarks>
/// Pre-Condition: Fails if the current node is not a JsonNodeType.StartObject or JsonNodeType.PrimitiveValue (with null value)
/// Post-Condition: almost anything - the node after the complex value (after the EndObject)
/// </remarks>
private ODataComplexValue ReadComplexValueImplementation(
IEdmComplexTypeReference complexValueTypeReference,
string payloadTypeName,
SerializationTypeNameAnnotation serializationTypeNameAnnotation,
DuplicatePropertyNamesChecker duplicatePropertyNamesChecker)
{
this.JsonReader.AssertNotBuffering();
this.IncreaseRecursionDepth();
// Read over the start object
this.JsonReader.ReadStartObject();
ODataComplexValue complexValue = new ODataComplexValue();
complexValue.TypeName = complexValueTypeReference != null ? complexValueTypeReference.ODataFullName() : payloadTypeName;
if (serializationTypeNameAnnotation != null)
{
complexValue.SetAnnotation(serializationTypeNameAnnotation);
}
if (duplicatePropertyNamesChecker == null)
{
duplicatePropertyNamesChecker = this.CreateDuplicatePropertyNamesChecker();
}
else
{
duplicatePropertyNamesChecker.Clear();
}
List<ODataProperty> properties = new List<ODataProperty>();
bool metadataPropertyFound = false;
while (this.JsonReader.NodeType == JsonNodeType.Property)
{
string propertyName = this.JsonReader.ReadPropertyName();
if (string.CompareOrdinal(JsonConstants.ODataMetadataName, propertyName) == 0)
{
// __metadata property.
if (metadataPropertyFound)
{
throw new ODataException(o.Strings.ODataJsonPropertyAndValueDeserializer_MultipleMetadataPropertiesInComplexValue);
}
metadataPropertyFound = true;
this.JsonReader.SkipValue();
}
else
{
if (!ValidationUtils.IsValidPropertyName(propertyName))
{
// We ignore properties with an invalid name since these are extension points for the future.
this.JsonReader.SkipValue();
}
else
{
// Any other property is data
ODataProperty property = new ODataProperty();
property.Name = propertyName;
// Lookup the property in metadata
IEdmProperty edmProperty = null;
bool ignoreProperty = false;
if (complexValueTypeReference != null)
{
edmProperty = ReaderValidationUtils.ValidateValuePropertyDefined(propertyName, complexValueTypeReference.ComplexDefinition(), this.MessageReaderSettings, out ignoreProperty);
}
if (ignoreProperty)
{
this.JsonReader.SkipValue();
}
else
{
ODataNullValueBehaviorKind nullValueReadBehaviorKind = this.ReadingResponse || edmProperty == null
? ODataNullValueBehaviorKind.Default
: this.Model.NullValueReadBehaviorKind(edmProperty);
// Read the property value
object propertyValue = this.ReadNonEntityValueImplementation(
edmProperty == null ? null : edmProperty.Type,
/*duplicatePropertyNamesChecker*/ null,
/*collectionValidator*/ null,
nullValueReadBehaviorKind == ODataNullValueBehaviorKind.Default);
if (nullValueReadBehaviorKind != ODataNullValueBehaviorKind.IgnoreValue || propertyValue != null)
{
duplicatePropertyNamesChecker.CheckForDuplicatePropertyNames(property);
property.Value = propertyValue;
properties.Add(property);
}
}
}
}
}
Debug.Assert(this.JsonReader.NodeType == JsonNodeType.EndObject, "After all the properties of a complex value are read the EndObject node is expected.");
this.JsonReader.ReadEndObject();
complexValue.Properties = new ReadOnlyEnumerable<ODataProperty>(properties);
this.JsonReader.AssertNotBuffering();
this.DecreaseRecursionDepth();
return complexValue;
}
/// <summary>
/// Reads a primitive, complex or collection value.
/// </summary>
/// <param name="expectedTypeReference">The expected type reference of the property value.</param>
/// <param name="duplicatePropertyNamesChecker">The duplicate property names checker to use - if null the method should create a new one if necessary.</param>
/// <param name="collectionValidator">The collection validator instance if no expected item type has been specified; otherwise null.</param>
/// <param name="validateNullValue">true to validate null values; otherwise false.</param>
/// <returns>The value of the property read.</returns>
/// <remarks>
/// Pre-Condition: JsonNodeType.PrimitiveValue - the value of the property is a primitive value
/// JsonNodeType.StartObject - the value of the property is an object
/// JsonNodeType.StartArray - the value of the property is an array - method will fail in this case.
/// Post-Condition: almost anything - the node after the property value.
///
/// Returns the value of the property read, which can be one of:
/// - null
/// - primitive value
/// - <see cref="ODataComplexValue"/>
/// - <see cref="ODataCollectionValue"/>
/// </remarks>
private object ReadNonEntityValueImplementation(
IEdmTypeReference expectedTypeReference,
DuplicatePropertyNamesChecker duplicatePropertyNamesChecker,
CollectionWithoutExpectedTypeValidator collectionValidator,
bool validateNullValue)
{
// TODO: can we ever get a non-null collection validator here? That would mean that we don't have
// an expected type; double-check
DebugUtils.CheckNoExternalCallers();
Debug.Assert(
this.JsonReader.NodeType == JsonNodeType.PrimitiveValue || this.JsonReader.NodeType == JsonNodeType.StartObject || this.JsonReader.NodeType == JsonNodeType.StartArray,
"Pre-Condition: expected JsonNodeType.PrimitiveValue or JsonNodeType.StartObject or JsonNodeType.StartArray");
Debug.Assert(
expectedTypeReference == null || !expectedTypeReference.IsODataEntityTypeKind(),
"Only primitive, complex or collection types can be read by this method.");
Debug.Assert(
expectedTypeReference == null || collectionValidator == null,
"If an expected value type reference is specified, no collection validator must be provided.");
this.JsonReader.AssertNotBuffering();
// Property values can be only primitives or objects. No property can have a JSON array value.
JsonNodeType nodeType = this.JsonReader.NodeType;
if (nodeType == JsonNodeType.StartArray)
{
throw new ODataException(o.Strings.ODataJsonPropertyAndValueDeserializer_CannotReadPropertyValue(nodeType));
}
// Try to read a null value
object result;
if (this.TryReadNullValue(expectedTypeReference, validateNullValue))
{
result = null;
}
else
{
// Read the payload type name
string payloadTypeName = this.FindTypeNameInPayload();
SerializationTypeNameAnnotation serializationTypeNameAnnotation;
EdmTypeKind targetTypeKind;
IEdmTypeReference targetTypeReference = ReaderValidationUtils.ResolvePayloadTypeNameAndComputeTargetType(
EdmTypeKind.None,
/*defaultPrimitivePayloadType*/ null,
expectedTypeReference,
payloadTypeName,
this.Model,
this.MessageReaderSettings,
this.Version,
this.GetNonEntityValueKind,
out targetTypeKind,
out serializationTypeNameAnnotation);
switch (targetTypeKind)
{
case EdmTypeKind.Primitive:
Debug.Assert(targetTypeReference == null || targetTypeReference.IsODataPrimitiveTypeKind(), "Expected an OData primitive type.");
IEdmPrimitiveTypeReference primitiveTargetTypeReference = targetTypeReference == null ? null : targetTypeReference.AsPrimitive();
if (payloadTypeName != null && !primitiveTargetTypeReference.IsSpatial())
{
throw new ODataException(o.Strings.ODataJsonPropertyAndValueDeserializer_InvalidPrimitiveTypeName(payloadTypeName));
}
result = this.ReadPrimitiveValueImplementation(
primitiveTargetTypeReference,
validateNullValue);
break;
case EdmTypeKind.Complex:
Debug.Assert(targetTypeReference == null || targetTypeReference.IsComplex(), "Expected a complex type.");
result = this.ReadComplexValueImplementation(
targetTypeReference == null ? null : targetTypeReference.AsComplex(),
payloadTypeName,
serializationTypeNameAnnotation,
duplicatePropertyNamesChecker);
break;
case EdmTypeKind.Collection:
Debug.Assert(this.Version >= ODataVersion.V3, "Type resolution should already fail if we would decide to read a collection value in V1/V2 payload.");
IEdmCollectionTypeReference collectionTypeReference = ValidationUtils.ValidateCollectionType(targetTypeReference);
result = this.ReadCollectionValueImplementation(
collectionTypeReference,
payloadTypeName,
serializationTypeNameAnnotation);
break;
default:
throw new ODataException(o.Strings.General_InternalError(InternalErrorCodes.ODataJsonPropertyAndValueDeserializer_ReadPropertyValue));
}
// If we have no expected type make sure the collection items are of the same kind and specify the same name.
if (collectionValidator != null)
{
string payloadTypeNameFromResult = ODataJsonReaderUtils.GetPayloadTypeName(result);
Debug.Assert(expectedTypeReference == null, "If a collection validator is specified there must not be an expected value type reference.");
collectionValidator.ValidateCollectionItem(payloadTypeNameFromResult, targetTypeKind);
}
}
this.JsonReader.AssertNotBuffering();
return result;
}
/// <summary>
/// Determines the value kind for a non-entity value (that is top-level property value, property value on a complex type, item in a collection)
/// </summary>
/// <returns>The type kind of the property value.</returns>
/// <remarks>
/// Doesn't move the JSON reader.
/// Pre-Condition: JsonNodeType.PrimitiveValue
/// JsonNodeType.StartObject
/// Post-Condition: JsonNodeType.PrimitiveValue
/// JsonNodeType.StartObject
/// </remarks>
private EdmTypeKind GetNonEntityValueKind()
{
Debug.Assert(
this.JsonReader.NodeType == JsonNodeType.PrimitiveValue || this.JsonReader.NodeType == JsonNodeType.StartObject,
"Pre-Condition: expected JsonNodeType.PrimitiveValue or JsonNodeType.StartObject");
this.JsonReader.AssertNotBuffering();
JsonNodeType nodeType = this.JsonReader.NodeType;
if (nodeType == JsonNodeType.PrimitiveValue)
{
return EdmTypeKind.Primitive;
}
else
{
Debug.Assert(nodeType == JsonNodeType.StartObject, "StartObject expected.");
// it can be either a complex value or a collection
// complex value might have a __metadata property or any other property.
// In the __metadata the type property (if present) would differentiate the two.
// Also collection has a results property which value is an array.
// Complex value cannot have any property with value of an array, so that's an easy thing to recognize.
// So we're looking for either __metadata or results, nothing else can exist on a collection.
// We need to buffer since once detected we need to go back and reread the real value.
this.JsonReader.StartBuffering();
try
{
// Read over the start object - the start of the complex or collection
this.JsonReader.ReadNext();
while (this.JsonReader.NodeType == JsonNodeType.Property)
{
string propertyName = this.JsonReader.ReadPropertyName();
if (string.Equals(JsonConstants.ODataResultsName, propertyName, StringComparison.Ordinal))
{
// "results" property, it might be a normal property of a complex type
// so we need to check it's value, if it's an array, it's a collection.
if (this.JsonReader.NodeType == JsonNodeType.StartArray && this.Version >= ODataVersion.V3)
{
return EdmTypeKind.Collection;
}
// If it's not an array, it's a normal property on a complex type
return EdmTypeKind.Complex;
}
// Skip over the property value
this.JsonReader.SkipValue();
}
// If we end here, it means we didn't find enough properties to tell if we're looking at collection or complex type
// In which case it must be a complex type, since collection requires the results property.
return EdmTypeKind.Complex;
}
finally
{
// Stop the buffering, since we're done deciding the type of the value.
this.JsonReader.StopBuffering();
this.JsonReader.AssertNotBuffering();
Debug.Assert(
this.JsonReader.NodeType == JsonNodeType.PrimitiveValue || this.JsonReader.NodeType == JsonNodeType.StartObject,
"Pre-Condition: expected JsonNodeType.PrimitiveValue or JsonNodeType.StartObject");
}
}
}
/// <summary>
/// Determines if the top-level property payload should be read as usual, or without the property wrapper.
/// </summary>
/// <param name="expectedPropertyTypeReference">The expected type reference for the property value to read.</param>
/// <returns>true if the property payload should be read without the property wrapper, false if it should be read as usual with the property wrapper.</returns>
/// <remarks>This method is to support backward compat behavior for WCF DS Server, which can read open property values without property wrapper.</remarks>
private bool ShouldReadTopLevelPropertyValueWithoutPropertyWrapper(IEdmTypeReference expectedPropertyTypeReference)
{
// We have to support reading top-level complex values without the { "property": ... } wrapper for open properties
// in WCF DS Server backward compat mode. (Open property == property without expected type for us).
if (this.UseServerFormatBehavior && expectedPropertyTypeReference == null)
{
// The behavior we need to emulate is:
// - If the JSON object has more than one property in it - read it as a complex value directly (without the property wrapper)
// - If the JSON object has exactly one property and it's called __metadata, read the value as a complex value directly
// this is because open property values must specify type names and thus if there's __metadata it might be a valid complex value (Without property wrapper)
// which has no properties on it.
// - In all other cases (single property not called __metadata),
// So turn on buffering so that we can read ahead to figure out which of the above cases it is
this.JsonReader.StartBuffering();
try
{
// Read the start of the object, as the payload must be an object regardless
this.JsonReader.ReadStartObject();
// Check for an empty object first
if (this.JsonReader.NodeType == JsonNodeType.EndObject)
{
return false;
}
// Now read the first property name
string firstPropertyName = this.JsonReader.ReadPropertyName();
// Skip its value
this.JsonReader.SkipValue();
// Is there a second property?
if (this.JsonReader.NodeType != JsonNodeType.EndObject)
{
// If there is - read the value in the special mode without the property wrapper
return true;
}
else
{
// Only one property
if (string.CompareOrdinal(firstPropertyName, JsonConstants.ODataMetadataName) == 0)
{
// It's __metadata, read the value in the special mode without the property wrapper
return true;
}
}
}
finally
{
this.JsonReader.StopBuffering();
}
}
return false;
}
/// <summary>
/// Tries to read a null value from the JSON reader.
/// </summary>
/// <param name="expectedTypeReference">The expected type reference of the value.</param>
/// <param name="validateNullValue">true to validate null values; otherwise false.</param>
/// <returns>true if a null value could be read from the JSON reader; otherwise false.</returns>
/// <remarks>If the method detects a null value it will read it (position the reader after the null value);
/// otherwise the reader does not move.</remarks>
private bool TryReadNullValue(IEdmTypeReference expectedTypeReference, bool validateNullValue)
{
if (this.JsonReader.NodeType == JsonNodeType.PrimitiveValue && this.JsonReader.Value == null)
{
this.JsonReader.ReadNext();
// NOTE: when reading a null value we will never ask the type resolver (if present) to resolve the
// type; we always fall back to the expected type.
ReaderValidationUtils.ValidateNullValue(this.Model, expectedTypeReference, this.MessageReaderSettings, validateNullValue, this.Version);
return true;
}
return false;
}
/// <summary>
/// Increases the recursion depth of values by 1. This will throw if the recursion depth exceeds the current limit.
/// </summary>
private void IncreaseRecursionDepth()
{
ValidationUtils.IncreaseAndValidateRecursionDepth(ref this.recursionDepth, this.MessageReaderSettings.MessageQuotas.MaxNestingDepth);
}
/// <summary>
/// Decreases the recursion depth of values by 1.
/// </summary>
private void DecreaseRecursionDepth()
{
Debug.Assert(this.recursionDepth > 0, "Can't decrease recursion depth below 0.");
this.recursionDepth--;
}
/// <summary>
/// Asserts that the current recursion depth of values is zero. This should be true on all calls into this class from outside of this class.
/// </summary>
[Conditional("DEBUG")]
[SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "The this is needed in DEBUG build.")]
private void AssertRecursionDepthIsZero()
{
Debug.Assert(this.recursionDepth == 0, "The current recursion depth must be 0.");
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.UseNullPropagation;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseNullPropagation
{
public partial class UseNullPropagationTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
=> (new CSharpUseNullPropagationDiagnosticAnalyzer(), new CSharpUseNullPropagationCodeFixProvider());
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestLeft_Equals()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
void M(object o)
{
var v = [||]o == null ? null : o.ToString();
}
}",
@"using System;
class C
{
void M(object o)
{
var v = o?.ToString();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestMissingOnCSharp5()
{
await TestMissingAsync(
@"using System;
class C
{
void M(object o)
{
var v = [||]o == null ? null : o.ToString();
}
}", new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestRight_Equals()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
void M(object o)
{
var v = [||]null == o ? null : o.ToString();
}
}",
@"using System;
class C
{
void M(object o)
{
var v = o?.ToString();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestLeft_NotEquals()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
void M(object o)
{
var v = [||]o != null ? o.ToString() : null;
}
}",
@"using System;
class C
{
void M(object o)
{
var v = o?.ToString();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestRight_NotEquals()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
void M(object o)
{
var v = [||]null != o ? o.ToString() : null;
}
}",
@"using System;
class C
{
void M(object o)
{
var v = o?.ToString();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestIndexer()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
void M(object o)
{
var v = [||]o == null ? null : o[0];
}
}",
@"using System;
class C
{
void M(object o)
{
var v = o?[0];
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestConditionalAccess()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
void M(object o)
{
var v = [||]o == null ? null : o.B?.C;
}
}",
@"using System;
class C
{
void M(object o)
{
var v = o?.B?.C;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestMemberAccess()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
void M(object o)
{
var v = [||]o == null ? null : o.B;
}
}",
@"using System;
class C
{
void M(object o)
{
var v = o?.B;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestMissingOnSimpleMatch()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class C
{
void M(object o)
{
var v = [||]o == null ? null : o;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestParenthesizedCondition()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
void M(object o)
{
var v = [||](o == null) ? null : o.ToString();
}
}",
@"using System;
class C
{
void M(object o)
{
var v = o?.ToString();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestFixAll1()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
void M(object o)
{
var v1 = {|FixAllInDocument:o|} == null ? null : o.ToString();
var v2 = o != null ? o.ToString() : null;
}
}",
@"using System;
class C
{
void M(object o)
{
var v1 = o?.ToString();
var v2 = o?.ToString();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestFixAll2()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
void M(object o1, object o2)
{
var v1 = {|FixAllInDocument:o1|} == null ? null : o1.ToString(o2 == null ? null : o2.ToString());
}
}",
@"using System;
class C
{
void M(object o1, object o2)
{
var v1 = o1?.ToString(o2?.ToString());
}
}");
}
[WorkItem(15505, "https://github.com/dotnet/roslyn/issues/15505")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestOtherValueIsNotNull1()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class C
{
void M(object o)
{
var v = [||]o == null ? 0 : o.ToString();
}
}");
}
[WorkItem(15505, "https://github.com/dotnet/roslyn/issues/15505")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestOtherValueIsNotNull2()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class C
{
void M(object o)
{
var v = [||]o != null ? o.ToString() : 0;
}
}");
}
[WorkItem(16287, "https://github.com/dotnet/roslyn/issues/16287")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestMethodGroup()
{
await TestMissingInRegularAndScriptAsync(
@"
using System;
class D
{
void Foo()
{
var c = new C();
Action<string> a = [||]c != null ? c.M : (Action<string>)null;
}
}
class C { public void M(string s) { } }");
}
[WorkItem(17623, "https://github.com/dotnet/roslyn/issues/17623")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestInExpressionTree()
{
await TestMissingInRegularAndScriptAsync(
@"
using System;
using System.Linq.Expressions;
class Program
{
void Main(string s)
{
Method<string>(t => [||]s != null ? s.ToString() : null); // works
}
public void Method<T>(Expression<Func<T, string>> functor)
{
}
}");
}
[WorkItem(19774, "https://github.com/dotnet/roslyn/issues/19774")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestNullableMemberAccess()
{
await TestInRegularAndScriptAsync(
@"
using System;
class C
{
void Main(DateTime? toDate)
{
var v = [||]toDate == null ? null : toDate.Value.ToString(""yyyy/MM/ dd"");
}
}
",
@"
using System;
class C
{
void Main(DateTime? toDate)
{
var v = toDate?.ToString(""yyyy/MM/ dd"");
}
}
");
}
[WorkItem(19774, "https://github.com/dotnet/roslyn/issues/19774")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestNullableElementAccess()
{
await TestInRegularAndScriptAsync(
@"
using System;
struct S
{
public string this[int i] => """";
}
class C
{
void Main(S? s)
{
var x = [||]s == null ? null : s.Value[0];
}
}
",
@"
using System;
struct S
{
public string this[int i] => """";
}
class C
{
void Main(S? s)
{
var x = s?[0];
}
}
");
}
}
}
| |
using System;
using System.Text;
using System.Collections;
using System.Windows.Forms;
using System.Collections.Specialized;
using System.Data;
using System.Drawing;
using System.Data.OleDb;
using System.Reflection;
using C1.Win.C1Preview;
using PCSComUtils.Common;
using PCSUtils.Utils;
namespace ImportMaterialReport
{
[Serializable]
public class ImportMaterialReport : MarshalByRefObject, IDynamicReport
{
public ImportMaterialReport()
{
}
#region Constants
private const string TABLE_NAME = "tbl_OutsideProcessing";
private const string NAME_FLD = "Name";
private const string EXCHANGE_RATE_FLD = "ExchangeRate";
private const string PRODUCT_ID_FLD = "ProductID";
private const string PRODUCT_CODE_FLD = "Code";
private const string PRODUCT_NAME_FLD = "Description";
#endregion
#region IDynamicReport Members
private bool mUseReportViewerRenderEngine = false;
private string mConnectionString;
private ReportBuilder mReportBuilder;
private C1PrintPreviewControl mReportViewer;
private object mResult;
/// <summary>
/// ConnectionString, provide for the Dynamic Report
/// ALlow Dynamic Report to access the DataBase of PCS
/// </summary>
public string PCSConnectionString
{
get { return mConnectionString; }
set { mConnectionString = value; }
}
/// <summary>
/// Report Builder Utility Object
/// Dynamic Report can use this object to render, modify, layout the report
/// </summary>
public ReportBuilder PCSReportBuilder
{
get { return mReportBuilder; }
set { mReportBuilder = value; }
}
/// <summary>
/// ReportViewer Object, provide for the DynamicReport,
/// allow Dynamic Report to manipulate with the REportViewer,
/// modify the report after rendered if needed
/// </summary>
public C1PrintPreviewControl PCSReportViewer
{
get { return mReportViewer; }
set { mReportViewer = value; }
}
/// <summary>
/// Store other result if any. Ussually we store return DataTable here to display on the ReportViewer Form's Grid
/// </summary>
public object Result
{
get { return mResult; }
set { mResult = value; }
}
/// <summary>
/// Notify PCS whether the rendering report process is run by
/// this IDynamicReport or the ReportViewer Engine (in the ReportViewer form)
/// </summary>
public bool UseReportViewerRenderEngine
{
get { return mUseReportViewerRenderEngine; }
set { mUseReportViewerRenderEngine = value; }
}
private string mstrReportDefinitionFolder = string.Empty;
/// <summary>
/// Inform External Process where to find out the ReportLayout ( the PCS' ReportDefinition Folder Path )
/// </summary>
public string ReportDefinitionFolder
{
get { return mstrReportDefinitionFolder; }
set { mstrReportDefinitionFolder = value; }
}
private string mstrReportLayoutFile = string.Empty;
/// <summary>
/// Inform External Process about the Layout file
/// in which PCS instruct to use
/// (PCS will assign this property while ReportViewer Form execute,
/// ReportVIewer form will use the layout file in the report config entry to put in this property)
/// </summary>
public string ReportLayoutFile
{
get
{
return mstrReportLayoutFile;
}
set
{
mstrReportLayoutFile = value;
}
}
#endregion
#region Detailed Item Price By PO Receipt Datat: Tuan TQ
/// <summary>
/// Get CCN Info
/// </summary>
/// <param name="pstrID"></param>
/// <returns></returns>
private string GetHomeCurrency(string pstrCCNID)
{
const string HOME_CURRENCY_FLD = "HomeCurrencyID";
OleDbConnection oconPCS = null;
try
{
string strResult = string.Empty;
OleDbDataReader odrPCS = null;
OleDbCommand ocmdPCS = null;
string strSql = "SELECT " + HOME_CURRENCY_FLD;
strSql += " FROM MST_CCN";
strSql += " WHERE CCNID = " + pstrCCNID;
oconPCS = new OleDbConnection(mConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
odrPCS = ocmdPCS.ExecuteReader();
if(odrPCS != null)
{
if(odrPCS.Read())
{
strResult = odrPCS[HOME_CURRENCY_FLD].ToString().Trim();
}
}
return strResult;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed) oconPCS.Close();
oconPCS = null;
}
}
}
DataTable GetImportMaterialReport(string pstrCCNID,
string pstrFromDate,
string pstrToDate,
string pstrCurrencyIDList
)
{
DataTable dtbResult = new DataTable();
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
StringBuilder strSqlBuilder = new StringBuilder();
strSqlBuilder.Append("SELECT DISTINCT PO_InvoiceMaster.PostDate, ");
strSqlBuilder.Append(" PO_InvoiceMaster.InvoiceNo, ");
strSqlBuilder.Append(" MST_Currency.Code as CurrencyCode, ");
strSqlBuilder.Append(" PO_InvoiceMaster.ExchangeRate, ");
strSqlBuilder.Append(" MST_Party.Code AS PartyCode, ");
strSqlBuilder.Append(" MST_Party.Name as PartyName, ");
strSqlBuilder.Append(" ITM_Product.Code AS PartNo, ");
strSqlBuilder.Append(" ITM_Product.Description as PartName, ");
strSqlBuilder.Append(" ITM_Product.Revision as PartModel, ");
strSqlBuilder.Append(" MST_UnitOfMeasure.Code as InvoiceUM, ");
strSqlBuilder.Append(" ITM_Category.Code AS CategoryCode, ");
strSqlBuilder.Append(" PO_InvoiceDetail.UnitPrice, ");
strSqlBuilder.Append(" SUM(PO_InvoiceDetail.InvoiceQuantity) as InvoiceQuantity, ");
strSqlBuilder.Append(" SUM(PO_InvoiceDetail.VATAmount) as VATAmount, ");
strSqlBuilder.Append(" SUM(PO_InvoiceDetail.ImportTaxAmount) as ImportTaxAmount, ");
strSqlBuilder.Append(" SUM(PO_InvoiceDetail.Inland) as Inland, ");
strSqlBuilder.Append(" SUM(PO_InvoiceDetail.CIFAmount) as CIFAmount, ");
strSqlBuilder.Append(" ( ");
strSqlBuilder.Append(" SELECT ISNULL(SUM(cst_FreightDetail.Amount), 0) ");
strSqlBuilder.Append(" FROM PO_PurchaseOrderReceiptMaster ");
strSqlBuilder.Append(" INNER JOIN cst_FreightMaster ON cst_FreightMaster.PurchaseOrderReceiptID = PO_PurchaseOrderReceiptMaster.PurchaseOrderReceiptID ");
strSqlBuilder.Append(" INNER JOIN cst_FreightDetail ON cst_FreightDetail.FreightMasterID = cst_FreightMaster.FreightMasterID ");
strSqlBuilder.Append(" WHERE PO_PurchaseOrderReceiptMaster.InvoiceMasterID = PO_InvoiceMaster.InvoiceMasterID ");
strSqlBuilder.Append(" AND cst_FreightDetail.ProductID = ITM_Product.ProductID ");
strSqlBuilder.Append(" AND cst_FreightMaster.ACPurposeID = 3 ");
strSqlBuilder.Append(" ) as CreditAmount, ");
strSqlBuilder.Append(" ( ");
strSqlBuilder.Append(" SELECT ISNULL(SUM(cst_FreightDetail.VATAmount), 0) ");
strSqlBuilder.Append(" FROM PO_PurchaseOrderReceiptMaster ");
strSqlBuilder.Append(" INNER JOIN cst_FreightMaster ON cst_FreightMaster.PurchaseOrderReceiptID = PO_PurchaseOrderReceiptMaster.PurchaseOrderReceiptID ");
strSqlBuilder.Append(" INNER JOIN cst_FreightDetail ON cst_FreightDetail.FreightMasterID = cst_FreightMaster.FreightMasterID ");
strSqlBuilder.Append(" WHERE PO_PurchaseOrderReceiptMaster.InvoiceMasterID = PO_InvoiceMaster.InvoiceMasterID ");
strSqlBuilder.Append(" AND cst_FreightDetail.ProductID = ITM_Product.ProductID ");
strSqlBuilder.Append(" AND cst_FreightMaster.ACPurposeID = 3 ");
strSqlBuilder.Append(" ) as CreditVATAmount, ");
strSqlBuilder.Append(" ( ");
strSqlBuilder.Append(" SELECT ISNULL(SUM(cst_FreightDetail.Amount), 0) ");
strSqlBuilder.Append(" FROM PO_PurchaseOrderReceiptMaster ");
strSqlBuilder.Append(" INNER JOIN cst_FreightMaster ON cst_FreightMaster.PurchaseOrderReceiptID = PO_PurchaseOrderReceiptMaster.PurchaseOrderReceiptID ");
strSqlBuilder.Append(" INNER JOIN cst_FreightDetail ON cst_FreightDetail.FreightMasterID = cst_FreightMaster.FreightMasterID ");
strSqlBuilder.Append(" WHERE PO_PurchaseOrderReceiptMaster.InvoiceMasterID = PO_InvoiceMaster.InvoiceMasterID ");
strSqlBuilder.Append(" AND cst_FreightDetail.ProductID = ITM_Product.ProductID ");
strSqlBuilder.Append(" AND cst_FreightMaster.ACPurposeID = 4 ");
strSqlBuilder.Append(" ) as DebitAmount, ");
strSqlBuilder.Append(" ( ");
strSqlBuilder.Append(" SELECT ISNULL(SUM(cst_FreightDetail.VATAmount), 0) ");
strSqlBuilder.Append(" FROM PO_PurchaseOrderReceiptMaster ");
strSqlBuilder.Append(" INNER JOIN cst_FreightMaster ON cst_FreightMaster.PurchaseOrderReceiptID = PO_PurchaseOrderReceiptMaster.PurchaseOrderReceiptID ");
strSqlBuilder.Append(" INNER JOIN cst_FreightDetail ON cst_FreightDetail.FreightMasterID = cst_FreightMaster.FreightMasterID ");
strSqlBuilder.Append(" WHERE PO_PurchaseOrderReceiptMaster.InvoiceMasterID = PO_InvoiceMaster.InvoiceMasterID ");
strSqlBuilder.Append(" AND cst_FreightDetail.ProductID = ITM_Product.ProductID ");
strSqlBuilder.Append(" AND cst_FreightMaster.ACPurposeID = 4 ");
strSqlBuilder.Append(" ) as DebitVATAmount ");
strSqlBuilder.Append(" FROM PO_InvoiceMaster ");
strSqlBuilder.Append(" INNER JOIN MST_Currency ON MST_Currency.CurrencyID = PO_InvoiceMaster.CurrencyID ");
strSqlBuilder.Append(" INNER JOIN MST_Party ON PO_InvoiceMaster.PartyID = MST_Party.PartyID ");
strSqlBuilder.Append(" INNER JOIN PO_InvoiceDetail ON PO_InvoiceMaster.InvoiceMasterID = PO_InvoiceDetail.InvoiceMasterID ");
strSqlBuilder.Append(" INNER JOIN ITM_Product ON PO_InvoiceDetail.ProductID = ITM_Product.ProductID ");
strSqlBuilder.Append(" INNER JOIN MST_UnitOfMeasure ON MST_UnitOfMeasure.UnitOfMeasureID = PO_InvoiceDetail.InvoiceUMID ");
strSqlBuilder.Append(" LEFT JOIN ITM_Category ON ITM_Product.CategoryID = ITM_Category.CategoryID");
strSqlBuilder.Append(" WHERE PO_InvoiceMaster.CCNID = " + pstrCCNID);
//From date
if(pstrFromDate != string.Empty && pstrFromDate != null)
{
strSqlBuilder.Append(" AND PO_InvoiceMaster.PostDate >= '" + pstrFromDate + "'");
}
//To date
if(pstrToDate != string.Empty && pstrToDate != null)
{
strSqlBuilder.Append(" AND PO_InvoiceMaster.PostDate <= '" + pstrToDate + "'");
}
//Currency List
if(pstrCurrencyIDList != string.Empty && pstrCurrencyIDList != null)
{
strSqlBuilder.Append(" AND PO_InvoiceMaster.CurrencyID IN (" + pstrCurrencyIDList + ")");
}
strSqlBuilder.Append(" GROUP BY ");
strSqlBuilder.Append(" PO_InvoiceMaster.PostDate,");
strSqlBuilder.Append(" PO_InvoiceMaster.InvoiceMasterID,");
strSqlBuilder.Append(" PO_InvoiceMaster.InvoiceNo,");
strSqlBuilder.Append(" MST_Currency.Code,");
strSqlBuilder.Append(" PO_InvoiceMaster.ExchangeRate,");
strSqlBuilder.Append(" MST_Party.Code,");
strSqlBuilder.Append(" MST_Party.Name,");
strSqlBuilder.Append(" PO_InvoiceDetail.UnitPrice,");
strSqlBuilder.Append(" ITM_Product.ProductID,");
strSqlBuilder.Append(" ITM_Product.Code,");
strSqlBuilder.Append(" ITM_Product.Description, ");
strSqlBuilder.Append(" ITM_Product.Revision,");
strSqlBuilder.Append(" MST_UnitOfMeasure.Code,");
strSqlBuilder.Append(" ITM_Category.Code");
//Write SQL string for debugging
Console.WriteLine(strSqlBuilder.ToString());
oconPCS = new OleDbConnection(mConnectionString);
ocmdPCS = new OleDbCommand(strSqlBuilder.ToString(), oconPCS);
ocmdPCS.CommandTimeout = 1000;
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dtbResult);
return dtbResult;
}
/// <summary>
/// Get CCN Info
/// </summary>
/// <param name="pstrID"></param>
/// <returns></returns>
private string GetCompanyFullName()
{
const string FULL_COMPANY_NAME = "CompanyFullName";
OleDbConnection oconPCS = null;
try
{
string strResult = string.Empty;
OleDbDataReader odrPCS = null;
OleDbCommand ocmdPCS = null;
string strSql = "SELECT [Value]"
+ " FROM Sys_Param"
+ " WHERE [Name] = '" + FULL_COMPANY_NAME + "'";
oconPCS = new OleDbConnection(mConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
odrPCS = ocmdPCS.ExecuteReader();
if(odrPCS != null)
{
if(odrPCS.Read())
{
strResult = odrPCS["Value"].ToString().Trim();
}
}
return strResult;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
oconPCS.Close();
oconPCS = null;
}
}
}
/// <summary>
/// Get CCN Info
/// </summary>
/// <param name="pstrID"></param>
/// <returns></returns>
private string GetCCNInfoByID(string pstrID)
{
string strResult = string.Empty;
OleDbConnection oconPCS = null;
try
{
OleDbDataReader odrPCS = null;
OleDbCommand ocmdPCS = null;
string strSql = "SELECT " + PRODUCT_CODE_FLD + ", " + PRODUCT_NAME_FLD
+ " FROM MST_CCN"
+ " WHERE MST_CCN.CCNID = " + pstrID;
oconPCS = new OleDbConnection(mConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
odrPCS = ocmdPCS.ExecuteReader();
if(odrPCS != null)
{
if(odrPCS.Read())
{
strResult = odrPCS[PRODUCT_CODE_FLD].ToString().Trim() + " (" + odrPCS[PRODUCT_NAME_FLD].ToString().Trim() + ")";
}
}
return strResult;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
oconPCS.Close();
oconPCS = null;
}
}
}
/// <summary>
/// Get PO Receipt Info
/// </summary>
/// <param name="pstrID"></param>
/// <returns></returns>
private string GetPOReceiptType(string pstrID)
{
string strResult = string.Empty;
OleDbDataReader odrPCS = null;
OleDbConnection oconPCS = null;
try
{
OleDbCommand ocmdPCS = null;
string strSql = "SELECT Description as " + PRODUCT_NAME_FLD;
strSql += " FROM enm_POReceiptType";
strSql += " WHERE POReceiptTypeCode = " + pstrID;
oconPCS = new OleDbConnection(mConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
odrPCS = ocmdPCS.ExecuteReader();
if(odrPCS != null)
{
if(odrPCS.Read())
{
strResult = odrPCS[PRODUCT_NAME_FLD].ToString().Trim();
}
}
return strResult;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
oconPCS.Close();
oconPCS = null;
}
}
}
/// <summary>
/// Get Location Info
/// </summary>
/// <param name="pstrID"></param>
/// <returns></returns>
private string GetCurrencyInfo(string pstrIDList)
{
const string SEMI_COLON = "; ";
string strResult = string.Empty;
OleDbDataReader odrPCS = null;
OleDbConnection oconPCS = null;
try
{
OleDbCommand ocmdPCS = null;
string strSql = "SELECT Code";
strSql += " FROM MST_Currency";
strSql += " WHERE CurrencyID IN (" + pstrIDList + ")";
oconPCS = new OleDbConnection(mConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
odrPCS = ocmdPCS.ExecuteReader();
if(odrPCS != null)
{
while(odrPCS.Read())
{
strResult += odrPCS[PRODUCT_CODE_FLD].ToString().Trim() + SEMI_COLON;
}
}
if(strResult.Length > 250)
{
int i = strResult.IndexOf(SEMI_COLON, 250);
if(i > 0)
{
strResult = strResult.Substring(0, i + SEMI_COLON.Length) + "...";
}
}
return strResult;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
oconPCS.Close();
oconPCS = null;
}
}
}
#endregion Delivery To Customer Schedule Report: Tuan TQ
#region Public Method
public object Invoke(string pstrMethod, object[] pobjParameters)
{
return this.GetType().InvokeMember(pstrMethod, BindingFlags.InvokeMethod, null, this, pobjParameters);
}
/// <summary>
/// Build and show Detai lItem Price By PO Receipt
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// <author> Tuan TQ, 11 Apr, 2006</author>
public DataTable ExecuteReport(string pstrCCNID,
string pstrFromDate,
string pstrToDate,
string pstrCurrencyIDList
)
{
try
{
string strPOTypeID = Convert.ToString((int)PCSComUtils.Common.POReceiptTypeEnum.ByInvoice);
const string DATE_HOUR_FORMAT = "dd-MM-yyyy HH:mm";
const string NUMERIC_FORMAT = "#,##0.00";
const string REPORT_TEMPLATE = "ImportMaterialReport.xml";
const string RPT_PAGE_HEADER = "PageHeader";
const string REPORT_NAME = "ImportMaterialReport";
const string RPT_TITLE_FLD = "fldTitle";
const string RPT_COMPANY_FLD = "fldCompany";
const string RPT_CCN_FLD = "CCN";
const string RPT_FROM_DATE_FLD = "From Date";
const string RPT_TO_DATE_FLD = "To Date";
const string RPT_CURRENCY_FLD = "Currency";
DataTable dtbDataSource = null;
dtbDataSource = GetImportMaterialReport(pstrCCNID, pstrFromDate, pstrToDate, pstrCurrencyIDList);
//Create builder object
ReportWithSubReportBuilder reportBuilder = new ReportWithSubReportBuilder();
//Set report name
reportBuilder.ReportName = REPORT_NAME;
//Set Datasource
reportBuilder.SourceDataTable = dtbDataSource;
//Set report layout location
reportBuilder.ReportDefinitionFolder = mstrReportDefinitionFolder;
reportBuilder.ReportLayoutFile = REPORT_TEMPLATE;
reportBuilder.UseLayoutFile = true;
reportBuilder.MakeDataTableForRender();
// and show it in preview dialog
PCSUtils.Framework.ReportFrame.C1PrintPreviewDialog printPreview = new PCSUtils.Framework.ReportFrame.C1PrintPreviewDialog();
//Attach report viewer
reportBuilder.ReportViewer = printPreview.ReportViewer;
reportBuilder.RenderReport();
reportBuilder.DrawPredefinedField(RPT_COMPANY_FLD, GetCompanyFullName());
//Draw parameters
System.Collections.Specialized.NameValueCollection arrParamAndValue = new System.Collections.Specialized.NameValueCollection();
arrParamAndValue.Add(RPT_CCN_FLD, GetCCNInfoByID(pstrCCNID));
if(pstrFromDate != null && pstrFromDate != string.Empty)
{
arrParamAndValue.Add(RPT_FROM_DATE_FLD, DateTime.Parse(pstrFromDate).ToString(DATE_HOUR_FORMAT));
}
if(pstrToDate != null && pstrToDate != string.Empty)
{
arrParamAndValue.Add(RPT_TO_DATE_FLD, DateTime.Parse(pstrToDate).ToString(DATE_HOUR_FORMAT));
}
if(pstrCurrencyIDList != null && pstrCurrencyIDList != string.Empty)
{
arrParamAndValue.Add(RPT_CURRENCY_FLD, GetCurrencyInfo(pstrCurrencyIDList));
}
//Anchor the Parameter drawing canvas cordinate to the fldTitle
C1.C1Report.Field fldTitle = reportBuilder.GetFieldByName(RPT_TITLE_FLD);
double dblStartX = fldTitle.Left;
double dblStartY = fldTitle.Top + 1.3 * fldTitle.RenderHeight;
reportBuilder.GetSectionByName(RPT_PAGE_HEADER).CanGrow = true;
reportBuilder.DrawParameters(reportBuilder.GetSectionByName(RPT_PAGE_HEADER), dblStartX, dblStartY, arrParamAndValue, reportBuilder.Report.Font.Size);
try
{
printPreview.FormTitle = reportBuilder.GetFieldByName(RPT_TITLE_FLD).Text;
}
catch
{}
reportBuilder.RefreshReport();
printPreview.Show();
//return table
return dtbDataSource;
}
catch (Exception ex)
{
throw ex;
}
}
#endregion Public Method
}
}
| |
#region Header
// Copyright (C) 2012 Daniel Schubert
//
// 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 Header
using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Runtime.Remoting;
using System.Text;
using System.Timers;
using Remoting.Core.Events;
using Remoting.Core.Exceptions;
namespace Remoting.Core
{
public class RemoteService : MarshalByRefObject, IRemoteService, IDisposable
{
#region Fields
private bool disposed = false;
private Dictionary<string, EventProxy> proxies = new Dictionary<string, EventProxy>();
private Timer timer;
#endregion Fields
#region Constructors
public RemoteService()
{
timer = new Timer(1000);
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
timer.Interval = 1000;
timer.Enabled = true;
}
~RemoteService()
{
Dispose(false);
}
#endregion Constructors
#region Events
public event EventHandler<ClientAddedEventArgs> ClientAdded;
public event EventHandler<ClientRemovedEventArgs> ClientRemoved;
public event EventHandler<MessageReceivedEventArgs> MessageReceived;
#endregion Events
#region Properties
protected virtual IEnumerable<MarshalByRefObject> NestedMarshalByRefObjects
{
get { yield break; }
}
#endregion Properties
#region Methods
// called from client to publish a messsage
public void DispatchCall(EventProxy proxy, Object data)
{
lock (this)
{
if (!proxies.ContainsKey(proxy.Sink))
{
OnClientAdded(new ClientAddedEventArgs(proxy.Sink));
}
proxies[proxy.Sink] = proxy;
OnMessageReceived(new MessageReceivedEventArgs(proxy.Sink, data));
}
}
// called from server/client to send client an event
public void DispatchEvent(String sink, Object data)
{
lock (this)
{
try
{
if (proxies.ContainsKey(sink))
{
EventProxy proxy = proxies[sink];
proxy.DispatchEvent(new EventDispatchedEventArgs(sink, data));
}
else
{
throw new SinkNotFoundException("Sink not found!", sink);
}
}
catch (SocketException)
{
proxies.Remove(sink);
OnClientRemoved(new ClientRemovedEventArgs(sink));
throw new SinkNotFoundException("Sink not found!", sink);
}
}
}
public void Dispose()
{
GC.SuppressFinalize(this);
Dispose(true);
}
public override sealed object InitializeLifetimeService()
{
// indicate that this lease never expires
return null;
}
protected virtual void Dispose(bool disposing)
{
if (disposed)
{
return;
}
Disconnect();
disposed = true;
}
private void Disconnect()
{
RemotingServices.Disconnect(this);
foreach (MarshalByRefObject byRefObject in NestedMarshalByRefObjects)
{
RemotingServices.Disconnect(byRefObject);
}
}
private void OnClientAdded(ClientAddedEventArgs e)
{
if (ClientAdded != null)
{
// asynchronous event dispatching
ClientAdded.BeginInvoke(this, e, null, null);
}
}
private void OnClientRemoved(ClientRemovedEventArgs e)
{
if (ClientRemoved != null)
{
// asynchronous event dispatching
ClientRemoved.BeginInvoke(this, e, null, null);
}
}
private void OnMessageReceived(MessageReceivedEventArgs e)
{
if (MessageReceived != null)
{
// asynchronous event dispatching
MessageReceived.BeginInvoke(this, e, null, null);
}
}
private void RemoveDanglingRemoteObjects()
{
lock (this)
{
List<string> keys = new List<string>();
// find keys to delete
foreach (string key in proxies.Keys)
{
try
{
// dummy read on proxy object to trigger exception
string sink = proxies[key].Sink;
}
catch (SocketException)
{
keys.Add(key);
}
}
// then modify dictionary
foreach (string key in keys)
{
proxies.Remove(key);
OnClientRemoved(new ClientRemovedEventArgs(key));
}
}
}
void timer_Elapsed(object sender, ElapsedEventArgs e)
{
RemoveDanglingRemoteObjects();
}
#endregion Methods
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.2.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.ContainerInstance
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for ContainerGroupsOperations.
/// </summary>
public static partial class ContainerGroupsOperationsExtensions
{
/// <summary>
/// Get the list of container groups in a given subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<ContainerGroup> List(this IContainerGroupsOperations operations)
{
return operations.ListAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Get the list of container groups in a given subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<ContainerGroup>> ListAsync(this IContainerGroupsOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get the list of container groups in a given resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Azure resource group name
/// </param>
public static IPage<ContainerGroup> ListByResourceGroup(this IContainerGroupsOperations operations, string resourceGroupName)
{
return operations.ListByResourceGroupAsync(resourceGroupName).GetAwaiter().GetResult();
}
/// <summary>
/// Get the list of container groups in a given resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Azure resource group name
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<ContainerGroup>> ListByResourceGroupAsync(this IContainerGroupsOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByResourceGroupWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get details for this container group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Azure resource group name
/// </param>
/// <param name='containerGroupName'>
/// Container group name
/// </param>
public static ContainerGroup Get(this IContainerGroupsOperations operations, string resourceGroupName, string containerGroupName)
{
return operations.GetAsync(resourceGroupName, containerGroupName).GetAwaiter().GetResult();
}
/// <summary>
/// Get details for this container group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Azure resource group name
/// </param>
/// <param name='containerGroupName'>
/// Container group name
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ContainerGroup> GetAsync(this IContainerGroupsOperations operations, string resourceGroupName, string containerGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, containerGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Create or update container groups.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Azure resource group name
/// </param>
/// <param name='containerGroupName'>
/// Container group name
/// </param>
/// <param name='containerGroup'>
/// Definition of the container to be created.
/// </param>
public static ContainerGroup CreateOrUpdate(this IContainerGroupsOperations operations, string resourceGroupName, string containerGroupName, ContainerGroup containerGroup)
{
return operations.CreateOrUpdateAsync(resourceGroupName, containerGroupName, containerGroup).GetAwaiter().GetResult();
}
/// <summary>
/// Create or update container groups.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Azure resource group name
/// </param>
/// <param name='containerGroupName'>
/// Container group name
/// </param>
/// <param name='containerGroup'>
/// Definition of the container to be created.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ContainerGroup> CreateOrUpdateAsync(this IContainerGroupsOperations operations, string resourceGroupName, string containerGroupName, ContainerGroup containerGroup, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, containerGroupName, containerGroup, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Delete container groups.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Azure resource group name
/// </param>
/// <param name='containerGroupName'>
/// Name of the container group to be deleted
/// </param>
public static ContainerGroup Delete(this IContainerGroupsOperations operations, string resourceGroupName, string containerGroupName)
{
return operations.DeleteAsync(resourceGroupName, containerGroupName).GetAwaiter().GetResult();
}
/// <summary>
/// Delete container groups.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Azure resource group name
/// </param>
/// <param name='containerGroupName'>
/// Name of the container group to be deleted
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ContainerGroup> DeleteAsync(this IContainerGroupsOperations operations, string resourceGroupName, string containerGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.DeleteWithHttpMessagesAsync(resourceGroupName, containerGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get the list of container groups in a given subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<ContainerGroup> ListNext(this IContainerGroupsOperations operations, string nextPageLink)
{
return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Get the list of container groups in a given subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<ContainerGroup>> ListNextAsync(this IContainerGroupsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get the list of container groups in a given resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<ContainerGroup> ListByResourceGroupNext(this IContainerGroupsOperations operations, string nextPageLink)
{
return operations.ListByResourceGroupNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Get the list of container groups in a given resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<ContainerGroup>> ListByResourceGroupNextAsync(this IContainerGroupsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByResourceGroupNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: POGOProtos/Networking/Requests/Messages/GetGymDetailsMessage.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 POGOProtos.Networking.Requests.Messages {
/// <summary>Holder for reflection information generated from POGOProtos/Networking/Requests/Messages/GetGymDetailsMessage.proto</summary>
public static partial class GetGymDetailsMessageReflection {
#region Descriptor
/// <summary>File descriptor for POGOProtos/Networking/Requests/Messages/GetGymDetailsMessage.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static GetGymDetailsMessageReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CkJQT0dPUHJvdG9zL05ldHdvcmtpbmcvUmVxdWVzdHMvTWVzc2FnZXMvR2V0",
"R3ltRGV0YWlsc01lc3NhZ2UucHJvdG8SJ1BPR09Qcm90b3MuTmV0d29ya2lu",
"Zy5SZXF1ZXN0cy5NZXNzYWdlcyKeAQoUR2V0R3ltRGV0YWlsc01lc3NhZ2US",
"DgoGZ3ltX2lkGAEgASgJEhcKD3BsYXllcl9sYXRpdHVkZRgCIAEoARIYChBw",
"bGF5ZXJfbG9uZ2l0dWRlGAMgASgBEhQKDGd5bV9sYXRpdHVkZRgEIAEoARIV",
"Cg1neW1fbG9uZ2l0dWRlGAUgASgBEhYKDmNsaWVudF92ZXJzaW9uGAYgASgJ",
"YgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Networking.Requests.Messages.GetGymDetailsMessage), global::POGOProtos.Networking.Requests.Messages.GetGymDetailsMessage.Parser, new[]{ "GymId", "PlayerLatitude", "PlayerLongitude", "GymLatitude", "GymLongitude", "ClientVersion" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class GetGymDetailsMessage : pb::IMessage<GetGymDetailsMessage> {
private static readonly pb::MessageParser<GetGymDetailsMessage> _parser = new pb::MessageParser<GetGymDetailsMessage>(() => new GetGymDetailsMessage());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<GetGymDetailsMessage> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::POGOProtos.Networking.Requests.Messages.GetGymDetailsMessageReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetGymDetailsMessage() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetGymDetailsMessage(GetGymDetailsMessage other) : this() {
gymId_ = other.gymId_;
playerLatitude_ = other.playerLatitude_;
playerLongitude_ = other.playerLongitude_;
gymLatitude_ = other.gymLatitude_;
gymLongitude_ = other.gymLongitude_;
clientVersion_ = other.clientVersion_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetGymDetailsMessage Clone() {
return new GetGymDetailsMessage(this);
}
/// <summary>Field number for the "gym_id" field.</summary>
public const int GymIdFieldNumber = 1;
private string gymId_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string GymId {
get { return gymId_; }
set {
gymId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "player_latitude" field.</summary>
public const int PlayerLatitudeFieldNumber = 2;
private double playerLatitude_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public double PlayerLatitude {
get { return playerLatitude_; }
set {
playerLatitude_ = value;
}
}
/// <summary>Field number for the "player_longitude" field.</summary>
public const int PlayerLongitudeFieldNumber = 3;
private double playerLongitude_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public double PlayerLongitude {
get { return playerLongitude_; }
set {
playerLongitude_ = value;
}
}
/// <summary>Field number for the "gym_latitude" field.</summary>
public const int GymLatitudeFieldNumber = 4;
private double gymLatitude_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public double GymLatitude {
get { return gymLatitude_; }
set {
gymLatitude_ = value;
}
}
/// <summary>Field number for the "gym_longitude" field.</summary>
public const int GymLongitudeFieldNumber = 5;
private double gymLongitude_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public double GymLongitude {
get { return gymLongitude_; }
set {
gymLongitude_ = value;
}
}
/// <summary>Field number for the "client_version" field.</summary>
public const int ClientVersionFieldNumber = 6;
private string clientVersion_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string ClientVersion {
get { return clientVersion_; }
set {
clientVersion_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as GetGymDetailsMessage);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(GetGymDetailsMessage other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (GymId != other.GymId) return false;
if (PlayerLatitude != other.PlayerLatitude) return false;
if (PlayerLongitude != other.PlayerLongitude) return false;
if (GymLatitude != other.GymLatitude) return false;
if (GymLongitude != other.GymLongitude) return false;
if (ClientVersion != other.ClientVersion) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (GymId.Length != 0) hash ^= GymId.GetHashCode();
if (PlayerLatitude != 0D) hash ^= PlayerLatitude.GetHashCode();
if (PlayerLongitude != 0D) hash ^= PlayerLongitude.GetHashCode();
if (GymLatitude != 0D) hash ^= GymLatitude.GetHashCode();
if (GymLongitude != 0D) hash ^= GymLongitude.GetHashCode();
if (ClientVersion.Length != 0) hash ^= ClientVersion.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 (GymId.Length != 0) {
output.WriteRawTag(10);
output.WriteString(GymId);
}
if (PlayerLatitude != 0D) {
output.WriteRawTag(17);
output.WriteDouble(PlayerLatitude);
}
if (PlayerLongitude != 0D) {
output.WriteRawTag(25);
output.WriteDouble(PlayerLongitude);
}
if (GymLatitude != 0D) {
output.WriteRawTag(33);
output.WriteDouble(GymLatitude);
}
if (GymLongitude != 0D) {
output.WriteRawTag(41);
output.WriteDouble(GymLongitude);
}
if (ClientVersion.Length != 0) {
output.WriteRawTag(50);
output.WriteString(ClientVersion);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (GymId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(GymId);
}
if (PlayerLatitude != 0D) {
size += 1 + 8;
}
if (PlayerLongitude != 0D) {
size += 1 + 8;
}
if (GymLatitude != 0D) {
size += 1 + 8;
}
if (GymLongitude != 0D) {
size += 1 + 8;
}
if (ClientVersion.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(ClientVersion);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(GetGymDetailsMessage other) {
if (other == null) {
return;
}
if (other.GymId.Length != 0) {
GymId = other.GymId;
}
if (other.PlayerLatitude != 0D) {
PlayerLatitude = other.PlayerLatitude;
}
if (other.PlayerLongitude != 0D) {
PlayerLongitude = other.PlayerLongitude;
}
if (other.GymLatitude != 0D) {
GymLatitude = other.GymLatitude;
}
if (other.GymLongitude != 0D) {
GymLongitude = other.GymLongitude;
}
if (other.ClientVersion.Length != 0) {
ClientVersion = other.ClientVersion;
}
}
[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: {
GymId = input.ReadString();
break;
}
case 17: {
PlayerLatitude = input.ReadDouble();
break;
}
case 25: {
PlayerLongitude = input.ReadDouble();
break;
}
case 33: {
GymLatitude = input.ReadDouble();
break;
}
case 41: {
GymLongitude = input.ReadDouble();
break;
}
case 50: {
ClientVersion = input.ReadString();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
using System;
using System.Linq;
using VaultAtlas.FlacAtlas;
using VaultAtlas.Properties;
using VaultAtlas.DataModel.ModelUI;
using VaultAtlas.DataModel;
using VaultAtlas.UI;
using VaultAtlas.UI.Controls;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
using System.IO;
namespace VaultAtlas
{
public class MainForm : System.Windows.Forms.Form, IPlugInEnvironment
{
private System.Windows.Forms.StatusBar statusBar1;
private System.Windows.Forms.StatusBarPanel statusBarPanel1;
private System.Windows.Forms.StatusBarPanel statusBarPanelLineNumber;
private System.Windows.Forms.StatusBarPanel statusBarPanelContent;
private IContainer components;
private static char[] digits = "1234567890".ToCharArray();
private System.Windows.Forms.MenuItem menuItem41;
private DataExplorer dataExplorer1;
private TabControl tabSearch;
private TabPage tabPage1;
private ImageList imageList1;
private MenuItem menuMatchFlacAtlas;
private readonly IList<Show> _recentlyEdited = new List<Show>( 5 );
private System.Windows.Forms.MenuItem menuItem1;
private System.Windows.Forms.MenuItem menuItem3;
private System.Windows.Forms.MenuItem menuExit;
private System.Windows.Forms.MenuItem menuItem8;
private System.Windows.Forms.MenuItem menuItem21;
private System.Windows.Forms.MenuItem menuItem22;
private System.Windows.Forms.MenuItem menuItem24;
private ShowListMenuItem MenuItem_RecentlyEdited;
private System.Windows.Forms.MenuItem menuItem28;
private System.Windows.Forms.MenuItem menuItem9;
private System.Windows.Forms.MenuItem menuItem23;
private System.Windows.Forms.MenuItem menuItem10;
private System.Windows.Forms.MenuItem menuItem19;
private System.Windows.Forms.MenuItem menuItem15;
private TabPage tabPageDiscs;
private FlacAtlasControl flacAtlasControl1;
private TabPage tabPage2;
private SearchControl searchControl1;
private MenuItem menuImportDisc;
private MenuItem menuItemImportHardDrive;
private MenuItem menuItem2;
private System.Windows.Forms.MainMenu mainMenu1;
public IList<Show> RecentlyEdited
{
get
{
return this._recentlyEdited;
}
}
public MainForm()
{
InitializeComponent();
VaultAtlasApplication.MainForm = this;
VaultAtlasApplication.Model.PlugInManager.LoadPlugIn( new BuiltInPlugIn());
this.Load += MainForm_Load;
this.Focus();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
this.statusBar1 = new System.Windows.Forms.StatusBar();
this.statusBarPanel1 = new System.Windows.Forms.StatusBarPanel();
this.statusBarPanelContent = new System.Windows.Forms.StatusBarPanel();
this.statusBarPanelLineNumber = new System.Windows.Forms.StatusBarPanel();
this.menuItem1 = new System.Windows.Forms.MenuItem();
this.menuExit = new System.Windows.Forms.MenuItem();
this.menuItem8 = new System.Windows.Forms.MenuItem();
this.menuItem21 = new System.Windows.Forms.MenuItem();
this.menuItem22 = new System.Windows.Forms.MenuItem();
this.menuItem24 = new System.Windows.Forms.MenuItem();
this.MenuItem_RecentlyEdited = new VaultAtlas.UI.Controls.ShowListMenuItem();
this.menuItem28 = new System.Windows.Forms.MenuItem();
this.menuItem9 = new System.Windows.Forms.MenuItem();
this.menuItem23 = new System.Windows.Forms.MenuItem();
this.menuImportDisc = new System.Windows.Forms.MenuItem();
this.menuItemImportHardDrive = new System.Windows.Forms.MenuItem();
this.menuItem2 = new System.Windows.Forms.MenuItem();
this.menuItem10 = new System.Windows.Forms.MenuItem();
this.menuItem19 = new System.Windows.Forms.MenuItem();
this.menuItem41 = new System.Windows.Forms.MenuItem();
this.menuItem15 = new System.Windows.Forms.MenuItem();
this.menuMatchFlacAtlas = new System.Windows.Forms.MenuItem();
this.mainMenu1 = new System.Windows.Forms.MainMenu(this.components);
this.tabSearch = new System.Windows.Forms.TabControl();
this.tabPage1 = new System.Windows.Forms.TabPage();
this.dataExplorer1 = new VaultAtlas.UI.Controls.DataExplorer();
this.tabPageDiscs = new System.Windows.Forms.TabPage();
this.flacAtlasControl1 = new VaultAtlas.FlacAtlas.FlacAtlasControl();
this.tabPage2 = new System.Windows.Forms.TabPage();
this.searchControl1 = new VaultAtlas.UI.SearchControl();
this.imageList1 = new System.Windows.Forms.ImageList(this.components);
((System.ComponentModel.ISupportInitialize)(this.statusBarPanel1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.statusBarPanelContent)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.statusBarPanelLineNumber)).BeginInit();
this.tabSearch.SuspendLayout();
this.tabPage1.SuspendLayout();
this.tabPageDiscs.SuspendLayout();
this.tabPage2.SuspendLayout();
this.SuspendLayout();
//
// statusBar1
//
resources.ApplyResources(this.statusBar1, "statusBar1");
this.statusBar1.Name = "statusBar1";
this.statusBar1.Panels.AddRange(new System.Windows.Forms.StatusBarPanel[] {
this.statusBarPanel1,
this.statusBarPanelContent,
this.statusBarPanelLineNumber});
this.statusBar1.ShowPanels = true;
this.statusBar1.SizingGrip = false;
//
// statusBarPanel1
//
resources.ApplyResources(this.statusBarPanel1, "statusBarPanel1");
//
// statusBarPanelContent
//
resources.ApplyResources(this.statusBarPanelContent, "statusBarPanelContent");
//
// statusBarPanelLineNumber
//
resources.ApplyResources(this.statusBarPanelLineNumber, "statusBarPanelLineNumber");
//
// menuItem1
//
this.menuItem1.Index = 0;
this.menuItem1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuExit});
resources.ApplyResources(this.menuItem1, "menuItem1");
//
// menuExit
//
this.menuExit.Index = 0;
resources.ApplyResources(this.menuExit, "menuExit");
this.menuExit.Click += new System.EventHandler(this.menuExit_Click);
//
// menuItem8
//
this.menuItem8.Index = 1;
this.menuItem8.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItem21,
this.menuItem22});
resources.ApplyResources(this.menuItem8, "menuItem8");
//
// menuItem21
//
resources.ApplyResources(this.menuItem21, "menuItem21");
this.menuItem21.Index = 0;
this.menuItem21.Click += new System.EventHandler(this.menuItem21_Click);
//
// menuItem22
//
resources.ApplyResources(this.menuItem22, "menuItem22");
this.menuItem22.Index = 1;
this.menuItem22.Click += new System.EventHandler(this.menuItem22_Click);
//
// menuItem24
//
this.menuItem24.Index = 2;
this.menuItem24.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.MenuItem_RecentlyEdited,
this.menuItem28,
this.menuItem9,
this.menuItem23,
this.menuImportDisc,
this.menuItemImportHardDrive,
this.menuItem2});
resources.ApplyResources(this.menuItem24, "menuItem24");
//
// MenuItem_RecentlyEdited
//
this.MenuItem_RecentlyEdited.Index = 0;
this.MenuItem_RecentlyEdited.ShowList = null;
resources.ApplyResources(this.MenuItem_RecentlyEdited, "MenuItem_RecentlyEdited");
//
// menuItem28
//
this.menuItem28.Index = 1;
resources.ApplyResources(this.menuItem28, "menuItem28");
//
// menuItem9
//
this.menuItem9.Index = 2;
resources.ApplyResources(this.menuItem9, "menuItem9");
this.menuItem9.Click += new System.EventHandler(this.menuItem9_Click);
//
// menuItem23
//
this.menuItem23.Index = 3;
resources.ApplyResources(this.menuItem23, "menuItem23");
this.menuItem23.Click += new System.EventHandler(this.menuItem23_Click);
//
// menuImportDisc
//
this.menuImportDisc.Index = 4;
resources.ApplyResources(this.menuImportDisc, "menuImportDisc");
this.menuImportDisc.Click += new System.EventHandler(this.menuImportDisc_Click);
//
// menuItemImportHardDrive
//
this.menuItemImportHardDrive.Index = 5;
resources.ApplyResources(this.menuItemImportHardDrive, "menuItemImportHardDrive");
this.menuItemImportHardDrive.Click += new System.EventHandler(this.menuItemImportHardDrive_Click);
//
// menuItem2
//
this.menuItem2.Index = 6;
resources.ApplyResources(this.menuItem2, "menuItem2");
this.menuItem2.Click += new System.EventHandler(this.menuItem2_Click);
//
// menuItem10
//
this.menuItem10.Index = 3;
this.menuItem10.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItem19,
this.menuItem41,
this.menuItem15,
this.menuMatchFlacAtlas});
resources.ApplyResources(this.menuItem10, "menuItem10");
this.menuItem10.Click += new System.EventHandler(this.menuItem10_Click);
//
// menuItem19
//
this.menuItem19.Index = 0;
resources.ApplyResources(this.menuItem19, "menuItem19");
this.menuItem19.Click += new System.EventHandler(this.menuItem19_Click);
//
// menuItem41
//
this.menuItem41.Index = 1;
resources.ApplyResources(this.menuItem41, "menuItem41");
this.menuItem41.Click += new System.EventHandler(this.menuItem41_Click);
//
// menuItem15
//
this.menuItem15.Index = 2;
resources.ApplyResources(this.menuItem15, "menuItem15");
this.menuItem15.Click += new System.EventHandler(this.menuItem15_Click);
//
// menuMatchFlacAtlas
//
this.menuMatchFlacAtlas.Index = 3;
resources.ApplyResources(this.menuMatchFlacAtlas, "menuMatchFlacAtlas");
this.menuMatchFlacAtlas.Click += new System.EventHandler(this.menuMatchFlacAtlas_Click);
//
// mainMenu1
//
this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItem1,
this.menuItem8,
this.menuItem24,
this.menuItem10});
//
// tabSearch
//
resources.ApplyResources(this.tabSearch, "tabSearch");
this.tabSearch.Controls.Add(this.tabPage1);
this.tabSearch.Controls.Add(this.tabPageDiscs);
this.tabSearch.Controls.Add(this.tabPage2);
this.tabSearch.ImageList = this.imageList1;
this.tabSearch.Name = "tabSearch";
this.tabSearch.SelectedIndex = 0;
//
// tabPage1
//
this.tabPage1.BackColor = System.Drawing.Color.White;
this.tabPage1.Controls.Add(this.dataExplorer1);
resources.ApplyResources(this.tabPage1, "tabPage1");
this.tabPage1.Name = "tabPage1";
this.tabPage1.UseVisualStyleBackColor = true;
//
// dataExplorer1
//
this.dataExplorer1.BackColor = System.Drawing.Color.White;
this.dataExplorer1.DataSource = null;
resources.ApplyResources(this.dataExplorer1, "dataExplorer1");
this.dataExplorer1.Name = "dataExplorer1";
this.dataExplorer1.RowNumber = -1;
//
// tabPageDiscs
//
this.tabPageDiscs.Controls.Add(this.flacAtlasControl1);
resources.ApplyResources(this.tabPageDiscs, "tabPageDiscs");
this.tabPageDiscs.Name = "tabPageDiscs";
this.tabPageDiscs.UseVisualStyleBackColor = true;
//
// flacAtlasControl1
//
resources.ApplyResources(this.flacAtlasControl1, "flacAtlasControl1");
this.flacAtlasControl1.Name = "flacAtlasControl1";
//
// tabPage2
//
this.tabPage2.Controls.Add(this.searchControl1);
resources.ApplyResources(this.tabPage2, "tabPage2");
this.tabPage2.Name = "tabPage2";
this.tabPage2.UseVisualStyleBackColor = true;
//
// searchControl1
//
resources.ApplyResources(this.searchControl1, "searchControl1");
this.searchControl1.Name = "searchControl1";
//
// imageList1
//
this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream")));
this.imageList1.TransparentColor = System.Drawing.Color.Transparent;
this.imageList1.Images.SetKeyName(0, "Movie Document 16 h p.png");
this.imageList1.Images.SetKeyName(1, "Music Document 16 h p.png");
this.imageList1.Images.SetKeyName(2, "Organizer 16 h p.png");
//
// MainForm
//
resources.ApplyResources(this, "$this");
this.Controls.Add(this.tabSearch);
this.Controls.Add(this.statusBar1);
this.Menu = this.mainMenu1;
this.Name = "MainForm";
((System.ComponentModel.ISupportInitialize)(this.statusBarPanel1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.statusBarPanelContent)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.statusBarPanelLineNumber)).EndInit();
this.tabSearch.ResumeLayout(false);
this.tabPage1.ResumeLayout(false);
this.tabPageDiscs.ResumeLayout(false);
this.tabPage2.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
try
{
Application.DoEvents();
MainForm mf = new MainForm();
Application.Run( mf );
}
catch (Exception exc)
{
Console.WriteLine( exc.Message+" "+exc.StackTrace );
MessageBox.Show( exc.Message+" "+exc.StackTrace );
}
}
private void menuItem9_Click(object sender, EventArgs e)
{
try
{
VaultAtlasApplication.RequestEnterShow("", new ShowDate("????-??-??"), "");
}
catch (Exception exc)
{
MessageBox.Show(exc.Message +" - " +exc.StackTrace);
}
}
public void UpdateStatusBarPanelLineNumber()
{
BeginInvoke(new Action(delegate {
this.statusBarPanelLineNumber.Text = this.dataExplorer1.RowNumber + " : " + VaultAtlasApplication.Model.ShowView.Count;
}));
}
public void RequestCloseTab(Control ctl)
{
Control p = ctl;
while (p != null && !(p is TabPage))
p = p.Parent;
if (p is TabPage)
{
this.tabSearch.TabPages.Remove((TabPage)p);
}
}
private void menuExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void menuItem19_Click(object sender, EventArgs e)
{
var exp = new UI.Export.XMLExporter();
this.AddOwnedForm(exp);
exp.StartPosition = FormStartPosition.CenterParent;
exp.ShowDialog();
}
private void MainForm_Load(object sender, EventArgs e)
{
var fileDrop = new FileDrop( this );
fileDrop.FileDropped += FileDropped;
VaultAtlasApplication.Model.UndoRedoStatusChanged += Model_UndoRedoStatusChanged;
this.MenuItem_RecentlyEdited.ShowList = _recentlyEdited;
}
private void FileDropped( object sender, FileDropEventArgs e )
{
ShowDate date = ShowDate.Now;
Artist probableArtist = null;
try
{
string strippedFileName = Path.GetFileNameWithoutExtension( e.FileName );
int firstDot = strippedFileName.IndexOf(".");
if ( firstDot != -1 )
strippedFileName = strippedFileName.Substring( 0, firstDot );
int firstDigit = strippedFileName.IndexOfAny( digits );
// int firstSeparator = strippedFileName.IndexOfAny( separators );
string artistAbbrev = strippedFileName.Substring(0, firstDigit);
string probableDate = strippedFileName.Substring(firstDigit);
if (probableDate.Length > 2 && !probableDate.StartsWith("19") && !probableDate.StartsWith("20"))
{
if (Int32.Parse( probableDate.Substring(0,2) ) < 50)
probableDate = "20"+probableDate;
else
probableDate = "19"+probableDate;
}
if (probableDate.Length > 10)
probableDate = probableDate.Substring(0, 10);
date = ShowDate.Parse( probableDate );
probableArtist = VaultAtlasApplication.Model.Artists.FindByAbbreviation( artistAbbrev );
}
catch {}
var attr = File.GetAttributes(e.FileName);
var directory = ((attr & FileAttributes.Directory) == FileAttributes.Directory) ? e.FileName : Path.GetDirectoryName(e.FileName);
var mediaFileInfoProvider = new MediaFileInfoProvider(directory);
//detect whether its a directory or file
var resourceFileName = ((attr & FileAttributes.Directory) == FileAttributes.Directory) ? null : e.FileName;
//avoid loading very long files
if (resourceFileName != null)
{
if (new FileInfo(resourceFileName).Length > 30000)
resourceFileName = null;
}
VaultAtlasApplication.RequestEnterShow(probableArtist != null ? probableArtist.SortName : null, date, resourceFileName, mediaFileInfoProvider.ApplyToShow);
}
private IEnumerable<TabPage> FindContentAll(Type contentType)
{
return tabSearch.TabPages.Cast<TabPage>()
.Where(tabPage => tabPage.Tag != null && tabPage.Tag.GetType() == contentType);
}
public void RequestEditShow( int showIndex, Show show )
{
TabPage tabPage = null;
foreach (var tabP in this.FindContentAll(typeof(EditShow)))
{
if (((EditShow)tabP.Tag).EditedShow.UID.Equals(show.UID))
tabPage = tabP;
}
if ( tabPage == null )
{
tabPage = new TabPage();
var es = new EditShow();
es.Bind( showIndex, show);
tabPage.Controls.Add(es);
tabPage.Text = es.Text;
es.Dock = DockStyle.Fill;
tabPage.Tag = es;
tabPage.ImageIndex = 1;
this.tabSearch.TabPages.Add(tabPage);
}
this.tabSearch.SelectedTab = tabPage;
}
private void menuItem15_Click(object sender, EventArgs e)
{
var length = 0;
var countItems = 0;
foreach( var show in VaultAtlasApplication.Model.ShowView.Shows.Shows )
{
countItems++;
try
{
var showLength = show.Length;
if (showLength.EndsWith("'"))
length += Int32.Parse( showLength.Substring(0, showLength.Length-1 ));
else if (showLength.EndsWith(" DVD"))
length += 90*Int32.Parse( showLength.Substring(0, showLength.Length-4 ));
else if (showLength.EndsWith(" CD"))
length += 60*Int32.Parse(showLength.Substring(0, showLength.Length - 3));
else
{
int lengthInt;
if (Int32.TryParse(showLength, out lengthInt))
length += lengthInt;
}
}
catch
{
}
}
MessageBox.Show(string.Format(resources.ApproximatelyXHours, (length / 60)+"", countItems.ToString()));
}
private void Model_UndoRedoStatusChanged(object sender, DataModel.UndoRedo.UndoRedoStateEventArgs args)
{
this.Text = Constants.ApplicationName + (args.IsSaved ? "" : " *");
this.menuItem21.Enabled = args.CanUndo;
this.menuItem22.Enabled = args.CanRedo;
}
private void menuItem10_Click(object sender, System.EventArgs e)
{
}
private void menuItem21_Click(object sender, EventArgs e)
{
VaultAtlasApplication.Model.UndoRedoManager.UndoAction();
}
private void menuItem22_Click(object sender, EventArgs e)
{
VaultAtlasApplication.Model.UndoRedoManager.RedoAction();
}
private void menuItem41_Click(object sender, System.EventArgs e)
{
var export = new VaultAtlas.UI.Export.ExcelExporter();
var sfd = new SaveFileDialog();
sfd.Title = Resources.SaveFile;
if (sfd.ShowDialog() != DialogResult.OK)
return;
export.WriteExcelFile( sfd.FileName, false );
}
private void menuItem23_Click(object sender, EventArgs e)
{
VaultAtlasApplication.RequestEnterArtist("");
}
private void menuMatchFlacAtlas_Click(object sender, EventArgs e)
{
/* TODO
IProgressCallback progressCallback = null;
new ShowDirectoryMatcher().Match(async (path, show) =>
{
if (progressCallback == null)
progressCallback = flacAtlasControl1.GetProgressDialog();
var ddi = await flacAtlasControl1.ImportLocalFolderStructure(path, progressCallback).ConfigureAwait(false);
show.UidDirectory = ddi.UID;
});
Model.SingleModel.Shows.Adapter.Update(Model.SingleModel.Shows.Table);
*/
}
public Model Model
{
get { return Model.SingleModel; }
}
private void menuImportDisc_Click(object sender, EventArgs e)
{
flacAtlasControl1.ImportDisc().ConfigureAwait(false);
}
private void menuItemImportHardDrive_Click(object sender, EventArgs e)
{
flacAtlasControl1.ImportHardDrive();
}
private void menuItem2_Click(object sender, EventArgs e)
{
flacAtlasControl1.ImportLocalFolderStructure().ConfigureAwait(false);
}
}
}
| |
//! \file ArcHXP.cs
//! \date Sun Nov 08 18:04:58 2015
//! \brief SH System resource archive.
//
// Copyright (C) 2015 by morkt
//
// 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.ComponentModel.Composition;
using System.IO;
using System.Linq;
using GameRes.Utility;
using System.Text;
namespace GameRes.Formats.SHSystem
{
[Export(typeof(ArchiveFormat))]
public class Him4Opener : ArchiveFormat
{
public override string Tag { get { return "HIM4"; } }
public override string Description { get { return "SH System engine resource archive"; } }
public override uint Signature { get { return 0x346D6948; } } // 'Him4'
public override bool IsHierarchic { get { return false; } }
public override bool CanCreate { get { return false; } }
public Him4Opener ()
{
Signatures = new uint[] { 0x346D6948, 0x36534853 }; // 'Him4', 'SHS6'
Extensions = new string[] { "hxp" };
}
public override ArcFile TryOpen (ArcView file)
{
int count = file.View.ReadInt32 (4);
if (!IsSaneCount (count))
return null;
long next_offset = file.View.ReadUInt32 (8);
uint index_offset = 0xC;
var dir = new List<Entry> (count);
for (int i = 0; i < count; ++i)
{
if (next_offset > file.MaxOffset)
return null;
var entry = new PackedEntry {
Name = i.ToString ("D5"),
Offset = next_offset,
};
next_offset = i + 1 == count ? file.MaxOffset : file.View.ReadUInt32 (index_offset);
index_offset += 4;
entry.Size = (uint)(next_offset - entry.Offset);
dir.Add (entry);
}
DetectFileTypes (file, dir);
return new ArcFile (file, this, dir);
}
static protected void DetectFileTypes (ArcView file, List<Entry> dir)
{
byte[] signature_buffer = new byte[4];
foreach (var entry in dir.Cast<PackedEntry>())
{
uint packed_size = file.View.ReadUInt32 (entry.Offset);
uint unpacked_size = file.View.ReadUInt32 (entry.Offset+4);
if (0 == packed_size)
packed_size = unpacked_size;
entry.IsPacked = packed_size != unpacked_size;
entry.Size = packed_size;
entry.UnpackedSize = unpacked_size;
entry.Offset += 8;
uint signature;
if (entry.IsPacked)
{
using (var input = file.CreateStream (entry.Offset, Math.Min (packed_size, 0x20u)))
using (var reader = new ShsCompression (input))
{
reader.Unpack (signature_buffer);
signature = LittleEndian.ToUInt32 (signature_buffer, 0);
}
}
else
{
signature = file.View.ReadUInt32 (entry.Offset);
}
if (0 != signature)
{
IResource res;
if (0x4D42 == (signature & 0xFFFF))
res = ImageFormat.Bmp;
else if (0x020000 == signature || 0x0A0000 == signature)
res = ImageFormat.Tga;
else
res = FormatCatalog.Instance.LookupSignature (signature).FirstOrDefault();
if (res != null)
{
entry.Type = res.Type;
var ext = res.Extensions.FirstOrDefault();
if (!string.IsNullOrEmpty (ext))
entry.Name = Path.ChangeExtension (entry.Name, ext);
}
}
}
}
public override Stream OpenEntry (ArcFile arc, Entry entry)
{
var input = base.OpenEntry (arc, entry);
var pent = entry as PackedEntry;
if (null == pent || !pent.IsPacked)
return input;
var data = new byte[pent.UnpackedSize];
using (var reader = new ShsCompression (input))
{
reader.Unpack (data);
return new MemoryStream (data);
}
}
}
[Export(typeof(ArchiveFormat))]
public class Him5Opener : Him4Opener
{
public override string Tag { get { return "HIM5"; } }
public override string Description { get { return "SH System engine resource archive"; } }
public override uint Signature { get { return 0x356D6948; } } // 'Him5'
public override bool IsHierarchic { get { return false; } }
public override bool CanCreate { get { return false; } }
public Him5Opener ()
{
Signatures = new uint[] { 0x356D6948, 0x37534853 }; // 'Him5', 'SHS7'
Extensions = new string[] { "hxp" };
}
public override ArcFile TryOpen (ArcView file)
{
int version = file.View.ReadByte (3) - '0';
int count = file.View.ReadInt32 (4);
if (!IsSaneCount (count))
return null;
int index_offset = 8;
var index = new List<Tuple<int, int>> (count);
for (int i = 0; i < count; ++i)
{
int size = file.View.ReadInt32 (index_offset);
int offset = file.View.ReadInt32 (index_offset+4);
index_offset += 8;
if (size != 0)
index.Add (Tuple.Create (offset, size));
}
var dir = new List<Entry>();
foreach (var section in index)
{
index_offset = section.Item1;
for (int section_size = section.Item2; section_size > 0; )
{
int entry_size = file.View.ReadByte (index_offset);
if (entry_size < 5)
break;
var entry = new PackedEntry {
Offset = Binary.BigEndian (file.View.ReadUInt32 (index_offset+1)),
Name = file.View.ReadString (index_offset+5, (uint)entry_size-5),
};
if (entry.Offset > file.MaxOffset)
return null;
index_offset += entry_size;
section_size -= entry_size;
dir.Add (entry);
}
}
DetectFileTypes (file, dir);
return new ArcFile (file, this, dir);
}
}
internal class ShsCompression : IDisposable
{
BinaryReader m_input;
public ShsCompression (Stream input, bool leave_open = false)
{
m_input = new BinaryReader (input, Encoding.UTF8, leave_open);
}
public int Unpack (byte[] output)
{
int dst = 0;
while (dst < output.Length)
{
int count;
int ctl = m_input.ReadByte();
if (ctl < 32)
{
switch (ctl)
{
case 0x1D:
count = m_input.ReadByte() + 0x1E;
break;
case 0x1E:
count = Binary.BigEndian (m_input.ReadUInt16()) + 0x11E;
break;
case 0x1F:
count = Binary.BigEndian (m_input.ReadInt32());
break;
default:
count = ctl + 1;
break;
}
count = Math.Min (count, output.Length - dst);
m_input.Read (output, dst, count);
}
else
{
int offset;
if (0 == (ctl & 0x80))
{
if (0x20 == (ctl & 0x60))
{
offset = (ctl >> 2) & 7;
count = ctl & 3;
}
else
{
offset = m_input.ReadByte();
if (0x40 == (ctl & 0x60))
count = (ctl & 0x1F) + 4;
else
{
offset |= (ctl & 0x1F) << 8;
ctl = m_input.ReadByte();
if (0xFE == ctl)
count = Binary.BigEndian (m_input.ReadUInt16()) + 0x102;
else if (0xFF == ctl)
count = Binary.BigEndian (m_input.ReadInt32());
else
count = ctl + 4;
}
}
}
else
{
count = (ctl >> 5) & 3;
offset = ((ctl & 0x1F) << 8) | m_input.ReadByte();
}
count += 3;
offset++;
count = Math.Min (count, output.Length-dst);
Binary.CopyOverlapped (output, dst-offset, dst, count);
}
dst += count;
}
return dst;
}
#region IDisposable Members
bool m_disposed = false;
public void Dispose ()
{
if (!m_disposed)
{
m_input.Dispose();
m_disposed = true;
}
}
#endregion
}
}
| |
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Orleans.Configuration;
using Orleans.Configuration.Validators;
using Orleans.Runtime.Configuration;
using Orleans.Runtime.ConsistentRing;
using Orleans.Runtime.Counters;
using Orleans.Runtime.GrainDirectory;
using Orleans.Runtime.MembershipService;
using Orleans.Metadata;
using Orleans.Runtime.Messaging;
using Orleans.Runtime.Placement;
using Orleans.Runtime.Providers;
using Orleans.Runtime.ReminderService;
using Orleans.Runtime.Scheduler;
using Orleans.Runtime.Versions;
using Orleans.Runtime.Versions.Compatibility;
using Orleans.Runtime.Versions.Selector;
using Orleans.Serialization;
using Orleans.Statistics;
using Orleans.Timers;
using Orleans.Versions;
using Orleans.Versions.Compatibility;
using Orleans.Versions.Selector;
using Orleans.Providers;
using Orleans.Runtime;
using Microsoft.Extensions.Logging;
using Orleans.Runtime.Utilities;
using System;
using System.Reflection;
using System.Linq;
using Microsoft.Extensions.Options;
using Orleans.Timers.Internal;
using Microsoft.AspNetCore.Connections;
using Orleans.Networking.Shared;
using Orleans.Configuration.Internal;
using Orleans.Runtime.Metadata;
using Orleans.GrainReferences;
using Orleans.Serialization.TypeSystem;
using Orleans.Serialization.Serializers;
using Orleans.Serialization.Cloning;
namespace Orleans.Hosting
{
internal static class DefaultSiloServices
{
private static readonly ServiceDescriptor ServiceDescriptor = new(typeof(ServicesAdded), new ServicesAdded());
internal static void AddDefaultServices(IServiceCollection services)
{
if (services.Contains(ServiceDescriptor))
{
return;
}
services.Add(ServiceDescriptor);
services.AddOptions();
services.TryAddSingleton(typeof(IOptionFormatter<>), typeof(DefaultOptionsFormatter<>));
services.TryAddSingleton(typeof(IOptionFormatterResolver<>), typeof(DefaultOptionsFormatterResolver<>));
services.AddSingleton<Silo>();
services.AddHostedService<SiloHostedService>();
services.AddTransient<IConfigurationValidator, EndpointOptionsValidator>();
services.PostConfigure<SiloOptions>(options => options.SiloName ??= $"Silo_{Guid.NewGuid().ToString("N").Substring(0, 5)}");
services.TryAddSingleton<ILocalSiloDetails, LocalSiloDetails>();
services.TryAddSingleton<SiloLifecycleSubject>();
services.TryAddFromExisting<ISiloLifecycleSubject, SiloLifecycleSubject>();
services.TryAddFromExisting<ISiloLifecycle, SiloLifecycleSubject>();
services.AddSingleton<SiloOptionsLogger>();
services.AddFromExisting<ILifecycleParticipant<ISiloLifecycle>, SiloOptionsLogger>();
services.TryAddSingleton<TelemetryManager>();
services.TryAddFromExisting<ITelemetryProducer, TelemetryManager>();
services.TryAddSingleton<IAppEnvironmentStatistics, AppEnvironmentStatistics>();
services.TryAddSingleton<IHostEnvironmentStatistics, NoOpHostEnvironmentStatistics>();
services.TryAddSingleton<SiloStatisticsManager>();
services.TryAddSingleton<ApplicationRequestsStatisticsGroup>();
services.TryAddSingleton<StageAnalysisStatisticsGroup>();
services.TryAddSingleton<SchedulerStatisticsGroup>();
services.TryAddSingleton<OverloadDetector>();
services.TryAddSingleton<FallbackSystemTarget>();
services.TryAddSingleton<LifecycleSchedulingSystemTarget>();
services.AddLogging();
services.TryAddSingleton<ITimerRegistry, TimerRegistry>();
services.TryAddSingleton<IReminderRegistry, ReminderRegistry>();
services.AddTransient<IConfigurationValidator, ReminderOptionsValidator>();
services.TryAddSingleton<GrainRuntime>();
services.TryAddSingleton<IGrainRuntime, GrainRuntime>();
services.TryAddSingleton<IGrainCancellationTokenRuntime, GrainCancellationTokenRuntime>();
services.AddTransient<CancellationSourcesExtension>();
services.AddTransientKeyedService<Type, IGrainExtension>(typeof(ICancellationSourcesExtension), (sp, _) => sp.GetRequiredService<CancellationSourcesExtension>());
services.TryAddSingleton<GrainFactory>(sp => sp.GetService<InsideRuntimeClient>().ConcreteGrainFactory);
services.TryAddSingleton<GrainInterfaceTypeToGrainTypeResolver>();
services.TryAddFromExisting<IGrainFactory, GrainFactory>();
services.TryAddFromExisting<IInternalGrainFactory, GrainFactory>();
services.TryAddSingleton<IGrainReferenceRuntime, GrainReferenceRuntime>();
services.TryAddSingleton<GrainReferenceActivator>();
services.AddSingleton<IGrainReferenceActivatorProvider, GrainReferenceActivatorProvider>();
services.AddSingleton<IGrainReferenceActivatorProvider, UntypedGrainReferenceActivatorProvider>();
services.AddSingleton<IConfigureGrainContextProvider, MayInterleaveConfiguratorProvider>();
services.AddSingleton<IConfigureGrainTypeComponents, ReentrantSharedComponentsConfigurator>();
services.TryAddSingleton<NewRpcProvider>();
services.TryAddSingleton<GrainReferenceKeyStringConverter>();
services.AddSingleton<GrainVersionManifest>();
services.TryAddSingleton<GrainBindingsResolver>();
services.TryAddSingleton<GrainTypeSharedContextResolver>();
services.TryAddSingleton<ActivationDirectory>();
services.TryAddSingleton<GrainCountStatistics>();
services.AddSingleton<ActivationCollector>();
services.AddFromExisting<IHealthCheckParticipant, ActivationCollector>();
services.AddFromExisting<IActivationWorkingSetObserver, ActivationCollector>();
services.AddFromExisting<ILifecycleParticipant<ISiloLifecycle>, ActivationCollector>();
services.AddSingleton<ActivationWorkingSet>();
services.AddFromExisting<IActivationWorkingSet, ActivationWorkingSet>();
services.AddFromExisting<ILifecycleParticipant<ISiloLifecycle>, ActivationWorkingSet>();
// Directory
services.TryAddSingleton<LocalGrainDirectory>();
services.TryAddFromExisting<ILocalGrainDirectory, LocalGrainDirectory>();
services.AddSingleton<GrainLocator>();
services.AddSingleton<GrainLocatorResolver>();
services.AddSingleton<DhtGrainLocator>(sp => DhtGrainLocator.FromLocalGrainDirectory(sp.GetService<LocalGrainDirectory>()));
services.AddSingleton<GrainDirectoryResolver>();
services.AddSingleton<IGrainDirectoryResolver, GenericGrainDirectoryResolver>();
services.AddSingleton<CachedGrainLocator>();
services.AddFromExisting<ILifecycleParticipant<ISiloLifecycle>, CachedGrainLocator>();
services.AddSingleton<ClientGrainLocator>();
services.TryAddSingleton<MessageCenter>();
services.TryAddFromExisting<IMessageCenter, MessageCenter>();
services.TryAddSingleton(FactoryUtility.Create<MessageCenter, Gateway>);
services.TryAddSingleton<IConnectedClientCollection>(sp => (IConnectedClientCollection)sp.GetRequiredService<MessageCenter>().Gateway ?? new EmptyConnectedClientCollection());
services.TryAddSingleton<InternalGrainRuntime>();
services.TryAddSingleton<InsideRuntimeClient>();
services.TryAddFromExisting<IRuntimeClient, InsideRuntimeClient>();
services.AddFromExisting<ILifecycleParticipant<ISiloLifecycle>, InsideRuntimeClient>();
services.TryAddSingleton<IGrainServiceFactory, GrainServiceFactory>();
services.TryAddSingleton<IFatalErrorHandler, FatalErrorHandler>();
services.TryAddSingleton<DeploymentLoadPublisher>();
services.TryAddSingleton<IAsyncTimerFactory, AsyncTimerFactory>();
services.TryAddSingleton<MembershipTableManager>();
services.AddFromExisting<IHealthCheckParticipant, MembershipTableManager>();
services.AddFromExisting<ILifecycleParticipant<ISiloLifecycle>, MembershipTableManager>();
services.TryAddSingleton<MembershipSystemTarget>();
services.AddFromExisting<IMembershipService, MembershipSystemTarget>();
services.TryAddSingleton<IMembershipGossiper, MembershipGossiper>();
services.TryAddSingleton<IRemoteSiloProber, RemoteSiloProber>();
services.TryAddSingleton<SiloStatusOracle>();
services.TryAddFromExisting<ISiloStatusOracle, SiloStatusOracle>();
services.AddSingleton<ClusterHealthMonitor>();
services.AddFromExisting<ILifecycleParticipant<ISiloLifecycle>, ClusterHealthMonitor>();
services.AddFromExisting<IHealthCheckParticipant, ClusterHealthMonitor>();
services.AddSingleton<ProbeRequestMonitor>();
services.AddSingleton<LocalSiloHealthMonitor>();
services.AddFromExisting<ILocalSiloHealthMonitor, LocalSiloHealthMonitor>();
services.AddFromExisting<ILifecycleParticipant<ISiloLifecycle>, LocalSiloHealthMonitor>();
services.AddSingleton<MembershipAgent>();
services.AddFromExisting<ILifecycleParticipant<ISiloLifecycle>, MembershipAgent>();
services.AddFromExisting<IHealthCheckParticipant, MembershipAgent>();
services.AddSingleton<MembershipTableCleanupAgent>();
services.AddFromExisting<ILifecycleParticipant<ISiloLifecycle>, MembershipTableCleanupAgent>();
services.AddFromExisting<IHealthCheckParticipant, MembershipTableCleanupAgent>();
services.AddSingleton<SiloStatusListenerManager>();
services.AddFromExisting<ILifecycleParticipant<ISiloLifecycle>, SiloStatusListenerManager>();
services.AddSingleton<ClusterMembershipService>();
services.TryAddFromExisting<IClusterMembershipService, ClusterMembershipService>();
services.AddFromExisting<ILifecycleParticipant<ISiloLifecycle>, ClusterMembershipService>();
services.TryAddSingleton<ClientDirectory>();
services.AddFromExisting<ILocalClientDirectory, ClientDirectory>();
services.AddFromExisting<ILifecycleParticipant<ISiloLifecycle>, ClientDirectory>();
services.TryAddSingleton<SiloProviderRuntime>();
services.TryAddFromExisting<IProviderRuntime, SiloProviderRuntime>();
services.TryAddSingleton<MessageFactory>();
services.TryAddSingleton(FactoryUtility.Create<GrainDirectoryPartition>);
// Placement
services.AddSingleton<IConfigurationValidator, ActivationCountBasedPlacementOptionsValidator>();
services.AddSingleton<PlacementService>();
services.AddSingleton<PlacementStrategyResolver>();
services.AddSingleton<PlacementDirectorResolver>();
services.AddSingleton<IPlacementStrategyResolver, ClientObserverPlacementStrategyResolver>();
// Configure the default placement strategy.
services.TryAddSingleton<PlacementStrategy, RandomPlacement>();
// Placement directors
services.AddPlacementDirector<RandomPlacement, RandomPlacementDirector>();
services.AddPlacementDirector<PreferLocalPlacement, PreferLocalPlacementDirector>();
services.AddPlacementDirector<StatelessWorkerPlacement, StatelessWorkerDirector>();
services.Replace(new ServiceDescriptor(typeof(StatelessWorkerPlacement), sp => new StatelessWorkerPlacement(), ServiceLifetime.Singleton));
services.AddPlacementDirector<ActivationCountBasedPlacement, ActivationCountPlacementDirector>();
services.AddPlacementDirector<HashBasedPlacement, HashBasedPlacementDirector>();
services.AddPlacementDirector<ClientObserversPlacement, ClientObserversPlacementDirector>();
services.AddPlacementDirector<SiloRoleBasedPlacement, SiloRoleBasedPlacementDirector>();
// Versioning
services.TryAddSingleton<VersionSelectorManager>();
services.TryAddSingleton<CachedVersionSelectorManager>();
// Version selector strategy
if (!services.Any(x => x.ServiceType == typeof(IVersionStore)))
{
services.TryAddSingleton<GrainVersionStore>();
services.AddFromExisting<IVersionStore, GrainVersionStore>();
}
services.AddFromExisting<ILifecycleParticipant<ISiloLifecycle>, GrainVersionStore>();
services.AddSingletonNamedService<VersionSelectorStrategy, AllCompatibleVersions>(nameof(AllCompatibleVersions));
services.AddSingletonNamedService<VersionSelectorStrategy, LatestVersion>(nameof(LatestVersion));
services.AddSingletonNamedService<VersionSelectorStrategy, MinimumVersion>(nameof(MinimumVersion));
// Versions selectors
services.AddSingletonKeyedService<Type, IVersionSelector, MinimumVersionSelector>(typeof(MinimumVersion));
services.AddSingletonKeyedService<Type, IVersionSelector, LatestVersionSelector>(typeof(LatestVersion));
services.AddSingletonKeyedService<Type, IVersionSelector, AllCompatibleVersionsSelector>(typeof(AllCompatibleVersions));
// Compatibility
services.TryAddSingleton<CompatibilityDirectorManager>();
// Compatability strategy
services.AddSingletonNamedService<CompatibilityStrategy, AllVersionsCompatible>(nameof(AllVersionsCompatible));
services.AddSingletonNamedService<CompatibilityStrategy, BackwardCompatible>(nameof(BackwardCompatible));
services.AddSingletonNamedService<CompatibilityStrategy, StrictVersionCompatible>(nameof(StrictVersionCompatible));
// Compatability directors
services.AddSingletonKeyedService<Type, ICompatibilityDirector, BackwardCompatilityDirector>(typeof(BackwardCompatible));
services.AddSingletonKeyedService<Type, ICompatibilityDirector, AllVersionsCompatibilityDirector>(typeof(AllVersionsCompatible));
services.AddSingletonKeyedService<Type, ICompatibilityDirector, StrictVersionCompatibilityDirector>(typeof(StrictVersionCompatible));
services.TryAddSingleton<Factory<IGrainRuntime>>(sp => () => sp.GetRequiredService<IGrainRuntime>());
// Grain activation
services.TryAddSingleton<PlacementService>();
services.TryAddSingleton<Catalog>();
services.TryAddSingleton<GrainContextActivator>();
services.AddSingleton<IConfigureGrainTypeComponents, ConfigureDefaultGrainActivator>();
services.TryAddSingleton<GrainReferenceActivator>();
services.TryAddSingleton<IGrainContextActivatorProvider, ActivationDataActivatorProvider>();
services.TryAddSingleton<IGrainContextAccessor, GrainContextAccessor>();
services.AddSingleton<IncomingRequestMonitor>();
services.AddFromExisting<ILifecycleParticipant<ISiloLifecycle>, IncomingRequestMonitor>();
services.AddFromExisting<IActivationWorkingSetObserver, IncomingRequestMonitor>();
services.TryAddSingleton<IConsistentRingProvider>(
sp =>
{
// TODO: make this not sux - jbragg
var consistentRingOptions = sp.GetRequiredService<IOptions<ConsistentRingOptions>>().Value;
var siloDetails = sp.GetRequiredService<ILocalSiloDetails>();
var loggerFactory = sp.GetRequiredService<ILoggerFactory>();
if (consistentRingOptions.UseVirtualBucketsConsistentRing)
{
return new VirtualBucketsRingProvider(siloDetails.SiloAddress, loggerFactory, consistentRingOptions.NumVirtualBucketsConsistentRing);
}
return new ConsistentRingProvider(siloDetails.SiloAddress, loggerFactory);
});
services.TryAddSingleton(typeof(IKeyedServiceCollection<,>), typeof(KeyedServiceCollection<,>));
services.AddSingleton<IConfigureOptions<GrainTypeOptions>, DefaultGrainTypeOptionsProvider>();
// Type metadata
services.AddSingleton<SiloManifestProvider>();
services.AddSingleton<GrainClassMap>(sp => sp.GetRequiredService<SiloManifestProvider>().GrainTypeMap);
services.AddSingleton<GrainTypeResolver>();
services.AddSingleton<IGrainTypeProvider, AttributeGrainTypeProvider>();
services.AddSingleton<GrainPropertiesResolver>();
services.AddSingleton<GrainInterfaceTypeResolver>();
services.AddSingleton<IGrainInterfaceTypeProvider, AttributeGrainInterfaceTypeProvider>();
services.AddSingleton<IGrainInterfacePropertiesProvider, AttributeGrainInterfacePropertiesProvider>();
services.AddSingleton<IGrainPropertiesProvider, AttributeGrainPropertiesProvider>();
services.AddSingleton<IGrainPropertiesProvider, AttributeGrainBindingsProvider>();
services.AddSingleton<IGrainInterfacePropertiesProvider, TypeNameGrainPropertiesProvider>();
services.AddSingleton<IGrainPropertiesProvider, TypeNameGrainPropertiesProvider>();
services.AddSingleton<IGrainPropertiesProvider, ImplementedInterfaceProvider>();
services.AddSingleton<ClusterManifestProvider>();
services.AddFromExisting<IClusterManifestProvider, ClusterManifestProvider>();
services.AddFromExisting<ILifecycleParticipant<ISiloLifecycle>, ClusterManifestProvider>();
//Add default option formatter if none is configured, for options which are required to be configured
services.ConfigureFormatter<SiloOptions>();
services.ConfigureFormatter<SchedulingOptions>();
services.ConfigureFormatter<PerformanceTuningOptions>();
services.ConfigureFormatter<ConnectionOptions>();
services.ConfigureFormatter<SiloMessagingOptions>();
services.ConfigureFormatter<ClusterMembershipOptions>();
services.ConfigureFormatter<GrainDirectoryOptions>();
services.ConfigureFormatter<ActivationCountBasedPlacementOptions>();
services.ConfigureFormatter<GrainCollectionOptions>();
services.ConfigureFormatter<GrainVersioningOptions>();
services.ConfigureFormatter<ConsistentRingOptions>();
services.ConfigureFormatter<StatisticsOptions>();
services.ConfigureFormatter<TelemetryOptions>();
services.ConfigureFormatter<LoadSheddingOptions>();
services.ConfigureFormatter<EndpointOptions>();
services.ConfigureFormatter<ClusterOptions>();
// This validator needs to construct the IMembershipOracle and the IMembershipTable
// so move it in the end so other validator are called first
services.AddTransient<IConfigurationValidator, ClusterOptionsValidator>();
services.AddTransient<IConfigurationValidator, SiloClusteringValidator>();
services.AddTransient<IConfigurationValidator, DevelopmentClusterMembershipOptionsValidator>();
services.AddTransient<IConfigurationValidator, GrainTypeOptionsValidator>();
// Enable hosted client.
services.TryAddSingleton<HostedClient>();
services.AddFromExisting<ILifecycleParticipant<ISiloLifecycle>, HostedClient>();
services.TryAddSingleton<InternalClusterClient>();
services.TryAddFromExisting<IInternalClusterClient, InternalClusterClient>();
services.TryAddFromExisting<IClusterClient, InternalClusterClient>();
// Enable collection specific Age limits
services.AddOptions<GrainCollectionOptions>()
.Configure<IOptions<GrainTypeOptions>>((options, grainTypeOptions) =>
{
foreach (var grainClass in grainTypeOptions.Value.Classes)
{
var attr = grainClass.GetCustomAttribute<CollectionAgeLimitAttribute>();
if (attr != null)
{
var className = RuntimeTypeNameFormatter.Format(grainClass);
options.ClassSpecificCollectionAge[className] = attr.Amount;
}
}
});
// Validate all CollectionAgeLimit values for the right configuration.
services.AddTransient<IConfigurationValidator, GrainCollectionOptionsValidator>();
services.AddTransient<IConfigurationValidator, LoadSheddingValidator>();
services.TryAddSingleton<ITimerManager, TimerManagerImpl>();
// persistent state facet support
services.TryAddSingleton<IPersistentStateFactory, PersistentStateFactory>();
services.TryAddSingleton(typeof(IAttributeToFactoryMapper<PersistentStateAttribute>), typeof(PersistentStateAttributeMapper));
// Networking
services.TryAddSingleton<ConnectionCommon>();
services.TryAddSingleton<ConnectionManager>();
services.TryAddSingleton<ConnectionPreambleHelper>();
services.AddSingleton<ILifecycleParticipant<ISiloLifecycle>, ConnectionManagerLifecycleAdapter<ISiloLifecycle>>();
services.AddSingleton<ILifecycleParticipant<ISiloLifecycle>, SiloConnectionMaintainer>();
services.AddSingletonKeyedService<object, IConnectionFactory>(
SiloConnectionFactory.ServicesKey,
(sp, key) => ActivatorUtilities.CreateInstance<SocketConnectionFactory>(sp));
services.AddSingletonKeyedService<object, IConnectionListenerFactory>(
SiloConnectionListener.ServicesKey,
(sp, key) => ActivatorUtilities.CreateInstance<SocketConnectionListenerFactory>(sp));
services.AddSingletonKeyedService<object, IConnectionListenerFactory>(
GatewayConnectionListener.ServicesKey,
(sp, key) => ActivatorUtilities.CreateInstance<SocketConnectionListenerFactory>(sp));
services.AddSerializer();
services.AddSingleton<ITypeFilter, AllowOrleansTypes>();
services.AddSingleton<ISpecializableCodec, GrainReferenceCodecProvider>();
services.AddSingleton<ISpecializableCopier, GrainReferenceCopierProvider>();
services.AddSingleton<OnDeserializedCallbacks>();
services.TryAddTransient<IMessageSerializer>(sp => ActivatorUtilities.CreateInstance<MessageSerializer>(
sp,
sp.GetRequiredService<IOptions<ClientMessagingOptions>>().Value.MaxMessageHeaderSize,
sp.GetRequiredService<IOptions<ClientMessagingOptions>>().Value.MaxMessageBodySize));
services.TryAddSingleton<ConnectionFactory, SiloConnectionFactory>();
services.AddSingleton<NetworkingTrace>();
services.AddSingleton<RuntimeMessagingTrace>();
services.AddFromExisting<MessagingTrace, RuntimeMessagingTrace>();
// Use Orleans server.
services.AddSingleton<ILifecycleParticipant<ISiloLifecycle>, SiloConnectionListener>();
services.AddSingleton<ILifecycleParticipant<ISiloLifecycle>, GatewayConnectionListener>();
services.AddSingleton<SocketSchedulers>();
services.AddSingleton<SharedMemoryPool>();
}
private class AllowOrleansTypes : ITypeFilter
{
public bool? IsTypeNameAllowed(string typeName, string assemblyName)
{
if (assemblyName is { Length: > 0} && assemblyName.Contains("Orleans"))
{
return true;
}
return null;
}
}
private class ServicesAdded { }
}
}
| |
using System;
using System.Diagnostics;
using Microsoft.Xna.Framework;
namespace Nez
{
/// <summary>
/// Describes a 2D-rectangle.
/// </summary>
[DebuggerDisplay("{DebugDisplayString,nq}")]
public struct RectangleF : IEquatable<RectangleF>
{
static RectangleF emptyRectangle = new RectangleF();
/// <summary>
/// The x coordinate of the top-left corner of this <see cref="RectangleF"/>.
/// </summary>
public float X;
/// <summary>
/// The y coordinate of the top-left corner of this <see cref="RectangleF"/>.
/// </summary>
public float Y;
/// <summary>
/// The width of this <see cref="RectangleF"/>.
/// </summary>
public float Width;
/// <summary>
/// The height of this <see cref="RectangleF"/>.
/// </summary>
public float Height;
#region Public Properties
/// <summary>
/// Returns a <see cref="RectangleF"/> with X=0, Y=0, Width=0, Height=0.
/// </summary>
public static RectangleF Empty => emptyRectangle;
/// <summary>
/// returns a RectangleF of float.Min/Max values
/// </summary>
/// <value>The max rect.</value>
public static RectangleF MaxRect => new RectangleF(float.MinValue / 2, float.MinValue / 2, float.MaxValue, float.MaxValue);
/// <summary>
/// Returns the x coordinate of the left edge of this <see cref="RectangleF"/>.
/// </summary>
public float Left => X;
/// <summary>
/// Returns the x coordinate of the right edge of this <see cref="RectangleF"/>.
/// </summary>
public float Right => (X + Width);
/// <summary>
/// Returns the y coordinate of the top edge of this <see cref="RectangleF"/>.
/// </summary>
public float Top => Y;
/// <summary>
/// Returns the y coordinate of the bottom edge of this <see cref="RectangleF"/>.
/// </summary>
public float Bottom => (Y + Height);
/// <summary>
/// gets the max point of the rectangle, the bottom-right corner
/// </summary>
/// <value>The max.</value>
public Vector2 Max => new Vector2(Right, Bottom);
/// <summary>
/// Whether or not this <see cref="RectangleF"/> has a <see cref="Width"/> and
/// <see cref="Height"/> of 0, and a <see cref="Location"/> of (0, 0).
/// </summary>
public bool IsEmpty => ((((Width == 0) && (Height == 0)) && (X == 0)) && (Y == 0));
/// <summary>
/// The top-left coordinates of this <see cref="RectangleF"/>.
/// </summary>
public Vector2 Location
{
get => new Vector2(X, Y);
set
{
X = value.X;
Y = value.Y;
}
}
/// <summary>
/// The width-height coordinates of this <see cref="RectangleF"/>.
/// </summary>
public Vector2 Size
{
get => new Vector2(Width, Height);
set
{
Width = value.X;
Height = value.Y;
}
}
/// <summary>
/// A <see cref="Point"/> located in the center of this <see cref="RectangleF"/>.
/// </summary>
/// <remarks>
/// If <see cref="Width"/> or <see cref="Height"/> is an odd number,
/// the center point will be rounded down.
/// </remarks>
public Vector2 Center => new Vector2(X + (Width / 2), Y + (Height / 2));
#endregion
// temp Matrixes used for bounds calculation
static Matrix2D _tempMat, _transformMat;
internal string DebugDisplayString =>
string.Concat(
X, " ",
Y, " ",
Width, " ",
Height
);
/// <summary>
/// Creates a new instance of <see cref="RectangleF"/> struct, with the specified
/// position, width, and height.
/// </summary>
/// <param name="x">The x coordinate of the top-left corner of the created <see cref="RectangleF"/>.</param>
/// <param name="y">The y coordinate of the top-left corner of the created <see cref="RectangleF"/>.</param>
/// <param name="width">The width of the created <see cref="RectangleF"/>.</param>
/// <param name="height">The height of the created <see cref="RectangleF"/>.</param>
public RectangleF(float x, float y, float width, float height)
{
X = x;
Y = y;
Width = width;
Height = height;
}
/// <summary>
/// Creates a new instance of <see cref="RectangleF"/> struct, with the specified
/// location and size.
/// </summary>
/// <param name="location">The x and y coordinates of the top-left corner of the created <see cref="RectangleF"/>.</param>
/// <param name="size">The width and height of the created <see cref="RectangleF"/>.</param>
public RectangleF(Vector2 location, Vector2 size)
{
X = location.X;
Y = location.Y;
Width = size.X;
Height = size.Y;
}
/// <summary>
/// creates a RectangleF given min/max points (top-left, bottom-right points)
/// </summary>
/// <returns>The minimum max points.</returns>
/// <param name="min">Minimum.</param>
/// <param name="max">Max.</param>
public static RectangleF FromMinMax(Vector2 min, Vector2 max)
{
return new RectangleF(min.X, min.Y, max.X - min.X, max.Y - min.Y);
}
/// <summary>
/// creates a RectangleF given min/max points (top-left, bottom-right points)
/// </summary>
/// <returns>The minimum max points.</returns>
/// <param name="min">Minimum.</param>
/// <param name="max">Max.</param>
public static RectangleF FromMinMax(float minX, float minY, float maxX, float maxY)
{
return new RectangleF(minX, minY, maxX - minX, maxY - minY);
}
/// <summary>
/// given the points of a polygon calculates the bounds
/// </summary>
/// <returns>The from polygon points.</returns>
/// <param name="points">Points.</param>
public static RectangleF RectEncompassingPoints(Vector2[] points)
{
// we need to find the min/max x/y values
var minX = float.PositiveInfinity;
var minY = float.PositiveInfinity;
var maxX = float.NegativeInfinity;
var maxY = float.NegativeInfinity;
for (var i = 0; i < points.Length; i++)
{
var pt = points[i];
if (pt.X < minX)
minX = pt.X;
if (pt.X > maxX)
maxX = pt.X;
if (pt.Y < minY)
minY = pt.Y;
if (pt.Y > maxY)
maxY = pt.Y;
}
return FromMinMax(minX, minY, maxX, maxY);
}
#region Public Methods
/// <summary>
/// gets the position of the specified edge
/// </summary>
/// <returns>The side.</returns>
/// <param name="edge">Side.</param>
public float GetSide(Edge edge)
{
switch (edge)
{
case Edge.Top:
return Top;
case Edge.Bottom:
return Bottom;
case Edge.Left:
return Left;
case Edge.Right:
return Right;
default:
throw new ArgumentOutOfRangeException();
}
}
/// <summary>
/// Gets whether or not the provided coordinates lie within the bounds of this <see cref="RectangleF"/>.
/// </summary>
/// <param name="x">The x coordinate of the point to check for containment.</param>
/// <param name="y">The y coordinate of the point to check for containment.</param>
/// <returns><c>true</c> if the provided coordinates lie inside this <see cref="RectangleF"/>; <c>false</c> otherwise.</returns>
public bool Contains(int x, int y)
{
return ((((X <= x) && (x < (X + Width))) && (Y <= y)) && (y < (Y + Height)));
}
/// <summary>
/// Gets whether or not the provided coordinates lie within the bounds of this <see cref="RectangleF"/>.
/// </summary>
/// <param name="x">The x coordinate of the point to check for containment.</param>
/// <param name="y">The y coordinate of the point to check for containment.</param>
/// <returns><c>true</c> if the provided coordinates lie inside this <see cref="RectangleF"/>; <c>false</c> otherwise.</returns>
public bool Contains(float x, float y)
{
return ((((X <= x) && (x < (X + Width))) && (Y <= y)) && (y < (Y + Height)));
}
/// <summary>
/// Gets whether or not the provided <see cref="Point"/> lies within the bounds of this <see cref="RectangleF"/>.
/// </summary>
/// <param name="value">The coordinates to check for inclusion in this <see cref="RectangleF"/>.</param>
/// <returns><c>true</c> if the provided <see cref="Point"/> lies inside this <see cref="RectangleF"/>; <c>false</c> otherwise.</returns>
public bool Contains(Point value)
{
return ((((X <= value.X) && (value.X < (X + Width))) && (Y <= value.Y)) &&
(value.Y < (Y + Height)));
}
/// <summary>
/// Gets whether or not the provided <see cref="Point"/> lies within the bounds of this <see cref="RectangleF"/>.
/// </summary>
/// <param name="value">The coordinates to check for inclusion in this <see cref="RectangleF"/>.</param>
/// <param name="result"><c>true</c> if the provided <see cref="Point"/> lies inside this <see cref="RectangleF"/>; <c>false</c> otherwise. As an output parameter.</param>
public void Contains(ref Point value, out bool result)
{
result = ((((X <= value.X) && (value.X < (X + Width))) && (Y <= value.Y)) &&
(value.Y < (Y + Height)));
}
/// <summary>
/// Gets whether or not the provided <see cref="Vector2"/> lies within the bounds of this <see cref="RectangleF"/>.
/// </summary>
/// <param name="value">The coordinates to check for inclusion in this <see cref="RectangleF"/>.</param>
/// <returns><c>true</c> if the provided <see cref="Vector2"/> lies inside this <see cref="RectangleF"/>; <c>false</c> otherwise.</returns>
public bool Contains(Vector2 value)
{
return ((((X <= value.X) && (value.X < (X + Width))) && (Y <= value.Y)) &&
(value.Y < (Y + Height)));
}
/// <summary>
/// Gets whether or not the provided <see cref="Vector2"/> lies within the bounds of this <see cref="RectangleF"/>.
/// </summary>
/// <param name="value">The coordinates to check for inclusion in this <see cref="RectangleF"/>.</param>
/// <param name="result"><c>true</c> if the provided <see cref="Vector2"/> lies inside this <see cref="RectangleF"/>; <c>false</c> otherwise. As an output parameter.</param>
public void Contains(ref Vector2 value, out bool result)
{
result = ((((X <= value.X) && (value.X < (X + Width))) && (Y <= value.Y)) &&
(value.Y < (Y + Height)));
}
/// <summary>
/// Gets whether or not the provided <see cref="RectangleF"/> lies within the bounds of this <see cref="RectangleF"/>.
/// </summary>
/// <param name="value">The <see cref="RectangleF"/> to check for inclusion in this <see cref="RectangleF"/>.</param>
/// <returns><c>true</c> if the provided <see cref="RectangleF"/>'s bounds lie entirely inside this <see cref="RectangleF"/>; <c>false</c> otherwise.</returns>
public bool Contains(RectangleF value)
{
return ((((X <= value.X) && ((value.X + value.Width) <= (X + Width))) &&
(Y <= value.Y)) && ((value.Y + value.Height) <= (Y + Height)));
}
/// <summary>
/// Gets whether or not the provided <see cref="RectangleF"/> lies within the bounds of this <see cref="RectangleF"/>.
/// </summary>
/// <param name="value">The <see cref="RectangleF"/> to check for inclusion in this <see cref="RectangleF"/>.</param>
/// <param name="result"><c>true</c> if the provided <see cref="RectangleF"/>'s bounds lie entirely inside this <see cref="RectangleF"/>; <c>false</c> otherwise. As an output parameter.</param>
public void Contains(ref RectangleF value, out bool result)
{
result = ((((X <= value.X) && ((value.X + value.Width) <= (X + Width))) &&
(Y <= value.Y)) && ((value.Y + value.Height) <= (Y + Height)));
}
/// <summary>
/// Adjusts the edges of this <see cref="RectangleF"/> by specified horizontal and vertical amounts.
/// </summary>
/// <param name="horizontalAmount">Value to adjust the left and right edges.</param>
/// <param name="verticalAmount">Value to adjust the top and bottom edges.</param>
public void Inflate(int horizontalAmount, int verticalAmount)
{
X -= horizontalAmount;
Y -= verticalAmount;
Width += horizontalAmount * 2;
Height += verticalAmount * 2;
}
/// <summary>
/// Adjusts the edges of this <see cref="RectangleF"/> by specified horizontal and vertical amounts.
/// </summary>
/// <param name="horizontalAmount">Value to adjust the left and right edges.</param>
/// <param name="verticalAmount">Value to adjust the top and bottom edges.</param>
public void Inflate(float horizontalAmount, float verticalAmount)
{
X -= horizontalAmount;
Y -= verticalAmount;
Width += horizontalAmount * 2;
Height += verticalAmount * 2;
}
/// <summary>
/// Gets whether or not the other <see cref="RectangleF"/> intersects with this rectangle.
/// </summary>
/// <param name="value">The other rectangle for testing.</param>
/// <returns><c>true</c> if other <see cref="RectangleF"/> intersects with this rectangle; <c>false</c> otherwise.</returns>
public bool Intersects(RectangleF value)
{
return value.Left < Right &&
Left < value.Right &&
value.Top < Bottom &&
Top < value.Bottom;
}
/// <summary>
/// Gets whether or not the other <see cref="RectangleF"/> intersects with this rectangle.
/// </summary>
/// <param name="value">The other rectangle for testing.</param>
/// <param name="result"><c>true</c> if other <see cref="RectangleF"/> intersects with this rectangle; <c>false</c> otherwise. As an output parameter.</param>
public void Intersects(ref RectangleF value, out bool result)
{
result = value.Left < Right &&
Left < value.Right &&
value.Top < Bottom &&
Top < value.Bottom;
}
/// <summary>
/// returns true if other intersects rect
/// </summary>
/// <param name="other">other.</param>
public bool Intersects(ref RectangleF other)
{
bool result;
Intersects(ref other, out result);
return result;
}
public bool RayIntersects(ref Ray2D ray, out float distance)
{
distance = 0f;
var maxValue = float.MaxValue;
if (Math.Abs(ray.Direction.X) < 1E-06f)
{
if ((ray.Start.X < X) || (ray.Start.X > X + Width))
return false;
}
else
{
var num11 = 1f / ray.Direction.X;
var num8 = (X - ray.Start.X) * num11;
var num7 = (X + Width - ray.Start.X) * num11;
if (num8 > num7)
{
var num14 = num8;
num8 = num7;
num7 = num14;
}
distance = MathHelper.Max(num8, distance);
maxValue = MathHelper.Min(num7, maxValue);
if (distance > maxValue)
return false;
}
if (Math.Abs(ray.Direction.Y) < 1E-06f)
{
if ((ray.Start.Y < Y) || (ray.Start.Y > Y + Height))
{
return false;
}
}
else
{
var num10 = 1f / ray.Direction.Y;
var num6 = (Y - ray.Start.Y) * num10;
var num5 = (Y + Height - ray.Start.Y) * num10;
if (num6 > num5)
{
var num13 = num6;
num6 = num5;
num5 = num13;
}
distance = MathHelper.Max(num6, distance);
maxValue = MathHelper.Min(num5, maxValue);
if (distance > maxValue)
return false;
}
return true;
}
public float? RayIntersects(Ray ray)
{
var num = 0f;
var maxValue = float.MaxValue;
if (Math.Abs(ray.Direction.X) < 1E-06f)
{
if ((ray.Position.X < Left) || (ray.Position.X > Right))
return null;
}
else
{
float num11 = 1f / ray.Direction.X;
float num8 = (Left - ray.Position.X) * num11;
float num7 = (Right - ray.Position.X) * num11;
if (num8 > num7)
{
float num14 = num8;
num8 = num7;
num7 = num14;
}
num = MathHelper.Max(num8, num);
maxValue = MathHelper.Min(num7, maxValue);
if (num > maxValue)
return null;
}
if (Math.Abs(ray.Direction.Y) < 1E-06f)
{
if ((ray.Position.Y < Top) || (ray.Position.Y > Bottom))
return null;
}
else
{
float num10 = 1f / ray.Direction.Y;
float num6 = (Top - ray.Position.Y) * num10;
float num5 = (Bottom - ray.Position.Y) * num10;
if (num6 > num5)
{
float num13 = num6;
num6 = num5;
num5 = num13;
}
num = MathHelper.Max(num6, num);
maxValue = MathHelper.Min(num5, maxValue);
if (num > maxValue)
return null;
}
return new float?(num);
}
public Vector2 GetClosestPointOnBoundsToOrigin()
{
var max = Max;
var minDist = Math.Abs(Location.X);
var boundsPoint = new Vector2(Location.X, 0);
if (Math.Abs(max.X) < minDist)
{
minDist = Math.Abs(max.X);
boundsPoint.X = max.X;
boundsPoint.Y = 0f;
}
if (Math.Abs(max.Y) < minDist)
{
minDist = Math.Abs(max.Y);
boundsPoint.X = 0f;
boundsPoint.Y = max.Y;
}
if (Math.Abs(Location.Y) < minDist)
{
minDist = Math.Abs(Location.Y);
boundsPoint.X = 0;
boundsPoint.Y = Location.Y;
}
return boundsPoint;
}
/// <summary>
/// returns the closest point that is in or on the RectangleF to the given point
/// </summary>
/// <returns>The closest point on rectangle to point.</returns>
/// <param name="point">Point.</param>
public Vector2 GetClosestPointOnRectangleFToPoint(Vector2 point)
{
// for each axis, if the point is outside the box clamp it to the box else leave it alone
var res = new Vector2();
res.X = MathHelper.Clamp(point.X, Left, Right);
res.Y = MathHelper.Clamp(point.Y, Top, Bottom);
return res;
}
/// <summary>
/// gets the closest point that is on the rectangle border to the given point
/// </summary>
/// <returns>The closest point on rectangle border to point.</returns>
/// <param name="point">Point.</param>
public Vector2 GetClosestPointOnRectangleBorderToPoint(Vector2 point, out Vector2 edgeNormal)
{
edgeNormal = Vector2.Zero;
// for each axis, if the point is outside the box clamp it to the box else leave it alone
var res = new Vector2();
res.X = MathHelper.Clamp(point.X, Left, Right);
res.Y = MathHelper.Clamp(point.Y, Top, Bottom);
// if point is inside the rectangle we need to push res to the border since it will be inside the rect
if (Contains(res))
{
var dl = res.X - Left;
var dr = Right - res.X;
var dt = res.Y - Top;
var db = Bottom - res.Y;
var min = Mathf.MinOf(dl, dr, dt, db);
if (min == dt)
{
res.Y = Top;
edgeNormal.Y = -1;
}
else if (min == db)
{
res.Y = Bottom;
edgeNormal.Y = 1;
}
else if (min == dl)
{
res.X = Left;
edgeNormal.X = -1;
}
else
{
res.X = Right;
edgeNormal.X = 1;
}
}
else
{
if (res.X == Left)
edgeNormal.X = -1;
if (res.X == Right)
edgeNormal.X = 1;
if (res.Y == Top)
edgeNormal.Y = -1;
if (res.Y == Bottom)
edgeNormal.Y = 1;
}
return res;
}
/// <summary>
/// Creates a new <see cref="RectangleF"/> that contains overlapping region of two other rectangles.
/// </summary>
/// <param name="value1">The first <see cref="RectangleF"/>.</param>
/// <param name="value2">The second <see cref="RectangleF"/>.</param>
/// <returns>Overlapping region of the two rectangles.</returns>
public static RectangleF Intersect(RectangleF value1, RectangleF value2)
{
RectangleF rectangle;
Intersect(ref value1, ref value2, out rectangle);
return rectangle;
}
/// <summary>
/// Creates a new <see cref="RectangleF"/> that contains overlapping region of two other rectangles.
/// </summary>
/// <param name="value1">The first <see cref="RectangleF"/>.</param>
/// <param name="value2">The second <see cref="RectangleF"/>.</param>
/// <param name="result">Overlapping region of the two rectangles as an output parameter.</param>
public static void Intersect(ref RectangleF value1, ref RectangleF value2, out RectangleF result)
{
if (value1.Intersects(value2))
{
var right_side = Math.Min(value1.X + value1.Width, value2.X + value2.Width);
var left_side = Math.Max(value1.X, value2.X);
var top_side = Math.Max(value1.Y, value2.Y);
var bottom_side = Math.Min(value1.Y + value1.Height, value2.Y + value2.Height);
result = new RectangleF(left_side, top_side, right_side - left_side, bottom_side - top_side);
}
else
{
result = new RectangleF(0, 0, 0, 0);
}
}
/// <summary>
/// Changes the <see cref="Location"/> of this <see cref="RectangleF"/>.
/// </summary>
/// <param name="offsetX">The x coordinate to add to this <see cref="RectangleF"/>.</param>
/// <param name="offsetY">The y coordinate to add to this <see cref="RectangleF"/>.</param>
public void Offset(int offsetX, int offsetY)
{
X += offsetX;
Y += offsetY;
}
/// <summary>
/// Changes the <see cref="Location"/> of this <see cref="RectangleF"/>.
/// </summary>
/// <param name="offsetX">The x coordinate to add to this <see cref="RectangleF"/>.</param>
/// <param name="offsetY">The y coordinate to add to this <see cref="RectangleF"/>.</param>
public void Offset(float offsetX, float offsetY)
{
X += offsetX;
Y += offsetY;
}
/// <summary>
/// Changes the <see cref="Location"/> of this <see cref="RectangleF"/>.
/// </summary>
/// <param name="amount">The x and y components to add to this <see cref="RectangleF"/>.</param>
public void Offset(Point amount)
{
X += amount.X;
Y += amount.Y;
}
/// <summary>
/// Changes the <see cref="Location"/> of this <see cref="RectangleF"/>.
/// </summary>
/// <param name="amount">The x and y components to add to this <see cref="RectangleF"/>.</param>
public void Offset(Vector2 amount)
{
X += amount.X;
Y += amount.Y;
}
/// <summary>
/// Creates a new <see cref="RectangleF"/> that completely contains two other rectangles.
/// </summary>
/// <param name="value1">The first <see cref="RectangleF"/>.</param>
/// <param name="value2">The second <see cref="RectangleF"/>.</param>
/// <returns>The union of the two rectangles.</returns>
public static RectangleF Union(RectangleF value1, RectangleF value2)
{
var x = Math.Min(value1.X, value2.X);
var y = Math.Min(value1.Y, value2.Y);
return new RectangleF(x, y,
Math.Max(value1.Right, value2.Right) - x,
Math.Max(value1.Bottom, value2.Bottom) - y);
}
/// <summary>
/// Creates a new <see cref="RectangleF"/> that completely contains two other rectangles.
/// </summary>
/// <param name="value1">The first <see cref="RectangleF"/>.</param>
/// <param name="value2">The second <see cref="RectangleF"/>.</param>
/// <param name="result">The union of the two rectangles as an output parameter.</param>
public static void Union(ref RectangleF value1, ref RectangleF value2, out RectangleF result)
{
result.X = Math.Min(value1.X, value2.X);
result.Y = Math.Min(value1.Y, value2.Y);
result.Width = Math.Max(value1.Right, value2.Right) - result.X;
result.Height = Math.Max(value1.Bottom, value2.Bottom) - result.Y;
}
/// <summary>
/// Creates a new <see cref="RectangleF"/> where the rectangles overlap.
/// </summary>
/// <param name="value1">The first <see cref="RectangleF"/>.</param>
/// <param name="value2">The second <see cref="RectangleF"/>.</param>
/// <returns>The overlap of the two rectangles.</returns>
public static RectangleF Overlap(RectangleF value1, RectangleF value2)
{
var x = Math.Max(Math.Max(value1.X, value2.X), 0);
var y = Math.Max(Math.Max(value1.Y, value2.Y), 0);
return new RectangleF(x, y,
Math.Max(Math.Min(value1.Right, value2.Right) - x, 0),
Math.Max(Math.Min(value1.Bottom, value2.Bottom) - y, 0));
}
/// <summary>
/// Creates a new <see cref="RectangleF"/> where the rectangles overlap.
/// </summary>
/// <param name="value1">The first <see cref="RectangleF"/>.</param>
/// <param name="value2">The second <see cref="RectangleF"/>.</param>
/// <param name="result">The overlap of the two rectangles as an output parameter.</param>
public static void Overlap(ref RectangleF value1, ref RectangleF value2, out RectangleF result)
{
result.X = Math.Max(Math.Max(value1.X, value2.X), 0);
result.Y = Math.Max(Math.Max(value1.Y, value2.Y), 0);
result.Width = Math.Max(Math.Min(value1.Right, value2.Right) - result.X, 0);
result.Height = Math.Max(Math.Min(value1.Bottom, value2.Bottom) - result.Y, 0);
}
public void CalculateBounds(Vector2 parentPosition, Vector2 position, Vector2 origin, Vector2 scale,
float rotation, float width, float height)
{
if (rotation == 0f)
{
X = parentPosition.X + position.X - origin.X * scale.X;
Y = parentPosition.Y + position.Y - origin.Y * scale.Y;
Width = width * scale.X;
Height = height * scale.Y;
}
else
{
// special care for rotated bounds. we need to find our absolute min/max values and create the bounds from that
var worldPosX = parentPosition.X + position.X;
var worldPosY = parentPosition.Y + position.Y;
// set the reference point to world reference taking origin into account
Matrix2D.CreateTranslation(-worldPosX - origin.X, -worldPosY - origin.Y, out _transformMat);
Matrix2D.CreateScale(scale.X, scale.Y, out _tempMat); // scale ->
Matrix2D.Multiply(ref _transformMat, ref _tempMat, out _transformMat);
Matrix2D.CreateRotation(rotation, out _tempMat); // rotate ->
Matrix2D.Multiply(ref _transformMat, ref _tempMat, out _transformMat);
Matrix2D.CreateTranslation(worldPosX, worldPosY, out _tempMat); // translate back
Matrix2D.Multiply(ref _transformMat, ref _tempMat, out _transformMat);
// TODO: this is a bit silly. we can just leave the worldPos translation in the Matrix and avoid this
// get all four corners in world space
var topLeft = new Vector2(worldPosX, worldPosY);
var topRight = new Vector2(worldPosX + width, worldPosY);
var bottomLeft = new Vector2(worldPosX, worldPosY + height);
var bottomRight = new Vector2(worldPosX + width, worldPosY + height);
// transform the corners into our work space
Vector2Ext.Transform(ref topLeft, ref _transformMat, out topLeft);
Vector2Ext.Transform(ref topRight, ref _transformMat, out topRight);
Vector2Ext.Transform(ref bottomLeft, ref _transformMat, out bottomLeft);
Vector2Ext.Transform(ref bottomRight, ref _transformMat, out bottomRight);
// find the min and max values so we can concoct our bounding box
var minX = Mathf.MinOf(topLeft.X, bottomRight.X, topRight.X, bottomLeft.X);
var maxX = Mathf.MaxOf(topLeft.X, bottomRight.X, topRight.X, bottomLeft.X);
var minY = Mathf.MinOf(topLeft.Y, bottomRight.Y, topRight.Y, bottomLeft.Y);
var maxY = Mathf.MaxOf(topLeft.Y, bottomRight.Y, topRight.Y, bottomLeft.Y);
Location = new Vector2(minX, minY);
Width = maxX - minX;
Height = maxY - minY;
}
}
/// <summary>
/// returns a RectangleF that spans the current rect and the provided delta positions
/// </summary>
/// <returns>The swept broadphase box.</returns>
/// <param name="velocityX">Velocity x.</param>
/// <param name="velocityY">Velocity y.</param>
public RectangleF GetSweptBroadphaseBounds(float deltaX, float deltaY)
{
var broadphasebox = Empty;
broadphasebox.X = deltaX > 0 ? X : X + deltaX;
broadphasebox.Y = deltaY > 0 ? Y : Y + deltaY;
broadphasebox.Width = deltaX > 0 ? deltaX + Width : Width - deltaX;
broadphasebox.Height = deltaY > 0 ? deltaY + Height : Height - deltaY;
return broadphasebox;
}
/// <summary>
/// returns true if the boxes are colliding
/// moveX and moveY will return the movement that b1 must move to avoid the collision
/// </summary>
/// <param name="other">Other.</param>
/// <param name="moveX">Move x.</param>
/// <param name="moveY">Move y.</param>
public bool CollisionCheck(ref RectangleF other, out float moveX, out float moveY)
{
moveX = moveY = 0.0f;
var l = other.X - (X + Width);
var r = (other.X + other.Width) - X;
var t = other.Y - (Y + Height);
var b = (other.Y + other.Height) - Y;
// check that there was a collision
if (l > 0 || r < 0 || t > 0 || b < 0)
return false;
// find the offset of both sides
moveX = Math.Abs(l) < r ? l : r;
moveY = Math.Abs(t) < b ? t : b;
// only use whichever offset is the smallest
if (Math.Abs(moveX) < Math.Abs(moveY))
moveY = 0.0f;
else
moveX = 0.0f;
return true;
}
/// <summary>
/// Calculates the signed depth of intersection between two rectangles.
/// </summary>
/// <returns>
/// The amount of overlap between two intersecting rectangles. These depth values can be negative depending on which sides the rectangles
/// intersect. This allows callers to determine the correct direction to push objects in order to resolve collisions.
/// If the rectangles are not intersecting, Vector2.Zero is returned.
/// </returns>
public static Vector2 GetIntersectionDepth(ref RectangleF rectA, ref RectangleF rectB)
{
// calculate half sizes
var halfWidthA = rectA.Width / 2.0f;
var halfHeightA = rectA.Height / 2.0f;
var halfWidthB = rectB.Width / 2.0f;
var halfHeightB = rectB.Height / 2.0f;
// calculate centers
var centerA = new Vector2(rectA.Left + halfWidthA, rectA.Top + halfHeightA);
var centerB = new Vector2(rectB.Left + halfWidthB, rectB.Top + halfHeightB);
// calculate current and minimum-non-intersecting distances between centers
var distanceX = centerA.X - centerB.X;
var distanceY = centerA.Y - centerB.Y;
var minDistanceX = halfWidthA + halfWidthB;
var minDistanceY = halfHeightA + halfHeightB;
// if we are not intersecting at all, return (0, 0)
if (Math.Abs(distanceX) >= minDistanceX || Math.Abs(distanceY) >= minDistanceY)
return Vector2.Zero;
// calculate and return intersection depths
var depthX = distanceX > 0 ? minDistanceX - distanceX : -minDistanceX - distanceX;
var depthY = distanceY > 0 ? minDistanceY - distanceY : -minDistanceY - distanceY;
return new Vector2(depthX, depthY);
}
/// <summary>
/// Compares whether current instance is equal to specified <see cref="Object"/>.
/// </summary>
/// <param name="obj">The <see cref="Object"/> to compare.</param>
/// <returns><c>true</c> if the instances are equal; <c>false</c> otherwise.</returns>
public override bool Equals(object obj)
{
return (obj is RectangleF) && this == ((RectangleF) obj);
}
/// <summary>
/// Compares whether current instance is equal to specified <see cref="RectangleF"/>.
/// </summary>
/// <param name="other">The <see cref="RectangleF"/> to compare.</param>
/// <returns><c>true</c> if the instances are equal; <c>false</c> otherwise.</returns>
public bool Equals(RectangleF other)
{
return this == other;
}
/// <summary>
/// Gets the hash code of this <see cref="RectangleF"/>.
/// </summary>
/// <returns>Hash code of this <see cref="RectangleF"/>.</returns>
public override int GetHashCode()
{
return ((int) X ^ (int) Y ^ (int) Width ^ (int) Height);
}
/// <summary>
/// Returns a <see cref="String"/> representation of this <see cref="RectangleF"/> in the format:
/// {X:[<see cref="X"/>] Y:[<see cref="Y"/>] Width:[<see cref="Width"/>] Height:[<see cref="Height"/>]}
/// </summary>
/// <returns><see cref="String"/> representation of this <see cref="RectangleF"/>.</returns>
public override string ToString()
{
return string.Format("X:{0}, Y:{1}, Width: {2}, Height: {3}", X, Y, Width, Height);
}
#endregion
#region Operators
/// <summary>
/// Compares whether two <see cref="RectangleF"/> instances are equal.
/// </summary>
/// <param name="a"><see cref="RectangleF"/> instance on the left of the equal sign.</param>
/// <param name="b"><see cref="RectangleF"/> instance on the right of the equal sign.</param>
/// <returns><c>true</c> if the instances are equal; <c>false</c> otherwise.</returns>
public static bool operator ==(RectangleF a, RectangleF b)
{
return ((a.X == b.X) && (a.Y == b.Y) && (a.Width == b.Width) && (a.Height == b.Height));
}
/// <summary>
/// Compares whether two <see cref="RectangleF"/> instances are not equal.
/// </summary>
/// <param name="a"><see cref="RectangleF"/> instance on the left of the not equal sign.</param>
/// <param name="b"><see cref="RectangleF"/> instance on the right of the not equal sign.</param>
/// <returns><c>true</c> if the instances are not equal; <c>false</c> otherwise.</returns>
public static bool operator !=(RectangleF a, RectangleF b)
{
return !(a == b);
}
public static implicit operator Rectangle(RectangleF self)
{
return RectangleExt.FromFloats(self.X, self.Y, self.Width, self.Height);
}
#endregion
}
}
| |
// Copyright (c) 2014 SIL International
// This software is licensed under the MIT License (http://opensource.org/licenses/MIT)
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using Palaso.Extensions;
using Palaso.Reporting;
namespace Palaso.IO
{
public static class PathUtilities
{
// On Unix there are more characters valid in file names, but we
// want the result to be identical on both platforms, so we want
// to use the larger invalid Windows list for both platforms
public static char[] GetInvalidOSIndependentFileNameChars()
{
return new char[]
{
'\0',
'\u0001',
'\u0002',
'\u0003',
'\u0004',
'\u0005',
'\u0006',
'\a',
'\b',
'\t',
'\n',
'\v',
'\f',
'\r',
'\u000e',
'\u000f',
'\u0010',
'\u0011',
'\u0012',
'\u0013',
'\u0014',
'\u0015',
'\u0016',
'\u0017',
'\u0018',
'\u0019',
'\u001a',
'\u001b',
'\u001c',
'\u001d',
'\u001e',
'\u001f',
'"',
'<',
'>',
'|',
':',
'*',
'?',
'\\',
'/'
};
}
public static int GetDeviceNumber(string filePath)
{
if (Palaso.PlatformUtilities.Platform.IsWindows)
{
var driveInfo = new DriveInfo(Path.GetPathRoot(filePath));
return driveInfo.Name.ToUpper()[0] - 'A' + 1;
}
// filePath can mean a file or a directory.
var pathToCheck = filePath;
if (!File.Exists(pathToCheck) && !Directory.Exists(pathToCheck))
{
pathToCheck = Path.GetDirectoryName(pathToCheck);
if (!Directory.Exists(pathToCheck))
return GetDeviceNumber(pathToCheck);
}
using (var process = new Process())
{
process.StartInfo = new ProcessStartInfo {
FileName = "stat",
Arguments = string.Format("-c %d \"{0}\"", pathToCheck),
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
};
process.Start();
process.WaitForExit();
var output = process.StandardOutput.ReadToEnd();
return Convert.ToInt32(output);
}
}
public static bool PathsAreOnSameVolume(string firstPath, string secondPath)
{
if (string.IsNullOrEmpty(firstPath) || string.IsNullOrEmpty(secondPath))
return false;
return PathUtilities.GetDeviceNumber(firstPath) == PathUtilities.GetDeviceNumber(secondPath);
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 1)]
private struct SHFILEOPSTRUCT
{
public IntPtr hwnd;
[MarshalAs(UnmanagedType.U4)]
public int wFunc;
public string pFrom;
public string pTo;
public short fFlags;
[MarshalAs(UnmanagedType.Bool)]
public bool fAnyOperationsAborted;
public IntPtr hNameMappings;
public string lpszProgressTitle;
}
[DllImport("shell32.dll", CharSet = CharSet.Auto)]
private static extern int SHFileOperation(ref SHFILEOPSTRUCT FileOp);
private const int FO_DELETE = 3;
private const int FOF_ALLOWUNDO = 0x40;
private const int FOF_NOCONFIRMATION = 0x10; // Don't prompt the user
private const int FOF_SIMPLEPROGRESS = 0x0100;
private static void WriteTrashInfoFile(string trashPath, string filePath, string trashedFile)
{
var trashInfo = Path.Combine(trashPath, "info", trashedFile + ".trashinfo");
var lines = new List<string>();
lines.Add("[Trash Info]");
lines.Add(string.Format("Path={0}", filePath));
lines.Add(string.Format("DeletionDate={0}",
DateTime.Now.ToString("yyyyMMddTHH:mm:ss", CultureInfo.InvariantCulture)));
File.WriteAllLines(trashInfo, lines);
}
/// <summary>
/// Delete a file or directory by moving it to the trash bin
/// </summary>
/// <param name="filePath">Full path of the file.</param>
/// <returns><c>true</c> if successfully deleted.</returns>
public static bool DeleteToRecycleBin(string filePath)
{
if (PlatformUtilities.Platform.IsWindows)
{
if (!File.Exists(filePath) && !Directory.Exists(filePath))
return false;
// alternative using visual basic dll:
// FileSystem.DeleteDirectory(item.FolderPath,UIOption.OnlyErrorDialogs), RecycleOption.SendToRecycleBin);
//moves it to the recyle bin
var shf = new SHFILEOPSTRUCT();
shf.wFunc = FO_DELETE;
shf.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION;
string pathWith2Nulls = filePath + "\0\0";
shf.pFrom = pathWith2Nulls;
SHFileOperation(ref shf);
return !shf.fAnyOperationsAborted;
}
// On Linux we'll have to move the file to $XDG_DATA_HOME/Trash/files and create
// a filename.trashinfo file in $XDG_DATA_HOME/Trash/info that contains the original
// filepath and the deletion date. See http://stackoverflow.com/a/20255190
// and http://freedesktop.org/wiki/Specifications/trash-spec/.
// Environment.SpecialFolder.LocalApplicationData corresponds to $XDG_DATA_HOME.
// move file or directory
if (Directory.Exists(filePath) || File.Exists(filePath))
{
var trashPath = Path.Combine(Environment.GetFolderPath(
Environment.SpecialFolder.LocalApplicationData), "Trash");
var trashedFileName = Path.GetRandomFileName();
if (!Directory.Exists(trashPath))
{
// in case the trash bin doesn't exist we create it. This can happen e.g.
// on the build machine
Directory.CreateDirectory(Path.Combine(trashPath, "files"));
Directory.CreateDirectory(Path.Combine(trashPath, "info"));
}
var recyclePath = Path.Combine(Path.Combine(trashPath, "files"), trashedFileName);
WriteTrashInfoFile(trashPath, filePath, trashedFileName);
// Directory.Move works for directories and files
DirectoryUtilities.MoveDirectorySafely(filePath, recyclePath);
return true;
}
return false;
}
/// <summary>
/// On Windows this selects the file in Windows Explorer; on Linux it selects the file
/// in the default file manager if that supports selecting a file and we know it,
/// otherwise we fall back to xdg-open and open the directory that contains that file.
/// </summary>
/// <param name="filePath">File path.</param>
public static void SelectFileInExplorer(string filePath)
{
var fileManager = DefaultFileManager;
string arguments;
switch (fileManager)
{
case "explorer.exe":
arguments = string.Format("/select, \"{0}\"", filePath);
break;
case "nautilus":
case "nemo":
arguments = string.Format("\"{0}\"", filePath);
break;
default:
fileManager = "xdg-open";
arguments = string.Format("\"{0}\"", Path.GetDirectoryName(filePath));
break;
}
Process.Start(fileManager, arguments);
}
/// <summary>
/// Opens the specified directory in the default file manager
/// </summary>
/// <param name="directory">Full path of the directory</param>
public static void OpenDirectoryInExplorer(string directory)
{
var fileManager = DefaultFileManager;
var arguments = "\"{0}\"";
// the value returned by GetDefaultFileManager() may include arguments
var firstSpace = fileManager.IndexOf(' ');
if (firstSpace > -1)
{
arguments = fileManager.Substring(firstSpace + 1) + " " + arguments;
fileManager = fileManager.Substring(0, firstSpace);
}
arguments = string.Format(arguments, directory);
Process.Start(new ProcessStartInfo()
{
FileName = fileManager,
Arguments = arguments,
UseShellExecute = false
});
}
/// <summary>
/// Opens the file in the application associated with the file type.
/// </summary>
/// <param name="filePath">Full path to the file</param>
public static void OpenFileInApplication(string filePath)
{
Process.Start(filePath);
}
private static string GetDefaultFileManager()
{
if (PlatformUtilities.Platform.IsWindows)
return "explorer.exe";
const string fallbackFileManager = "xdg-open";
using (var xdgmime = new Process())
{
bool processError = false;
xdgmime.RunProcess("xdg-mime", "query default inode/directory", exception => {
processError = true;
});
if (processError)
{
Logger.WriteMinorEvent("Error executing 'xdg-mime query default inode/directory'");
return fallbackFileManager;
}
string desktopFile = xdgmime.StandardOutput.ReadToEnd().TrimEnd(' ', '\n', '\r');
xdgmime.WaitForExit();
if (string.IsNullOrEmpty(desktopFile))
{
Logger.WriteMinorEvent("Didn't find default value for mime type inode/directory");
return fallbackFileManager;
}
// Look in /usr/share/applications for .desktop file
var desktopFilename = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
"applications", desktopFile);
if (!File.Exists(desktopFilename))
{
// We didn't find the .desktop file yet, so check in ~/.local/share/applications
desktopFilename = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"applications", desktopFile);
}
if (!File.Exists(desktopFilename))
{
Logger.WriteMinorEvent("Can't find desktop file for {0}", desktopFile);
return fallbackFileManager;
}
using (var reader = File.OpenText(desktopFilename))
{
string line;
for (line = reader.ReadLine();
!line.StartsWith("Exec=", StringComparison.InvariantCultureIgnoreCase) && !reader.EndOfStream;
line = reader.ReadLine())
{
}
if (!line.StartsWith("Exec=", StringComparison.InvariantCultureIgnoreCase))
{
Logger.WriteMinorEvent("Can't find Exec line in {0}", desktopFile);
_defaultFileManager = string.Empty;
return _defaultFileManager;
}
var start = "Exec=".Length;
var argStart = line.IndexOf('%');
var cmdLine = argStart > 0 ? line.Substring(start, argStart - start) : line.Substring(start);
cmdLine = cmdLine.TrimEnd();
Logger.WriteMinorEvent("Detected default file manager as {0}", cmdLine);
return cmdLine;
}
}
}
private static string _defaultFileManager;
private static string DefaultFileManager
{
get
{
if (_defaultFileManager == null)
_defaultFileManager = GetDefaultFileManager();
return _defaultFileManager;
}
}
}
}
| |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// 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.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using Gallio.Common.Policies;
using Gallio.Common.Platform;
namespace Gallio.Common.Concurrency
{
/// <summary>
/// A process task provides support for launching external processes
/// and collecting their output.
/// </summary>
/// <remarks>
/// <para>
/// The process task provides a guarantee that when you call <see cref="Task.Join" />
/// all redirected output from the console output and error streams will already
/// have been captured and delivered to the event handlers, as appropriate.
/// </para>
/// </remarks>
public class ProcessTask : Task
{
private readonly string executablePath;
private readonly string arguments;
private readonly string workingDirectory;
private Dictionary<string, string> environmentVariables;
private bool captureConsoleOutput;
private bool captureConsoleError;
private bool useShellExecute;
private bool createWindow;
private StringWriter consoleOutputCaptureWriter;
private StringWriter consoleErrorCaptureWriter;
private Process process;
private int exited;
private bool loggingStarted;
private ManualResetEvent exitedEvent;
/// <summary>
/// Creates a process task.
/// </summary>
/// <param name="executablePath">The path of the executable executable.</param>
/// <param name="arguments">The arguments for the executable.</param>
/// <param name="workingDirectory">The working directory.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="executablePath"/>,
/// <paramref name="arguments"/> or <paramref name="workingDirectory"/> is null.</exception>
public ProcessTask(string executablePath, string arguments, string workingDirectory)
: base(executablePath + @" " + arguments)
{
if (executablePath == null)
throw new ArgumentNullException(@"executablePath");
if (arguments == null)
throw new ArgumentNullException(@"arguments");
if (workingDirectory == null)
throw new ArgumentNullException("workingDirectory");
this.executablePath = Path.GetFullPath(executablePath);
this.arguments = arguments;
this.workingDirectory = workingDirectory;
exitedEvent = new ManualResetEvent(false);
}
/// <summary>
/// Gets the executable path.
/// </summary>
public string ExecutablePath
{
get { return executablePath; }
}
/// <summary>
/// Gets the arguments.
/// </summary>
public string Arguments
{
get { return arguments; }
}
/// <summary>
/// Gets the working directory path.
/// </summary>
public string WorkingDirectory
{
get { return workingDirectory; }
}
/// <summary>
/// Gets the <see cref="Process" /> that was started or null if the
/// process has not been started yet.
/// </summary>
/// <remarks>
/// Please be aware that <see cref="Process" /> is not thread-safe.
/// You must lock the process object before accessing it.
/// </remarks>
public Process Process
{
get { return process; }
}
/// <summary>
/// Gets or sets whether console output stream of the process should be captured
/// and made available via the <see cref="ConsoleOutput" /> property.
/// </summary>
/// <remarks>
/// <para>
/// The default value is <c>false</c>.
/// </para>
/// </remarks>
public bool CaptureConsoleOutput
{
get { return captureConsoleOutput; }
set { captureConsoleOutput = value; }
}
/// <summary>
/// Gets or sets whether console error stream of the process should be captured
/// and made available via the <see cref="ConsoleError" /> property.
/// </summary>
/// <remarks>
/// <para>
/// The default value is <c>false</c>.
/// </para>
/// </remarks>
public bool CaptureConsoleError
{
get { return captureConsoleError; }
set { captureConsoleError = value; }
}
/// <summary>
/// Gets or sets whether to execute the command with the Windows shell.
/// </summary>
/// <remarks>
/// <para>
/// The default value is <c>false</c>.
/// </para>
/// </remarks>
public bool UseShellExecute
{
get { return useShellExecute; }
set { useShellExecute = value; }
}
/// <summary>
/// Gets or sets whether to create a window for the command prompt.
/// </summary>
/// <remarks>
/// <para>
/// The default value is <c>false</c>.
/// </para>
/// </remarks>
public bool CreateWindow
{
get { return createWindow; }
set { createWindow = value; }
}
/// <summary>
/// Gets the captured contents of the console output stream written by the process.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown if the process has not been started
/// or if <see cref="CaptureConsoleOutput" /> is <c>null</c>.</exception>
public string ConsoleOutput
{
get
{
if (consoleOutputCaptureWriter == null)
throw new InvalidOperationException("The process has not been started or the console output stream is not being captured.");
return consoleOutputCaptureWriter.ToString();
}
}
/// <summary>
/// Gets the captured contents of the console error stream written by the process.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown if the process has not been started
/// or if <see cref="CaptureConsoleError" /> is <c>null</c>.</exception>
public string ConsoleError
{
get
{
if (consoleErrorCaptureWriter == null)
throw new InvalidOperationException("The process has not been started or the console error stream is not being captured.");
return consoleErrorCaptureWriter.ToString();
}
}
/// <summary>
/// Gets the exit code of the process, or -1 if the process did not run or has not exited.
/// </summary>
public int ExitCode
{
get
{
if (process == null)
return -1;
lock (process)
{
return process.HasExited ? process.ExitCode : -1;
}
}
}
/// <summary>
/// Gets a description of the exit code, if available, or null otherwise.
/// </summary>
public string ExitCodeDescription
{
get
{
if (!DotNetRuntimeSupport.IsUsingMono)
{
int exitCode = ExitCode;
if (exitCode < -1)
{
Exception ex = Marshal.GetExceptionForHR(exitCode);
if (ex != null && !ex.Message.Contains("HRESULT"))
return ex.Message;
}
}
return null;
}
}
/// <summary>
/// The event fired to configure <see cref="ProcessStartInfo" /> just before the process is started.
/// </summary>
public event EventHandler<ConfigureProcessStartInfoEventArgs> ConfigureProcessStartInfo;
/// <summary>
/// The event fired when each line of new output is received on the console output stream.
/// </summary>
/// <remarks>
/// <para>
/// This event should be wired up before starting the task to ensure that
/// no data is lost.
/// </para>
/// <para>
/// Please note that the <see cref="DataReceivedEventArgs.Data" /> property
/// will be null when the redirected stream is closed after the process exits.
/// </para>
/// </remarks>
public event EventHandler<DataReceivedEventArgs> ConsoleOutputDataReceived;
/// <summary>
/// The event fired when each line of new output is received on the console error stream.
/// </summary>
/// <remarks>
/// <para>
/// This event should be wired up before starting the task to ensure that
/// no data is lost.
/// </para>
/// <para>
/// Please note that the <see cref="DataReceivedEventArgs.Data" /> property
/// will be null when the redirected stream is closed after the process exits.
/// </para>
/// </remarks>
public event EventHandler<DataReceivedEventArgs> ConsoleErrorDataReceived;
/// <summary>
/// Sets an environment variable to be passed to the process when started.
/// </summary>
/// <param name="name">The variable name.</param>
/// <param name="value">The variable value, or null to remove the environment variable
/// so it will not be inherited by the child process.</param>
/// <exception cref="InvalidOperationException">Thrown if the process has already been started.</exception>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="name"/> is null.</exception>
public void SetEnvironmentVariable(string name, string value)
{
if (name == null)
throw new ArgumentNullException("name");
if (process != null)
throw new InvalidOperationException("The process has already been started.");
if (environmentVariables == null)
environmentVariables = new Dictionary<string, string>();
environmentVariables[name] = value;
}
/// <inheritdoc />
protected override void StartImpl()
{
if (process != null)
throw new InvalidOperationException("The process has already been started.");
if (captureConsoleOutput)
consoleOutputCaptureWriter = new StringWriter();
if (captureConsoleError)
consoleErrorCaptureWriter = new StringWriter();
ProcessStartInfo startInfo = CreateProcessStartInfo();
startInfo.WorkingDirectory = workingDirectory;
startInfo.UseShellExecute = useShellExecute;
startInfo.CreateNoWindow = ! createWindow;
startInfo.RedirectStandardOutput = captureConsoleOutput || ConsoleOutputDataReceived != null;
startInfo.RedirectStandardError = captureConsoleError || ConsoleErrorDataReceived != null;
if (environmentVariables != null)
{
foreach (var pair in environmentVariables)
{
if (pair.Value == null)
startInfo.EnvironmentVariables.Remove(pair.Key);
else
startInfo.EnvironmentVariables[pair.Key] = pair.Value;
}
}
if (ConfigureProcessStartInfo != null)
ConfigureProcessStartInfo(this, new ConfigureProcessStartInfoEventArgs(startInfo));
process = StartProcess(startInfo);
lock (process)
{
process.EnableRaisingEvents = true;
}
StartLogging();
StartProcessExitDetection();
}
/// <summary>
/// Starts a <see cref="Process" />.
/// </summary>
/// <remarks>
/// <para>
/// This method may be override to change how the process is created and
/// started.
/// </para>
/// </remarks>
/// <param name="startInfo">The <see cref="ProcessStartInfo" /> that has been started.</param>
/// <returns>The process.</returns>
protected virtual Process StartProcess(ProcessStartInfo startInfo)
{
return Process.Start(startInfo);
}
private void StartProcessExitDetection()
{
if (DotNetRuntimeSupport.IsUsingMono)
{
// On Mono 1.9.1, the process exited event does not seem to be reliably delivered.
// So we have to hack around it...
var thread = new Thread(() =>
{
try
{
for (;;)
{
lock (process)
{
if (process.HasExited)
break;
}
Thread.Sleep(100);
}
}
catch
{
// Give up.
}
finally
{
HandleProcessExit();
}
});
thread.IsBackground = true;
thread.Start();
}
else
{
// Handle process exit including the case where the process might already
// have exited just prior to adding the event handler.
lock (process)
{
process.Exited += delegate { HandleProcessExit(); };
if (process.HasExited)
HandleProcessExit();
}
}
}
private void HandleProcessExit()
{
// The process lock may already be held by this thread since the
// Process object can call its Exited event handler as a side effect of
// several operations on the Process object. This could result in a
// deadlock if the task's Terminated event waits on some other thread that
// is also blocked on the process. So we make it asynchronous instead.
// Join then blocks on the exitedEvent to restore the required synchronization.
if (Interlocked.Exchange(ref exited, 1) == 0)
{
ThreadPool.QueueUserWorkItem((state) =>
{
try
{
WaitForConsoleToBeCompletelyReadOnceProcessHasExited();
NotifyTerminated(TaskResult<object>.CreateFromValue(ExitCode));
}
finally
{
exitedEvent.Set();
}
}, null);
}
}
/// <inheritdoc />
protected override void AbortImpl()
{
if (process == null)
return;
lock (process)
{
if (!process.HasExited)
process.Kill();
}
}
/// <inheritdoc />
protected override bool JoinImpl(TimeSpan? timeout)
{
if (process == null)
return true;
// There might be multiple threads blocked on Join simultaneously with
// different timeouts. Unfortunately they can't all just wait at the
// same time because the Process object is not threadsafe. So instead
// we only lock for short intervals.
Stopwatch stopwatch = Stopwatch.StartNew();
for (;;)
{
lock (process)
{
int incrementalTimeout = timeout.HasValue && timeout.Value.Ticks >= 0
? Math.Min((int) (timeout.Value - stopwatch.Elapsed).TotalMilliseconds, 100)
: 100;
if (incrementalTimeout < 0)
incrementalTimeout = 0;
if (process.WaitForExit(incrementalTimeout))
break;
if (incrementalTimeout == 0)
return false;
}
}
WaitForConsoleToBeCompletelyReadOnceProcessHasExited();
exitedEvent.WaitOne();
return true;
}
private ProcessStartInfo CreateProcessStartInfo()
{
return DotNetRuntimeSupport.CreateReentrantProcessStartInfo(executablePath, arguments);
}
private void StartLogging()
{
lock (process)
{
if (process.StartInfo.RedirectStandardOutput)
{
process.OutputDataReceived += LogOutputData;
process.BeginOutputReadLine();
}
if (process.StartInfo.RedirectStandardError)
{
process.ErrorDataReceived += LogErrorData;
process.BeginErrorReadLine();
}
}
loggingStarted = true;
}
private void LogOutputData(object sender, DataReceivedEventArgs e)
{
if (captureConsoleOutput && e.Data != null)
consoleOutputCaptureWriter.WriteLine(e.Data);
EventHandlerPolicy.SafeInvoke(ConsoleOutputDataReceived, this, e);
}
private void LogErrorData(object sender, DataReceivedEventArgs e)
{
if (captureConsoleError && e.Data != null)
consoleErrorCaptureWriter.WriteLine(e.Data);
EventHandlerPolicy.SafeInvoke(ConsoleErrorDataReceived, this, e);
}
private void WaitForConsoleToBeCompletelyReadOnceProcessHasExited()
{
if (!loggingStarted)
return;
// Wait for all pending I/O to be consumed. It turns out that calling
// WaitForExit with no timeout waits for the output and error streams
// to be full read (when using BeginOutput/ErrorReadLine) but the same
// courtesy is not extended to WaitForExit with a timeout. Since the process
// has already exited, we should only be waiting to read the streams
// which ought to be pretty quick.
lock (process)
{
process.WaitForExit();
}
}
}
}
| |
using System;
using System.Collections.ObjectModel;
using System.IO;
namespace Tacto.Core {
public class VcfManager : FileFormatManager {
public enum State { TopLevel, InCard };
public static readonly ReadOnlyCollection<char> AttributeSeparators = new ReadOnlyCollection<char>(
new char[]{ ';', ',' }
);
public const char DataSeparator = ':';
public const string EtqBeginSection = "BEGIN";
public const string EtqEndSection = "END";
public const string EtqCardAttribute = "VCARD";
public const string EtqNameSection = "N";
public const string EtqEmailSection = "EMAIL";
public const string EtqPhoneSection = "TEL";
public const string EtqAddressSection = "ADR";
public const string EtqPref = "PREF";
public const string EtqHome = "HOME";
public const string EtqWork = "WORK";
public const string EtqMobile = "MOBILE";
private State status;
public State Status {
get { return this.status; }
set { status = value; }
}
public VcfManager(string fileName) : base( fileName )
{}
public override void Export(PersonsList pl)
{
using(var file = new StreamWriter( FileName ) ) {
file.WriteLine( pl.ToVCard() );
file.WriteLine();
}
}
private void SplitVcfLine(string line, out string section, out string[] attributes, out string data)
{
section = data = "";
attributes = new string[ 0 ];
// Find data and section
string[] mainParts = line.Split( DataSeparator );
// Split section data
if ( mainParts.Length == 2 ) {
data = mainParts[ 1 ].Trim();
section = mainParts[ 0 ].Trim().ToUpper();
char[] attrSeparators = new char[AttributeSeparators.Count];
AttributeSeparators.CopyTo( attrSeparators, 0 );
string[] attrs = section.Split( attrSeparators );
if ( attrs.Length == 1 ) {
section = attrs[ 0 ].Trim();
}
else
if ( attrs.Length >= 2 ) {
attributes = new string[ attrs.Length - 1 ];
section = attrs[ 0 ].Trim();
for(int i = 1; i < attrs.Length; ++i) {
attributes[ i -1 ] = attrs[ i ].Trim();
}
}
} else throw new Exception( "Malformed section" );
return;
}
public static bool AttributesContain(string[] attributes, string key)
{
bool toret = false;
foreach(var attr in attributes) {
if ( attr.IndexOf( key ) > -1 ) {
toret = true;
break;
}
}
return toret;
}
private void FillCard(Person p, string section, string[] attributes, string data)
{
if ( section == EtqNameSection
&& data.Length > 0 )
{
string[] nameParts = data.Split( ';' );
if ( nameParts.Length < 2 ) {
throw new ApplicationException( "Malformed name" );
}
p.Name = nameParts[ 1 ];
p.Surname = nameParts[ 0 ];
}
else
if ( section == EtqEmailSection
&& data.Length > 0
&& AttributesContain( attributes, EtqPref ) )
{
p.Email = data;
}
else
if ( section == EtqEmailSection
&& data.Length > 0 )
{
p.Email2 = data;
}
else
if ( section == EtqPhoneSection
&& data.Length > 0
&& AttributesContain( attributes, EtqWork ) )
{
p.WorkPhone = data;
}
else
if ( section == EtqPhoneSection
&& data.Length > 0
&& AttributesContain( attributes, EtqMobile ) )
{
p.MobilePhone = data;
}
else
if ( section == EtqPhoneSection
&& data.Length > 0
&& AttributesContain( attributes, EtqHome ) )
{
p.HomePhone = data;
}
else
if ( section == EtqAddressSection
&& data.Length > 0 )
{
p.Address = data;
}
}
public override PersonsList Import()
{
string section;
string[] attributes;
string data;
string line;
PersonsList toret = new PersonsList();
Person p = null;
var file = new StreamReader( FileName );
Status = State.TopLevel;
line = file.ReadLine().Trim();
while( !file.EndOfStream ) {
if ( line.Length > 0 ) {
SplitVcfLine( line, out section, out attributes, out data);
if ( Status == State.TopLevel
&& section == EtqBeginSection
&& data.ToUpper() == EtqCardAttribute
&& attributes.Length == 0 )
{
// Start vCard
Status = State.InCard;
p = new Person();
}
else
if ( Status == State.InCard
&& section == EtqEndSection
&& data.ToUpper() == EtqCardAttribute
&& attributes.Length == 0 )
{
// Finish VCard
Status = State.TopLevel;
toret.Insert( p );
p = null;
}
else
if ( Status == State.InCard ) {
// Fill fields
FillCard( p, section, attributes, data );
}
else throw new ApplicationException( "Misplaced statement:'"
+ section + "'\nin '"
+ line + "'\nwhile in state: "
+ Status
);
}
line = file.ReadLine().Trim();
}
file.Close();
return toret;
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2007 Charlie Poole, Rob Prouse
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using NUnit.Framework;
#if !NETCOREAPP1_1
using System.Security.Principal;
#endif
namespace NUnit.TestData.TestFixtureTests
{
/// <summary>
/// Classes used for testing NUnit
/// </summary>
[TestFixture]
public class RegularFixtureWithOneTest
{
[Test]
public void OneTest()
{
}
}
[TestFixture]
public class NoDefaultCtorFixture
{
public NoDefaultCtorFixture(int index)
{
}
[Test]
public void OneTest()
{
}
}
[TestFixture(7,3)]
public class FixtureWithArgsSupplied
{
public FixtureWithArgsSupplied(int x, int y)
{
}
[Test]
public void OneTest()
{
}
}
[TestFixture(7, 3)]
[TestFixture(8, 4)]
public class FixtureWithMultipleArgsSupplied
{
public FixtureWithMultipleArgsSupplied(int x, int y)
{
}
[Test]
public void OneTest()
{
}
}
[TestFixture]
public class BadCtorFixture
{
public BadCtorFixture()
{
throw new Exception();
}
[Test] public void OneTest()
{
}
}
[TestFixture]
public class FixtureWithTestFixtureAttribute
{
[Test]
public void SomeTest()
{
}
}
public class FixtureWithoutTestFixtureAttributeContainingTest
{
[Test]
public void SomeTest()
{
}
}
public class FixtureWithoutTestFixtureAttributeContainingTestCase
{
[TestCase(42)]
public void SomeTest(int x)
{
}
}
[TestFixture]
public class FixtureWithParameterizedTestAndArgsSupplied
{
[TestCase(42, "abc")]
public void SomeTest(int x, string y)
{
}
}
[TestFixture]
public class FixtureWithParameterizedTestAndMultipleArgsSupplied
{
[TestCase(42, "abc")]
[TestCase(24, "cba")]
public void SomeTest(int x, string y)
{
}
}
public class FixtureWithoutTestFixtureAttributeContainingTestCaseSource
{
[TestCaseSource("data")]
public void SomeTest(int x)
{
}
}
public class FixtureWithoutTestFixtureAttributeContainingTheory
{
[Theory]
public void SomeTest(int x)
{
}
}
public static class StaticFixtureWithoutTestFixtureAttribute
{
[Test]
public static void StaticTest()
{
}
}
[TestFixture]
public class MultipleSetUpAttributes
{
[SetUp]
public void Init1()
{
}
[SetUp]
public void Init2()
{
}
[Test] public void OneTest()
{
}
}
[TestFixture]
public class MultipleTearDownAttributes
{
[TearDown]
public void Destroy1()
{
}
[TearDown]
public void Destroy2()
{
}
[Test] public void OneTest()
{
}
}
[TestFixture]
[Ignore("testing ignore a fixture")]
public class FixtureUsingIgnoreAttribute
{
[Test]
public void Success()
{
}
}
[TestFixture(Ignore = "testing ignore a fixture")]
public class FixtureUsingIgnoreProperty
{
[Test]
public void Success()
{
}
}
[TestFixture(IgnoreReason = "testing ignore a fixture")]
public class FixtureUsingIgnoreReasonProperty
{
[Test]
public void Success()
{
}
}
[TestFixture]
public class OuterClass
{
[TestFixture]
public class NestedTestFixture
{
[TestFixture]
public class DoublyNestedTestFixture
{
[Test]
public void Test()
{
}
}
}
}
[TestFixture]
public abstract class AbstractTestFixture
{
[TearDown]
public void Destroy1()
{
}
[Test]
public void SomeTest()
{
}
}
public class DerivedFromAbstractTestFixture : AbstractTestFixture
{
}
[TestFixture]
public class BaseClassTestFixture
{
[Test]
public void Success()
{
}
}
public abstract class AbstractDerivedTestFixture : BaseClassTestFixture
{
[Test]
public void Test()
{
}
}
public class DerivedFromAbstractDerivedTestFixture : AbstractDerivedTestFixture
{
}
[TestFixture]
public abstract class AbstractBaseFixtureWithAttribute
{
}
[TestFixture]
public abstract class AbstractDerivedFixtureWithSecondAttribute : AbstractBaseFixtureWithAttribute
{
}
public class DoubleDerivedClassWithTwoInheritedAttributes : AbstractDerivedFixtureWithSecondAttribute
{
}
[TestFixture]
public class MultipleFixtureSetUpAttributes
{
[OneTimeSetUp]
public void Init1()
{
}
[OneTimeSetUp]
public void Init2()
{
}
[Test] public void OneTest()
{
}
}
[TestFixture]
public class MultipleFixtureTearDownAttributes
{
[OneTimeTearDown]
public void Destroy1()
{
}
[OneTimeTearDown]
public void Destroy2()
{
}
[Test] public void OneTest()
{
}
}
// Base class used to ensure following classes
// all have at least one test
public class OneTestBase
{
[Test] public void OneTest()
{
}
}
[TestFixture]
public class PrivateSetUp : OneTestBase
{
[SetUp]
private void Setup()
{
}
}
[TestFixture]
public class ProtectedSetUp : OneTestBase
{
[SetUp]
protected void Setup()
{
}
}
[TestFixture]
public class StaticSetUp : OneTestBase
{
[SetUp]
public static void Setup()
{
}
}
[TestFixture]
public class SetUpWithReturnValue : OneTestBase
{
[SetUp]
public int Setup()
{
return 0;
}
}
[TestFixture]
public class SetUpWithParameters : OneTestBase
{
[SetUp]
public void Setup(int j)
{
}
}
[TestFixture]
public class PrivateTearDown : OneTestBase
{
[TearDown]
private void Teardown()
{
}
}
[TestFixture]
public class ProtectedTearDown : OneTestBase
{
[TearDown]
protected void Teardown()
{
}
}
[TestFixture]
public class StaticTearDown : OneTestBase
{
[SetUp]
public static void TearDown()
{
}
}
[TestFixture]
public class TearDownWithReturnValue : OneTestBase
{
[TearDown]
public int Teardown()
{
return 0;
}
}
[TestFixture]
public class TearDownWithParameters : OneTestBase
{
[TearDown]
public void Teardown(int j)
{
}
}
[TestFixture]
public class PrivateFixtureSetUp : OneTestBase
{
[OneTimeSetUp]
private void Setup()
{
}
}
[TestFixture]
public class ProtectedFixtureSetUp : OneTestBase
{
[OneTimeSetUp]
protected void Setup()
{
}
}
[TestFixture]
public class StaticFixtureSetUp : OneTestBase
{
[OneTimeSetUp]
public static void Setup()
{
}
}
[TestFixture]
public class FixtureSetUpWithReturnValue : OneTestBase
{
[OneTimeSetUp]
public int Setup()
{
return 0;
}
}
[TestFixture]
public class FixtureSetUpWithParameters : OneTestBase
{
[OneTimeSetUp]
public void Setup(int j)
{
}
}
[TestFixture]
public class PrivateFixtureTearDown : OneTestBase
{
[OneTimeTearDown]
private void Teardown()
{
}
}
[TestFixture]
public class ProtectedFixtureTearDown : OneTestBase
{
[OneTimeTearDown]
protected void Teardown()
{
}
}
[TestFixture]
public class StaticFixtureTearDown : OneTestBase
{
[OneTimeTearDown]
public static void Teardown()
{
}
}
[TestFixture]
public class FixtureTearDownWithReturnValue : OneTestBase
{
[OneTimeTearDown]
public int Teardown()
{
return 0;
}
}
[TestFixture]
public class FixtureTearDownWithParameters : OneTestBase
{
[OneTimeTearDown]
public void Teardown(int j)
{
}
}
#if !(NETCOREAPP1_1 || NETCOREAPP2_0)
[TestFixture]
public class FixtureThatChangesTheCurrentPrincipal
{
[Test]
public void ChangeCurrentPrincipal()
{
WindowsIdentity identity = WindowsIdentity.GetCurrent();
GenericPrincipal principal = new GenericPrincipal( identity, new string[] { } );
System.Threading.Thread.CurrentPrincipal = principal;
}
}
#endif
[TestFixture(typeof(int))]
[TestFixture(typeof(string))]
public class GenericFixtureWithProperArgsProvided<T>
{
[Test]
public void SomeTest()
{
}
}
public class GenericFixtureWithNoTestFixtureAttribute<T>
{
[Test]
public void SomeTest()
{
}
}
[TestFixture]
public class GenericFixtureWithNoArgsProvided<T>
{
[Test]
public void SomeTest()
{
}
}
[TestFixture]
public abstract class AbstractFixtureBase
{
[Test]
public void SomeTest()
{
}
}
public class GenericFixtureDerivedFromAbstractFixtureWithNoArgsProvided<T> : AbstractFixtureBase
{
}
[TestFixture(typeof(int))]
[TestFixture(typeof(string))]
public class GenericFixtureDerivedFromAbstractFixtureWithArgsProvided<T> : AbstractFixtureBase
{
}
}
| |
using System.Linq;
using Marten.Testing.Documents;
using Marten.Testing.Harness;
using Shouldly;
using Xunit;
namespace Marten.Testing.CoreFunctionality
{
public class ejecting_a_document_type : IntegrationContext
{
[Fact]
public void eject_a_document_type_clears_it_from_the_identity_map_regular()
{
var target1 = Target.Random();
var target2 = Target.Random();
var user1 = new User();
var user2 = new User();
using var session = theStore.OpenSession();
session.Store(target1, target2);
session.Store(user1, user2);
session.Load<Target>(target1.Id).ShouldBeTheSameAs(target1);
session.Load<Target>(target2.Id).ShouldBeTheSameAs(target2);
session.Load<User>(user1.Id).ShouldBeTheSameAs(user1);
session.Load<User>(user2.Id).ShouldBeTheSameAs(user2);
session.EjectAllOfType(typeof(Target));
session.PendingChanges.OperationsFor<User>().Any().ShouldBeTrue();
session.PendingChanges.OperationsFor<Target>().Any().ShouldBeFalse();
session.SaveChanges();
session.Load<Target>(target1.Id).ShouldBeNull();
session.Load<Target>(target2.Id).ShouldBeNull();
session.Load<User>(user1.Id).ShouldBeTheSameAs(user1);
session.Load<User>(user2.Id).ShouldBeTheSameAs(user2);
}
[Fact]
public void eject_a_document_type_clears_it_from_the_identity_map_dirty()
{
var target1 = Target.Random();
var target2 = Target.Random();
var user1 = new User();
var user2 = new User();
using var session = theStore.DirtyTrackedSession();
session.Store(target1, target2);
session.Store(user1, user2);
session.Load<Target>(target1.Id).ShouldBeTheSameAs(target1);
session.Load<Target>(target2.Id).ShouldBeTheSameAs(target2);
session.Load<User>(user1.Id).ShouldBeTheSameAs(user1);
session.Load<User>(user2.Id).ShouldBeTheSameAs(user2);
session.EjectAllOfType(typeof(Target));
session.PendingChanges.OperationsFor<User>().Any().ShouldBeTrue();
session.PendingChanges.OperationsFor<Target>().Any().ShouldBeFalse();
session.Load<Target>(target1.Id).ShouldBeNull();
session.Load<Target>(target2.Id).ShouldBeNull();
session.Load<User>(user1.Id).ShouldBeTheSameAs(user1);
session.Load<User>(user2.Id).ShouldBeTheSameAs(user2);
}
[Fact]
public void eject_a_document_type_clears_it_from_the_unit_of_work_regular()
{
var target1 = Target.Random();
var target2 = Target.Random();
var user1 = new User();
var user2 = new User();
using (var session = theStore.OpenSession())
{
session.Insert(target1);
session.Store(target2);
session.Insert(user1);
session.Store(user2);
session.EjectAllOfType(typeof(Target));
session.SaveChanges();
}
using (var session = theStore.QuerySession())
{
session.Query<Target>().ShouldBeEmpty();
session.Load<User>(user1.Id).ShouldNotBeNull();
session.Load<User>(user2.Id).ShouldNotBeNull();
}
}
[Fact]
public void eject_a_document_type_clears_updates_from_the_unit_of_work_regular()
{
var target1 = new Target { Number = 1 };
var target2 = new Target { Number = 2 };
var user1 = new User { Age = 10 };
var user2 = new User { Age = 20 };
using (var session = theStore.OpenSession())
{
session.Store(target1, target2);
session.Store(user1, user2);
session.SaveChanges();
}
using (var session = theStore.OpenSession())
{
target1.Number = 3;
target2.Number = 4;
user1.Age = 30;
user2.Age = 40;
session.Update(target1);
session.Update(target2);
session.Update(user1);
session.Update(user2);
session.EjectAllOfType(typeof(Target));
session.SaveChanges();
}
using (var session = theStore.QuerySession())
{
session.Load<Target>(target1.Id).ShouldNotBeNull().Number.ShouldBe(1);
session.Load<Target>(target2.Id).ShouldNotBeNull().Number.ShouldBe(2);
session.Load<User>(user1.Id).ShouldNotBeNull().Age.ShouldBe(30);
session.Load<User>(user2.Id).ShouldNotBeNull().Age.ShouldBe(40);
}
}
[Fact]
public void eject_a_document_type_clears_it_from_the_unit_of_work_dirty()
{
var target1 = Target.Random();
var target2 = Target.Random();
var user1 = new User();
var user2 = new User();
using (var session = theStore.DirtyTrackedSession())
{
session.Insert(target1);
session.Store(target2);
session.Insert(user1);
session.Store(user2);
session.EjectAllOfType(typeof(Target));
session.SaveChanges();
}
using (var session = theStore.QuerySession())
{
session.Query<Target>().ShouldBeEmpty();
session.Load<User>(user1.Id).ShouldNotBeNull();
session.Load<User>(user2.Id).ShouldNotBeNull();
}
}
[Fact]
public void eject_a_document_type_clears_updates_from_the_unit_of_work_dirty()
{
var target1 = new Target { Number = 1 };
var target2 = new Target { Number = 2 };
var user1 = new User { Age = 10 };
var user2 = new User { Age = 20 };
using (var session = theStore.OpenSession())
{
session.Store(target1, target2);
session.Store(user1, user2);
session.SaveChanges();
}
using (var session = theStore.DirtyTrackedSession())
{
// Need to reload the objects inside the dirty session for it to know about them
session.Load<Target>(target1.Id)!.Number = 3;
session.Load<Target>(target2.Id)!.Number = 4;
session.Load<User>(user1.Id)!.Age = 30;
session.Load<User>(user2.Id)!.Age = 40;
session.EjectAllOfType(typeof(Target));
session.SaveChanges();
}
using (var session = theStore.QuerySession())
{
session.Load<Target>(target1.Id).ShouldNotBeNull().Number.ShouldBe(1);
session.Load<Target>(target2.Id).ShouldNotBeNull().Number.ShouldBe(2);
session.Load<User>(user1.Id).ShouldNotBeNull().Age.ShouldBe(30);
session.Load<User>(user2.Id).ShouldNotBeNull().Age.ShouldBe(40);
}
}
[Fact]
public void eject_a_document_type_clears_it_from_the_unit_of_work_lightweight()
{
var target1 = Target.Random();
var target2 = Target.Random();
var user1 = new User();
var user2 = new User();
using (var session = theStore.LightweightSession())
{
session.Insert(target1);
session.Store(target2);
session.Insert(user1);
session.Store(user2);
session.EjectAllOfType(typeof(Target));
session.SaveChanges();
}
using (var session = theStore.QuerySession())
{
session.Query<Target>().ShouldBeEmpty();
session.Load<User>(user1.Id).ShouldNotBeNull();
session.Load<User>(user2.Id).ShouldNotBeNull();
}
}
[Fact]
public void eject_a_document_type_clears_updates_from_the_unit_of_work_lightweight()
{
var target1 = new Target { Number = 1 };
var target2 = new Target { Number = 2 };
var user1 = new User { Age = 10 };
var user2 = new User { Age = 20 };
using (var session = theStore.OpenSession())
{
session.Store(target1, target2);
session.Store(user1, user2);
session.SaveChanges();
}
using (var session = theStore.LightweightSession())
{
target1.Number = 3;
target2.Number = 4;
user1.Age = 30;
user2.Age = 40;
session.Update(target1);
session.Update(target2);
session.Update(user1);
session.Update(user2);
session.EjectAllOfType(typeof(Target));
session.SaveChanges();
}
using (var session = theStore.QuerySession())
{
session.Load<Target>(target1.Id).ShouldNotBeNull().Number.ShouldBe(1);
session.Load<Target>(target2.Id).ShouldNotBeNull().Number.ShouldBe(2);
session.Load<User>(user1.Id).ShouldNotBeNull().Age.ShouldBe(30);
session.Load<User>(user2.Id).ShouldNotBeNull().Age.ShouldBe(40);
}
}
public ejecting_a_document_type(DefaultStoreFixture fixture) : base(fixture)
{
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Net.Http;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Common;
using Microsoft.WindowsAzure.Scheduler;
using Microsoft.WindowsAzure.Scheduler.Models;
namespace Microsoft.WindowsAzure.Scheduler
{
public partial class SchedulerClient : ServiceClient<SchedulerClient>, ISchedulerClient
{
private string _apiVersion;
/// <summary>
/// Gets the API version.
/// </summary>
public string ApiVersion
{
get { return this._apiVersion; }
}
private Uri _baseUri;
/// <summary>
/// Gets the URI used as the base for all cloud service requests.
/// </summary>
public Uri BaseUri
{
get { return this._baseUri; }
}
private string _cloudServiceName;
public string CloudServiceName
{
get { return this._cloudServiceName; }
set { this._cloudServiceName = value; }
}
private SubscriptionCloudCredentials _credentials;
/// <summary>
/// Gets subscription credentials which uniquely identify Microsoft
/// Azure subscription. The subscription ID forms part of the URI for
/// every service call.
/// </summary>
public SubscriptionCloudCredentials Credentials
{
get { return this._credentials; }
}
private string _jobCollectionName;
public string JobCollectionName
{
get { return this._jobCollectionName; }
set { this._jobCollectionName = value; }
}
private int _longRunningOperationInitialTimeout;
/// <summary>
/// Gets or sets the initial timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationInitialTimeout
{
get { return this._longRunningOperationInitialTimeout; }
set { this._longRunningOperationInitialTimeout = value; }
}
private int _longRunningOperationRetryTimeout;
/// <summary>
/// Gets or sets the retry timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationRetryTimeout
{
get { return this._longRunningOperationRetryTimeout; }
set { this._longRunningOperationRetryTimeout = value; }
}
private IJobOperations _jobs;
public virtual IJobOperations Jobs
{
get { return this._jobs; }
}
/// <summary>
/// Initializes a new instance of the SchedulerClient class.
/// </summary>
private SchedulerClient()
: base()
{
this._jobs = new JobOperations(this);
this._apiVersion = "2013-03-01";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the SchedulerClient class.
/// </summary>
/// <param name='cloudServiceName'>
/// Required.
/// </param>
/// <param name='jobCollectionName'>
/// Required.
/// </param>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
public SchedulerClient(string cloudServiceName, string jobCollectionName, SubscriptionCloudCredentials credentials, Uri baseUri)
: this()
{
if (cloudServiceName == null)
{
throw new ArgumentNullException("cloudServiceName");
}
if (jobCollectionName == null)
{
throw new ArgumentNullException("jobCollectionName");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._cloudServiceName = cloudServiceName;
this._jobCollectionName = jobCollectionName;
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the SchedulerClient class.
/// </summary>
/// <param name='cloudServiceName'>
/// Required.
/// </param>
/// <param name='jobCollectionName'>
/// Required.
/// </param>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
public SchedulerClient(string cloudServiceName, string jobCollectionName, SubscriptionCloudCredentials credentials)
: this()
{
if (cloudServiceName == null)
{
throw new ArgumentNullException("cloudServiceName");
}
if (jobCollectionName == null)
{
throw new ArgumentNullException("jobCollectionName");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._cloudServiceName = cloudServiceName;
this._jobCollectionName = jobCollectionName;
this._credentials = credentials;
this._baseUri = new Uri("https://management.core.windows.net/");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the SchedulerClient class.
/// </summary>
/// <param name='httpClient'>
/// The Http client
/// </param>
private SchedulerClient(HttpClient httpClient)
: base(httpClient)
{
this._jobs = new JobOperations(this);
this._apiVersion = "2013-03-01";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the SchedulerClient class.
/// </summary>
/// <param name='cloudServiceName'>
/// Required.
/// </param>
/// <param name='jobCollectionName'>
/// Required.
/// </param>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public SchedulerClient(string cloudServiceName, string jobCollectionName, SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient)
: this(httpClient)
{
if (cloudServiceName == null)
{
throw new ArgumentNullException("cloudServiceName");
}
if (jobCollectionName == null)
{
throw new ArgumentNullException("jobCollectionName");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._cloudServiceName = cloudServiceName;
this._jobCollectionName = jobCollectionName;
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the SchedulerClient class.
/// </summary>
/// <param name='cloudServiceName'>
/// Required.
/// </param>
/// <param name='jobCollectionName'>
/// Required.
/// </param>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public SchedulerClient(string cloudServiceName, string jobCollectionName, SubscriptionCloudCredentials credentials, HttpClient httpClient)
: this(httpClient)
{
if (cloudServiceName == null)
{
throw new ArgumentNullException("cloudServiceName");
}
if (jobCollectionName == null)
{
throw new ArgumentNullException("jobCollectionName");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._cloudServiceName = cloudServiceName;
this._jobCollectionName = jobCollectionName;
this._credentials = credentials;
this._baseUri = new Uri("https://management.core.windows.net/");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Clones properties from current instance to another SchedulerClient
/// instance
/// </summary>
/// <param name='client'>
/// Instance of SchedulerClient to clone to
/// </param>
protected override void Clone(ServiceClient<SchedulerClient> client)
{
base.Clone(client);
if (client is SchedulerClient)
{
SchedulerClient clonedClient = ((SchedulerClient)client);
clonedClient._cloudServiceName = this._cloudServiceName;
clonedClient._jobCollectionName = this._jobCollectionName;
clonedClient._credentials = this._credentials;
clonedClient._baseUri = this._baseUri;
clonedClient._apiVersion = this._apiVersion;
clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout;
clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout;
clonedClient.Credentials.InitializeServiceClient(clonedClient);
}
}
/// <summary>
/// Parse enum values for type HttpAuthenticationType.
/// </summary>
/// <param name='value'>
/// The value to parse.
/// </param>
/// <returns>
/// The enum value.
/// </returns>
internal static HttpAuthenticationType ParseHttpAuthenticationType(string value)
{
if ("NotSpecified".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return HttpAuthenticationType.NotSpecified;
}
if ("ClientCertificate".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return HttpAuthenticationType.ClientCertificate;
}
if ("ActiveDirectoryOAuth".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return HttpAuthenticationType.ActiveDirectoryOAuth;
}
if ("Basic".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return HttpAuthenticationType.Basic;
}
throw new ArgumentOutOfRangeException("value");
}
/// <summary>
/// Convert an enum of type HttpAuthenticationType to a string.
/// </summary>
/// <param name='value'>
/// The value to convert to a string.
/// </param>
/// <returns>
/// The enum value as a string.
/// </returns>
internal static string HttpAuthenticationTypeToString(HttpAuthenticationType value)
{
if (value == HttpAuthenticationType.NotSpecified)
{
return "NotSpecified";
}
if (value == HttpAuthenticationType.ClientCertificate)
{
return "ClientCertificate";
}
if (value == HttpAuthenticationType.ActiveDirectoryOAuth)
{
return "ActiveDirectoryOAuth";
}
if (value == HttpAuthenticationType.Basic)
{
return "Basic";
}
throw new ArgumentOutOfRangeException("value");
}
/// <summary>
/// Parse enum values for type JobActionType.
/// </summary>
/// <param name='value'>
/// The value to parse.
/// </param>
/// <returns>
/// The enum value.
/// </returns>
internal static JobActionType ParseJobActionType(string value)
{
if ("http".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return JobActionType.Http;
}
if ("https".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return JobActionType.Https;
}
if ("storageQueue".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return JobActionType.StorageQueue;
}
throw new ArgumentOutOfRangeException("value");
}
/// <summary>
/// Convert an enum of type JobActionType to a string.
/// </summary>
/// <param name='value'>
/// The value to convert to a string.
/// </param>
/// <returns>
/// The enum value as a string.
/// </returns>
internal static string JobActionTypeToString(JobActionType value)
{
if (value == JobActionType.Http)
{
return "http";
}
if (value == JobActionType.Https)
{
return "https";
}
if (value == JobActionType.StorageQueue)
{
return "storageQueue";
}
throw new ArgumentOutOfRangeException("value");
}
/// <summary>
/// Parse enum values for type JobHistoryActionName.
/// </summary>
/// <param name='value'>
/// The value to parse.
/// </param>
/// <returns>
/// The enum value.
/// </returns>
internal static JobHistoryActionName ParseJobHistoryActionName(string value)
{
if ("MainAction".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return JobHistoryActionName.MainAction;
}
if ("ErrorAction".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return JobHistoryActionName.ErrorAction;
}
throw new ArgumentOutOfRangeException("value");
}
/// <summary>
/// Convert an enum of type JobHistoryActionName to a string.
/// </summary>
/// <param name='value'>
/// The value to convert to a string.
/// </param>
/// <returns>
/// The enum value as a string.
/// </returns>
internal static string JobHistoryActionNameToString(JobHistoryActionName value)
{
if (value == JobHistoryActionName.MainAction)
{
return "MainAction";
}
if (value == JobHistoryActionName.ErrorAction)
{
return "ErrorAction";
}
throw new ArgumentOutOfRangeException("value");
}
/// <summary>
/// Parse enum values for type JobHistoryStatus.
/// </summary>
/// <param name='value'>
/// The value to parse.
/// </param>
/// <returns>
/// The enum value.
/// </returns>
internal static JobHistoryStatus ParseJobHistoryStatus(string value)
{
if ("completed".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return JobHistoryStatus.Completed;
}
if ("failed".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return JobHistoryStatus.Failed;
}
if ("postponed".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return JobHistoryStatus.Postponed;
}
throw new ArgumentOutOfRangeException("value");
}
/// <summary>
/// Convert an enum of type JobHistoryStatus to a string.
/// </summary>
/// <param name='value'>
/// The value to convert to a string.
/// </param>
/// <returns>
/// The enum value as a string.
/// </returns>
internal static string JobHistoryStatusToString(JobHistoryStatus value)
{
if (value == JobHistoryStatus.Completed)
{
return "completed";
}
if (value == JobHistoryStatus.Failed)
{
return "failed";
}
if (value == JobHistoryStatus.Postponed)
{
return "postponed";
}
throw new ArgumentOutOfRangeException("value");
}
/// <summary>
/// Parse enum values for type JobRecurrenceFrequency.
/// </summary>
/// <param name='value'>
/// The value to parse.
/// </param>
/// <returns>
/// The enum value.
/// </returns>
internal static JobRecurrenceFrequency ParseJobRecurrenceFrequency(string value)
{
if ("minute".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return JobRecurrenceFrequency.Minute;
}
if ("hour".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return JobRecurrenceFrequency.Hour;
}
if ("day".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return JobRecurrenceFrequency.Day;
}
if ("week".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return JobRecurrenceFrequency.Week;
}
if ("month".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return JobRecurrenceFrequency.Month;
}
if ("year".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return JobRecurrenceFrequency.Year;
}
throw new ArgumentOutOfRangeException("value");
}
/// <summary>
/// Convert an enum of type JobRecurrenceFrequency to a string.
/// </summary>
/// <param name='value'>
/// The value to convert to a string.
/// </param>
/// <returns>
/// The enum value as a string.
/// </returns>
internal static string JobRecurrenceFrequencyToString(JobRecurrenceFrequency value)
{
if (value == JobRecurrenceFrequency.Minute)
{
return "minute";
}
if (value == JobRecurrenceFrequency.Hour)
{
return "hour";
}
if (value == JobRecurrenceFrequency.Day)
{
return "day";
}
if (value == JobRecurrenceFrequency.Week)
{
return "week";
}
if (value == JobRecurrenceFrequency.Month)
{
return "month";
}
if (value == JobRecurrenceFrequency.Year)
{
return "year";
}
throw new ArgumentOutOfRangeException("value");
}
/// <summary>
/// Parse enum values for type JobScheduleDay.
/// </summary>
/// <param name='value'>
/// The value to parse.
/// </param>
/// <returns>
/// The enum value.
/// </returns>
internal static JobScheduleDay ParseJobScheduleDay(string value)
{
if ("monday".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return JobScheduleDay.Monday;
}
if ("tuesday".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return JobScheduleDay.Tuesday;
}
if ("wednesday".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return JobScheduleDay.Wednesday;
}
if ("thursday".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return JobScheduleDay.Thursday;
}
if ("friday".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return JobScheduleDay.Friday;
}
if ("saturday".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return JobScheduleDay.Saturday;
}
if ("sunday".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return JobScheduleDay.Sunday;
}
throw new ArgumentOutOfRangeException("value");
}
/// <summary>
/// Convert an enum of type JobScheduleDay to a string.
/// </summary>
/// <param name='value'>
/// The value to convert to a string.
/// </param>
/// <returns>
/// The enum value as a string.
/// </returns>
internal static string JobScheduleDayToString(JobScheduleDay value)
{
if (value == JobScheduleDay.Monday)
{
return "monday";
}
if (value == JobScheduleDay.Tuesday)
{
return "tuesday";
}
if (value == JobScheduleDay.Wednesday)
{
return "wednesday";
}
if (value == JobScheduleDay.Thursday)
{
return "thursday";
}
if (value == JobScheduleDay.Friday)
{
return "friday";
}
if (value == JobScheduleDay.Saturday)
{
return "saturday";
}
if (value == JobScheduleDay.Sunday)
{
return "sunday";
}
throw new ArgumentOutOfRangeException("value");
}
/// <summary>
/// Parse enum values for type JobState.
/// </summary>
/// <param name='value'>
/// The value to parse.
/// </param>
/// <returns>
/// The enum value.
/// </returns>
internal static JobState ParseJobState(string value)
{
if ("enabled".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return JobState.Enabled;
}
if ("disabled".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return JobState.Disabled;
}
if ("faulted".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return JobState.Faulted;
}
if ("completed".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return JobState.Completed;
}
throw new ArgumentOutOfRangeException("value");
}
/// <summary>
/// Convert an enum of type JobState to a string.
/// </summary>
/// <param name='value'>
/// The value to convert to a string.
/// </param>
/// <returns>
/// The enum value as a string.
/// </returns>
internal static string JobStateToString(JobState value)
{
if (value == JobState.Enabled)
{
return "enabled";
}
if (value == JobState.Disabled)
{
return "disabled";
}
if (value == JobState.Faulted)
{
return "faulted";
}
if (value == JobState.Completed)
{
return "completed";
}
throw new ArgumentOutOfRangeException("value");
}
/// <summary>
/// Parse enum values for type RetryType.
/// </summary>
/// <param name='value'>
/// The value to parse.
/// </param>
/// <returns>
/// The enum value.
/// </returns>
internal static RetryType ParseRetryType(string value)
{
if ("none".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return RetryType.None;
}
if ("fixed".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return RetryType.Fixed;
}
throw new ArgumentOutOfRangeException("value");
}
/// <summary>
/// Convert an enum of type RetryType to a string.
/// </summary>
/// <param name='value'>
/// The value to convert to a string.
/// </param>
/// <returns>
/// The enum value as a string.
/// </returns>
internal static string RetryTypeToString(RetryType value)
{
if (value == RetryType.None)
{
return "none";
}
if (value == RetryType.Fixed)
{
return "fixed";
}
throw new ArgumentOutOfRangeException("value");
}
}
}
| |
using System;
using System.Diagnostics;
using NBitcoin.BouncyCastle.Crypto.Parameters;
using NBitcoin.BouncyCastle.Crypto.Utilities;
namespace NBitcoin.BouncyCastle.Crypto.Engines
{
/**
* an implementation of the AES (Rijndael), from FIPS-197.
* <p>
* For further details see: <a href="http://csrc.nist.gov/encryption/aes/">http://csrc.nist.gov/encryption/aes/</a>.
*
* This implementation is based on optimizations from Dr. Brian Gladman's paper and C code at
* <a href="http://fp.gladman.plus.com/cryptography_technology/rijndael/">http://fp.gladman.plus.com/cryptography_technology/rijndael/</a>
*
* There are three levels of tradeoff of speed vs memory
* Because java has no preprocessor, they are written as three separate classes from which to choose
*
* The fastest uses 8Kbytes of static tables to precompute round calculations, 4 256 word tables for encryption
* and 4 for decryption.
*
* The middle performance version uses only one 256 word table for each, for a total of 2Kbytes,
* adding 12 rotate operations per round to compute the values contained in the other tables from
* the contents of the first.
*
* The slowest version uses no static tables at all and computes the values in each round.
* </p>
* <p>
* This file contains the middle performance version with 2Kbytes of static tables for round precomputation.
* </p>
*/
public class AesEngine
: IBlockCipher
{
// The S box
private static readonly byte[] S =
{
99, 124, 119, 123, 242, 107, 111, 197,
48, 1, 103, 43, 254, 215, 171, 118,
202, 130, 201, 125, 250, 89, 71, 240,
173, 212, 162, 175, 156, 164, 114, 192,
183, 253, 147, 38, 54, 63, 247, 204,
52, 165, 229, 241, 113, 216, 49, 21,
4, 199, 35, 195, 24, 150, 5, 154,
7, 18, 128, 226, 235, 39, 178, 117,
9, 131, 44, 26, 27, 110, 90, 160,
82, 59, 214, 179, 41, 227, 47, 132,
83, 209, 0, 237, 32, 252, 177, 91,
106, 203, 190, 57, 74, 76, 88, 207,
208, 239, 170, 251, 67, 77, 51, 133,
69, 249, 2, 127, 80, 60, 159, 168,
81, 163, 64, 143, 146, 157, 56, 245,
188, 182, 218, 33, 16, 255, 243, 210,
205, 12, 19, 236, 95, 151, 68, 23,
196, 167, 126, 61, 100, 93, 25, 115,
96, 129, 79, 220, 34, 42, 144, 136,
70, 238, 184, 20, 222, 94, 11, 219,
224, 50, 58, 10, 73, 6, 36, 92,
194, 211, 172, 98, 145, 149, 228, 121,
231, 200, 55, 109, 141, 213, 78, 169,
108, 86, 244, 234, 101, 122, 174, 8,
186, 120, 37, 46, 28, 166, 180, 198,
232, 221, 116, 31, 75, 189, 139, 138,
112, 62, 181, 102, 72, 3, 246, 14,
97, 53, 87, 185, 134, 193, 29, 158,
225, 248, 152, 17, 105, 217, 142, 148,
155, 30, 135, 233, 206, 85, 40, 223,
140, 161, 137, 13, 191, 230, 66, 104,
65, 153, 45, 15, 176, 84, 187, 22,
};
// The inverse S-box
private static readonly byte[] Si =
{
82, 9, 106, 213, 48, 54, 165, 56,
191, 64, 163, 158, 129, 243, 215, 251,
124, 227, 57, 130, 155, 47, 255, 135,
52, 142, 67, 68, 196, 222, 233, 203,
84, 123, 148, 50, 166, 194, 35, 61,
238, 76, 149, 11, 66, 250, 195, 78,
8, 46, 161, 102, 40, 217, 36, 178,
118, 91, 162, 73, 109, 139, 209, 37,
114, 248, 246, 100, 134, 104, 152, 22,
212, 164, 92, 204, 93, 101, 182, 146,
108, 112, 72, 80, 253, 237, 185, 218,
94, 21, 70, 87, 167, 141, 157, 132,
144, 216, 171, 0, 140, 188, 211, 10,
247, 228, 88, 5, 184, 179, 69, 6,
208, 44, 30, 143, 202, 63, 15, 2,
193, 175, 189, 3, 1, 19, 138, 107,
58, 145, 17, 65, 79, 103, 220, 234,
151, 242, 207, 206, 240, 180, 230, 115,
150, 172, 116, 34, 231, 173, 53, 133,
226, 249, 55, 232, 28, 117, 223, 110,
71, 241, 26, 113, 29, 41, 197, 137,
111, 183, 98, 14, 170, 24, 190, 27,
252, 86, 62, 75, 198, 210, 121, 32,
154, 219, 192, 254, 120, 205, 90, 244,
31, 221, 168, 51, 136, 7, 199, 49,
177, 18, 16, 89, 39, 128, 236, 95,
96, 81, 127, 169, 25, 181, 74, 13,
45, 229, 122, 159, 147, 201, 156, 239,
160, 224, 59, 77, 174, 42, 245, 176,
200, 235, 187, 60, 131, 83, 153, 97,
23, 43, 4, 126, 186, 119, 214, 38,
225, 105, 20, 99, 85, 33, 12, 125,
};
// vector used in calculating key schedule (powers of x in GF(256))
private static readonly byte[] rcon =
{
0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a,
0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91
};
// precomputation tables of calculations for rounds
private static readonly uint[] T0 =
{
0xa56363c6, 0x847c7cf8, 0x997777ee, 0x8d7b7bf6, 0x0df2f2ff,
0xbd6b6bd6, 0xb16f6fde, 0x54c5c591, 0x50303060, 0x03010102,
0xa96767ce, 0x7d2b2b56, 0x19fefee7, 0x62d7d7b5, 0xe6abab4d,
0x9a7676ec, 0x45caca8f, 0x9d82821f, 0x40c9c989, 0x877d7dfa,
0x15fafaef, 0xeb5959b2, 0xc947478e, 0x0bf0f0fb, 0xecadad41,
0x67d4d4b3, 0xfda2a25f, 0xeaafaf45, 0xbf9c9c23, 0xf7a4a453,
0x967272e4, 0x5bc0c09b, 0xc2b7b775, 0x1cfdfde1, 0xae93933d,
0x6a26264c, 0x5a36366c, 0x413f3f7e, 0x02f7f7f5, 0x4fcccc83,
0x5c343468, 0xf4a5a551, 0x34e5e5d1, 0x08f1f1f9, 0x937171e2,
0x73d8d8ab, 0x53313162, 0x3f15152a, 0x0c040408, 0x52c7c795,
0x65232346, 0x5ec3c39d, 0x28181830, 0xa1969637, 0x0f05050a,
0xb59a9a2f, 0x0907070e, 0x36121224, 0x9b80801b, 0x3de2e2df,
0x26ebebcd, 0x6927274e, 0xcdb2b27f, 0x9f7575ea, 0x1b090912,
0x9e83831d, 0x742c2c58, 0x2e1a1a34, 0x2d1b1b36, 0xb26e6edc,
0xee5a5ab4, 0xfba0a05b, 0xf65252a4, 0x4d3b3b76, 0x61d6d6b7,
0xceb3b37d, 0x7b292952, 0x3ee3e3dd, 0x712f2f5e, 0x97848413,
0xf55353a6, 0x68d1d1b9, 0x00000000, 0x2cededc1, 0x60202040,
0x1ffcfce3, 0xc8b1b179, 0xed5b5bb6, 0xbe6a6ad4, 0x46cbcb8d,
0xd9bebe67, 0x4b393972, 0xde4a4a94, 0xd44c4c98, 0xe85858b0,
0x4acfcf85, 0x6bd0d0bb, 0x2aefefc5, 0xe5aaaa4f, 0x16fbfbed,
0xc5434386, 0xd74d4d9a, 0x55333366, 0x94858511, 0xcf45458a,
0x10f9f9e9, 0x06020204, 0x817f7ffe, 0xf05050a0, 0x443c3c78,
0xba9f9f25, 0xe3a8a84b, 0xf35151a2, 0xfea3a35d, 0xc0404080,
0x8a8f8f05, 0xad92923f, 0xbc9d9d21, 0x48383870, 0x04f5f5f1,
0xdfbcbc63, 0xc1b6b677, 0x75dadaaf, 0x63212142, 0x30101020,
0x1affffe5, 0x0ef3f3fd, 0x6dd2d2bf, 0x4ccdcd81, 0x140c0c18,
0x35131326, 0x2fececc3, 0xe15f5fbe, 0xa2979735, 0xcc444488,
0x3917172e, 0x57c4c493, 0xf2a7a755, 0x827e7efc, 0x473d3d7a,
0xac6464c8, 0xe75d5dba, 0x2b191932, 0x957373e6, 0xa06060c0,
0x98818119, 0xd14f4f9e, 0x7fdcdca3, 0x66222244, 0x7e2a2a54,
0xab90903b, 0x8388880b, 0xca46468c, 0x29eeeec7, 0xd3b8b86b,
0x3c141428, 0x79dedea7, 0xe25e5ebc, 0x1d0b0b16, 0x76dbdbad,
0x3be0e0db, 0x56323264, 0x4e3a3a74, 0x1e0a0a14, 0xdb494992,
0x0a06060c, 0x6c242448, 0xe45c5cb8, 0x5dc2c29f, 0x6ed3d3bd,
0xefacac43, 0xa66262c4, 0xa8919139, 0xa4959531, 0x37e4e4d3,
0x8b7979f2, 0x32e7e7d5, 0x43c8c88b, 0x5937376e, 0xb76d6dda,
0x8c8d8d01, 0x64d5d5b1, 0xd24e4e9c, 0xe0a9a949, 0xb46c6cd8,
0xfa5656ac, 0x07f4f4f3, 0x25eaeacf, 0xaf6565ca, 0x8e7a7af4,
0xe9aeae47, 0x18080810, 0xd5baba6f, 0x887878f0, 0x6f25254a,
0x722e2e5c, 0x241c1c38, 0xf1a6a657, 0xc7b4b473, 0x51c6c697,
0x23e8e8cb, 0x7cdddda1, 0x9c7474e8, 0x211f1f3e, 0xdd4b4b96,
0xdcbdbd61, 0x868b8b0d, 0x858a8a0f, 0x907070e0, 0x423e3e7c,
0xc4b5b571, 0xaa6666cc, 0xd8484890, 0x05030306, 0x01f6f6f7,
0x120e0e1c, 0xa36161c2, 0x5f35356a, 0xf95757ae, 0xd0b9b969,
0x91868617, 0x58c1c199, 0x271d1d3a, 0xb99e9e27, 0x38e1e1d9,
0x13f8f8eb, 0xb398982b, 0x33111122, 0xbb6969d2, 0x70d9d9a9,
0x898e8e07, 0xa7949433, 0xb69b9b2d, 0x221e1e3c, 0x92878715,
0x20e9e9c9, 0x49cece87, 0xff5555aa, 0x78282850, 0x7adfdfa5,
0x8f8c8c03, 0xf8a1a159, 0x80898909, 0x170d0d1a, 0xdabfbf65,
0x31e6e6d7, 0xc6424284, 0xb86868d0, 0xc3414182, 0xb0999929,
0x772d2d5a, 0x110f0f1e, 0xcbb0b07b, 0xfc5454a8, 0xd6bbbb6d,
0x3a16162c
};
private static readonly uint[] Tinv0 =
{
0x50a7f451, 0x5365417e, 0xc3a4171a, 0x965e273a, 0xcb6bab3b,
0xf1459d1f, 0xab58faac, 0x9303e34b, 0x55fa3020, 0xf66d76ad,
0x9176cc88, 0x254c02f5, 0xfcd7e54f, 0xd7cb2ac5, 0x80443526,
0x8fa362b5, 0x495ab1de, 0x671bba25, 0x980eea45, 0xe1c0fe5d,
0x02752fc3, 0x12f04c81, 0xa397468d, 0xc6f9d36b, 0xe75f8f03,
0x959c9215, 0xeb7a6dbf, 0xda595295, 0x2d83bed4, 0xd3217458,
0x2969e049, 0x44c8c98e, 0x6a89c275, 0x78798ef4, 0x6b3e5899,
0xdd71b927, 0xb64fe1be, 0x17ad88f0, 0x66ac20c9, 0xb43ace7d,
0x184adf63, 0x82311ae5, 0x60335197, 0x457f5362, 0xe07764b1,
0x84ae6bbb, 0x1ca081fe, 0x942b08f9, 0x58684870, 0x19fd458f,
0x876cde94, 0xb7f87b52, 0x23d373ab, 0xe2024b72, 0x578f1fe3,
0x2aab5566, 0x0728ebb2, 0x03c2b52f, 0x9a7bc586, 0xa50837d3,
0xf2872830, 0xb2a5bf23, 0xba6a0302, 0x5c8216ed, 0x2b1ccf8a,
0x92b479a7, 0xf0f207f3, 0xa1e2694e, 0xcdf4da65, 0xd5be0506,
0x1f6234d1, 0x8afea6c4, 0x9d532e34, 0xa055f3a2, 0x32e18a05,
0x75ebf6a4, 0x39ec830b, 0xaaef6040, 0x069f715e, 0x51106ebd,
0xf98a213e, 0x3d06dd96, 0xae053edd, 0x46bde64d, 0xb58d5491,
0x055dc471, 0x6fd40604, 0xff155060, 0x24fb9819, 0x97e9bdd6,
0xcc434089, 0x779ed967, 0xbd42e8b0, 0x888b8907, 0x385b19e7,
0xdbeec879, 0x470a7ca1, 0xe90f427c, 0xc91e84f8, 0x00000000,
0x83868009, 0x48ed2b32, 0xac70111e, 0x4e725a6c, 0xfbff0efd,
0x5638850f, 0x1ed5ae3d, 0x27392d36, 0x64d90f0a, 0x21a65c68,
0xd1545b9b, 0x3a2e3624, 0xb1670a0c, 0x0fe75793, 0xd296eeb4,
0x9e919b1b, 0x4fc5c080, 0xa220dc61, 0x694b775a, 0x161a121c,
0x0aba93e2, 0xe52aa0c0, 0x43e0223c, 0x1d171b12, 0x0b0d090e,
0xadc78bf2, 0xb9a8b62d, 0xc8a91e14, 0x8519f157, 0x4c0775af,
0xbbdd99ee, 0xfd607fa3, 0x9f2601f7, 0xbcf5725c, 0xc53b6644,
0x347efb5b, 0x7629438b, 0xdcc623cb, 0x68fcedb6, 0x63f1e4b8,
0xcadc31d7, 0x10856342, 0x40229713, 0x2011c684, 0x7d244a85,
0xf83dbbd2, 0x1132f9ae, 0x6da129c7, 0x4b2f9e1d, 0xf330b2dc,
0xec52860d, 0xd0e3c177, 0x6c16b32b, 0x99b970a9, 0xfa489411,
0x2264e947, 0xc48cfca8, 0x1a3ff0a0, 0xd82c7d56, 0xef903322,
0xc74e4987, 0xc1d138d9, 0xfea2ca8c, 0x360bd498, 0xcf81f5a6,
0x28de7aa5, 0x268eb7da, 0xa4bfad3f, 0xe49d3a2c, 0x0d927850,
0x9bcc5f6a, 0x62467e54, 0xc2138df6, 0xe8b8d890, 0x5ef7392e,
0xf5afc382, 0xbe805d9f, 0x7c93d069, 0xa92dd56f, 0xb31225cf,
0x3b99acc8, 0xa77d1810, 0x6e639ce8, 0x7bbb3bdb, 0x097826cd,
0xf418596e, 0x01b79aec, 0xa89a4f83, 0x656e95e6, 0x7ee6ffaa,
0x08cfbc21, 0xe6e815ef, 0xd99be7ba, 0xce366f4a, 0xd4099fea,
0xd67cb029, 0xafb2a431, 0x31233f2a, 0x3094a5c6, 0xc066a235,
0x37bc4e74, 0xa6ca82fc, 0xb0d090e0, 0x15d8a733, 0x4a9804f1,
0xf7daec41, 0x0e50cd7f, 0x2ff69117, 0x8dd64d76, 0x4db0ef43,
0x544daacc, 0xdf0496e4, 0xe3b5d19e, 0x1b886a4c, 0xb81f2cc1,
0x7f516546, 0x04ea5e9d, 0x5d358c01, 0x737487fa, 0x2e410bfb,
0x5a1d67b3, 0x52d2db92, 0x335610e9, 0x1347d66d, 0x8c61d79a,
0x7a0ca137, 0x8e14f859, 0x893c13eb, 0xee27a9ce, 0x35c961b7,
0xede51ce1, 0x3cb1477a, 0x59dfd29c, 0x3f73f255, 0x79ce1418,
0xbf37c773, 0xeacdf753, 0x5baafd5f, 0x146f3ddf, 0x86db4478,
0x81f3afca, 0x3ec468b9, 0x2c342438, 0x5f40a3c2, 0x72c31d16,
0x0c25e2bc, 0x8b493c28, 0x41950dff, 0x7101a839, 0xdeb30c08,
0x9ce4b4d8, 0x90c15664, 0x6184cb7b, 0x70b632d5, 0x745c6c48,
0x4257b8d0
};
private static uint Shift(uint r, int shift)
{
return (r >> shift) | (r << (32 - shift));
}
/* multiply four bytes in GF(2^8) by 'x' {02} in parallel */
private const uint m1 = 0x80808080;
private const uint m2 = 0x7f7f7f7f;
private const uint m3 = 0x0000001b;
private static uint FFmulX(uint x)
{
return ((x & m2) << 1) ^ (((x & m1) >> 7) * m3);
}
/*
The following defines provide alternative definitions of FFmulX that might
give improved performance if a fast 32-bit multiply is not available.
private int FFmulX(int x) { int u = x & m1; u |= (u >> 1); return ((x & m2) << 1) ^ ((u >>> 3) | (u >>> 6)); }
private static final int m4 = 0x1b1b1b1b;
private int FFmulX(int x) { int u = x & m1; return ((x & m2) << 1) ^ ((u - (u >>> 7)) & m4); }
*/
private static uint Inv_Mcol(uint x)
{
uint f2 = FFmulX(x);
uint f4 = FFmulX(f2);
uint f8 = FFmulX(f4);
uint f9 = x ^ f8;
return f2 ^ f4 ^ f8 ^ Shift(f2 ^ f9, 8) ^ Shift(f4 ^ f9, 16) ^ Shift(f9, 24);
}
private static uint SubWord(uint x)
{
return (uint)S[x&255]
| (((uint)S[(x>>8)&255]) << 8)
| (((uint)S[(x>>16)&255]) << 16)
| (((uint)S[(x>>24)&255]) << 24);
}
/**
* Calculate the necessary round keys
* The number of calculations depends on key size and block size
* AES specified a fixed block size of 128 bits and key sizes 128/192/256 bits
* This code is written assuming those are the only possible values
*/
private uint[][] GenerateWorkingKey(
byte[] key,
bool forEncryption)
{
int KC = key.Length / 4; // key length in words
int t;
if ((KC != 4) && (KC != 6) && (KC != 8))
throw new ArgumentException("Key length not 128/192/256 bits.");
ROUNDS = KC + 6; // This is not always true for the generalized Rijndael that allows larger block sizes
uint[][] W = new uint[ROUNDS + 1][]; // 4 words in a block
for (int i = 0; i <= ROUNDS; ++i)
{
W[i] = new uint[4];
}
//
// copy the key into the round key array
//
t = 0;
for (int i = 0; i < key.Length; t++)
{
W[t >> 2][t & 3] = Pack.LE_To_UInt32(key, i);
i+=4;
}
//
// while not enough round key material calculated
// calculate new values
//
int k = (ROUNDS + 1) << 2;
for (int i = KC; (i < k); i++)
{
uint temp = W[(i-1)>>2][(i-1)&3];
if ((i % KC) == 0)
{
temp = SubWord(Shift(temp, 8)) ^ rcon[(i / KC)-1];
}
else if ((KC > 6) && ((i % KC) == 4))
{
temp = SubWord(temp);
}
W[i>>2][i&3] = W[(i - KC)>>2][(i-KC)&3] ^ temp;
}
if (!forEncryption)
{
for (int j = 1; j < ROUNDS; j++)
{
uint[] w = W[j];
for (int i = 0; i < 4; i++)
{
w[i] = Inv_Mcol(w[i]);
}
}
}
return W;
}
private int ROUNDS;
private uint[][] WorkingKey;
private uint C0, C1, C2, C3;
private bool forEncryption;
private const int BLOCK_SIZE = 16;
/**
* default constructor - 128 bit block size.
*/
public AesEngine()
{
}
/**
* initialise an AES cipher.
*
* @param forEncryption whether or not we are for encryption.
* @param parameters the parameters required to set up the cipher.
* @exception ArgumentException if the parameters argument is
* inappropriate.
*/
public void Init(
bool forEncryption,
ICipherParameters parameters)
{
KeyParameter keyParameter = parameters as KeyParameter;
if (keyParameter == null)
throw new ArgumentException("invalid parameter passed to AES init - " + parameters.GetType().Name);
WorkingKey = GenerateWorkingKey(keyParameter.GetKey(), forEncryption);
this.forEncryption = forEncryption;
}
public string AlgorithmName
{
get { return "AES"; }
}
public bool IsPartialBlockOkay
{
get { return false; }
}
public int GetBlockSize()
{
return BLOCK_SIZE;
}
public int ProcessBlock(
byte[] input,
int inOff,
byte[] output,
int outOff)
{
if (WorkingKey == null)
{
throw new InvalidOperationException("AES engine not initialised");
}
if ((inOff + (32 / 2)) > input.Length)
{
throw new DataLengthException("input buffer too short");
}
if ((outOff + (32 / 2)) > output.Length)
{
throw new DataLengthException("output buffer too short");
}
UnPackBlock(input, inOff);
if (forEncryption)
{
EncryptBlock(WorkingKey);
}
else
{
DecryptBlock(WorkingKey);
}
PackBlock(output, outOff);
return BLOCK_SIZE;
}
public void Reset()
{
}
private void UnPackBlock(
byte[] bytes,
int off)
{
C0 = Pack.LE_To_UInt32(bytes, off);
C1 = Pack.LE_To_UInt32(bytes, off + 4);
C2 = Pack.LE_To_UInt32(bytes, off + 8);
C3 = Pack.LE_To_UInt32(bytes, off + 12);
}
private void PackBlock(
byte[] bytes,
int off)
{
Pack.UInt32_To_LE(C0, bytes, off);
Pack.UInt32_To_LE(C1, bytes, off + 4);
Pack.UInt32_To_LE(C2, bytes, off + 8);
Pack.UInt32_To_LE(C3, bytes, off + 12);
}
private void EncryptBlock(uint[][] KW)
{
uint[] kw = KW[0];
uint t0 = this.C0 ^ kw[0];
uint t1 = this.C1 ^ kw[1];
uint t2 = this.C2 ^ kw[2];
uint r0, r1, r2, r3 = this.C3 ^ kw[3];
int r = 1;
while (r < ROUNDS - 1)
{
kw = KW[r++];
r0 = T0[t0 & 255] ^ Shift(T0[(t1 >> 8) & 255], 24) ^ Shift(T0[(t2 >> 16) & 255], 16) ^ Shift(T0[(r3 >> 24) & 255], 8) ^ kw[0];
r1 = T0[t1 & 255] ^ Shift(T0[(t2 >> 8) & 255], 24) ^ Shift(T0[(r3 >> 16) & 255], 16) ^ Shift(T0[(t0 >> 24) & 255], 8) ^ kw[1];
r2 = T0[t2 & 255] ^ Shift(T0[(r3 >> 8) & 255], 24) ^ Shift(T0[(t0 >> 16) & 255], 16) ^ Shift(T0[(t1 >> 24) & 255], 8) ^ kw[2];
r3 = T0[r3 & 255] ^ Shift(T0[(t0 >> 8) & 255], 24) ^ Shift(T0[(t1 >> 16) & 255], 16) ^ Shift(T0[(t2 >> 24) & 255], 8) ^ kw[3];
kw = KW[r++];
t0 = T0[r0 & 255] ^ Shift(T0[(r1 >> 8) & 255], 24) ^ Shift(T0[(r2 >> 16) & 255], 16) ^ Shift(T0[(r3 >> 24) & 255], 8) ^ kw[0];
t1 = T0[r1 & 255] ^ Shift(T0[(r2 >> 8) & 255], 24) ^ Shift(T0[(r3 >> 16) & 255], 16) ^ Shift(T0[(r0 >> 24) & 255], 8) ^ kw[1];
t2 = T0[r2 & 255] ^ Shift(T0[(r3 >> 8) & 255], 24) ^ Shift(T0[(r0 >> 16) & 255], 16) ^ Shift(T0[(r1 >> 24) & 255], 8) ^ kw[2];
r3 = T0[r3 & 255] ^ Shift(T0[(r0 >> 8) & 255], 24) ^ Shift(T0[(r1 >> 16) & 255], 16) ^ Shift(T0[(r2 >> 24) & 255], 8) ^ kw[3];
}
kw = KW[r++];
r0 = T0[t0 & 255] ^ Shift(T0[(t1 >> 8) & 255], 24) ^ Shift(T0[(t2 >> 16) & 255], 16) ^ Shift(T0[(r3 >> 24) & 255], 8) ^ kw[0];
r1 = T0[t1 & 255] ^ Shift(T0[(t2 >> 8) & 255], 24) ^ Shift(T0[(r3 >> 16) & 255], 16) ^ Shift(T0[(t0 >> 24) & 255], 8) ^ kw[1];
r2 = T0[t2 & 255] ^ Shift(T0[(r3 >> 8) & 255], 24) ^ Shift(T0[(t0 >> 16) & 255], 16) ^ Shift(T0[(t1 >> 24) & 255], 8) ^ kw[2];
r3 = T0[r3 & 255] ^ Shift(T0[(t0 >> 8) & 255], 24) ^ Shift(T0[(t1 >> 16) & 255], 16) ^ Shift(T0[(t2 >> 24) & 255], 8) ^ kw[3];
// the final round's table is a simple function of S so we don't use a whole other four tables for it
kw = KW[r];
this.C0 = (uint)S[r0 & 255] ^ (((uint)S[(r1 >> 8) & 255]) << 8) ^ (((uint)S[(r2 >> 16) & 255]) << 16) ^ (((uint)S[(r3 >> 24) & 255]) << 24) ^ kw[0];
this.C1 = (uint)S[r1 & 255] ^ (((uint)S[(r2 >> 8) & 255]) << 8) ^ (((uint)S[(r3 >> 16) & 255]) << 16) ^ (((uint)S[(r0 >> 24) & 255]) << 24) ^ kw[1];
this.C2 = (uint)S[r2 & 255] ^ (((uint)S[(r3 >> 8) & 255]) << 8) ^ (((uint)S[(r0 >> 16) & 255]) << 16) ^ (((uint)S[(r1 >> 24) & 255]) << 24) ^ kw[2];
this.C3 = (uint)S[r3 & 255] ^ (((uint)S[(r0 >> 8) & 255]) << 8) ^ (((uint)S[(r1 >> 16) & 255]) << 16) ^ (((uint)S[(r2 >> 24) & 255]) << 24) ^ kw[3];
}
private void DecryptBlock(uint[][] KW)
{
uint[] kw = KW[ROUNDS];
uint t0 = this.C0 ^ kw[0];
uint t1 = this.C1 ^ kw[1];
uint t2 = this.C2 ^ kw[2];
uint r0, r1, r2, r3 = this.C3 ^ kw[3];
int r = ROUNDS - 1;
while (r > 1)
{
kw = KW[r--];
r0 = Tinv0[t0 & 255] ^ Shift(Tinv0[(r3 >> 8) & 255], 24) ^ Shift(Tinv0[(t2 >> 16) & 255], 16) ^ Shift(Tinv0[(t1 >> 24) & 255], 8) ^ kw[0];
r1 = Tinv0[t1 & 255] ^ Shift(Tinv0[(t0 >> 8) & 255], 24) ^ Shift(Tinv0[(r3 >> 16) & 255], 16) ^ Shift(Tinv0[(t2 >> 24) & 255], 8) ^ kw[1];
r2 = Tinv0[t2 & 255] ^ Shift(Tinv0[(t1 >> 8) & 255], 24) ^ Shift(Tinv0[(t0 >> 16) & 255], 16) ^ Shift(Tinv0[(r3 >> 24) & 255], 8) ^ kw[2];
r3 = Tinv0[r3 & 255] ^ Shift(Tinv0[(t2 >> 8) & 255], 24) ^ Shift(Tinv0[(t1 >> 16) & 255], 16) ^ Shift(Tinv0[(t0 >> 24) & 255], 8) ^ kw[3];
kw = KW[r--];
t0 = Tinv0[r0 & 255] ^ Shift(Tinv0[(r3 >> 8) & 255], 24) ^ Shift(Tinv0[(r2 >> 16) & 255], 16) ^ Shift(Tinv0[(r1 >> 24) & 255], 8) ^ kw[0];
t1 = Tinv0[r1 & 255] ^ Shift(Tinv0[(r0 >> 8) & 255], 24) ^ Shift(Tinv0[(r3 >> 16) & 255], 16) ^ Shift(Tinv0[(r2 >> 24) & 255], 8) ^ kw[1];
t2 = Tinv0[r2 & 255] ^ Shift(Tinv0[(r1 >> 8) & 255], 24) ^ Shift(Tinv0[(r0 >> 16) & 255], 16) ^ Shift(Tinv0[(r3 >> 24) & 255], 8) ^ kw[2];
r3 = Tinv0[r3 & 255] ^ Shift(Tinv0[(r2 >> 8) & 255], 24) ^ Shift(Tinv0[(r1 >> 16) & 255], 16) ^ Shift(Tinv0[(r0 >> 24) & 255], 8) ^ kw[3];
}
kw = KW[1];
r0 = Tinv0[t0 & 255] ^ Shift(Tinv0[(r3 >> 8) & 255], 24) ^ Shift(Tinv0[(t2 >> 16) & 255], 16) ^ Shift(Tinv0[(t1 >> 24) & 255], 8) ^ kw[0];
r1 = Tinv0[t1 & 255] ^ Shift(Tinv0[(t0 >> 8) & 255], 24) ^ Shift(Tinv0[(r3 >> 16) & 255], 16) ^ Shift(Tinv0[(t2 >> 24) & 255], 8) ^ kw[1];
r2 = Tinv0[t2 & 255] ^ Shift(Tinv0[(t1 >> 8) & 255], 24) ^ Shift(Tinv0[(t0 >> 16) & 255], 16) ^ Shift(Tinv0[(r3 >> 24) & 255], 8) ^ kw[2];
r3 = Tinv0[r3 & 255] ^ Shift(Tinv0[(t2 >> 8) & 255], 24) ^ Shift(Tinv0[(t1 >> 16) & 255], 16) ^ Shift(Tinv0[(t0 >> 24) & 255], 8) ^ kw[3];
// the final round's table is a simple function of Si so we don't use a whole other four tables for it
kw = KW[0];
this.C0 = (uint)Si[r0 & 255] ^ (((uint)Si[(r3 >> 8) & 255]) << 8) ^ (((uint)Si[(r2 >> 16) & 255]) << 16) ^ (((uint)Si[(r1 >> 24) & 255]) << 24) ^ kw[0];
this.C1 = (uint)Si[r1 & 255] ^ (((uint)Si[(r0 >> 8) & 255]) << 8) ^ (((uint)Si[(r3 >> 16) & 255]) << 16) ^ (((uint)Si[(r2 >> 24) & 255]) << 24) ^ kw[1];
this.C2 = (uint)Si[r2 & 255] ^ (((uint)Si[(r1 >> 8) & 255]) << 8) ^ (((uint)Si[(r0 >> 16) & 255]) << 16) ^ (((uint)Si[(r3 >> 24) & 255]) << 24) ^ kw[2];
this.C3 = (uint)Si[r3 & 255] ^ (((uint)Si[(r2 >> 8) & 255]) << 8) ^ (((uint)Si[(r1 >> 16) & 255]) << 16) ^ (((uint)Si[(r0 >> 24) & 255]) << 24) ^ kw[3];
}
}
}
| |
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using IdentityServer4.Configuration;
using IdentityServer4.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Threading.Tasks;
using IdentityServer4.Models;
using IdentityServer4.Stores;
using System.Linq;
using Microsoft.AspNetCore.Authentication;
#pragma warning disable 1591
namespace IdentityServer4.Extensions
{
public static class HttpContextExtensions
{
public static async Task<bool> GetSchemeSupportsSignOutAsync(this HttpContext context, string scheme)
{
var provider = context.RequestServices.GetRequiredService<IAuthenticationHandlerProvider>();
var handler = await provider.GetHandlerAsync(context, scheme);
return (handler != null && handler is IAuthenticationSignOutHandler);
}
public static void SetIdentityServerOrigin(this HttpContext context, string value)
{
if (context == null) throw new ArgumentNullException(nameof(context));
if (value == null) throw new ArgumentNullException(nameof(value));
var split = value.Split(new[] { "://" }, StringSplitOptions.RemoveEmptyEntries);
var request = context.Request;
request.Scheme = split.First();
request.Host = new HostString(split.Last());
}
public static void SetIdentityServerBasePath(this HttpContext context, string value)
{
if (context == null) throw new ArgumentNullException(nameof(context));
context.Items[Constants.EnvironmentKeys.IdentityServerBasePath] = value;
}
public static string GetIdentityServerOrigin(this HttpContext context)
{
var options = context.RequestServices.GetRequiredService<IdentityServerOptions>();
var request = context.Request;
if (options.MutualTls.Enabled && options.MutualTls.DomainName.IsPresent())
{
if (!options.MutualTls.DomainName.Contains("."))
{
if (request.Host.Value.StartsWith(options.MutualTls.DomainName, StringComparison.OrdinalIgnoreCase))
{
return request.Scheme + "://" +
request.Host.Value.Substring(options.MutualTls.DomainName.Length + 1);
}
}
}
return request.Scheme + "://" + request.Host.Value;
}
internal static void SetSignOutCalled(this HttpContext context)
{
if (context == null) throw new ArgumentNullException(nameof(context));
context.Items[Constants.EnvironmentKeys.SignOutCalled] = "true";
}
internal static bool GetSignOutCalled(this HttpContext context)
{
return context.Items.ContainsKey(Constants.EnvironmentKeys.SignOutCalled);
}
/// <summary>
/// Gets the host name of IdentityServer.
/// </summary>
/// <param name="context">The context.</param>
/// <returns></returns>
public static string GetIdentityServerHost(this HttpContext context)
{
var request = context.Request;
return request.Scheme + "://" + request.Host.ToUriComponent();
}
/// <summary>
/// Gets the base path of IdentityServer.
/// </summary>
/// <param name="context">The context.</param>
/// <returns></returns>
public static string GetIdentityServerBasePath(this HttpContext context)
{
return context.Items[Constants.EnvironmentKeys.IdentityServerBasePath] as string;
}
/// <summary>
/// Gets the public base URL for IdentityServer.
/// </summary>
/// <param name="context">The context.</param>
/// <returns></returns>
public static string GetIdentityServerBaseUrl(this HttpContext context)
{
return context.GetIdentityServerHost() + context.GetIdentityServerBasePath();
}
/// <summary>
/// Gets the identity server relative URL.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="path">The path.</param>
/// <returns></returns>
public static string GetIdentityServerRelativeUrl(this HttpContext context, string path)
{
if (!path.IsLocalUrl())
{
return null;
}
if (path.StartsWith("~/")) path = path.Substring(1);
path = context.GetIdentityServerBaseUrl().EnsureTrailingSlash() + path.RemoveLeadingSlash();
return path;
}
/// <summary>
/// Gets the identity server issuer URI.
/// </summary>
/// <param name="context">The context.</param>
/// <returns></returns>
/// <exception cref="System.ArgumentNullException">context</exception>
public static string GetIdentityServerIssuerUri(this HttpContext context)
{
if (context == null) throw new ArgumentNullException(nameof(context));
// if they've explicitly configured a URI then use it,
// otherwise dynamically calculate it
var options = context.RequestServices.GetRequiredService<IdentityServerOptions>();
var uri = options.IssuerUri;
if (uri.IsMissing())
{
uri = context.GetIdentityServerOrigin() + context.GetIdentityServerBasePath();
if (uri.EndsWith("/")) uri = uri.Substring(0, uri.Length - 1);
if (options.LowerCaseIssuerUri)
{
uri = uri.ToLowerInvariant();
}
}
return uri;
}
internal static async Task<string> GetIdentityServerSignoutFrameCallbackUrlAsync(this HttpContext context, LogoutMessage logoutMessage = null)
{
var userSession = context.RequestServices.GetRequiredService<IUserSession>();
var user = await userSession.GetUserAsync();
var currentSubId = user?.GetSubjectId();
EndSession endSessionMsg = null;
// if we have a logout message, then that take precedence over the current user
if (logoutMessage?.ClientIds?.Any() == true)
{
var clientIds = logoutMessage?.ClientIds;
// check if current user is same, since we migth have new clients (albeit unlikely)
if (currentSubId == logoutMessage?.SubjectId)
{
clientIds = clientIds.Union(await userSession.GetClientListAsync());
clientIds = clientIds.Distinct();
}
endSessionMsg = new EndSession
{
SubjectId = logoutMessage.SubjectId,
SessionId = logoutMessage.SessionId,
ClientIds = clientIds
};
}
else if (currentSubId != null)
{
// see if current user has any clients they need to signout of
var clientIds = await userSession.GetClientListAsync();
if (clientIds.Any())
{
endSessionMsg = new EndSession
{
SubjectId = currentSubId,
SessionId = await userSession.GetSessionIdAsync(),
ClientIds = clientIds
};
}
}
if (endSessionMsg != null)
{
var clock = context.RequestServices.GetRequiredService<ISystemClock>();
var msg = new Message<EndSession>(endSessionMsg, clock.UtcNow.UtcDateTime);
var endSessionMessageStore = context.RequestServices.GetRequiredService<IMessageStore<EndSession>>();
var id = await endSessionMessageStore.WriteAsync(msg);
var signoutIframeUrl = context.GetIdentityServerBaseUrl().EnsureTrailingSlash() + Constants.ProtocolRoutePaths.EndSessionCallback;
signoutIframeUrl = signoutIframeUrl.AddQueryString(Constants.UIConstants.DefaultRoutePathParams.EndSessionCallback, id);
return signoutIframeUrl;
}
// no sessions, so nothing to cleanup
return null;
}
}
}
| |
/*
* 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.
*/
using System;
using System.Collections;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using Quartz;
using Quartz.Impl;
using Quartz.Simpl;
using Quartz.Spi;
using Quartz.Util;
using Spring.Context;
using Spring.Context.Events;
using Spring.Core.IO;
using Spring.Data.Common;
using Spring.Objects.Factory;
namespace Spring.Scheduling.Quartz
{
/// <summary>
/// FactoryObject that sets up a Quartz Scheduler and exposes it for object references.
/// </summary>
/// <remarks>
/// <p>
/// Allows registration of JobDetails, Calendars and Triggers, automatically
/// starting the scheduler on initialization and shutting it down on destruction.
/// In scenarios that just require static registration of jobs at startup, there
/// is no need to access the Scheduler instance itself in application code.
/// </p>
///
/// <p>
/// For dynamic registration of jobs at runtime, use a object reference to
/// this SchedulerFactoryObject to get direct access to the Quartz Scheduler
/// (<see cref="IScheduler" />). This allows you to create new jobs
/// and triggers, and also to control and monitor the entire Scheduler.
/// </p>
///
/// <p>
/// Note that Quartz instantiates a new Job for each execution, in
/// contrast to Timer which uses a TimerTask instance that is shared
/// between repeated executions. Just JobDetail descriptors are shared.
/// </p>
///
/// <p>
/// When using persistent jobs, it is strongly recommended to perform all
/// operations on the Scheduler within Spring-managed transactions.
/// Else, database locking will not properly work and might even break.
/// </p>
/// <p>
/// The preferred way to achieve transactional execution is to demarcate
/// declarative transactions at the business facade level, which will
/// automatically apply to Scheduler operations performed within those scopes.
/// Alternatively, define a TransactionProxyFactoryObject for the Scheduler itself.
/// </p>
/// </remarks>
/// <author>Juergen Hoeller</author>
/// <author>Marko Lahma (.NET)</author>
/// <seealso cref="IScheduler" />
/// <seealso cref="ISchedulerFactory" />
/// <seealso cref="StdSchedulerFactory" />
public class SchedulerFactoryObject : SchedulerAccessor, IFactoryObject, IObjectNameAware,
IApplicationContextAware, IApplicationEventListener, IInitializingObject, IDisposable
{
/// <summary>
/// Default thread count to be set to thread pool.
/// </summary>
public const int DEFAULT_THREAD_COUNT = 10;
/// <summary>
/// Property name for thread count in thread pool.
/// </summary>
public const string PROP_THREAD_COUNT = "quartz.threadPool.threadCount";
[ThreadStatic]
private static IDbProvider configTimeDbProvider;
[ThreadStatic]
private static ITaskExecutor configTimeTaskExecutor;
/// <summary>
/// Return the IDbProvider for the currently configured Quartz Scheduler,
/// to be used by LocalDataSourceJobStore.
/// </summary>
/// <remarks>
/// This instance will be set before initialization of the corresponding
/// Scheduler, and reset immediately afterwards. It is thus only available
/// during configuration.
/// </remarks>
/// <seealso cref="DbProvider" />
/// <seealso cref="LocalDataSourceJobStore" />
public static IDbProvider ConfigTimeDbProvider
{
get { return configTimeDbProvider; }
}
/// <summary>
/// Return the TaskExecutor for the currently configured Quartz Scheduler,
/// to be used by LocalTaskExecutorThreadPool.
/// </summary>
/// <remarks>
/// This instance will be set before initialization of the corresponding
/// Scheduler, and reset immediately afterwards. It is thus only available
/// during configuration.
/// </remarks>
public static ITaskExecutor ConfigTimeTaskExecutor
{
get { return configTimeTaskExecutor; }
}
private IApplicationContext applicationContext;
private string applicationContextSchedulerContextKey;
private bool autoStartup = true;
private IResource configLocation;
private IJobFactory jobFactory;
private bool jobFactorySet;
private IDictionary quartzProperties;
private IScheduler scheduler;
private IDictionary schedulerContextMap;
private Type schedulerFactoryType;
private string schedulerName;
private TimeSpan startupDelay = TimeSpan.Zero;
private ITaskExecutor taskExecutor;
private bool exposeSchedulerInRepository;
private bool waitForJobsToCompleteOnShutdown;
private IDbProvider dbProvider;
/// <summary>
/// Initializes a new instance of the <see cref="SchedulerFactoryObject"/> class.
/// </summary>
public SchedulerFactoryObject()
{
schedulerFactoryType = typeof (StdSchedulerFactory);
}
/// <summary>
/// Set the Quartz SchedulerFactory implementation to use.
/// </summary>
/// <remarks>
/// Default is StdSchedulerFactory, reading in the standard
/// quartz.properties from Quartz' dll. To use custom Quartz
/// properties, specify "configLocation" or "quartzProperties".
/// </remarks>
/// <value>The scheduler factory class.</value>
/// <seealso cref="StdSchedulerFactory"/>
/// <seealso cref="ConfigLocation"/>
/// <seealso cref="QuartzProperties"/>
public virtual Type SchedulerFactoryType
{
set
{
if (value == null || !typeof (ISchedulerFactory).IsAssignableFrom(value))
{
throw new ArgumentException("schedulerFactoryType must implement [Quartz.ISchedulerFactory]");
}
schedulerFactoryType = value;
}
}
/// <summary>
/// Set the name of the Scheduler to fetch from the SchedulerFactory.
/// If not specified, the default Scheduler will be used.
/// </summary>
/// <value>The name of the scheduler.</value>
/// <seealso cref="ISchedulerFactory.GetScheduler(string)"/>
/// <seealso cref="ISchedulerFactory.GetScheduler()"/>
public virtual string SchedulerName
{
set { schedulerName = value; }
}
/// <summary>
/// Set the location of the Quartz properties config file, for example
/// as assembly resource "assembly:quartz.properties".
/// </summary>
/// <remarks>
/// Note: Can be omitted when all necessary properties are specified
/// locally via this object, or when relying on Quartz' default configuration.
/// </remarks>
/// <seealso cref="QuartzProperties" />
public virtual IResource ConfigLocation
{
set { configLocation = value; }
}
/// <summary>
/// Set Quartz properties, like "quartz.threadPool.type".
/// </summary>
/// <remarks>
/// Can be used to override values in a Quartz properties config file,
/// or to specify all necessary properties locally.
/// </remarks>
/// <seealso cref="ConfigLocation" />
public virtual IDictionary QuartzProperties
{
set { quartzProperties = value; }
}
/// <summary>
/// Set the Spring TaskExecutor to use as Quartz backend.
/// Exposed as thread pool through the Quartz SPI.
/// </summary>
/// <remarks>
/// By default, a Quartz SimpleThreadPool will be used, configured through
/// the corresponding Quartz properties.
/// </remarks>
/// <value>The task executor.</value>
/// <seealso cref="QuartzProperties"/>
/// <seealso cref="LocalTaskExecutorThreadPool"/>
public virtual ITaskExecutor TaskExecutor
{
set { taskExecutor = value; }
}
/// <summary>
/// Register objects in the Scheduler context via a given Map.
/// These objects will be available to any Job that runs in this Scheduler.
/// </summary>
/// <remarks>
/// Note: When using persistent Jobs whose JobDetail will be kept in the
/// database, do not put Spring-managed object or an ApplicationContext
/// reference into the JobDataMap but rather into the SchedulerContext.
/// </remarks>
/// <value>
/// Map with string keys and any objects as
/// values (for example Spring-managed objects)
/// </value>
/// <seealso cref="JobDetailObject.JobDataAsMap" />
public virtual IDictionary SchedulerContextAsMap
{
set { schedulerContextMap = value; }
}
/// <summary>
/// Set the key of an IApplicationContext reference to expose in the
/// SchedulerContext, for example "applicationContext". Default is none.
/// Only applicable when running in a Spring ApplicationContext.
/// </summary>
/// <remarks>
/// <p>
/// Note: When using persistent Jobs whose JobDetail will be kept in the
/// database, do not put an IApplicationContext reference into the JobDataMap
/// but rather into the SchedulerContext.
/// </p>
///
/// <p>
/// In case of a QuartzJobObject, the reference will be applied to the Job
/// instance as object property. An "applicationContext" attribute will
/// correspond to a "setApplicationContext" method in that scenario.
/// </p>
///
/// <p>
/// Note that ObjectFactory callback interfaces like IApplicationContextAware
/// are not automatically applied to Quartz Job instances, because Quartz
/// itself is reponsible for the lifecycle of its Jobs.
/// </p>
/// </remarks>
/// <value>The application context scheduler context key.</value>
/// <seealso cref="JobDetailObject.ApplicationContextJobDataKey"/>
public virtual string ApplicationContextSchedulerContextKey
{
set { applicationContextSchedulerContextKey = value; }
}
/// <summary>
/// Set the Quartz JobFactory to use for this Scheduler.
/// </summary>
/// <remarks>
/// <p>
/// Default is Spring's <see cref="AdaptableJobFactory" />, which supports
/// standard Quartz <see cref="IJob" /> instances. Note that this default only applies
/// to a <i>local</i> Scheduler, not to a RemoteScheduler (where setting
/// a custom JobFactory is not supported by Quartz).
/// </p>
/// <p>
/// Specify an instance of Spring's <see cref="SpringObjectJobFactory" /> here
/// (typically as an inner object definition) to automatically populate a job's
/// object properties from the specified job data map and scheduler context.
/// </p>
/// </remarks>
/// <seealso cref="AdaptableJobFactory" />
/// <seealso cref="SpringObjectJobFactory" />
public virtual IJobFactory JobFactory
{
set
{
jobFactory = value;
jobFactorySet = true;
}
}
/// <summary>
/// Set whether to expose the Spring-managed <see cref="IScheduler" /> instance in the
/// Quartz <see cref="SchedulerRepository" />. Default is "false", since the Spring-managed
/// Scheduler is usually exclusively intended for access within the Spring context.
/// </summary>
/// <remarks>
/// Switch this flag to "true" in order to expose the Scheduler globally.
/// This is not recommended unless you have an existing Spring application that
/// relies on this behavior.
/// </remarks>
public virtual bool ExposeSchedulerInRepository
{
set { exposeSchedulerInRepository = value; }
}
/// <summary>
/// Set whether to automatically start the scheduler after initialization.
/// Default is "true"; set this to "false" to allow for manual startup.
/// </summary>
public virtual bool AutoStartup
{
set { autoStartup = value; }
}
/// <summary>
/// Set the time span to wait after initialization before
/// starting the scheduler asynchronously. Default is 0, meaning
/// immediate synchronous startup on initialization of this object.
/// </summary>
/// <remarks>
/// Setting this to 10 or 20 seconds makes sense if no jobs
/// should be run before the entire application has started up.
/// </remarks>
public virtual TimeSpan StartupDelay
{
set { startupDelay = value; }
}
/// <summary>
/// Set whether to wait for running jobs to complete on Shutdown.
/// Default is "false".
/// </summary>
/// <value>
/// <c>true</c> if [wait for jobs to complete on Shutdown]; otherwise, <c>false</c>.
/// </value>
/// <seealso cref="IScheduler.Shutdown(bool)"/>
public virtual bool WaitForJobsToCompleteOnShutdown
{
set { waitForJobsToCompleteOnShutdown = value; }
}
/// <summary>
/// Set the default DbProvider to be used by the Scheduler. If set,
/// this will override corresponding settings in Quartz properties.
/// </summary>
/// <remarks>
/// <p>
/// Note: If this is set, the Quartz settings should not define
/// a job store "dataSource" to avoid meaningless double configuration.
/// </p>
/// <p>
/// A Spring-specific subclass of Quartz' JobStoreSupport will be used.
/// It is therefore strongly recommended to perform all operations on
/// the Scheduler within Spring-managed transactions.
/// Else, database locking will not properly work and might even break
/// (e.g. if trying to obtain a lock on Oracle without a transaction).
/// </p>
/// </remarks>
/// <seealso cref="QuartzProperties" />
/// <seealso cref="LocalDataSourceJobStore" />
public IDbProvider DbProvider
{
set { dbProvider = value; }
}
/// <summary>
/// Set the name of the object in the object factory that created this object.
/// </summary>
/// <value>The name of the object in the factory.</value>
/// <remarks>
/// <p>
/// Invoked after population of normal object properties but before an init
/// callback like <see cref="Spring.Objects.Factory.IInitializingObject"/>'s
/// <see cref="Spring.Objects.Factory.IInitializingObject.AfterPropertiesSet"/>
/// method or a custom init-method.
/// </p>
/// </remarks>
public string ObjectName
{
set
{
if (schedulerName == null)
{
schedulerName = value;
}
}
}
/// <summary>
/// Gets a value indicating whether this <see cref="SchedulerFactoryObject"/> is running.
/// </summary>
/// <value><c>true</c> if running; otherwise, <c>false</c>.</value>
public virtual bool Running
{
get
{
if (scheduler != null)
{
try
{
return !scheduler.InStandbyMode;
}
catch (SchedulerException)
{
return false;
}
}
return false;
}
}
#region IApplicationContextAware Members
/// <summary>
/// Sets the <see cref="Spring.Context.IApplicationContext"/> that this
/// object runs in.
/// </summary>
/// <value></value>
/// <remarks>
/// <p>
/// Normally this call will be used to initialize the object.
/// </p>
/// <p>
/// Invoked after population of normal object properties but before an
/// init callback such as
/// <see cref="Spring.Objects.Factory.IInitializingObject"/>'s
/// <see cref="Spring.Objects.Factory.IInitializingObject.AfterPropertiesSet"/>
/// or a custom init-method. Invoked after the setting of any
/// <see cref="Spring.Context.IResourceLoaderAware"/>'s
/// <see cref="Spring.Context.IResourceLoaderAware.ResourceLoader"/>
/// property.
/// </p>
/// </remarks>
/// <exception cref="Spring.Context.ApplicationContextException">
/// In the case of application context initialization errors.
/// </exception>
/// <exception cref="Spring.Objects.ObjectsException">
/// If thrown by any application context methods.
/// </exception>
/// <exception cref="Spring.Objects.Factory.ObjectInitializationException"/>
public virtual IApplicationContext ApplicationContext
{
set { applicationContext = value; }
}
#endregion
#region IDisposable Members
/// <summary>
/// Shut down the Quartz scheduler on object factory Shutdown,
/// stopping all scheduled jobs.
/// </summary>
public virtual void Dispose()
{
Logger.Info("Shutting down Quartz Scheduler");
scheduler.Shutdown(waitForJobsToCompleteOnShutdown);
}
#endregion
/// <summary>
/// Template method that determines the Scheduler to operate on.
/// To be implemented by subclasses.
/// </summary>
/// <returns></returns>
protected override IScheduler GetScheduler()
{
return scheduler;
}
#region IFactoryObject Members
/// <summary>
/// Return an instance (possibly shared or independent) of the object
/// managed by this factory.
/// </summary>
/// <returns>
/// An instance (possibly shared or independent) of the object managed by
/// this factory.
/// </returns>
/// <remarks>
/// <note type="caution">
/// If this method is being called in the context of an enclosing IoC container and
/// returns <see langword="null"/>, the IoC container will consider this factory
/// object as not being fully initialized and throw a corresponding (and most
/// probably fatal) exception.
/// </note>
/// </remarks>
public virtual object GetObject()
{
return scheduler;
}
/// <summary>
/// Return the <see cref="System.Type"/> of object that this
/// <see cref="Spring.Objects.Factory.IFactoryObject"/> creates, or
/// <see langword="null"/> if not known in advance.
/// </summary>
/// <value></value>
public virtual Type ObjectType
{
get { return (scheduler != null) ? scheduler.GetType() : typeof (IScheduler); }
}
/// <summary>
/// Is the object managed by this factory a singleton or a prototype?
/// </summary>
/// <value></value>
public virtual bool IsSingleton
{
get { return true; }
}
#endregion
//---------------------------------------------------------------------
// Implementation of IInitializingObject interface
//---------------------------------------------------------------------
#region IInitializingObject Members
/// <summary>
/// Invoked by an <see cref="Spring.Objects.Factory.IObjectFactory"/>
/// after it has injected all of an object's dependencies.
/// </summary>
/// <remarks>
/// <p>
/// This method allows the object instance to perform the kind of
/// initialization only possible when all of it's dependencies have
/// been injected (set), and to throw an appropriate exception in the
/// event of misconfiguration.
/// </p>
/// <p>
/// Please do consult the class level documentation for the
/// <see cref="Spring.Objects.Factory.IObjectFactory"/> interface for a
/// description of exactly <i>when</i> this method is invoked. In
/// particular, it is worth noting that the
/// <see cref="Spring.Objects.Factory.IObjectFactoryAware"/>
/// and <see cref="Spring.Context.IApplicationContextAware"/>
/// callbacks will have been invoked <i>prior</i> to this method being
/// called.
/// </p>
/// </remarks>
/// <exception cref="System.Exception">
/// In the event of misconfiguration (such as the failure to set a
/// required property) or if initialization fails.
/// </exception>
public virtual void AfterPropertiesSet()
{
// Create SchedulerFactory instance.
ISchedulerFactory schedulerFactory = ObjectUtils.InstantiateType<ISchedulerFactory>(schedulerFactoryType);
InitSchedulerFactory(schedulerFactory);
if (taskExecutor != null)
{
// Make given TaskExecutor available for SchedulerFactory configuration.
configTimeTaskExecutor = taskExecutor;
}
if (dbProvider != null)
{
// Make given db provider available for SchedulerFactory configuration.
configTimeDbProvider = dbProvider;
}
try
{
// Get Scheduler instance from SchedulerFactory.
scheduler = CreateScheduler(schedulerFactory, schedulerName);
PopulateSchedulerContext();
if (!jobFactorySet && !(scheduler is RemoteScheduler))
{
// Use AdaptableJobFactory as default for a local Scheduler, unless when
// explicitly given a null value through the "jobFactory" object property.
jobFactory = new AdaptableJobFactory();
}
if (jobFactory != null)
{
if (jobFactory is ISchedulerContextAware)
{
((ISchedulerContextAware) jobFactory).SchedulerContext = scheduler.Context;
}
scheduler.JobFactory = jobFactory;
}
}
finally
{
if (taskExecutor != null)
{
configTimeTaskExecutor = null;
}
if (dbProvider != null)
{
configTimeDbProvider = null;
}
}
RegisterListeners();
RegisterJobsAndTriggers();
}
#endregion
/// <summary>
/// Load and/or apply Quartz properties to the given SchedulerFactory.
/// </summary>
/// <param name="schedulerFactory">the SchedulerFactory to Initialize</param>
private void InitSchedulerFactory(ISchedulerFactory schedulerFactory)
{
if (!(schedulerFactory is StdSchedulerFactory))
{
if (configLocation != null || quartzProperties != null || schedulerName != null ||
taskExecutor != null || dbProvider != null)
{
throw new ArgumentException("StdSchedulerFactory required for applying Quartz properties: " + schedulerFactory);
}
// Otherwise assume that no initialization is necessary...
return;
}
NameValueCollection mergedProps = new NameValueCollection();
// Set necessary default properties here, as Quartz will not apply
// its default configuration when explicitly given properties.
if (taskExecutor != null)
{
mergedProps[StdSchedulerFactory.PropertyThreadPoolType] =
typeof (LocalTaskExecutorThreadPool).AssemblyQualifiedName;
}
else
{
mergedProps.Set(StdSchedulerFactory.PropertyThreadPoolType, typeof (SimpleThreadPool).AssemblyQualifiedName);
mergedProps[PROP_THREAD_COUNT] = Convert.ToString(DEFAULT_THREAD_COUNT);
}
if (configLocation != null)
{
if (Logger.IsInfoEnabled)
{
Logger.Info("Loading Quartz config from [" + configLocation + "]");
}
using (StreamReader sr = new StreamReader(configLocation.InputStream))
{
string line;
while ((line = sr.ReadLine()) != null)
{
string[] lineItems = line.Split(new char[] {'='}, 2);
if (lineItems.Length == 2)
{
mergedProps[lineItems[0].Trim()] = lineItems[1].Trim();
}
}
}
}
if (quartzProperties != null)
{
// if given quartz properties, merge to them to configuration
MergePropertiesIntoMap(quartzProperties, mergedProps);
}
if (dbProvider != null)
{
mergedProps[StdSchedulerFactory.PropertyJobStoreType] = typeof (LocalDataSourceJobStore).AssemblyQualifiedName;
}
// Make sure to set the scheduler name as configured in the Spring configuration.
if (schedulerName != null)
{
mergedProps[StdSchedulerFactory.PropertySchedulerInstanceName] = schedulerName;
}
((StdSchedulerFactory) schedulerFactory).Initialize(mergedProps);
}
/// <summary>
/// Merges the properties into map. This effectively also
/// overwrites existing properties with same key in map.
/// </summary>
/// <param name="properties">The properties to merge into given map.</param>
/// <param name="map">The map to merge to.</param>
protected virtual void MergePropertiesIntoMap(IDictionary properties, NameValueCollection map)
{
foreach (string key in properties.Keys)
{
map[key] = (string) properties[key];
}
}
/// <summary>
/// Create the Scheduler instance for the given factory and scheduler name.
/// Called by afterPropertiesSet.
/// </summary>
/// <remarks>
/// Default implementation invokes SchedulerFactory's <code>GetScheduler</code>
/// method. Can be overridden for custom Scheduler creation.
/// </remarks>
/// <param name="schedulerFactory">the factory to create the Scheduler with</param>
/// <param name="schedName">the name of the scheduler to create</param>
/// <returns>the Scheduler instance</returns>
/// <seealso cref="AfterPropertiesSet"/>
/// <seealso cref="ISchedulerFactory.GetScheduler()"/>
protected virtual IScheduler CreateScheduler(ISchedulerFactory schedulerFactory, string schedName)
{
SchedulerRepository repository = SchedulerRepository.Instance;
lock (repository)
{
IScheduler existingScheduler = (schedulerName != null ? repository.Lookup(schedulerName) : null);
IScheduler newScheduler = schedulerFactory.GetScheduler();
if (newScheduler == existingScheduler)
{
throw new InvalidOperationException(
string.Format(
"Active Scheduler of name '{0}' already registered in Quartz SchedulerRepository. Cannot create a new Spring-managed Scheduler of the same name!",
schedulerName));
}
if (!exposeSchedulerInRepository)
{
// Need to explicitly remove it if not intended for exposure,
// since Quartz shares the Scheduler instance by default!
SchedulerRepository.Instance.Remove(newScheduler.SchedulerName);
}
return newScheduler;
}
}
/// <summary>
/// Expose the specified context attributes and/or the current
/// IApplicationContext in the Quartz SchedulerContext.
/// </summary>
private void PopulateSchedulerContext()
{
// Put specified objects into Scheduler context.
if (schedulerContextMap != null)
{
var dictionary = schedulerContextMap.Cast<DictionaryEntry>().ToDictionary(entry => entry.Key.ToString(), entry => entry.Value);
scheduler.Context.PutAll(dictionary);
}
// Register IApplicationContext in Scheduler context.
if (applicationContextSchedulerContextKey != null)
{
if (applicationContext == null)
{
throw new SystemException("SchedulerFactoryObject needs to be set up in an IApplicationContext " +
"to be able to handle an 'applicationContextSchedulerContextKey'");
}
scheduler.Context.Put(applicationContextSchedulerContextKey, applicationContext);
}
}
/// <summary>
/// Start the Quartz Scheduler, respecting the "startDelay" setting.
/// </summary>
/// <param name="sched">the Scheduler to start</param>
/// <param name="startDelay">the time span to wait before starting
/// the Scheduler asynchronously</param>
protected virtual void StartScheduler(IScheduler sched, TimeSpan startDelay)
{
if (startDelay.TotalSeconds <= 0)
{
Logger.Info("Starting Quartz Scheduler now");
sched.Start();
}
else
{
if (Logger.IsInfoEnabled)
{
Logger.InfoFormat("Will start Quartz Scheduler [{0}] in {1} seconds", sched.SchedulerName, startDelay);
}
sched.StartDelayed(startDelay);
}
}
//---------------------------------------------------------------------
// Implementation of Lifecycle interface
//---------------------------------------------------------------------
/// <summary>
/// Starts this instance.
/// </summary>
public virtual void Start()
{
if (scheduler != null)
{
try
{
scheduler.Start();
}
catch (SchedulerException ex)
{
throw new SchedulingException("Could not start Quartz Scheduler", ex);
}
}
}
/// <summary>
/// Stops this instance.
/// </summary>
public virtual void Stop()
{
if (scheduler != null)
{
try
{
scheduler.Standby();
}
catch (SchedulerException ex)
{
throw new SchedulingException("Could not stop Quartz Scheduler", ex);
}
}
}
/// <summary>
/// Handles the application context's refresh event and starts the scheduler.
/// </summary>
public void HandleApplicationEvent(object sender, ApplicationEventArgs e)
{
// auto-start Scheduler if demanded
if (e is ContextRefreshedEventArgs && autoStartup)
{
try
{
StartScheduler(scheduler, startupDelay);
}
catch (SchedulerException ex)
{
throw new ObjectInitializationException("failed to auto-start scheduler", ex);
}
}
}
}
}
| |
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Neo.Cryptography;
using Neo.Cryptography.ECC;
using Neo.Ledger;
using Neo.Network.P2P;
using Neo.Network.P2P.Payloads;
using Neo.SmartContract;
using Neo.SmartContract.Enumerators;
using Neo.SmartContract.Iterators;
using Neo.SmartContract.Manifest;
using Neo.VM;
using Neo.VM.Types;
using Neo.Wallets;
using System.Linq;
using VMArray = Neo.VM.Types.Array;
namespace Neo.UnitTests.SmartContract
{
public partial class UT_InteropService
{
[TestMethod]
public void TestCheckSig()
{
var engine = GetEngine(true);
IVerifiable iv = engine.ScriptContainer;
byte[] message = iv.GetHashData();
byte[] privateKey = { 0x01,0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01};
KeyPair keyPair = new KeyPair(privateKey);
ECPoint pubkey = keyPair.PublicKey;
byte[] signature = Crypto.Default.Sign(message, privateKey, pubkey.EncodePoint(false).Skip(1).ToArray());
engine.CurrentContext.EvaluationStack.Push(signature);
engine.CurrentContext.EvaluationStack.Push(pubkey.EncodePoint(false));
engine.CurrentContext.EvaluationStack.Push(StackItem.Null);
InteropService.Invoke(engine, InteropService.Neo_Crypto_ECDsaVerify).Should().BeTrue();
engine.CurrentContext.EvaluationStack.Pop().ToBoolean().Should().BeTrue();
engine.CurrentContext.EvaluationStack.Push(signature);
engine.CurrentContext.EvaluationStack.Push(new byte[70]);
engine.CurrentContext.EvaluationStack.Push(StackItem.Null);
InteropService.Invoke(engine, InteropService.Neo_Crypto_ECDsaVerify).Should().BeTrue();
engine.CurrentContext.EvaluationStack.Pop().ToBoolean().Should().BeFalse();
}
[TestMethod]
public void TestCrypto_CheckMultiSig()
{
var engine = GetEngine(true);
IVerifiable iv = engine.ScriptContainer;
byte[] message = iv.GetHashData();
byte[] privkey1 = { 0x01,0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01};
KeyPair key1 = new KeyPair(privkey1);
ECPoint pubkey1 = key1.PublicKey;
byte[] signature1 = Crypto.Default.Sign(message, privkey1, pubkey1.EncodePoint(false).Skip(1).ToArray());
byte[] privkey2 = { 0x01,0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02};
KeyPair key2 = new KeyPair(privkey2);
ECPoint pubkey2 = key2.PublicKey;
byte[] signature2 = Crypto.Default.Sign(message, privkey2, pubkey2.EncodePoint(false).Skip(1).ToArray());
var pubkeys = new VMArray
{
pubkey1.EncodePoint(false),
pubkey2.EncodePoint(false)
};
var signatures = new VMArray
{
signature1,
signature2
};
engine.CurrentContext.EvaluationStack.Push(signatures);
engine.CurrentContext.EvaluationStack.Push(pubkeys);
engine.CurrentContext.EvaluationStack.Push(StackItem.Null);
InteropService.Invoke(engine, InteropService.Neo_Crypto_ECDsaCheckMultiSig).Should().BeTrue();
engine.CurrentContext.EvaluationStack.Pop().ToBoolean().Should().BeTrue();
pubkeys = new VMArray();
engine.CurrentContext.EvaluationStack.Push(signatures);
engine.CurrentContext.EvaluationStack.Push(pubkeys);
engine.CurrentContext.EvaluationStack.Push(StackItem.Null);
InteropService.Invoke(engine, InteropService.Neo_Crypto_ECDsaCheckMultiSig).Should().BeFalse();
pubkeys = new VMArray
{
pubkey1.EncodePoint(false),
pubkey2.EncodePoint(false)
};
signatures = new VMArray();
engine.CurrentContext.EvaluationStack.Push(signatures);
engine.CurrentContext.EvaluationStack.Push(pubkeys);
engine.CurrentContext.EvaluationStack.Push(StackItem.Null);
InteropService.Invoke(engine, InteropService.Neo_Crypto_ECDsaCheckMultiSig).Should().BeFalse();
pubkeys = new VMArray
{
pubkey1.EncodePoint(false),
pubkey2.EncodePoint(false)
};
signatures = new VMArray
{
signature1,
new byte[64]
};
engine.CurrentContext.EvaluationStack.Push(signatures);
engine.CurrentContext.EvaluationStack.Push(pubkeys);
engine.CurrentContext.EvaluationStack.Push(StackItem.Null);
InteropService.Invoke(engine, InteropService.Neo_Crypto_ECDsaCheckMultiSig).Should().BeTrue();
engine.CurrentContext.EvaluationStack.Pop().ToBoolean().Should().BeFalse();
pubkeys = new VMArray
{
pubkey1.EncodePoint(false),
new byte[70]
};
signatures = new VMArray
{
signature1,
signature2
};
engine.CurrentContext.EvaluationStack.Push(signatures);
engine.CurrentContext.EvaluationStack.Push(pubkeys);
engine.CurrentContext.EvaluationStack.Push(StackItem.Null);
InteropService.Invoke(engine, InteropService.Neo_Crypto_ECDsaCheckMultiSig).Should().BeTrue();
engine.CurrentContext.EvaluationStack.Pop().ToBoolean().Should().BeFalse();
}
[TestMethod]
public void TestAccount_IsStandard()
{
var engine = GetEngine(false, true);
var hash = new byte[] { 0x01, 0x01, 0x01 ,0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01 };
engine.CurrentContext.EvaluationStack.Push(hash);
InteropService.Invoke(engine, InteropService.Neo_Account_IsStandard).Should().BeTrue();
engine.CurrentContext.EvaluationStack.Pop().ToBoolean().Should().BeTrue();
var snapshot = Blockchain.Singleton.GetSnapshot();
var state = TestUtils.GetContract();
snapshot.Contracts.Add(state.ScriptHash, state);
engine = new ApplicationEngine(TriggerType.Application, null, snapshot, 0);
engine.LoadScript(new byte[] { 0x01 });
engine.CurrentContext.EvaluationStack.Push(state.ScriptHash.ToArray());
InteropService.Invoke(engine, InteropService.Neo_Account_IsStandard).Should().BeTrue();
engine.CurrentContext.EvaluationStack.Pop().ToBoolean().Should().BeFalse();
}
[TestMethod]
public void TestContract_Create()
{
var engine = GetEngine(false, true);
var script = new byte[1024 * 1024 + 1];
engine.CurrentContext.EvaluationStack.Push(script);
InteropService.Invoke(engine, InteropService.Neo_Contract_Create).Should().BeFalse();
string manifestStr = new string(new char[ContractManifest.MaxLength + 1]);
script = new byte[] { 0x01 };
engine.CurrentContext.EvaluationStack.Push(manifestStr);
engine.CurrentContext.EvaluationStack.Push(script);
InteropService.Invoke(engine, InteropService.Neo_Contract_Create).Should().BeFalse();
var manifest = ContractManifest.CreateDefault(UInt160.Parse("0xa400ff00ff00ff00ff00ff00ff00ff00ff00ff01"));
engine.CurrentContext.EvaluationStack.Push(manifest.ToString());
engine.CurrentContext.EvaluationStack.Push(script);
InteropService.Invoke(engine, InteropService.Neo_Contract_Create).Should().BeFalse();
manifest.Abi.Hash = script.ToScriptHash();
engine.CurrentContext.EvaluationStack.Push(manifest.ToString());
engine.CurrentContext.EvaluationStack.Push(script);
InteropService.Invoke(engine, InteropService.Neo_Contract_Create).Should().BeTrue();
var snapshot = Blockchain.Singleton.GetSnapshot();
var state = TestUtils.GetContract();
snapshot.Contracts.Add(state.ScriptHash, state);
engine = new ApplicationEngine(TriggerType.Application, null, snapshot, 0);
engine.LoadScript(new byte[] { 0x01 });
engine.CurrentContext.EvaluationStack.Push(manifest.ToString());
engine.CurrentContext.EvaluationStack.Push(state.Script);
InteropService.Invoke(engine, InteropService.Neo_Contract_Create).Should().BeFalse();
}
[TestMethod]
public void TestContract_Update()
{
var engine = GetEngine(false, true);
var script = new byte[1024 * 1024 + 1];
engine.CurrentContext.EvaluationStack.Push(script);
InteropService.Invoke(engine, InteropService.Neo_Contract_Update).Should().BeFalse();
string manifestStr = new string(new char[ContractManifest.MaxLength + 1]);
script = new byte[] { 0x01 };
engine.CurrentContext.EvaluationStack.Push(manifestStr);
engine.CurrentContext.EvaluationStack.Push(script);
InteropService.Invoke(engine, InteropService.Neo_Contract_Update).Should().BeFalse();
manifestStr = "";
engine.CurrentContext.EvaluationStack.Push(manifestStr);
engine.CurrentContext.EvaluationStack.Push(script);
InteropService.Invoke(engine, InteropService.Neo_Contract_Update).Should().BeFalse();
var manifest = ContractManifest.CreateDefault(script.ToScriptHash());
byte[] privkey = { 0x01,0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01};
KeyPair key = new KeyPair(privkey);
ECPoint pubkey = key.PublicKey;
byte[] signature = Crypto.Default.Sign(script.ToScriptHash().ToArray(), privkey, pubkey.EncodePoint(false).Skip(1).ToArray());
manifest.Groups = new ContractGroup[]
{
new ContractGroup()
{
PubKey = pubkey,
Signature = signature
}
};
var snapshot = Blockchain.Singleton.GetSnapshot();
var state = TestUtils.GetContract();
state.Manifest.Features = ContractFeatures.HasStorage;
var storageItem = new StorageItem
{
Value = new byte[] { 0x01 },
IsConstant = false
};
var storageKey = new StorageKey
{
ScriptHash = state.ScriptHash,
Key = new byte[] { 0x01 }
};
snapshot.Contracts.Add(state.ScriptHash, state);
snapshot.Storages.Add(storageKey, storageItem);
engine = new ApplicationEngine(TriggerType.Application, null, snapshot, 0);
engine.LoadScript(state.Script);
engine.CurrentContext.EvaluationStack.Push(manifest.ToString());
engine.CurrentContext.EvaluationStack.Push(script);
InteropService.Invoke(engine, InteropService.Neo_Contract_Update).Should().BeTrue();
// Remove Storage flag with something stored
state.Manifest.Features = ContractFeatures.NoProperty;
snapshot.Contracts.Add(state.ScriptHash, state);
snapshot.Storages.Add(storageKey, storageItem);
engine = new ApplicationEngine(TriggerType.Application, null, snapshot, 0);
engine.LoadScript(state.Script);
engine.CurrentContext.EvaluationStack.Push(manifest.ToString());
engine.CurrentContext.EvaluationStack.Push(script);
InteropService.Invoke(engine, InteropService.Neo_Contract_Update).Should().BeFalse();
}
[TestMethod]
public void TestStorage_Find()
{
var snapshot = Blockchain.Singleton.GetSnapshot();
var state = TestUtils.GetContract();
state.Manifest.Features = ContractFeatures.HasStorage;
var storageItem = new StorageItem
{
Value = new byte[] { 0x01, 0x02, 0x03, 0x04 },
IsConstant = true
};
var storageKey = new StorageKey
{
ScriptHash = state.ScriptHash,
Key = new byte[] { 0x01 }
};
snapshot.Contracts.Add(state.ScriptHash, state);
snapshot.Storages.Add(storageKey, storageItem);
var engine = new ApplicationEngine(TriggerType.Application, null, snapshot, 0);
engine.LoadScript(new byte[] { 0x01 });
engine.CurrentContext.EvaluationStack.Push(new byte[] { 0x01 });
engine.CurrentContext.EvaluationStack.Push(new InteropInterface<StorageContext>(new StorageContext
{
ScriptHash = state.ScriptHash,
IsReadOnly = false
}));
InteropService.Invoke(engine, InteropService.Neo_Storage_Find).Should().BeTrue();
var iterator = ((InteropInterface<StorageIterator>)engine.CurrentContext.EvaluationStack.Pop()).GetInterface<StorageIterator>();
iterator.Next();
var ele = iterator.Value();
ele.GetSpan().ToHexString().Should().Be(storageItem.Value.ToHexString());
engine.CurrentContext.EvaluationStack.Push(1);
InteropService.Invoke(engine, InteropService.Neo_Storage_Find).Should().BeFalse();
}
[TestMethod]
public void TestEnumerator_Create()
{
var engine = GetEngine();
var arr = new VMArray {
new byte[]{ 0x01 },
new byte[]{ 0x02 }
};
engine.CurrentContext.EvaluationStack.Push(arr);
InteropService.Invoke(engine, InteropService.Neo_Enumerator_Create).Should().BeTrue();
var ret = (InteropInterface<IEnumerator>)engine.CurrentContext.EvaluationStack.Pop();
ret.GetInterface<IEnumerator>().Next();
ret.GetInterface<IEnumerator>().Value().GetSpan().ToHexString()
.Should().Be(new byte[] { 0x01 }.ToHexString());
engine.CurrentContext.EvaluationStack.Push(1);
InteropService.Invoke(engine, InteropService.Neo_Enumerator_Create).Should().BeTrue();
}
[TestMethod]
public void TestEnumerator_Next()
{
var engine = GetEngine();
var arr = new VMArray {
new byte[]{ 0x01 },
new byte[]{ 0x02 }
};
engine.CurrentContext.EvaluationStack.Push(new InteropInterface<ArrayWrapper>(new ArrayWrapper(arr)));
InteropService.Invoke(engine, InteropService.Neo_Enumerator_Next).Should().BeTrue();
engine.CurrentContext.EvaluationStack.Pop().ToBoolean().Should().BeTrue();
engine.CurrentContext.EvaluationStack.Push(1);
InteropService.Invoke(engine, InteropService.Neo_Enumerator_Next).Should().BeFalse();
}
[TestMethod]
public void TestEnumerator_Value()
{
var engine = GetEngine();
var arr = new VMArray {
new byte[]{ 0x01 },
new byte[]{ 0x02 }
};
var wrapper = new ArrayWrapper(arr);
wrapper.Next();
engine.CurrentContext.EvaluationStack.Push(new InteropInterface<ArrayWrapper>(wrapper));
InteropService.Invoke(engine, InteropService.Neo_Enumerator_Value).Should().BeTrue();
engine.CurrentContext.EvaluationStack.Pop().GetSpan().ToHexString().Should().Be(new byte[] { 0x01 }.ToHexString());
engine.CurrentContext.EvaluationStack.Push(1);
InteropService.Invoke(engine, InteropService.Neo_Enumerator_Value).Should().BeFalse();
}
[TestMethod]
public void TestEnumerator_Concat()
{
var engine = GetEngine();
var arr1 = new VMArray {
new byte[]{ 0x01 },
new byte[]{ 0x02 }
};
var arr2 = new VMArray {
new byte[]{ 0x03 },
new byte[]{ 0x04 }
};
var wrapper1 = new ArrayWrapper(arr1);
var wrapper2 = new ArrayWrapper(arr2);
engine.CurrentContext.EvaluationStack.Push(new InteropInterface<ArrayWrapper>(wrapper2));
engine.CurrentContext.EvaluationStack.Push(new InteropInterface<ArrayWrapper>(wrapper1));
InteropService.Invoke(engine, InteropService.Neo_Enumerator_Concat).Should().BeTrue();
var ret = ((InteropInterface<IEnumerator>)engine.CurrentContext.EvaluationStack.Pop()).GetInterface<IEnumerator>();
ret.Next().Should().BeTrue();
ret.Value().GetSpan().ToHexString().Should().Be(new byte[] { 0x01 }.ToHexString());
}
[TestMethod]
public void TestIterator_Create()
{
var engine = GetEngine();
var arr = new VMArray {
new byte[]{ 0x01 },
new byte[]{ 0x02 }
};
engine.CurrentContext.EvaluationStack.Push(arr);
InteropService.Invoke(engine, InteropService.Neo_Iterator_Create).Should().BeTrue();
var ret = (InteropInterface<IIterator>)engine.CurrentContext.EvaluationStack.Pop();
ret.GetInterface<IIterator>().Next();
ret.GetInterface<IIterator>().Value().GetSpan().ToHexString()
.Should().Be(new byte[] { 0x01 }.ToHexString());
var interop = new InteropInterface<object>(1);
engine.CurrentContext.EvaluationStack.Push(interop);
InteropService.Invoke(engine, InteropService.Neo_Iterator_Create).Should().BeFalse();
var map = new Map
{
{ new Integer(1), new Integer(2) },
{ new Integer(3), new Integer(4) }
};
engine.CurrentContext.EvaluationStack.Push(map);
InteropService.Invoke(engine, InteropService.Neo_Iterator_Create).Should().BeTrue();
ret = (InteropInterface<IIterator>)engine.CurrentContext.EvaluationStack.Pop();
ret.GetInterface<IIterator>().Next();
ret.GetInterface<IIterator>().Key().GetBigInteger().Should().Be(1);
ret.GetInterface<IIterator>().Value().GetBigInteger().Should().Be(2);
engine.CurrentContext.EvaluationStack.Push(1);
InteropService.Invoke(engine, InteropService.Neo_Iterator_Create).Should().BeTrue();
}
[TestMethod]
public void TestIterator_Key()
{
var engine = GetEngine();
var arr = new VMArray {
new byte[]{ 0x01 },
new byte[]{ 0x02 }
};
var wrapper = new ArrayWrapper(arr);
wrapper.Next();
engine.CurrentContext.EvaluationStack.Push(new InteropInterface<ArrayWrapper>(wrapper));
InteropService.Invoke(engine, InteropService.Neo_Iterator_Key).Should().BeTrue();
engine.CurrentContext.EvaluationStack.Pop().GetBigInteger().Should().Be(0);
engine.CurrentContext.EvaluationStack.Push(1);
InteropService.Invoke(engine, InteropService.Neo_Iterator_Key).Should().BeFalse();
}
[TestMethod]
public void TestIterator_Keys()
{
var engine = GetEngine();
var arr = new VMArray {
new byte[]{ 0x01 },
new byte[]{ 0x02 }
};
var wrapper = new ArrayWrapper(arr);
engine.CurrentContext.EvaluationStack.Push(new InteropInterface<ArrayWrapper>(wrapper));
InteropService.Invoke(engine, InteropService.Neo_Iterator_Keys).Should().BeTrue();
var ret = ((InteropInterface<IteratorKeysWrapper>)engine.CurrentContext.EvaluationStack.Pop()).GetInterface<IteratorKeysWrapper>();
ret.Next();
ret.Value().GetBigInteger().Should().Be(0);
engine.CurrentContext.EvaluationStack.Push(1);
InteropService.Invoke(engine, InteropService.Neo_Iterator_Keys).Should().BeFalse();
}
[TestMethod]
public void TestIterator_Values()
{
var engine = GetEngine();
var arr = new VMArray {
new byte[]{ 0x01 },
new byte[]{ 0x02 }
};
var wrapper = new ArrayWrapper(arr);
engine.CurrentContext.EvaluationStack.Push(new InteropInterface<ArrayWrapper>(wrapper));
InteropService.Invoke(engine, InteropService.Neo_Iterator_Values).Should().BeTrue();
var ret = ((InteropInterface<IteratorValuesWrapper>)engine.CurrentContext.EvaluationStack.Pop()).GetInterface<IteratorValuesWrapper>();
ret.Next();
ret.Value().GetSpan().ToHexString().Should().Be(new byte[] { 0x01 }.ToHexString());
engine.CurrentContext.EvaluationStack.Push(1);
InteropService.Invoke(engine, InteropService.Neo_Iterator_Values).Should().BeFalse();
}
[TestMethod]
public void TestIterator_Concat()
{
var engine = GetEngine();
var arr1 = new VMArray {
new byte[]{ 0x01 },
new byte[]{ 0x02 }
};
var arr2 = new VMArray {
new byte[]{ 0x03 },
new byte[]{ 0x04 }
};
var wrapper1 = new ArrayWrapper(arr1);
var wrapper2 = new ArrayWrapper(arr2);
engine.CurrentContext.EvaluationStack.Push(new InteropInterface<ArrayWrapper>(wrapper2));
engine.CurrentContext.EvaluationStack.Push(new InteropInterface<ArrayWrapper>(wrapper1));
InteropService.Invoke(engine, InteropService.Neo_Iterator_Concat).Should().BeTrue();
var ret = ((InteropInterface<IIterator>)engine.CurrentContext.EvaluationStack.Pop()).GetInterface<IIterator>();
ret.Next().Should().BeTrue();
ret.Value().GetSpan().ToHexString().Should().Be(new byte[] { 0x01 }.ToHexString());
}
[TestMethod]
public void TestJson_Deserialize()
{
var engine = GetEngine();
engine.CurrentContext.EvaluationStack.Push("1");
InteropService.Invoke(engine, InteropService.Neo_Json_Deserialize).Should().BeTrue();
var ret = engine.CurrentContext.EvaluationStack.Pop();
ret.GetBigInteger().Should().Be(1);
}
[TestMethod]
public void TestJson_Serialize()
{
var engine = GetEngine();
engine.CurrentContext.EvaluationStack.Push(1);
InteropService.Invoke(engine, InteropService.Neo_Json_Serialize).Should().BeTrue();
var ret = engine.CurrentContext.EvaluationStack.Pop();
ret.GetString().Should().Be("1");
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class WhereKeywordRecommenderTests : KeywordRecommenderTests
{
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAtRoot_Interactive()
{
VerifyAbsence(SourceCodeKind.Script,
@"$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterClass_Interactive()
{
VerifyAbsence(SourceCodeKind.Script,
@"class C { }
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterGlobalStatement_Interactive()
{
VerifyAbsence(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterGlobalVariableDeclaration_Interactive()
{
VerifyAbsence(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInUsingAlias()
{
VerifyAbsence(
@"using Foo = $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInEmptyStatement()
{
VerifyAbsence(AddInsideMethod(
@"$$"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NewClause()
{
VerifyKeyword(AddInsideMethod(
@"var q = from x in y
$$"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterPreviousClause()
{
VerifyKeyword(AddInsideMethod(
@"var v = from x in y
where x > y
$$"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterPreviousContinuationClause()
{
VerifyKeyword(AddInsideMethod(
@"var v = from x in y
group x by y into g
$$"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAtEndOfPreviousClause()
{
VerifyAbsence(AddInsideMethod(
@"var q = from x in y$$"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void BetweenClauses()
{
VerifyKeyword(AddInsideMethod(
@"var q = from x in y
$$
from z in w"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterWhere()
{
VerifyAbsence(AddInsideMethod(
@"var q = from x in y
where $$
from z in w"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterClass()
{
VerifyAbsence(
@"class C $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterGenericClass()
{
VerifyKeyword(
@"class C<T> $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterClassBaseList()
{
VerifyAbsence(
@"class C : IFoo $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterGenericClassBaseList()
{
VerifyKeyword(
@"class C<T> : IFoo $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterDelegate()
{
VerifyAbsence(
@"delegate void D() $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterGenericDelegate()
{
VerifyKeyword(
@"delegate void D<T>() $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterPreviousClassConstraint()
{
VerifyKeyword(
@"class C<T> where T : class $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterPreviousStructConstraint()
{
VerifyKeyword(
@"class C<T> where T : struct $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterPreviousNewConstraint()
{
VerifyKeyword(
@"class C<T> where T : new() $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterPreviousConstraint()
{
VerifyKeyword(
@"class C<T> where T : IList<T> $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterPreviousDelegateClassConstraint()
{
VerifyKeyword(
@"delegate void D<T>() where T : class $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterPreviousDelegateStructConstraint()
{
VerifyKeyword(
@"delegate void D<T>() where T : struct $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterPreviousDelegateNewConstraint()
{
VerifyKeyword(
@"delegate void D<T>() where T : new() $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterPreviousDelegateConstraint()
{
VerifyKeyword(
@"delegate void D<T>() where T : IList<T> $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterMethod()
{
VerifyAbsence(
@"class C {
void D() $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterGenericMethod()
{
VerifyKeyword(
@"class C {
void D<T>() $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterPreviousMethodClassConstraint()
{
VerifyKeyword(
@"class C {
void D<T>() where T : class $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterPreviousMethodStructConstraint()
{
VerifyKeyword(
@"class C {
void D<T>() where T : struct $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterPreviousMethodNewConstraint()
{
VerifyKeyword(
@"class C {
void D<T>() where T : new() $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterPreviousMethodConstraint()
{
VerifyKeyword(
@"class C {
void D<T>() where T : IList<T> $$");
}
[WorkItem(550715)]
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterWhereTypeConstraint()
{
VerifyAbsence(
@"public class Foo<T> : System.Object where $$
{
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterWhereWhere()
{
VerifyAbsence(
@"public class Foo<T> : System.Object where where $$
{
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterWhereWhereWhere()
{
VerifyAbsence(
@"public class Foo<T> : System.Object where where where $$
{
}");
}
[WorkItem(550720)]
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NoWhereAfterDot()
{
VerifyAbsence(
@"public class Foo<where> : System.$$
{
}");
}
}
}
| |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
*********************************************************************/
using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using Axiom.MathLib;
using Axiom.Utility;
namespace Multiverse.Gui {
/// <summary>
/// Variant of StaticText that allows me to control which widget
/// is in front. This is the core window object that is able to
/// draw text.
/// </summary>
public class LayeredComplexText : LayeredText, IDisposable
{
public static TimingMeter generateTextRegionsMeter = MeterManager.GetMeter("GenerateTextRegions", "LayeredComplexText");
public static TimingMeter clearMeter = MeterManager.GetMeter("Clear", "LayeredComplexText");
public static TimingMeter drawMeter = MeterManager.GetMeter("DrawString", "LayeredComplexText");
public static TimingMeter bitmapSaveMeter = MeterManager.GetMeter("Save Bitmap", "LayeredComplexText");
public static TimingMeter imageFromStreamMeter = MeterManager.GetMeter("Image.FromStream", "LayeredComplexText");
public static TimingMeter loadImageMeter = MeterManager.GetMeter("LoadImage", "LayeredComplexText");
public static TimingMeter measureStringMeter = MeterManager.GetMeter("MeasureString", "LayeredComplexText");
public static TimingMeter measureMeter = MeterManager.GetMeter("MeasureCharacterRanges", "LayeredComplexText");
public static TimingMeter drawTextMeter = MeterManager.GetMeter("DrawText", "LayeredComplexText");
bool rightToLeft = false;
Font font;
FontFamily fontFamily;
StringFormat format;
float emSize;
bool textDirty = true;
bool regionsDirty = true;
TextureAtlas chunkAtlas;
Bitmap bitmap;
bool dynamic = false;
Region[] regions;
TextureInfo[] chunks;
Graphics staticGraphics = null;
/// <summary>
/// Needed to offset the start of the in memory bitmap to exclude this data.
/// </summary>
const int BitmapHeaderSize = 54;
public LayeredComplexText(string name, Window clipWindow, bool dynamic, bool rightToLeft)
: base(name)
{
clipParent = clipWindow;
this.dynamic = dynamic;
int bitmapWidth = 128;
int bitmapHeight = 128;
format = (StringFormat)StringFormat.GenericTypographic.Clone();
format.Trimming = StringTrimming.None;
format.FormatFlags = StringFormatFlags.MeasureTrailingSpaces;
if (rightToLeft)
format.FormatFlags |= StringFormatFlags.DirectionRightToLeft;
CreateImage(bitmapWidth, bitmapHeight);
}
protected void CreateImage(int width, int height)
{
string imgName = String.Format("_font_string_{0}", this.name);
Axiom.Core.Texture fontTexture = null;
if (Axiom.Core.TextureManager.Instance.HasResource(imgName))
{
fontTexture = Axiom.Core.TextureManager.Instance.GetByName(imgName);
chunkAtlas = AtlasManager.Instance.GetTextureAtlas(imgName);
}
else
{
fontTexture = Axiom.Core.TextureManager.Instance.LoadImage(imgName, null);
chunkAtlas = AtlasManager.Instance.CreateAtlas(imgName, fontTexture);
}
System.Diagnostics.Debug.Assert(bitmap == null);
if (dynamic)
bitmap = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
else
bitmap = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
CopyBitmapToTexture(bitmap, fontTexture);
textDirty = true;
}
protected override void DrawText(float z)
{
if (textDirty || regionsDirty)
GenerateTextRegions();
drawTextMeter.Enter();
// throw new NotImplementedException();
Graphics g = GetGraphics();
// Rect renderRect = TextRenderArea;
Rect renderRect = GetVisibleTextArea();
for (int i = 0; i < regions.Length; ++i)
{
RectangleF rect = regions[i].GetBounds(g);
rect.Offset(renderRect.Left, renderRect.Top);
TextureInfo chunk = chunks[i];
chunk.Draw(new Vector3(rect.Left, rect.Top, z), this.TextRenderArea);
}
ReleaseGraphics(g);
drawTextMeter.Exit();
}
/// <summary>
/// It looks like GDI+ will draw into an area, and then tell me the
/// area that it used. If I try to draw the text into that returned
/// area, it is often too small, so this method lets me know when I
/// need to grow the area before I draw into it.
/// </summary>
/// <param name="g"></param>
/// <param name="text"></param>
/// <param name="range"></param>
/// <param name="font"></param>
/// <param name="r"></param>
/// <param name="origWidth"></param>
/// <param name="format"></param>
/// <returns></returns>
protected bool CheckTextRegion(Graphics g, string text, CharacterRange range, Font font, RectangleF r, float origWidth, StringFormat format)
{
CharacterRange[] testRanges = new CharacterRange[] { range };
format.SetMeasurableCharacterRanges(testRanges);
Region[] test = g.MeasureCharacterRanges(text.Substring(range.First, range.Length), font, r, format);
System.Diagnostics.Debug.Assert(test.Length == 1);
RectangleF testRect = test[0].GetBounds(g);
if (testRect.Width == origWidth)
return true;
return false;
}
protected void GenerateTextRegions()
{
generateTextRegionsMeter.Enter();
Graphics g = GetGraphics();
string text = GetAllText();
SetAlignment();
// this first call is to initialize the scroll data, so the
// visible text area will be correct.
// UpdateScrollPosition(textDirty);
float textHeight = GetTextHeight(g, text, true);
float textWidth = GetTextWidth(g, text);
// Update the scrollbars to take the new text into account
ConfigureScrollbars(textWidth, textHeight);
if (MaybeGrowTexture())
{
// If we resized the texture, we will need to use a new graphics object.
ReleaseGraphics(g);
g = GetGraphics();
}
RectangleF localRect = this.GetVisibleTextArea().ToRectangleF();
//string tmp = GetAllText();
//if (tmp != null && tmp.Length > 0)
// System.Diagnostics.Debug.Assert(tmp[0] != '[');
localRect.Offset(-localRect.Left, -localRect.Top);
measureMeter.Enter();
CharacterRange[] charRanges = new CharacterRange[] { new CharacterRange(0, text.Length) };
format.SetMeasurableCharacterRanges(charRanges);
regions = g.MeasureCharacterRanges(text, font, localRect, format);
measureMeter.Exit();
clearMeter.Enter();
// Ideally, gdi would handle alpha correctly, but it doesn't seem to
// g.Clear(normalTextStyle.bgColor.ToColor());
Color clearColor = normalTextStyle.bgColor.ToColor();
if (chunkAtlas.texture.HasAlpha && !normalTextStyle.bgEnabled)
// They didn't ask for a background, and we don't require one
clearColor = Color.FromArgb(0, clearColor);
g.Clear(clearColor);
// g.CompositingMode = CompositingMode.SourceCopy;
// g.CompositingQuality = CompositingQuality.HighQuality;
// Region fillRegion = new Region(RectangleF.FromLTRB(0, 0, chunkAtlas.texture.Width, chunkAtlas.texture.Height));
// g.FillRegion(new SolidBrush(clearColor), fillRegion);
// g.CompositingMode = CompositingMode.SourceOver;
clearMeter.Exit();
if (regions.Length == 0)
{
log.DebugFormat("Region dimensions for '{0}': None", text);
// nothing to draw
textDirty = false;
regionsDirty = false;
ReleaseGraphics(g);
generateTextRegionsMeter.Exit();
return;
}
chunks = new TextureInfo[regions.Length];
Brush brush = new SolidBrush(normalTextStyle.textColor.ToColor());
chunkAtlas.Clear();
drawMeter.Enter();
System.Diagnostics.Debug.Assert(charRanges.Length == regions.Length);
for (int i = 0; i < regions.Length; ++i)
{
Region region = regions[i];
CharacterRange range = charRanges[i];
RectangleF r = region.GetBounds(g);
float origWidth = r.Width;
// This loop basically keeps resizing the region we are drawing into
// until we get the same size result we got in our original region.
if (!CheckTextRegion(g, text, range, font, r, origWidth, format))
{
log.InfoFormat("Increasing size to fit string. Old size: {0}; New size: {1}", r, RectangleF.FromLTRB(r.Left, r.Top, r.Right + 1, r.Bottom));
r = RectangleF.FromLTRB(r.Left, r.Top, r.Right + 1, r.Bottom);
if (!CheckTextRegion(g, text, range, font, r, origWidth, format))
{
log.ErrorFormat("Increasing size to fit string. Old size: {0}; New size: {1}", r, RectangleF.FromLTRB(r.Left, r.Top, r.Right + 1, r.Bottom));
r = RectangleF.FromLTRB(r.Left, r.Top, r.Right + 1, r.Bottom);
if (!CheckTextRegion(g, text, range, font, r, origWidth, format))
log.Error("Even after increasing size twice, the string doesn't fit");
}
}
#if TEST_BOUNDS
Region[] test = g.MeasureCharacterRanges(text.Substring(range.First, range.Length), font, localRect, format);
System.Diagnostics.Debug.Assert(test.Length == 1);
RectangleF debugRect = test[0].GetBounds(g);
System.Diagnostics.Debug.Assert(debugRect == r);
test = g.MeasureCharacterRanges(text.Substring(range.First, range.Length), font, r, format);
System.Diagnostics.Debug.Assert(test.Length == 1);
debugRect = test[0].GetBounds(g);
System.Diagnostics.Debug.Assert(debugRect == r);
#endif
#if PAD_BOUNDS
// I have a hunch that for some reason, my text doesn't always
// render right unless I provide a little extra space.
RectangleF r2 = RectangleF.FromLTRB(r.Left, r.Top, r.Right + 1, r.Bottom + 1);
g.DrawString(text.Substring(range.First, range.Length), font, brush, r2, format);
#endif
g.DrawString(text.Substring(range.First, range.Length), font, brush, r, format);
// Construct and populate the atlas and chunk data structures
chunks[i] = chunkAtlas.DefineImage(string.Format("_region{0}", i), r);
log.DebugFormat("Region dimensions for '{0}': {1}", text.Substring(range.First, range.Length), r);
}
drawMeter.Exit();
// Now that I have updated my area, fetch the text height and width again
textHeight = GetTextHeight(g, text, true);
textWidth = GetTextWidth(g, text);
UpdateScrollPosition(textHeight, textWidth, textDirty);
textDirty = false;
regionsDirty = false;
ReleaseGraphics(g);
if (!dynamic)
// If we aren't dynamic, the underlying texture isn't
// automatically updated, so we need to copy the bitmap
// onto the texture. This also flips the bitmap, but
// since we clear it between draws, that should be fine.
CopyBitmapToTexture(bitmap, chunkAtlas.texture);
generateTextRegionsMeter.Exit();
}
protected void SetAlignment() {
format.Alignment = StringAlignment.Near;
switch (this.HorizontalFormat)
{
case HorizontalTextFormat.Left:
format.Alignment = rightToLeft ? StringAlignment.Far : StringAlignment.Near;
format.FormatFlags |= StringFormatFlags.NoWrap;
break;
case HorizontalTextFormat.WordWrapLeft:
format.Alignment = rightToLeft ? StringAlignment.Far : StringAlignment.Near;
format.FormatFlags &= ~StringFormatFlags.NoWrap;
break;
case HorizontalTextFormat.Centered:
format.Alignment = StringAlignment.Center;
format.FormatFlags |= StringFormatFlags.NoWrap;
break;
case HorizontalTextFormat.WordWrapCentered:
format.Alignment = StringAlignment.Center;
format.FormatFlags &= ~StringFormatFlags.NoWrap;
break;
case HorizontalTextFormat.Right:
format.Alignment = rightToLeft ? StringAlignment.Near : StringAlignment.Far;
format.FormatFlags |= StringFormatFlags.NoWrap;
break;
case HorizontalTextFormat.WordWrapRight:
format.Alignment = rightToLeft ? StringAlignment.Near : StringAlignment.Far;
format.FormatFlags &= ~StringFormatFlags.NoWrap;
break;
}
format.LineAlignment = StringAlignment.Near;
switch (this.VerticalFormat)
{
case VerticalTextFormat.Top:
format.LineAlignment = StringAlignment.Near;
break;
case VerticalTextFormat.Centered:
format.LineAlignment = StringAlignment.Center;
break;
case VerticalTextFormat.Bottom:
format.LineAlignment = StringAlignment.Far;
break;
}
}
protected void CopyBitmapToTexture(Bitmap fontBitmap, Axiom.Core.Texture fontTexture)
{
// save the image to a memory stream
Stream stream = new MemoryStream();
// flip the image
fontBitmap.RotateFlip(System.Drawing.RotateFlipType.RotateNoneFlipY);
fontBitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
// Bitmap headers are 54 bytes.. skip them
stream.Position = BitmapHeaderSize;
loadImageMeter.Enter();
if (dynamic)
fontTexture.LoadRawData(stream, fontBitmap.Width, fontBitmap.Height, Axiom.Media.PixelFormat.R8G8B8);
else
fontTexture.LoadRawData(stream, fontBitmap.Width, fontBitmap.Height, Axiom.Media.PixelFormat.A8R8G8B8);
loadImageMeter.Exit();
}
/// <summary>
/// Check to see if we need to resize the texture, and return true if
/// we do resize it.
/// </summary>
/// <returns></returns>
protected bool MaybeGrowTexture() {
// I actually need the entire area for the computation of how much
// space I need, so instead of GetVisibleArea, like I would
// normally use, I use TextRenderArea here.
Rect renderArea = this.GetVisibleTextArea();
Size textureDims = new Size(chunkAtlas.texture.Width, chunkAtlas.texture.Height);
while (renderArea.Height > textureDims.Height)
textureDims.Height = textureDims.Height * 2;
while (renderArea.Width > textureDims.Width)
textureDims.Width = textureDims.Width * 2;
if (chunkAtlas.texture.Width != textureDims.Width ||
chunkAtlas.texture.Height != textureDims.Height)
{
log.DebugFormat("Recreating texture with larger size: {0}", textureDims);
DisposeBitmap();
CreateImage(textureDims.Width, textureDims.Height);
return true;
}
return false;
}
/// <summary>
/// This computes how much horizontal space would be required to draw
/// all of the text. This is the width of the widest line.
/// </summary>
/// <returns>number of pixels of horizontal space required to draw the text</returns>
public override float GetTextWidth()
{
string text = GetAllText();
Graphics g = GetGraphics();
float rv = GetTextWidth(g, text);
ReleaseGraphics(g);
return rv;
}
/// <summary>
/// This computes how much horizontal space would be required to draw
/// all of the text. This is the width of the widest line.
/// </summary>
/// <returns>number of pixels of horizontal space required to draw the text</returns>
protected float GetTextWidth(Graphics g, string text)
{
SizeF size = g.MeasureString(text, font, (int)GetVisibleTextArea().Width, format);
return (float)Math.Ceiling(size.Width + shadowOffset.X);
}
/// <summary>
/// This computes how much vertical space would be required to draw
/// all the text, wrapping based on window width.
/// </summary>
/// <returns>number of pixels of vertical space required to draw the text</returns>
public override float GetTextHeight(bool includeEmpty)
{
string text = GetAllText();
Graphics g = GetGraphics();
float rv = GetTextHeight(g, text, includeEmpty);
ReleaseGraphics(g);
return rv;
}
/// <summary>
/// This computes how much vertical space would be required to draw
/// all the text, wrapping based on window width.
/// </summary>
/// <returns>number of pixels of vertical space required to draw the text</returns>
protected float GetTextHeight(Graphics g, string text, bool includeEmpty)
{
SizeF size = g.MeasureString(text, font, (int)GetVisibleTextArea().Width, format);
log.DebugFormat("Size of text: {0}, {1}", text.Length, size);
return (float)Math.Ceiling(size.Height + shadowOffset.Y);
}
public override int GetStringWidth()
{
return (int)Math.Ceiling(GetTextWidth());
}
public override void ScrollUp()
{
SetVScrollPosition(vertScrollPosition - font.Height);
OnAreaChanged(new EventArgs());
}
public override void ScrollDown()
{
SetVScrollPosition(vertScrollPosition + font.Height);
OnAreaChanged(new EventArgs());
}
protected internal override void OnTextChanged(EventArgs args)
{
log.Debug("In LayeredComplexText.OnTextChanged");
textDirty = true;
}
protected internal override void OnFontChanged(EventArgs args)
{
log.Debug("In LayeredComplexText.OnFontChanged");
regionsDirty = true;
}
protected internal override void OnAreaChanged(EventArgs args)
{
log.Debug("In LayeredComplexText.OnAreaChanged");
regionsDirty = true;
}
protected internal override void OnFormatChanged(EventArgs args)
{
log.Debug("In LayeredComplexText.OnFormatChanged");
regionsDirty = true;
}
public override void SetFont(string fontFace, int fontHeight, string characterSet)
{
// string fontName = string.Format("{0}-{1}", fontFace, fontHeight);
fontFamily = FontManager.GetFontFamily(fontFace);
this.emSize = (float)fontHeight;
this.font = new Font(fontFamily, emSize, FontStyle.Regular, GraphicsUnit.Pixel);
log.DebugFormat("Code page for {0} = {1}", font, font.GdiCharSet);
//if (!FontManager.Instance.ContainsKey(fontName))
// FontManager.Instance.CreateFont(fontName, fontFace, fontHeight, 0, characterSet);
}
protected Graphics GetGraphics()
{
Graphics g = null;
if (staticGraphics != null)
return staticGraphics;
if (dynamic)
g = chunkAtlas.texture.GetGraphics();
else if (staticGraphics == null) {
staticGraphics = Graphics.FromImage(bitmap);
g = staticGraphics;
}
g.PageUnit = GraphicsUnit.Pixel;
g.SmoothingMode = SmoothingMode.HighQuality;
g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
return g;
}
protected void ReleaseGraphics(Graphics g) {
if (dynamic) {
g.Dispose();
chunkAtlas.texture.ReleaseGraphics();
}
}
public void Dispose()
{
DisposeBitmap();
}
protected void DisposeBitmap()
{
if (staticGraphics != null)
{
staticGraphics.Dispose();
staticGraphics = null;
}
// dispose of the bitmap
if (bitmap != null)
{
bitmap.Dispose();
bitmap = null;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.IO.PortsTests;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Legacy.Support;
using Xunit;
namespace System.IO.Ports.Tests
{
public class ReadByte : PortsTest
{
//The number of random bytes to receive
private const int numRndByte = 8;
private enum ReadDataFromEnum { NonBuffered, Buffered, BufferedAndNonBuffered };
#region Test Cases
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void ASCIIEncoding()
{
Debug.WriteLine("Verifying read with bytes encoded with ASCIIEncoding");
VerifyRead(new ASCIIEncoding());
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void UTF8Encoding()
{
Debug.WriteLine("Verifying read with bytes encoded with UTF8Encoding");
VerifyRead(new UTF8Encoding());
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void UTF32Encoding()
{
Debug.WriteLine("Verifying read with bytes encoded with UTF32Encoding");
VerifyRead(new UTF32Encoding());
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void SerialPort_ReadBufferedData()
{
VerifyRead(Encoding.ASCII, ReadDataFromEnum.Buffered);
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void SerialPort_IterativeReadBufferedData()
{
VerifyRead(Encoding.ASCII, ReadDataFromEnum.Buffered);
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void SerialPort_ReadBufferedAndNonBufferedData()
{
VerifyRead(Encoding.ASCII, ReadDataFromEnum.BufferedAndNonBuffered);
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void SerialPort_IterativeReadBufferedAndNonBufferedData()
{
VerifyRead(Encoding.ASCII, ReadDataFromEnum.BufferedAndNonBuffered);
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void Read_DataReceivedBeforeTimeout()
{
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
byte[] byteXmitBuffer = TCSupport.GetRandomBytes(512);
byte[] byteRcvBuffer = new byte[byteXmitBuffer.Length];
ASyncRead asyncRead = new ASyncRead(com1);
var asyncReadTask = new Task(asyncRead.Read);
Debug.WriteLine(
"Verifying that ReadByte() will read bytes that have been received after the call to Read was made");
com1.Encoding = Encoding.UTF8;
com2.Encoding = Encoding.UTF8;
com1.ReadTimeout = 20000; // 20 seconds
com1.Open();
if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
com2.Open();
asyncReadTask.Start();
asyncRead.ReadStartedEvent.WaitOne();
//This only tells us that the thread has started to execute code in the method
Thread.Sleep(2000); //We need to wait to guarentee that we are executing code in SerialPort
com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length);
asyncRead.ReadCompletedEvent.WaitOne();
if (null != asyncRead.Exception)
{
Fail("Err_04448ajhied Unexpected exception thrown from async read:\n{0}", asyncRead.Exception);
}
else if (asyncRead.Result != byteXmitBuffer[0])
{
Fail("Err_0158ahei Expected ReadChar to read {0}({0:X}) actual {1}({1:X})", byteXmitBuffer[0], asyncRead.Result);
}
else
{
Thread.Sleep(1000); //We need to wait for all of the bytes to be received
byteRcvBuffer[0] = (byte)asyncRead.Result;
int readResult = com1.Read(byteRcvBuffer, 1, byteRcvBuffer.Length - 1);
if (1 + readResult != byteXmitBuffer.Length)
{
Fail("Err_051884ajoedo Expected Read to read {0} bytes actually read {1}",
byteXmitBuffer.Length - 1, readResult);
}
else
{
for (int i = 0; i < byteXmitBuffer.Length; ++i)
{
if (byteRcvBuffer[i] != byteXmitBuffer[i])
{
Fail(
"Err_05188ahed Characters differ at {0} expected:{1}({1:X}) actual:{2}({2:X}) asyncRead.Result={3}",
i, byteXmitBuffer[i], byteRcvBuffer[i], asyncRead.Result);
}
}
}
}
TCSupport.WaitForTaskCompletion(asyncReadTask);
}
}
#endregion
#region Verification for Test Cases
private void VerifyRead(Encoding encoding)
{
VerifyRead(encoding, ReadDataFromEnum.NonBuffered);
}
private void VerifyRead(Encoding encoding, ReadDataFromEnum readDataFrom)
{
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
Random rndGen = new Random(-55);
int bufferSize = numRndByte;
byte[] byteXmitBuffer = new byte[bufferSize];
//Genrate random bytes
for (int i = 0; i < byteXmitBuffer.Length; i++)
{
byteXmitBuffer[i] = (byte)rndGen.Next(0, 256);
}
com1.ReadTimeout = 500;
com1.Encoding = encoding;
TCSupport.SetHighSpeed(com1, com2);
com1.Open();
if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
com2.Open();
switch (readDataFrom)
{
case ReadDataFromEnum.NonBuffered:
VerifyReadNonBuffered(com1, com2, byteXmitBuffer);
break;
case ReadDataFromEnum.Buffered:
VerifyReadBuffered(com1, com2, byteXmitBuffer);
break;
case ReadDataFromEnum.BufferedAndNonBuffered:
VerifyReadBufferedAndNonBuffered(com1, com2, byteXmitBuffer);
break;
default:
throw new ArgumentOutOfRangeException(nameof(readDataFrom));
}
}
}
private void VerifyReadNonBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite)
{
VerifyBytesReadOnCom1FromCom2(com1, com2, bytesToWrite, bytesToWrite);
}
private void VerifyReadBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite)
{
BufferData(com1, com2, bytesToWrite);
PerformReadOnCom1FromCom2(com1, com2, bytesToWrite);
}
private void VerifyReadBufferedAndNonBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite)
{
byte[] expectedBytes = new byte[(2 * bytesToWrite.Length)];
BufferData(com1, com2, bytesToWrite);
Buffer.BlockCopy(bytesToWrite, 0, expectedBytes, 0, bytesToWrite.Length);
Buffer.BlockCopy(bytesToWrite, 0, expectedBytes, bytesToWrite.Length, bytesToWrite.Length);
VerifyBytesReadOnCom1FromCom2(com1, com2, bytesToWrite, expectedBytes);
}
private void BufferData(SerialPort com1, SerialPort com2, byte[] bytesToWrite)
{
com2.Write(bytesToWrite, 0, 1); // Write one byte at the begining because we are going to read this to buffer the rest of the data
com2.Write(bytesToWrite, 0, bytesToWrite.Length);
TCSupport.WaitForReadBufferToLoad(com1, bytesToWrite.Length);
com1.Read(new char[1], 0, 1); // This should put the rest of the bytes in SerialPorts own internal buffer
if (com1.BytesToRead != bytesToWrite.Length)
{
Fail("Err_7083zaz Expected com1.BytesToRead={0} actual={1}", bytesToWrite.Length, com1.BytesToRead);
}
}
private void VerifyBytesReadOnCom1FromCom2(SerialPort com1, SerialPort com2, byte[] bytesToWrite, byte[] expectedBytes)
{
com2.Write(bytesToWrite, 0, bytesToWrite.Length);
com1.ReadTimeout = 500;
Thread.Sleep((int)(((bytesToWrite.Length * 10.0) / com1.BaudRate) * 1000) + 250);
PerformReadOnCom1FromCom2(com1, com2, expectedBytes);
}
private void PerformReadOnCom1FromCom2(SerialPort com1, SerialPort com2, byte[] expectedBytes)
{
byte[] byteRcvBuffer = new byte[expectedBytes.Length];
int readInt;
int i;
i = 0;
while (true)
{
try
{
readInt = com1.ReadByte();
}
catch (TimeoutException)
{
break;
}
//While their are more bytes to be read
if (expectedBytes.Length <= i)
{
//If we have read in more bytes then were actually sent
Fail("ERROR!!!: We have received more bytes then were sent");
break;
}
byteRcvBuffer[i] = (byte)readInt;
if (readInt != expectedBytes[i])
{
//If the byte read is not the expected byte
Fail("ERROR!!!: Expected to read {0} actual read byte {1}", (int)expectedBytes[i], readInt);
}
i++;
if (expectedBytes.Length - i != com1.BytesToRead)
{
Fail("ERROR!!!: Expected BytesToRead={0} actual={1}", expectedBytes.Length - i, com1.BytesToRead);
}
}
if (0 != com1.BytesToRead)
{
Fail("ERROR!!!: Expected BytesToRead=0 actual BytesToRead={0}", com1.BytesToRead);
}
if (com1.IsOpen)
com1.Close();
if (com2.IsOpen)
com2.Close();
}
public class ASyncRead
{
private readonly SerialPort _com;
private int _result;
private readonly AutoResetEvent _readCompletedEvent;
private readonly AutoResetEvent _readStartedEvent;
private Exception _exception;
public ASyncRead(SerialPort com)
{
_com = com;
_result = int.MinValue;
_readCompletedEvent = new AutoResetEvent(false);
_readStartedEvent = new AutoResetEvent(false);
_exception = null;
}
public void Read()
{
try
{
_readStartedEvent.Set();
_result = _com.ReadByte();
}
catch (Exception e)
{
_exception = e;
}
finally
{
_readCompletedEvent.Set();
}
}
public AutoResetEvent ReadStartedEvent
{
get
{
return _readStartedEvent;
}
}
public AutoResetEvent ReadCompletedEvent
{
get
{
return _readCompletedEvent;
}
}
public int Result
{
get
{
return _result;
}
}
public Exception Exception
{
get
{
return _exception;
}
}
}
#endregion
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using BTCPayServer.Client.Models;
using BTCPayServer.Configuration;
using BTCPayServer.Data;
using BTCPayServer.Events;
using BTCPayServer.Lightning;
using BTCPayServer.Logging;
using BTCPayServer.Services;
using BTCPayServer.Services.Invoices;
using BTCPayServer.Services.Stores;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NBXplorer;
namespace BTCPayServer.Payments.Lightning
{
public class LightningListener : IHostedService
{
public Logs Logs { get; }
readonly EventAggregator _Aggregator;
readonly InvoiceRepository _InvoiceRepository;
private readonly IMemoryCache _memoryCache;
readonly BTCPayNetworkProvider _NetworkProvider;
private readonly LightningClientFactoryService lightningClientFactory;
private readonly LightningLikePaymentHandler _lightningLikePaymentHandler;
private readonly StoreRepository _storeRepository;
private readonly PaymentService _paymentService;
readonly Channel<string> _CheckInvoices = Channel.CreateUnbounded<string>();
Task _CheckingInvoice;
readonly Dictionary<(string, string), LightningInstanceListener> _InstanceListeners = new Dictionary<(string, string), LightningInstanceListener>();
public LightningListener(EventAggregator aggregator,
InvoiceRepository invoiceRepository,
IMemoryCache memoryCache,
BTCPayNetworkProvider networkProvider,
LightningClientFactoryService lightningClientFactory,
LightningLikePaymentHandler lightningLikePaymentHandler,
StoreRepository storeRepository,
IOptions<LightningNetworkOptions> options,
PaymentService paymentService,
Logs logs)
{
Logs = logs;
_Aggregator = aggregator;
_InvoiceRepository = invoiceRepository;
_memoryCache = memoryCache;
_NetworkProvider = networkProvider;
this.lightningClientFactory = lightningClientFactory;
_lightningLikePaymentHandler = lightningLikePaymentHandler;
_storeRepository = storeRepository;
_paymentService = paymentService;
Options = options;
}
async Task CheckingInvoice(CancellationToken cancellation)
{
while (await _CheckInvoices.Reader.WaitToReadAsync(cancellation) &&
_CheckInvoices.Reader.TryRead(out var invoiceId))
{
try
{
foreach (var listenedInvoice in (await GetListenedInvoices(invoiceId)).Where(i => !i.IsExpired()))
{
var instanceListenerKey = (listenedInvoice.Network.CryptoCode, GetLightningUrl(listenedInvoice.SupportedPaymentMethod).ToString());
if (!_InstanceListeners.TryGetValue(instanceListenerKey, out var instanceListener) ||
!instanceListener.IsListening)
{
instanceListener ??= new LightningInstanceListener(_InvoiceRepository, _Aggregator, lightningClientFactory, listenedInvoice.Network, GetLightningUrl(listenedInvoice.SupportedPaymentMethod), _paymentService, Logs);
var status = await instanceListener.PollPayment(listenedInvoice, cancellation);
if (status is null ||
status is LightningInvoiceStatus.Paid ||
status is LightningInvoiceStatus.Expired)
{
continue;
}
instanceListener.AddListenedInvoice(listenedInvoice);
instanceListener.EnsureListening(cancellation);
_InstanceListeners.TryAdd(instanceListenerKey, instanceListener);
}
else
{
instanceListener.AddListenedInvoice(listenedInvoice);
}
}
foreach (var kv in _InstanceListeners)
{
kv.Value.RemoveExpiredInvoices();
}
foreach (var k in _InstanceListeners
.Where(kv => !kv.Value.IsListening)
.Select(kv => kv.Key).ToArray())
{
_InstanceListeners.Remove(k);
}
}
catch when (!_Cts.Token.IsCancellationRequested)
{
}
}
}
private string GetCacheKey(string invoiceId)
{
return $"{nameof(GetListenedInvoices)}-{invoiceId}";
}
private Task<List<ListenedInvoice>> GetListenedInvoices(string invoiceId)
{
return _memoryCache.GetOrCreateAsync(GetCacheKey(invoiceId), async (cacheEntry) =>
{
var listenedInvoices = new List<ListenedInvoice>();
var invoice = await _InvoiceRepository.GetInvoice(invoiceId);
foreach (var paymentMethod in invoice.GetPaymentMethods()
.Where(c => new[] { PaymentTypes.LightningLike, LNURLPayPaymentType.Instance }.Contains(c.GetId().PaymentType)))
{
LightningLikePaymentMethodDetails lightningMethod;
LightningSupportedPaymentMethod lightningSupportedMethod;
switch (paymentMethod.GetPaymentMethodDetails())
{
case LNURLPayPaymentMethodDetails lnurlPayPaymentMethodDetails:
lightningMethod = lnurlPayPaymentMethodDetails;
lightningSupportedMethod = lnurlPayPaymentMethodDetails.LightningSupportedPaymentMethod;
break;
case LightningLikePaymentMethodDetails { Activated: true } lightningLikePaymentMethodDetails:
lightningMethod = lightningLikePaymentMethodDetails;
lightningSupportedMethod = invoice.GetSupportedPaymentMethod<LightningSupportedPaymentMethod>()
.FirstOrDefault(c => c.CryptoCode == paymentMethod.GetId().CryptoCode);
break;
default:
continue;
}
if (lightningSupportedMethod == null || string.IsNullOrEmpty(lightningMethod.InvoiceId))
continue;
var network = _NetworkProvider.GetNetwork<BTCPayNetwork>(paymentMethod.GetId().CryptoCode);
listenedInvoices.Add(new ListenedInvoice()
{
Expiration = invoice.ExpirationTime,
Uri = GetLightningUrl(lightningSupportedMethod).BaseUri.AbsoluteUri,
PaymentMethodDetails = lightningMethod,
SupportedPaymentMethod = lightningSupportedMethod,
PaymentMethod = paymentMethod,
Network = network,
InvoiceId = invoice.Id
});
}
var expiredIn = DateTimeOffset.UtcNow - invoice.ExpirationTime;
cacheEntry.AbsoluteExpiration = DateTimeOffset.UtcNow + (expiredIn >= TimeSpan.FromMinutes(5.0) ? expiredIn : TimeSpan.FromMinutes(5.0));
return listenedInvoices;
});
}
readonly ConcurrentDictionary<string, LightningInstanceListener> _ListeningInstances = new ConcurrentDictionary<string, LightningInstanceListener>();
readonly CompositeDisposable leases = new CompositeDisposable();
public Task StartAsync(CancellationToken cancellationToken)
{
leases.Add(_Aggregator.SubscribeAsync<Events.InvoiceEvent>(async inv =>
{
if (inv.Name == InvoiceEvent.Created)
{
_CheckInvoices.Writer.TryWrite(inv.Invoice.Id);
}
if (inv.Name == InvoiceEvent.ReceivedPayment && inv.Invoice.Status == InvoiceStatusLegacy.New && inv.Invoice.ExceptionStatus == InvoiceExceptionStatus.PaidPartial)
{
var pm = inv.Invoice.GetPaymentMethods().First();
if (pm.Calculate().Due.GetValue(pm.Network as BTCPayNetwork) > 0m)
{
await CreateNewLNInvoiceForBTCPayInvoice(inv.Invoice);
}
}
}));
leases.Add(_Aggregator.SubscribeAsync<Events.InvoiceDataChangedEvent>(async inv =>
{
if (inv.State.Status == InvoiceStatusLegacy.New &&
inv.State.ExceptionStatus == InvoiceExceptionStatus.PaidPartial)
{
var invoice = await _InvoiceRepository.GetInvoice(inv.InvoiceId);
await CreateNewLNInvoiceForBTCPayInvoice(invoice);
}
}));
leases.Add(_Aggregator.Subscribe<Events.InvoicePaymentMethodActivated>(inv =>
{
if (inv.PaymentMethodId.PaymentType == LightningPaymentType.Instance)
{
_memoryCache.Remove(GetCacheKey(inv.InvoiceId));
_CheckInvoices.Writer.TryWrite(inv.InvoiceId);
}
}));
leases.Add(_Aggregator.Subscribe<Events.InvoiceNewPaymentDetailsEvent>(inv =>
{
if (inv.PaymentMethodId.PaymentType == LNURLPayPaymentType.Instance)
{
_memoryCache.Remove(GetCacheKey(inv.InvoiceId));
_CheckInvoices.Writer.TryWrite(inv.InvoiceId);
}
}));
_CheckingInvoice = CheckingInvoice(_Cts.Token);
_ListenPoller = new Timer(async s =>
{
try
{
var invoiceIds = await _InvoiceRepository.GetPendingInvoices();
foreach (var invoiceId in invoiceIds)
_CheckInvoices.Writer.TryWrite(invoiceId);
}
catch { } // Never throw an unhandled exception on async void
}, null, 0, (int)PollInterval.TotalMilliseconds);
leases.Add(_ListenPoller);
return Task.CompletedTask;
}
private async Task CreateNewLNInvoiceForBTCPayInvoice(InvoiceEntity invoice)
{
var paymentMethods = invoice.GetPaymentMethods()
.Where(method => new[] { PaymentTypes.LightningLike, LNURLPayPaymentType.Instance }.Contains(method.GetId().PaymentType))
.ToArray();
var store = await _storeRepository.FindStore(invoice.StoreId);
if (paymentMethods.Any())
{
var logs = new InvoiceLogs();
logs.Write(
"Partial payment detected, attempting to update all lightning payment methods with new bolt11 with correct due amount.",
InvoiceEventData.EventSeverity.Info);
foreach (var paymentMethod in paymentMethods)
{
try
{
var oldDetails = (LightningLikePaymentMethodDetails)paymentMethod.GetPaymentMethodDetails();
if (!oldDetails.Activated)
{
continue;
}
if (oldDetails is LNURLPayPaymentMethodDetails lnurlPayPaymentMethodDetails && !string.IsNullOrEmpty(lnurlPayPaymentMethodDetails.BOLT11))
{
try
{
var client = _lightningLikePaymentHandler.CreateLightningClient(lnurlPayPaymentMethodDetails.LightningSupportedPaymentMethod,
(BTCPayNetwork)paymentMethod.Network);
await client.CancelInvoice(oldDetails.InvoiceId);
}
catch
{
//not a fully supported option
}
lnurlPayPaymentMethodDetails = new LNURLPayPaymentMethodDetails()
{
Activated = lnurlPayPaymentMethodDetails.Activated,
Bech32Mode = lnurlPayPaymentMethodDetails.Bech32Mode,
InvoiceId = null,
NodeInfo = lnurlPayPaymentMethodDetails.NodeInfo,
GeneratedBoltAmount = null,
BOLT11 = null,
LightningSupportedPaymentMethod = lnurlPayPaymentMethodDetails.LightningSupportedPaymentMethod,
BTCPayInvoiceId = lnurlPayPaymentMethodDetails.BTCPayInvoiceId
};
await _InvoiceRepository.NewPaymentDetails(invoice.Id, lnurlPayPaymentMethodDetails,
paymentMethod.Network);
_Aggregator.Publish(new Events.InvoiceNewPaymentDetailsEvent(invoice.Id,
lnurlPayPaymentMethodDetails, paymentMethod.GetId()));
continue;
}
LightningSupportedPaymentMethod supportedMethod = invoice
.GetSupportedPaymentMethod<LightningSupportedPaymentMethod>(paymentMethod.GetId()).First();
try
{
var client = _lightningLikePaymentHandler.CreateLightningClient(supportedMethod,
(BTCPayNetwork)paymentMethod.Network);
await client.CancelInvoice(oldDetails.InvoiceId);
}
catch
{
//not a fully supported option
}
var prepObj =
_lightningLikePaymentHandler.PreparePayment(supportedMethod, store, paymentMethod.Network);
var newPaymentMethodDetails =
(LightningLikePaymentMethodDetails)(await _lightningLikePaymentHandler
.CreatePaymentMethodDetails(logs, supportedMethod, paymentMethod, store,
paymentMethod.Network, prepObj));
var instanceListenerKey = (paymentMethod.Network.CryptoCode,
GetLightningUrl(supportedMethod).ToString());
if (_InstanceListeners.TryGetValue(instanceListenerKey, out var instanceListener))
{
await _InvoiceRepository.NewPaymentDetails(invoice.Id, newPaymentMethodDetails,
paymentMethod.Network);
instanceListener.AddListenedInvoice(new ListenedInvoice()
{
Expiration = invoice.ExpirationTime,
Uri = GetLightningUrl(supportedMethod).BaseUri.AbsoluteUri,
PaymentMethodDetails = newPaymentMethodDetails,
SupportedPaymentMethod = supportedMethod,
PaymentMethod = paymentMethod,
Network = (BTCPayNetwork)paymentMethod.Network,
InvoiceId = invoice.Id
});
_Aggregator.Publish(new Events.InvoiceNewPaymentDetailsEvent(invoice.Id,
newPaymentMethodDetails, paymentMethod.GetId()));
}
}
catch (Exception e)
{
logs.Write($"Could not update {paymentMethod.GetId().ToPrettyString()}: {e.Message}",
InvoiceEventData.EventSeverity.Error);
}
}
await _InvoiceRepository.AddInvoiceLogs(invoice.Id, logs);
_CheckInvoices.Writer.TryWrite(invoice.Id);
}
}
private LightningConnectionString GetLightningUrl(LightningSupportedPaymentMethod supportedMethod)
{
var url = supportedMethod.GetExternalLightningUrl();
if (url != null)
return url;
if (Options.Value.InternalLightningByCryptoCode.TryGetValue(supportedMethod.CryptoCode, out var conn))
return conn;
throw new InvalidOperationException($"{supportedMethod.CryptoCode}: The internal lightning node is not set up");
}
TimeSpan _PollInterval = TimeSpan.FromMinutes(1.0);
public TimeSpan PollInterval
{
get
{
return _PollInterval;
}
set
{
_PollInterval = value;
if (_ListenPoller != null)
{
_ListenPoller.Change(0, (int)value.TotalMilliseconds);
}
}
}
public IOptions<LightningNetworkOptions> Options { get; }
readonly CancellationTokenSource _Cts = new CancellationTokenSource();
private Timer _ListenPoller;
public async Task StopAsync(CancellationToken cancellationToken)
{
leases.Dispose();
_Cts.Cancel();
try
{
await _CheckingInvoice;
}
catch (OperationCanceledException)
{
}
try
{
await Task.WhenAll(_ListeningInstances.Select(c => c.Value.Listening).ToArray());
}
catch (OperationCanceledException)
{
}
Logs.PayServer.LogInformation($"{this.GetType().Name} successfully exited...");
}
}
public class LightningInstanceListener
{
public Logs Logs { get; }
private readonly InvoiceRepository _invoiceRepository;
private readonly EventAggregator _eventAggregator;
private readonly BTCPayNetwork _network;
private readonly PaymentService _paymentService;
private readonly LightningClientFactoryService _lightningClientFactory;
public LightningConnectionString ConnectionString { get; }
public LightningInstanceListener(InvoiceRepository invoiceRepository,
EventAggregator eventAggregator,
LightningClientFactoryService lightningClientFactory,
BTCPayNetwork network,
LightningConnectionString connectionString,
PaymentService paymentService,
Logs logs)
{
ArgumentNullException.ThrowIfNull(connectionString);
Logs = logs;
this._invoiceRepository = invoiceRepository;
_eventAggregator = eventAggregator;
this._network = network;
_paymentService = paymentService;
_lightningClientFactory = lightningClientFactory;
ConnectionString = connectionString;
}
internal bool AddListenedInvoice(ListenedInvoice invoice)
{
return _ListenedInvoices.TryAdd(invoice.PaymentMethodDetails.InvoiceId, invoice);
}
internal async Task<LightningInvoiceStatus?> PollPayment(ListenedInvoice listenedInvoice, CancellationToken cancellation)
{
var client = _lightningClientFactory.Create(ConnectionString, _network);
LightningInvoice lightningInvoice = await client.GetInvoice(listenedInvoice.PaymentMethodDetails.InvoiceId, cancellation);
if (lightningInvoice?.Status is LightningInvoiceStatus.Paid &&
await AddPayment(lightningInvoice, listenedInvoice.InvoiceId, listenedInvoice.PaymentMethod.GetId().PaymentType))
{
Logs.PayServer.LogInformation($"{_network.CryptoCode} (Lightning): Payment detected via polling on {listenedInvoice.InvoiceId}");
}
return lightningInvoice?.Status;
}
public bool IsListening => Listening?.Status is TaskStatus.Running || Listening?.Status is TaskStatus.WaitingForActivation;
public Task Listening { get; set; }
public void EnsureListening(CancellationToken cancellation)
{
if (!IsListening)
{
StopListeningCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellation);
Listening = Listen(StopListeningCancellationTokenSource.Token);
}
}
public CancellationTokenSource StopListeningCancellationTokenSource;
async Task Listen(CancellationToken cancellation)
{
Logs.PayServer.LogInformation($"{_network.CryptoCode} (Lightning): Start listening {ConnectionString.BaseUri}");
try
{
var lightningClient = _lightningClientFactory.Create(ConnectionString, _network);
using var session = await lightningClient.Listen(cancellation);
// Just in case the payment arrived after our last poll but before we listened.
await PollAllListenedInvoices(cancellation);
if (_ErrorAlreadyLogged)
{
Logs.PayServer.LogInformation($"{_network.CryptoCode} (Lightning): Could reconnect successfully to {ConnectionString.BaseUri}");
}
_ErrorAlreadyLogged = false;
while (!_ListenedInvoices.IsEmpty)
{
var notification = await session.WaitInvoice(cancellation);
if (!_ListenedInvoices.TryGetValue(notification.Id, out var listenedInvoice))
continue;
if (notification.Id == listenedInvoice.PaymentMethodDetails.InvoiceId &&
(notification.BOLT11 == listenedInvoice.PaymentMethodDetails.BOLT11 ||
BOLT11PaymentRequest.Parse(notification.BOLT11, _network.NBitcoinNetwork).PaymentHash ==
listenedInvoice.PaymentMethodDetails.GetPaymentHash(_network.NBitcoinNetwork)))
{
if (notification.Status == LightningInvoiceStatus.Paid &&
notification.PaidAt.HasValue && notification.Amount != null)
{
if (await AddPayment(notification, listenedInvoice.InvoiceId, listenedInvoice.PaymentMethod.GetId().PaymentType))
{
Logs.PayServer.LogInformation($"{_network.CryptoCode} (Lightning): Payment detected via notification ({listenedInvoice.InvoiceId})");
}
_ListenedInvoices.TryRemove(notification.Id, out var _);
}
else if (notification.Status == LightningInvoiceStatus.Expired)
{
_ListenedInvoices.TryRemove(notification.Id, out var _);
}
}
}
}
catch (Exception ex) when (!cancellation.IsCancellationRequested && !_ErrorAlreadyLogged)
{
_ErrorAlreadyLogged = true;
Logs.PayServer.LogError(ex, $"{_network.CryptoCode} (Lightning): Error while contacting {ConnectionString.BaseUri}");
Logs.PayServer.LogInformation($"{_network.CryptoCode} (Lightning): Stop listening {ConnectionString.BaseUri}");
}
catch (OperationCanceledException) when (cancellation.IsCancellationRequested) { }
if (_ListenedInvoices.IsEmpty)
Logs.PayServer.LogInformation($"{_network.CryptoCode} (Lightning): No more invoice to listen on {ConnectionString.BaseUri}, releasing the connection.");
}
public DateTimeOffset? LastFullPoll { get; set; }
internal async Task PollAllListenedInvoices(CancellationToken cancellation)
{
foreach (var invoice in _ListenedInvoices.Values)
{
var status = await PollPayment(invoice, cancellation);
if (status is null ||
status is LightningInvoiceStatus.Paid ||
status is LightningInvoiceStatus.Expired)
_ListenedInvoices.TryRemove(invoice.PaymentMethodDetails.InvoiceId, out var _);
}
LastFullPoll = DateTimeOffset.UtcNow;
if (_ListenedInvoices.IsEmpty)
{
StopListeningCancellationTokenSource?.Cancel();
}
}
bool _ErrorAlreadyLogged = false;
readonly ConcurrentDictionary<string, ListenedInvoice> _ListenedInvoices = new ConcurrentDictionary<string, ListenedInvoice>();
public async Task<bool> AddPayment(LightningInvoice notification, string invoiceId, PaymentType paymentType)
{
var payment = await _paymentService.AddPayment(invoiceId, notification.PaidAt.Value, new LightningLikePaymentData()
{
BOLT11 = notification.BOLT11,
PaymentHash = BOLT11PaymentRequest.Parse(notification.BOLT11, _network.NBitcoinNetwork).PaymentHash,
Amount = notification.AmountReceived ?? notification.Amount, // if running old version amount received might be unavailable,
PaymentType = paymentType.ToString()
}, _network, accounted: true);
if (payment != null)
{
var invoice = await _invoiceRepository.GetInvoice(invoiceId);
if (invoice != null)
_eventAggregator.Publish(new InvoiceEvent(invoice, InvoiceEvent.ReceivedPayment) { Payment = payment });
}
return payment != null;
}
internal void RemoveExpiredInvoices()
{
foreach (var invoice in _ListenedInvoices)
{
if (invoice.Value.IsExpired())
_ListenedInvoices.TryRemove(invoice.Key, out var _);
}
if (_ListenedInvoices.IsEmpty)
StopListeningCancellationTokenSource?.Cancel();
}
}
class ListenedInvoice
{
public bool IsExpired() { return DateTimeOffset.UtcNow > Expiration; }
public DateTimeOffset Expiration { get; set; }
public LightningLikePaymentMethodDetails PaymentMethodDetails { get; set; }
public LightningSupportedPaymentMethod SupportedPaymentMethod { get; set; }
public PaymentMethod PaymentMethod { get; set; }
public string Uri { get; internal set; }
public BTCPayNetwork Network { get; internal set; }
public string InvoiceId { get; internal set; }
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.Management.Automation.Language;
using System.Runtime.Serialization;
#if !CORECLR
using System.Security.Permissions;
#else
// Use stub for SerializableAttribute, SecurityPermissionAttribute and ISerializable related types.
using Microsoft.PowerShell.CoreClr.Stubs;
#endif
namespace System.Management.Automation
{
/// <summary>
/// RuntimeException is the base class for exceptions likely to occur
/// while a Monad command is running.
/// </summary>
/// <remarks>
/// Monad scripts can trap RuntimeException using the
/// "trap (exceptionclass) {handler}" script construct.
///
/// Instances of this exception class are usually generated by the
/// Monad Engine. It is unusual for code outside the Monad Engine
/// to create an instance of this class.
/// </remarks>
[Serializable]
public class RuntimeException
: SystemException, IContainsErrorRecord
{
#region ctor
/// <summary>
/// Initializes a new instance of the RuntimeException class.
/// </summary>
/// <returns> constructed object </returns>
public RuntimeException()
: base()
{
}
#region Serialization
/// <summary>
/// Initializes a new instance of the RuntimeException class
/// using data serialized via
/// <see cref="ISerializable"/>
/// </summary>
/// <param name="info"> serialization information </param>
/// <param name="context"> streaming context </param>
/// <returns> constructed object </returns>
protected RuntimeException(SerializationInfo info,
StreamingContext context)
: base(info, context)
{
_errorId = info.GetString("ErrorId");
_errorCategory = (ErrorCategory)info.GetInt32("ErrorCategory");
}
/// <summary>
/// Serializer for <see cref="ISerializable"/>
/// </summary>
/// <param name="info"> serialization information </param>
/// <param name="context"> streaming context </param>
[SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new PSArgumentNullException("info");
}
base.GetObjectData(info, context);
info.AddValue("ErrorId", _errorId);
info.AddValue("ErrorCategory", (Int32)_errorCategory);
}
#endregion Serialization
/// <summary>
/// Initializes a new instance of the RuntimeException class.
/// </summary>
/// <param name="message"> </param>
/// <returns> constructed object </returns>
public RuntimeException(string message)
: base(message)
{
}
/// <summary>
/// Initializes a new instance of the RuntimeException class.
/// </summary>
/// <param name="message"> </param>
/// <param name="innerException"> </param>
/// <returns> constructed object </returns>
public RuntimeException(string message,
Exception innerException)
: base(message, innerException)
{
}
/// <summary>
/// Initializes a new instance of the RuntimeException class
/// starting with an already populated error record.
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
/// <param name="errorRecord"></param>
/// <returns> constructed object </returns>
public RuntimeException(string message,
Exception innerException,
ErrorRecord errorRecord)
: base(message, innerException)
{
_errorRecord = errorRecord;
}
internal RuntimeException(ErrorCategory errorCategory,
InvocationInfo invocationInfo,
IScriptExtent errorPosition,
string errorIdAndResourceId,
string message,
Exception innerException)
: base(message, innerException)
{
SetErrorCategory(errorCategory);
SetErrorId(errorIdAndResourceId);
if ((errorPosition == null) && (invocationInfo != null))
{
errorPosition = invocationInfo.ScriptPosition;
}
if (invocationInfo == null) return;
_errorRecord = new ErrorRecord(
new ParentContainsErrorRecordException(this),
_errorId,
_errorCategory,
_targetObject);
_errorRecord.SetInvocationInfo(new InvocationInfo(invocationInfo.MyCommand, errorPosition));
}
#endregion ctor
#region ErrorRecord
// If RuntimeException subclasses need to do more than change
// the ErrorId, ErrorCategory and TargetObject, they can access
// the ErrorRecord property and make changes directly. However,
// not that calling SetErrorId, SetErrorCategory or SetTargetObject
// will clean the cached ErrorRecord and erase any other changes,
// so the ErrorId etc. should be set first.
/// <summary>
/// Additional information about the error
/// </summary>
/// <value></value>
/// <remarks>
/// Note that ErrorRecord.Exception is
/// <see cref="System.Management.Automation.ParentContainsErrorRecordException"/>.
/// </remarks>
public virtual ErrorRecord ErrorRecord
{
get
{
if (null == _errorRecord)
{
_errorRecord = new ErrorRecord(
new ParentContainsErrorRecordException(this),
_errorId,
_errorCategory,
_targetObject);
}
return _errorRecord;
}
}
private ErrorRecord _errorRecord;
private string _errorId = "RuntimeException";
private ErrorCategory _errorCategory = ErrorCategory.NotSpecified;
private object _targetObject = null;
/// <summary>
/// Subclasses can use this method to set the ErrorId.
/// Note that this will clear the cached ErrorRecord, so be sure
/// to change this before writing to ErrorRecord.ErrorDetails
/// or the like.
/// </summary>
/// <param name="errorId">per ErrorRecord constructors</param>
internal void SetErrorId(string errorId)
{
if (_errorId != errorId)
{
_errorId = errorId;
_errorRecord = null;
}
}
/// <summary>
/// Subclasses can use this method to set the ErrorCategory.
/// Note that this will clear the cached ErrorRecord, so be sure
/// to change this before writing to ErrorRecord.ErrorDetails
/// or the like.
/// </summary>
/// <param name="errorCategory">
/// per ErrorRecord.CategoryInfo.Category
/// </param>
internal void SetErrorCategory(ErrorCategory errorCategory)
{
if (_errorCategory != errorCategory)
{
_errorCategory = errorCategory;
_errorRecord = null;
}
}
/// <summary>
/// Subclasses can use this method to set or update the TargetObject.
/// This convenience function doesn't clobber the error record if it
/// already exists...
/// </summary>
/// <param name="targetObject">
/// per ErrorRecord.TargetObject
/// </param>
internal void SetTargetObject(object targetObject)
{
_targetObject = targetObject;
if (_errorRecord != null)
_errorRecord.SetTargetObject(targetObject);
}
#endregion ErrorRecord
#region Internal
internal static string RetrieveMessage(ErrorRecord errorRecord)
{
if (null == errorRecord)
return "";
if (null != errorRecord.ErrorDetails &&
!String.IsNullOrEmpty(errorRecord.ErrorDetails.Message))
{
return errorRecord.ErrorDetails.Message;
}
if (null == errorRecord.Exception)
return "";
return errorRecord.Exception.Message;
}
internal static string RetrieveMessage(Exception e)
{
if (null == e)
return "";
IContainsErrorRecord icer = e as IContainsErrorRecord;
if (null == icer)
return e.Message;
ErrorRecord er = icer.ErrorRecord;
if (null == er)
return e.Message;
ErrorDetails ed = er.ErrorDetails;
if (null == ed)
return e.Message;
string detailsMessage = ed.Message;
return (String.IsNullOrEmpty(detailsMessage)) ? e.Message : detailsMessage;
}
internal static Exception RetrieveException(ErrorRecord errorRecord)
{
if (null == errorRecord)
return null;
return errorRecord.Exception;
}
/// <summary>
///
/// </summary>
public bool WasThrownFromThrowStatement
{
get { return _thrownByThrowStatement; }
set
{
_thrownByThrowStatement = value;
if (_errorRecord != null)
{
RuntimeException exception = _errorRecord.Exception as RuntimeException;
if (exception != null)
{
exception.WasThrownFromThrowStatement = value;
}
}
}
}
private bool _thrownByThrowStatement;
/// <summary>
/// fix for BUG: Windows Out Of Band Releases: 906263 and 906264
/// The interpreter prompt CommandBaseStrings:InquireHalt
/// should be suppressed when this flag is set. This will be set
/// when this prompt has already occurred and Break was chosen,
/// or for ActionPreferenceStopException in all cases.
/// </summary>
internal bool SuppressPromptInInterpreter
{
get { return _suppressPromptInInterpreter; }
set { _suppressPromptInInterpreter = value; }
}
private bool _suppressPromptInInterpreter;
#endregion Internal
private Token _errorToken;
internal Token ErrorToken
{
get
{
return _errorToken;
}
set
{
_errorToken = value;
}
}
} // RuntimeException
} // System.Management.Automation
| |
using System;
using System.Collections.Generic;
using System.Linq;
namespace Avalonia.Styling
{
/// <summary>
/// Extension methods for <see cref="Selector"/>.
/// </summary>
public static class Selectors
{
/// <summary>
/// Returns a selector which matches a previous selector's child.
/// </summary>
/// <param name="previous">The previous selector.</param>
/// <returns>The selector.</returns>
public static Selector Child(this Selector previous)
{
return new ChildSelector(previous);
}
/// <summary>
/// Returns a selector which matches a control's style class.
/// </summary>
/// <param name="previous">The previous selector.</param>
/// <param name="name">The name of the style class.</param>
/// <returns>The selector.</returns>
public static Selector Class(this Selector? previous, string name)
{
_ = name ?? throw new ArgumentNullException(nameof(name));
if (string.IsNullOrWhiteSpace(name))
{
throw new ArgumentException("Name may not be empty", nameof(name));
}
var tac = previous as TypeNameAndClassSelector;
if (tac != null)
{
tac.Classes.Add(name);
return tac;
}
else
{
return TypeNameAndClassSelector.ForClass(previous, name);
}
}
/// <summary>
/// Returns a selector which matches a descendant of a previous selector.
/// </summary>
/// <param name="previous">The previous selector.</param>
/// <returns>The selector.</returns>
public static Selector Descendant(this Selector? previous)
{
return new DescendantSelector(previous);
}
/// <summary>
/// Returns a selector which matches a type or a derived type.
/// </summary>
/// <param name="previous">The previous selector.</param>
/// <param name="type">The type.</param>
/// <returns>The selector.</returns>
public static Selector Is(this Selector? previous, Type type)
{
_ = type ?? throw new ArgumentNullException(nameof(type));
return TypeNameAndClassSelector.Is(previous, type);
}
/// <summary>
/// Returns a selector which matches a type or a derived type.
/// </summary>
/// <typeparam name="T">The type.</typeparam>
/// <param name="previous">The previous selector.</param>
/// <returns>The selector.</returns>
public static Selector Is<T>(this Selector? previous) where T : IStyleable
{
return previous.Is(typeof(T));
}
/// <summary>
/// Returns a selector which matches a control's Name.
/// </summary>
/// <param name="previous">The previous selector.</param>
/// <param name="name">The name.</param>
/// <returns>The selector.</returns>
public static Selector Name(this Selector? previous, string name)
{
_ = name ?? throw new ArgumentNullException(nameof(name));
if (string.IsNullOrWhiteSpace(name))
{
throw new ArgumentException("Name may not be empty", nameof(name));
}
var tac = previous as TypeNameAndClassSelector;
if (tac != null)
{
tac.Name = name;
return tac;
}
else
{
return TypeNameAndClassSelector.ForName(previous, name);
}
}
/// <summary>
/// Returns a selector which inverts the results of selector argument.
/// </summary>
/// <param name="previous">The previous selector.</param>
/// <param name="argument">The selector to be not-ed.</param>
/// <returns>The selector.</returns>
public static Selector Not(this Selector? previous, Func<Selector?, Selector> argument)
{
return new NotSelector(previous, argument(null));
}
/// <summary>
/// Returns a selector which inverts the results of selector argument.
/// </summary>
/// <param name="previous">The previous selector.</param>
/// <param name="argument">The selector to be not-ed.</param>
/// <returns>The selector.</returns>
public static Selector Not(this Selector? previous, Selector argument)
{
return new NotSelector(previous, argument);
}
/// <inheritdoc cref="NthChildSelector"/>
/// <inheritdoc cref="NthChildSelector(Selector?, int, int)"/>
/// <returns>The selector.</returns>
public static Selector NthChild(this Selector? previous, int step, int offset)
{
return new NthChildSelector(previous, step, offset);
}
/// <inheritdoc cref="NthLastChildSelector"/>
/// <inheritdoc cref="NthLastChildSelector(Selector?, int, int)"/>
/// <returns>The selector.</returns>
public static Selector NthLastChild(this Selector? previous, int step, int offset)
{
return new NthLastChildSelector(previous, step, offset);
}
/// <summary>
/// Returns a selector which matches a type.
/// </summary>
/// <param name="previous">The previous selector.</param>
/// <param name="type">The type.</param>
/// <returns>The selector.</returns>
public static Selector OfType(this Selector? previous, Type type)
{
_ = type ?? throw new ArgumentNullException(nameof(type));
return TypeNameAndClassSelector.OfType(previous, type);
}
/// <summary>
/// Returns a selector which matches a type.
/// </summary>
/// <typeparam name="T">The type.</typeparam>
/// <param name="previous">The previous selector.</param>
/// <returns>The selector.</returns>
public static Selector OfType<T>(this Selector? previous) where T : IStyleable
{
return previous.OfType(typeof(T));
}
/// <summary>
/// Returns a selector which ORs selectors.
/// </summary>
/// <param name="selectors">The selectors to be OR'd.</param>
/// <returns>The selector.</returns>
public static Selector Or(params Selector[] selectors)
{
return new OrSelector(selectors);
}
/// <summary>
/// Returns a selector which ORs selectors.
/// </summary>
/// <param name="selectors">The selectors to be OR'd.</param>
/// <returns>The selector.</returns>
public static Selector Or(IReadOnlyList<Selector> selectors)
{
return new OrSelector(selectors);
}
/// <summary>
/// Returns a selector which matches a control with the specified property value.
/// </summary>
/// <typeparam name="T">The property type.</typeparam>
/// <param name="previous">The previous selector.</param>
/// <param name="property">The property.</param>
/// <param name="value">The property value.</param>
/// <returns>The selector.</returns>
public static Selector PropertyEquals<T>(this Selector? previous, AvaloniaProperty<T> property, object? value)
{
_ = property ?? throw new ArgumentNullException(nameof(property));
return new PropertyEqualsSelector(previous, property, value);
}
/// <summary>
/// Returns a selector which matches a control with the specified property value.
/// </summary>
/// <param name="previous">The previous selector.</param>
/// <param name="property">The property.</param>
/// <param name="value">The property value.</param>
/// <returns>The selector.</returns>
public static Selector PropertyEquals(this Selector? previous, AvaloniaProperty property, object? value)
{
_ = property ?? throw new ArgumentNullException(nameof(property));
return new PropertyEqualsSelector(previous, property, value);
}
/// <summary>
/// Returns a selector which enters a lookless control's template.
/// </summary>
/// <param name="previous">The previous selector.</param>
/// <returns>The selector.</returns>
public static Selector Template(this Selector previous)
{
return new TemplateSelector(previous);
}
}
}
| |
/* ====================================================================
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.HSSF.Record
{
using System;
using System.Text;
using System.Collections;
using NPOI.Util;
public enum BOFRecordType {
Workbook = 0x05,
VBModule = 0x06,
Worksheet = 0x10,
Chart = 0x20,
Excel4Macro = 0x40,
WorkspaceFile = 0x100
}
/**
* Title: Beginning Of File
* Description: Somewhat of a misnomer, its used for the beginning of a Set of
* records that have a particular pupose or subject.
* Used in sheets and workbooks.
* REFERENCE: PG 289 Microsoft Excel 97 Developer's Kit (ISBN: 1-57231-498-2)
* @author Andrew C. Oliver
* @author Jason Height (jheight at chariot dot net dot au)
* @version 2.0-pre
*/
public class BOFRecord : StandardRecord, ICloneable
{
/**
* for BIFF8 files the BOF is 0x809. For earlier versions see
* {@link #biff2_sid} {@link #biff3_sid} {@link #biff4_sid}
* {@link #biff5_sid}
*/
public const short sid = 0x809;
// SIDs from earlier BIFF versions
public const short biff2_sid = 0x009;
public const short biff3_sid = 0x209;
public const short biff4_sid = 0x409;
public const short biff5_sid = 0x809;
private int field_1_version;
private int field_2_type;
private int field_3_build;
private int field_4_year;
private int field_5_history;
private int field_6_rversion;
/**
* suggested default (0x06 - BIFF8)
*/
public const short VERSION = 0x06;
/**
* suggested default 0x10d3
*/
public const short BUILD = 0x10d3;
/**
* suggested default 0x07CC (1996)
*/
public const short BUILD_YEAR = 0x07CC; // 1996
/**
* suggested default for a normal sheet (0x41)
*/
public const short HISTORY_MASK = 0x41;
/**
* Constructs an empty BOFRecord with no fields Set.
*/
public BOFRecord()
{
}
private BOFRecord(BOFRecordType type)
{
field_1_version = VERSION;
field_2_type = (int) type;
field_3_build = BUILD;
field_4_year = BUILD_YEAR;
field_5_history = 0x01;
field_6_rversion = VERSION;
}
public static BOFRecord CreateSheetBOF()
{
return new BOFRecord(BOFRecordType.Worksheet);
}
/**
* Constructs a BOFRecord and Sets its fields appropriately
* @param in the RecordInputstream to Read the record from
*/
public BOFRecord(RecordInputStream in1)
{
field_1_version = in1.ReadShort();
field_2_type = in1.ReadShort();
// Some external tools don't generate all of
// the remaining fields
if (in1.Remaining >= 2)
{
field_3_build = in1.ReadShort();
}
if (in1.Remaining >= 2)
{
field_4_year = in1.ReadShort();
}
if (in1.Remaining >= 4)
{
field_5_history = in1.ReadInt();
}
if (in1.Remaining >= 4)
{
field_6_rversion = in1.ReadInt();
}
}
/**
* Version number - for BIFF8 should be 0x06
* @see #VERSION
* @param version version to be Set
*/
public int Version
{
set { field_1_version = value; }
get { return field_1_version; }
}
/**
* Set the history bit mask (not very useful)
* @see #HISTORY_MASK
* @param bitmask bitmask to Set for the history
*/
public int HistoryBitMask
{
set { field_5_history = value; }
get { return field_5_history; }
}
/**
* Set the minimum version required to Read this file
*
* @see #VERSION
* @param version version to Set
*/
public int RequiredVersion
{
set { field_6_rversion = value; }
get { return field_6_rversion; }
}
/**
* type of object this marks
* @see #TYPE_WORKBOOK
* @see #TYPE_VB_MODULE
* @see #TYPE_WORKSHEET
* @see #TYPE_CHART
* @see #TYPE_EXCEL_4_MACRO
* @see #TYPE_WORKSPACE_FILE
* @return short type of object
*/
public BOFRecordType Type
{
get { return (BOFRecordType) field_2_type; }
set { field_2_type = (int) value; }
}
private String TypeName
{
get
{
switch (Type)
{
case BOFRecordType.Chart: return "chart";
case BOFRecordType.Excel4Macro: return "excel 4 macro";
case BOFRecordType.VBModule: return "vb module";
case BOFRecordType.Workbook: return "workbook";
case BOFRecordType.Worksheet: return "worksheet";
case BOFRecordType.WorkspaceFile: return "workspace file";
}
return "#error unknown type#";
}
}
/**
* Get the build that wrote this file
* @see #BUILD
* @return short build number of the generator of this file
*/
public int Build
{
get { return field_3_build; }
set { field_3_build = value; }
}
/**
* Year of the build that wrote this file
* @see #BUILD_YEAR
* @return short build year of the generator of this file
*/
public int BuildYear
{
get { return field_4_year; }
set { field_4_year = value; }
}
public override String ToString()
{
StringBuilder buffer = new StringBuilder();
buffer.Append("[BOF RECORD]\n");
buffer.Append(" .version = ")
.Append(StringUtil.ToHexString(Version)).Append("\n");
buffer.Append(" .type = ")
.Append(StringUtil.ToHexString((int) Type)).Append("\n");
buffer.Append(" (").Append(TypeName).Append(")").Append("\n");
buffer.Append(" .build = ")
.Append(StringUtil.ToHexString(Build)).Append("\n");
buffer.Append(" .buildyear = ").Append(BuildYear)
.Append("\n");
buffer.Append(" .history = ")
.Append(StringUtil.ToHexString(HistoryBitMask)).Append("\n");
buffer.Append(" .requiredversion = ")
.Append(StringUtil.ToHexString(RequiredVersion)).Append("\n");
buffer.Append("[/BOF RECORD]\n");
return buffer.ToString();
}
public override void Serialize(ILittleEndianOutput out1)
{
out1.WriteShort(Version);
out1.WriteShort((int) Type);
out1.WriteShort(Build);
out1.WriteShort(BuildYear);
out1.WriteInt(HistoryBitMask);
out1.WriteInt(RequiredVersion);
}
protected override int DataSize
{
get { return 16; }
}
public override short Sid
{
get { return sid; }
}
public override object Clone()
{
BOFRecord rec = new BOFRecord();
rec.field_1_version = field_1_version;
rec.field_2_type = field_2_type;
rec.field_3_build = field_3_build;
rec.field_4_year = field_4_year;
rec.field_5_history = field_5_history;
rec.field_6_rversion = field_6_rversion;
return rec;
}
}
}
| |
using ExitGames.Client.Photon;
using System;
using System.Collections;
using Mod;
using Mod.Exceptions;
using Photon;
using Photon.Enums;
using UnityEngine;
using Debug = UnityEngine.Debug;
using LogType = Mod.Logging.LogType;
using MonoBehaviour = Photon.MonoBehaviour;
// ReSharper disable once CheckNamespace
public class PhotonHandler : MonoBehaviour, IPhotonPeerListener
{
private static PhotonHandler _instance;
public static bool AppQuits;
public int nextSendTickCount;
public int nextSendTickCountOnSerialize;
public static Type PingImplementation;
private static bool sendThreadShouldRun;
public int updateInterval;
public int updateIntervalOnSerialize;
protected void Awake()
{
if (_instance != null && _instance != this)
DestroyImmediate(_instance.gameObject);
_instance = this;
DontDestroyOnLoad(gameObject);
this.updateInterval = 1000 / PhotonNetwork.sendRate;
this.updateIntervalOnSerialize = 1000 / PhotonNetwork.sendRateOnSerialize;
StartFallbackSendAckThread();
}
public void DebugReturn(DebugLevel level, string message)
{
switch (level)
{
case DebugLevel.ERROR:
Shelter.Log(message, LogType.Error);
break;
case DebugLevel.WARNING:
Shelter.Log(message, LogType.Warning);
break;
case DebugLevel.INFO when PhotonNetwork.LogLevel >= PhotonLogLevel.Informational:
case DebugLevel.ALL when PhotonNetwork.LogLevel == PhotonLogLevel.Full:
Shelter.Log(message);
break;
}
}
private static bool FallbackSendAckThread()
{
if (sendThreadShouldRun && PhotonNetwork.networkingPeer != null)
{
PhotonNetwork.networkingPeer.SendAcksOnly();
}
return sendThreadShouldRun;
}
protected void OnApplicationQuit()
{
AppQuits = true;
StopFallbackSendAckThread();
PhotonNetwork.Disconnect();
}
protected void OnCreatedRoom()
{
PhotonNetwork.networkingPeer.SetLevelInPropsIfSynced(Application.loadedLevelName);
}
public void OnEvent(EventData photonEvent)
{
}
protected void OnJoinedRoom()
{
PhotonNetwork.networkingPeer.LoadLevelIfSynced();
}
protected void OnLevelWasLoaded(int level)
{
PhotonNetwork.networkingPeer.NewSceneLoaded();
PhotonNetwork.networkingPeer.SetLevelInPropsIfSynced(Application.loadedLevelName);
}
public void OnOperationResponse(OperationResponse operationResponse)
{
}
public void OnStatusChanged(StatusCode statusCode)
{
}
protected internal static void PingAvailableRegionsAndConnectToBest()
{
_instance.StartCoroutine(PingAvailableRegionsCoroutine(true));
}
public static void StartFallbackSendAckThread()
{
if (!sendThreadShouldRun)
{
sendThreadShouldRun = true;
SupportClass.CallInBackground(FallbackSendAckThread);
}
}
private static void StopFallbackSendAckThread()
{
sendThreadShouldRun = false;
}
protected void Update()
{
if (PhotonNetwork.networkingPeer == null)
{
Shelter.LogBoth("NetworkingPeer broke while PhotonHandler is still active.", LogType.Error);
return;
}
if (PhotonNetwork.connectionStatesDetailed != ClientState.PeerCreated && PhotonNetwork.connectionStatesDetailed != ClientState.Disconnected && !PhotonNetwork.offlineMode && PhotonNetwork.isMessageQueueRunning)
{
bool flag = true;
while (PhotonNetwork.isMessageQueueRunning && flag)
{
try
{
flag = PhotonNetwork.networkingPeer.DispatchIncomingCommands();
}
catch (CustomException)
{
// do nothing
}
catch (Exception e)
{
Shelter.LogConsole("A {0} has been thrown in Photon3Unity3D.dll", LogType.Error, e.GetType().Name);
Shelter.Log("{0}: {1}\n{2}", LogType.Error, e.GetType().FullName, e.Message, e.StackTrace);
flag = false;
}
}
int num = (int)(Time.realtimeSinceStartup * 1000f);
if (PhotonNetwork.isMessageQueueRunning && num > this.nextSendTickCountOnSerialize)
{
PhotonNetwork.networkingPeer.RunViewUpdate();
this.nextSendTickCountOnSerialize = num + this.updateIntervalOnSerialize;
this.nextSendTickCount = 0;
}
num = (int)(Time.realtimeSinceStartup * 1000f);
if (num > this.nextSendTickCount)
{
while (PhotonNetwork.isMessageQueueRunning && PhotonNetwork.networkingPeer.SendOutgoingCommands()) // SendOutgoingCommands was being called once more if isMessageQueueRunning turns false
{
}
this.nextSendTickCount = num + this.updateInterval;
}
}
}
internal static CloudRegionCode BestRegionCodeInPreferences
{
get
{
string str = PlayerPrefs.GetString("PUNCloudBestRegion", string.Empty);
if (!string.IsNullOrEmpty(str))
{
return Region.Parse(str);
}
return CloudRegionCode.None;
}
set
{
if (value == CloudRegionCode.None)
{
PlayerPrefs.DeleteKey("PUNCloudBestRegion");
}
else
{
PlayerPrefs.SetString("PUNCloudBestRegion", value.ToString());
}
}
}
private static IEnumerator PingAvailableRegionsCoroutine(bool connectToBest)
{
while (PhotonNetwork.networkingPeer.AvailableRegions == null)
{
if (PhotonNetwork.connectionStatesDetailed != ClientState.ConnectingToNameServer && PhotonNetwork.connectionStatesDetailed != ClientState.ConnectedToNameServer)
{
Debug.LogError("Call ConnectToNameServer to ping available regions.");
yield break; // break if we don't connect to the nameserver at all
}
Shelter.Log("Waiting for AvailableRegions. State: {0} Server: {1} PhotonNetwork.networkingPeer.AvailableRegions {2}",
LogType.Info, PhotonNetwork.connectionStatesDetailed, PhotonNetwork.Server, PhotonNetwork.networkingPeer.AvailableRegions != null);
yield return new WaitForSeconds(0.25f); // wait until pinging finished (offline mode won't ping)
}
if (PhotonNetwork.networkingPeer.AvailableRegions == null || PhotonNetwork.networkingPeer.AvailableRegions.Count == 0)
{
Debug.LogError("No regions available. Are you sure your appid is valid and setup?");
yield break; // break if we don't get regions at all
}
PhotonPingManager pingManager = new PhotonPingManager();
foreach (Region region in PhotonNetwork.networkingPeer.AvailableRegions)
{
_instance.StartCoroutine(pingManager.PingSocket(region));
}
while (!pingManager.Done)
{
yield return new WaitForSeconds(0.1f); // wait until pinging finished (offline mode won't ping)
}
Region best = PhotonPingManager.BestRegion;
BestRegionCodeInPreferences = best.Code;
Debug.Log("Found best region: " + best.Code + " ping: " + best.Ping + ". Calling ConnectToRegionMaster() is: " + connectToBest);
if (connectToBest)
{
PhotonNetwork.networkingPeer.ConnectToRegionMaster(best.Code);
}
}
}
| |
#region Copyright notice and license
// Copyright 2015 gRPC 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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Grpc.Core;
using Grpc.Core.Internal;
using Grpc.Core.Profiling;
using Grpc.Core.Utils;
using NUnit.Framework;
namespace Grpc.Core.Tests
{
public class ClientServerTest
{
const string Host = "127.0.0.1";
MockServiceHelper helper;
Server server;
Channel channel;
[SetUp]
public void Init()
{
helper = new MockServiceHelper(Host);
server = helper.GetServer();
server.Start();
channel = helper.GetChannel();
}
[TearDown]
public void Cleanup()
{
channel.ShutdownAsync().Wait();
server.ShutdownAsync().Wait();
}
[Test]
public async Task UnaryCall()
{
helper.UnaryHandler = new UnaryServerMethod<string, string>((request, context) =>
{
return Task.FromResult(request);
});
Assert.AreEqual("ABC", Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "ABC"));
Assert.AreEqual("ABC", await Calls.AsyncUnaryCall(helper.CreateUnaryCall(), "ABC"));
}
[Test]
public void UnaryCall_ServerHandlerThrows()
{
helper.UnaryHandler = new UnaryServerMethod<string, string>((request, context) =>
{
throw new Exception("This was thrown on purpose by a test");
});
var ex = Assert.Throws<RpcException>(() => Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "abc"));
Assert.AreEqual(StatusCode.Unknown, ex.Status.StatusCode);
var ex2 = Assert.ThrowsAsync<RpcException>(async () => await Calls.AsyncUnaryCall(helper.CreateUnaryCall(), "abc"));
Assert.AreEqual(StatusCode.Unknown, ex2.Status.StatusCode);
}
[Test]
public void UnaryCall_ServerHandlerThrowsRpcException()
{
helper.UnaryHandler = new UnaryServerMethod<string, string>((request, context) =>
{
throw new RpcException(new Status(StatusCode.Unauthenticated, ""));
});
var ex = Assert.Throws<RpcException>(() => Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "abc"));
Assert.AreEqual(StatusCode.Unauthenticated, ex.Status.StatusCode);
Assert.AreEqual(0, ex.Trailers.Count);
var ex2 = Assert.ThrowsAsync<RpcException>(async () => await Calls.AsyncUnaryCall(helper.CreateUnaryCall(), "abc"));
Assert.AreEqual(StatusCode.Unauthenticated, ex2.Status.StatusCode);
Assert.AreEqual(0, ex.Trailers.Count);
}
[Test]
public void UnaryCall_ServerHandlerThrowsRpcExceptionWithTrailers()
{
helper.UnaryHandler = new UnaryServerMethod<string, string>((request, context) =>
{
var trailers = new Metadata { {"xyz", "xyz-value"} };
throw new RpcException(new Status(StatusCode.Unauthenticated, ""), trailers);
});
var ex = Assert.Throws<RpcException>(() => Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "abc"));
Assert.AreEqual(StatusCode.Unauthenticated, ex.Status.StatusCode);
Assert.AreEqual(1, ex.Trailers.Count);
Assert.AreEqual("xyz", ex.Trailers[0].Key);
Assert.AreEqual("xyz-value", ex.Trailers[0].Value);
var ex2 = Assert.ThrowsAsync<RpcException>(async () => await Calls.AsyncUnaryCall(helper.CreateUnaryCall(), "abc"));
Assert.AreEqual(StatusCode.Unauthenticated, ex2.Status.StatusCode);
Assert.AreEqual(1, ex2.Trailers.Count);
Assert.AreEqual("xyz", ex2.Trailers[0].Key);
Assert.AreEqual("xyz-value", ex2.Trailers[0].Value);
}
[Test]
public void UnaryCall_ServerHandlerSetsStatus()
{
helper.UnaryHandler = new UnaryServerMethod<string, string>((request, context) =>
{
context.Status = new Status(StatusCode.Unauthenticated, "");
return Task.FromResult("");
});
var ex = Assert.Throws<RpcException>(() => Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "abc"));
Assert.AreEqual(StatusCode.Unauthenticated, ex.Status.StatusCode);
Assert.AreEqual(0, ex.Trailers.Count);
var ex2 = Assert.ThrowsAsync<RpcException>(async () => await Calls.AsyncUnaryCall(helper.CreateUnaryCall(), "abc"));
Assert.AreEqual(StatusCode.Unauthenticated, ex2.Status.StatusCode);
Assert.AreEqual(0, ex2.Trailers.Count);
}
[Test]
public void UnaryCall_ServerHandlerSetsStatusAndTrailers()
{
helper.UnaryHandler = new UnaryServerMethod<string, string>((request, context) =>
{
context.Status = new Status(StatusCode.Unauthenticated, "");
context.ResponseTrailers.Add("xyz", "xyz-value");
return Task.FromResult("");
});
var ex = Assert.Throws<RpcException>(() => Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "abc"));
Assert.AreEqual(StatusCode.Unauthenticated, ex.Status.StatusCode);
Assert.AreEqual(1, ex.Trailers.Count);
Assert.AreEqual("xyz", ex.Trailers[0].Key);
Assert.AreEqual("xyz-value", ex.Trailers[0].Value);
var ex2 = Assert.ThrowsAsync<RpcException>(async () => await Calls.AsyncUnaryCall(helper.CreateUnaryCall(), "abc"));
Assert.AreEqual(StatusCode.Unauthenticated, ex2.Status.StatusCode);
Assert.AreEqual(1, ex2.Trailers.Count);
Assert.AreEqual("xyz", ex2.Trailers[0].Key);
Assert.AreEqual("xyz-value", ex2.Trailers[0].Value);
}
[Test]
public async Task ClientStreamingCall()
{
helper.ClientStreamingHandler = new ClientStreamingServerMethod<string, string>(async (requestStream, context) =>
{
string result = "";
await requestStream.ForEachAsync((request) =>
{
result += request;
return TaskUtils.CompletedTask;
});
await Task.Delay(100);
return result;
});
var call = Calls.AsyncClientStreamingCall(helper.CreateClientStreamingCall());
await call.RequestStream.WriteAllAsync(new string[] { "A", "B", "C" });
Assert.AreEqual("ABC", await call.ResponseAsync);
Assert.AreEqual(StatusCode.OK, call.GetStatus().StatusCode);
Assert.IsNotNull(call.GetTrailers());
}
[Test]
public async Task ServerStreamingCall()
{
helper.ServerStreamingHandler = new ServerStreamingServerMethod<string, string>(async (request, responseStream, context) =>
{
await responseStream.WriteAllAsync(request.Split(new []{' '}));
context.ResponseTrailers.Add("xyz", "");
});
var call = Calls.AsyncServerStreamingCall(helper.CreateServerStreamingCall(), "A B C");
CollectionAssert.AreEqual(new string[] { "A", "B", "C" }, await call.ResponseStream.ToListAsync());
Assert.AreEqual(StatusCode.OK, call.GetStatus().StatusCode);
Assert.AreEqual("xyz", call.GetTrailers()[0].Key);
}
[Test]
public async Task ServerStreamingCall_EndOfStreamIsIdempotent()
{
helper.ServerStreamingHandler = new ServerStreamingServerMethod<string, string>((request, responseStream, context) => TaskUtils.CompletedTask);
var call = Calls.AsyncServerStreamingCall(helper.CreateServerStreamingCall(), "");
Assert.IsFalse(await call.ResponseStream.MoveNext());
Assert.IsFalse(await call.ResponseStream.MoveNext());
}
[Test]
public void ServerStreamingCall_ErrorCanBeAwaitedTwice()
{
helper.ServerStreamingHandler = new ServerStreamingServerMethod<string, string>((request, responseStream, context) =>
{
context.Status = new Status(StatusCode.InvalidArgument, "");
return TaskUtils.CompletedTask;
});
var call = Calls.AsyncServerStreamingCall(helper.CreateServerStreamingCall(), "");
var ex = Assert.ThrowsAsync<RpcException>(async () => await call.ResponseStream.MoveNext());
Assert.AreEqual(StatusCode.InvalidArgument, ex.Status.StatusCode);
// attempting MoveNext again should result in throwing the same exception.
var ex2 = Assert.ThrowsAsync<RpcException>(async () => await call.ResponseStream.MoveNext());
Assert.AreEqual(StatusCode.InvalidArgument, ex2.Status.StatusCode);
}
[Test]
public void ServerStreamingCall_TrailersFromMultipleSourcesGetConcatenated()
{
helper.ServerStreamingHandler = new ServerStreamingServerMethod<string, string>((request, responseStream, context) =>
{
context.ResponseTrailers.Add("xyz", "xyz-value");
throw new RpcException(new Status(StatusCode.InvalidArgument, ""), new Metadata { {"abc", "abc-value"} });
});
var call = Calls.AsyncServerStreamingCall(helper.CreateServerStreamingCall(), "");
var ex = Assert.ThrowsAsync<RpcException>(async () => await call.ResponseStream.MoveNext());
Assert.AreEqual(StatusCode.InvalidArgument, ex.Status.StatusCode);
Assert.AreEqual(2, call.GetTrailers().Count);
Assert.AreEqual(2, ex.Trailers.Count);
Assert.AreEqual("xyz", ex.Trailers[0].Key);
Assert.AreEqual("xyz-value", ex.Trailers[0].Value);
Assert.AreEqual("abc", ex.Trailers[1].Key);
Assert.AreEqual("abc-value", ex.Trailers[1].Value);
}
[Test]
public async Task DuplexStreamingCall()
{
helper.DuplexStreamingHandler = new DuplexStreamingServerMethod<string, string>(async (requestStream, responseStream, context) =>
{
while (await requestStream.MoveNext())
{
await responseStream.WriteAsync(requestStream.Current);
}
context.ResponseTrailers.Add("xyz", "xyz-value");
});
var call = Calls.AsyncDuplexStreamingCall(helper.CreateDuplexStreamingCall());
await call.RequestStream.WriteAllAsync(new string[] { "A", "B", "C" });
CollectionAssert.AreEqual(new string[] { "A", "B", "C" }, await call.ResponseStream.ToListAsync());
Assert.AreEqual(StatusCode.OK, call.GetStatus().StatusCode);
Assert.AreEqual("xyz-value", call.GetTrailers()[0].Value);
}
[Test]
public async Task ClientStreamingCall_CancelAfterBegin()
{
var barrier = new TaskCompletionSource<object>();
helper.ClientStreamingHandler = new ClientStreamingServerMethod<string, string>(async (requestStream, context) =>
{
barrier.SetResult(null);
await requestStream.ToListAsync();
return "";
});
var cts = new CancellationTokenSource();
var call = Calls.AsyncClientStreamingCall(helper.CreateClientStreamingCall(new CallOptions(cancellationToken: cts.Token)));
await barrier.Task; // make sure the handler has started.
cts.Cancel();
try
{
// cannot use Assert.ThrowsAsync because it uses Task.Wait and would deadlock.
await call.ResponseAsync;
Assert.Fail();
}
catch (RpcException ex)
{
Assert.AreEqual(StatusCode.Cancelled, ex.Status.StatusCode);
}
}
[Test]
public async Task ClientStreamingCall_ServerSideReadAfterCancelNotificationReturnsNull()
{
var handlerStartedBarrier = new TaskCompletionSource<object>();
var cancelNotificationReceivedBarrier = new TaskCompletionSource<object>();
var successTcs = new TaskCompletionSource<string>();
helper.ClientStreamingHandler = new ClientStreamingServerMethod<string, string>(async (requestStream, context) =>
{
handlerStartedBarrier.SetResult(null);
// wait for cancellation to be delivered.
context.CancellationToken.Register(() => cancelNotificationReceivedBarrier.SetResult(null));
await cancelNotificationReceivedBarrier.Task;
var moveNextResult = await requestStream.MoveNext();
successTcs.SetResult(!moveNextResult ? "SUCCESS" : "FAIL");
return "";
});
var cts = new CancellationTokenSource();
var call = Calls.AsyncClientStreamingCall(helper.CreateClientStreamingCall(new CallOptions(cancellationToken: cts.Token)));
await handlerStartedBarrier.Task;
cts.Cancel();
try
{
await call.ResponseAsync;
Assert.Fail();
}
catch (RpcException ex)
{
Assert.AreEqual(StatusCode.Cancelled, ex.Status.StatusCode);
}
Assert.AreEqual("SUCCESS", await successTcs.Task);
}
[Test]
public async Task AsyncUnaryCall_EchoMetadata()
{
helper.UnaryHandler = new UnaryServerMethod<string, string>((request, context) =>
{
foreach (Metadata.Entry metadataEntry in context.RequestHeaders)
{
if (metadataEntry.Key != "user-agent")
{
context.ResponseTrailers.Add(metadataEntry);
}
}
return Task.FromResult("");
});
var headers = new Metadata
{
{ "ascii-header", "abcdefg" },
{ "binary-header-bin", new byte[] { 1, 2, 3, 0, 0xff } }
};
var call = Calls.AsyncUnaryCall(helper.CreateUnaryCall(new CallOptions(headers: headers)), "ABC");
await call;
Assert.AreEqual(StatusCode.OK, call.GetStatus().StatusCode);
var trailers = call.GetTrailers();
Assert.AreEqual(2, trailers.Count);
Assert.AreEqual(headers[0].Key, trailers[0].Key);
Assert.AreEqual(headers[0].Value, trailers[0].Value);
Assert.AreEqual(headers[1].Key, trailers[1].Key);
CollectionAssert.AreEqual(headers[1].ValueBytes, trailers[1].ValueBytes);
}
[Test]
public void UnknownMethodHandler()
{
var nonexistentMethod = new Method<string, string>(
MethodType.Unary,
MockServiceHelper.ServiceName,
"NonExistentMethod",
Marshallers.StringMarshaller,
Marshallers.StringMarshaller);
var callDetails = new CallInvocationDetails<string, string>(channel, nonexistentMethod, new CallOptions());
var ex = Assert.Throws<RpcException>(() => Calls.BlockingUnaryCall(callDetails, "abc"));
Assert.AreEqual(StatusCode.Unimplemented, ex.Status.StatusCode);
}
[Test]
public void StatusDetailIsUtf8()
{
// some japanese and chinese characters
var nonAsciiString = "\u30a1\u30a2\u30a3 \u62b5\u6297\u662f\u5f92\u52b3\u7684";
helper.UnaryHandler = new UnaryServerMethod<string, string>((request, context) =>
{
context.Status = new Status(StatusCode.Unknown, nonAsciiString);
return Task.FromResult("");
});
var ex = Assert.Throws<RpcException>(() => Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "abc"));
Assert.AreEqual(StatusCode.Unknown, ex.Status.StatusCode);
Assert.AreEqual(nonAsciiString, ex.Status.Detail);
}
[Test]
public void ServerCallContext_PeerInfoPresent()
{
helper.UnaryHandler = new UnaryServerMethod<string, string>((request, context) =>
{
return Task.FromResult(context.Peer);
});
string peer = Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "abc");
Assert.IsTrue(peer.Contains(Host));
}
[Test]
public void ServerCallContext_HostAndMethodPresent()
{
helper.UnaryHandler = new UnaryServerMethod<string, string>((request, context) =>
{
Assert.IsTrue(context.Host.Contains(Host));
Assert.AreEqual("/tests.Test/Unary", context.Method);
return Task.FromResult("PASS");
});
Assert.AreEqual("PASS", Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "abc"));
}
[Test]
public void ServerCallContext_AuthContextNotPopulated()
{
helper.UnaryHandler = new UnaryServerMethod<string, string>((request, context) =>
{
Assert.IsFalse(context.AuthContext.IsPeerAuthenticated);
Assert.AreEqual(0, context.AuthContext.Properties.Count());
return Task.FromResult("PASS");
});
Assert.AreEqual("PASS", Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "abc"));
}
[Test]
public async Task Channel_WaitForStateChangedAsync()
{
helper.UnaryHandler = new UnaryServerMethod<string, string>((request, context) =>
{
return Task.FromResult(request);
});
Assert.ThrowsAsync(typeof(TaskCanceledException),
async () => await channel.WaitForStateChangedAsync(channel.State, DateTime.UtcNow.AddMilliseconds(10)));
var stateChangedTask = channel.WaitForStateChangedAsync(channel.State);
await Calls.AsyncUnaryCall(helper.CreateUnaryCall(), "abc");
await stateChangedTask;
Assert.AreEqual(ChannelState.Ready, channel.State);
}
[Test]
public async Task Channel_ConnectAsync()
{
await channel.ConnectAsync();
Assert.AreEqual(ChannelState.Ready, channel.State);
await channel.ConnectAsync(DateTime.UtcNow.AddMilliseconds(1000));
Assert.AreEqual(ChannelState.Ready, channel.State);
}
}
}
| |
// Copyright (c) Alexandre Mutel. All rights reserved.
// Licensed under the BSD-Clause 2 license.
// See license.txt file in the project root for full license information.
#nullable disable
using System;
using System.Diagnostics;
namespace Scriban.Syntax
{
/// <summary>
/// Slice of a string
/// </summary>
[DebuggerDisplay("{ToString()}")]
#if SCRIBAN_PUBLIC
public
#else
internal
#endif
readonly struct ScriptStringSlice : IEquatable<ScriptStringSlice>, IComparable<ScriptStringSlice>, IComparable<string>
{
public static readonly ScriptStringSlice Empty = new ScriptStringSlice(string.Empty);
public ScriptStringSlice(string fullText)
{
FullText = fullText;
Index = 0;
Length = fullText?.Length ?? 0;
}
public ScriptStringSlice(string fullText, int index, int length)
{
if (index < 0 || fullText != null && index >= fullText.Length) throw new ArgumentOutOfRangeException(nameof(index));
if (length < 0 || fullText != null && index + length > fullText.Length) throw new ArgumentOutOfRangeException(nameof(length));
FullText = fullText;
Index = index;
Length = length;
}
/// <summary>
/// The text of this slice.
/// </summary>
public readonly string FullText;
/// <summary>
/// Index into the text
/// </summary>
public readonly int Index;
/// <summary>
/// Length of the slice
/// </summary>
public readonly int Length;
public char this[int index]
{
get
{
if ((uint)index >= (uint)Length) throw new ArgumentOutOfRangeException(nameof(index));
return FullText[Index + index];
}
}
public string Substring(int index)
{
if (index == Length) return "";
if ((uint)index > (uint)Length) throw new ArgumentOutOfRangeException(nameof(index));
return FullText?.Substring(Index + index, Length - index);
}
public override string ToString()
{
return FullText?.Substring(Index, Length);
}
public bool Equals(ScriptStringSlice other)
{
if (Length != other.Length) return false;
if (FullText == null && other.FullText == null) return true;
if (FullText == null || other.FullText == null) return false;
return string.CompareOrdinal(FullText, Index, other.FullText, other.Index, Length) == 0;
}
public override bool Equals(object obj)
{
return obj is ScriptStringSlice other && Equals(other);
}
public override int GetHashCode()
{
unchecked
{
if (FullText == null) return 0;
// TODO: optimize with Span for >= netstandard 2.1
var hashCode = Length;
for (int i = Index; i < Length; i++)
{
hashCode = (hashCode * 397) ^ FullText[i];
}
return hashCode;
}
}
public static bool operator ==(ScriptStringSlice left, ScriptStringSlice right) => left.Equals(right);
public static bool operator !=(ScriptStringSlice left, ScriptStringSlice right) => !left.Equals(right);
public static bool operator ==(ScriptStringSlice left, string right) => left.CompareTo(right) == 0;
public static bool operator !=(ScriptStringSlice left, string right) => left.CompareTo(right) != 0;
public static bool operator ==(string left, ScriptStringSlice right) => right.CompareTo(left) == 0;
public static bool operator !=(string left, ScriptStringSlice right) => right.CompareTo(left) != 0;
public int CompareTo(ScriptStringSlice other)
{
if (FullText == null || other.FullText == null)
{
if (object.ReferenceEquals(FullText, other.FullText))
{
return 0;
}
return FullText == null ? -1 : 1;
}
if (Length == 0 && other.Length == 0) return 0;
var minLength = Math.Min(Length, other.Length);
var textComparison = string.CompareOrdinal(FullText, Index, other.FullText, other.Index, minLength);
return textComparison != 0 ? textComparison < 0 ? -1 : 1 : Length.CompareTo(other.Length);
}
public int CompareTo(string other)
{
if (FullText == null || other == null)
{
if (object.ReferenceEquals(FullText, other))
{
return 0;
}
return FullText == null ? -1 : 1;
}
if (Length == 0 && other.Length == 0) return 0;
var minLength = Math.Min(Length, other.Length);
var textComparison = string.CompareOrdinal(FullText, Index, other, 0, minLength);
return textComparison != 0 ? textComparison < 0 ? -1 : 1 : Length.CompareTo(other.Length);
}
public static explicit operator ScriptStringSlice(string text) => new ScriptStringSlice(text);
public static explicit operator string(ScriptStringSlice slice) => slice.ToString();
public ScriptStringSlice TrimStart()
{
var text = FullText;
for (int i = 0; i < Length; i++)
{
var c = text[Index + i];
if (!char.IsWhiteSpace(c))
{
return new ScriptStringSlice(text, Index + i, Length - i);
}
}
return Empty;
}
public ScriptStringSlice TrimEnd()
{
var text = FullText;
for (int i = Length - 1; i >= 0; i--)
{
var c = text[Index + i];
if (!char.IsWhiteSpace(c))
{
return new ScriptStringSlice(text, Index, i + 1);
}
}
return Empty;
}
public ScriptStringSlice TrimEndKeepNewLine()
{
var text = FullText;
for (int i = Length - 1; i >= 0; i--)
{
var c = text[Index + i];
if (!char.IsWhiteSpace(c) || c == '\n')
{
return new ScriptStringSlice(text, Index, i + 1);
}
}
return Empty;
}
}
#if SCRIBAN_PUBLIC
public
#else
internal
#endif
static class ScriptStringSliceExtensions
{
public static ScriptStringSlice Slice(this string text, int index)
{
return new ScriptStringSlice(text, index, text.Length - index);
}
public static ScriptStringSlice Slice(this string text, int index, int length)
{
return new ScriptStringSlice(text, index, length);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
namespace Microsoft.Azure.Management.DataLake.Analytics
{
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 Microsoft.Rest.Azure.OData;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// JobOperations operations.
/// </summary>
internal partial class JobOperations : IServiceOperations<DataLakeAnalyticsJobManagementClient>, IJobOperations
{
/// <summary>
/// Tests the existence of job information for the specified job ID.
/// </summary>
/// <param name='accountName'>
/// The Azure Data Lake Analytics account to execute job operations on.
/// </param>
/// <param name='jobIdentity'>
/// JobInfo ID to test the existence of.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<bool>> ExistsWithHttpMessagesAsync(string accountName, Guid jobIdentity, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (accountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "accountName");
}
if (this.Client.AdlaJobDnsSuffix == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.AdlaJobDnsSuffix");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("accountName", accountName);
tracingParameters.Add("jobIdentity", jobIdentity);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri;
var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "Jobs/{jobIdentity}";
_url = _url.Replace("{accountName}", accountName);
_url = _url.Replace("{adlaJobDnsSuffix}", this.Client.AdlaJobDnsSuffix);
_url = _url.Replace("{jobIdentity}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(jobIdentity, this.Client.SerializationSettings).Trim('"')));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
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 CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
if (_httpResponse.StatusCode == HttpStatusCode.NotFound && ex.Body.Code.Equals("JobNotFound", StringComparison.OrdinalIgnoreCase))
{
var _toReturn = new AzureOperationResponse<bool>();
_toReturn.Request = _httpRequest;
_toReturn.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_toReturn.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
_toReturn.Body = false;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _toReturn);
}
return _toReturn;
}
}
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<bool>();
_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)
{
_result.Body = true;
}
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.
/******************************************************************************
* 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 ShiftRightArithmeticInt161()
{
var test = new ImmUnaryOpTest__ShiftRightArithmeticInt161();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.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 (Sse2.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 (Sse2.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 ImmUnaryOpTest__ShiftRightArithmeticInt161
{
private struct TestStruct
{
public Vector128<Int16> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld), ref Unsafe.As<Int16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
return testStruct;
}
public void RunStructFldScenario(ImmUnaryOpTest__ShiftRightArithmeticInt161 testClass)
{
var result = Sse2.ShiftRightArithmetic(_fld, 1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16);
private static Int16[] _data = new Int16[Op1ElementCount];
private static Vector128<Int16> _clsVar;
private Vector128<Int16> _fld;
private SimpleUnaryOpTest__DataTable<Int16, Int16> _dataTable;
static ImmUnaryOpTest__ShiftRightArithmeticInt161()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar), ref Unsafe.As<Int16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
}
public ImmUnaryOpTest__ShiftRightArithmeticInt161()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld), ref Unsafe.As<Int16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt16(); }
_dataTable = new SimpleUnaryOpTest__DataTable<Int16, Int16>(_data, new Int16[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse2.ShiftRightArithmetic(
Unsafe.Read<Vector128<Int16>>(_dataTable.inArrayPtr),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse2.ShiftRightArithmetic(
Sse2.LoadVector128((Int16*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse2.ShiftRightArithmetic(
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightArithmetic), new Type[] { typeof(Vector128<Int16>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int16>>(_dataTable.inArrayPtr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightArithmetic), new Type[] { typeof(Vector128<Int16>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int16*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightArithmetic), new Type[] { typeof(Vector128<Int16>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.ShiftRightArithmetic(
_clsVar,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var firstOp = Unsafe.Read<Vector128<Int16>>(_dataTable.inArrayPtr);
var result = Sse2.ShiftRightArithmetic(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var firstOp = Sse2.LoadVector128((Int16*)(_dataTable.inArrayPtr));
var result = Sse2.ShiftRightArithmetic(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var firstOp = Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArrayPtr));
var result = Sse2.ShiftRightArithmetic(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmUnaryOpTest__ShiftRightArithmeticInt161();
var result = Sse2.ShiftRightArithmetic(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.ShiftRightArithmetic(_fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.ShiftRightArithmetic(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _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(Vector128<Int16> firstOp, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray = new Int16[Op1ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray = new Int16[Op1ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Int16[] firstOp, Int16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((short)(firstOp[0] >> 1) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((short)(firstOp[i] >> 1) != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.ShiftRightArithmetic)}<Int16>(Vector128<Int16><9>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
namespace System.Net.Http.Headers
{
public class MediaTypeHeaderValue : ICloneable
{
private const string charSet = "charset";
private ObjectCollection<NameValueHeaderValue> _parameters;
private string _mediaType;
public string CharSet
{
get
{
NameValueHeaderValue charSetParameter = NameValueHeaderValue.Find(_parameters, charSet);
if (charSetParameter != null)
{
return charSetParameter.Value;
}
return null;
}
set
{
// We don't prevent a user from setting whitespace-only charsets. Like we can't prevent a user from
// setting a non-existing charset.
NameValueHeaderValue charSetParameter = NameValueHeaderValue.Find(_parameters, charSet);
if (string.IsNullOrEmpty(value))
{
// Remove charset parameter
if (charSetParameter != null)
{
_parameters.Remove(charSetParameter);
}
}
else
{
if (charSetParameter != null)
{
charSetParameter.Value = value;
}
else
{
Parameters.Add(new NameValueHeaderValue(charSet, value));
}
}
}
}
public ICollection<NameValueHeaderValue> Parameters
{
get
{
if (_parameters == null)
{
_parameters = new ObjectCollection<NameValueHeaderValue>();
}
return _parameters;
}
}
public string MediaType
{
get { return _mediaType; }
set
{
CheckMediaTypeFormat(value, nameof(value));
_mediaType = value;
}
}
internal MediaTypeHeaderValue()
{
// Used by the parser to create a new instance of this type.
}
protected MediaTypeHeaderValue(MediaTypeHeaderValue source)
{
Debug.Assert(source != null);
_mediaType = source._mediaType;
if (source._parameters != null)
{
foreach (var parameter in source._parameters)
{
this.Parameters.Add((NameValueHeaderValue)((ICloneable)parameter).Clone());
}
}
}
public MediaTypeHeaderValue(string mediaType)
{
CheckMediaTypeFormat(mediaType, nameof(mediaType));
_mediaType = mediaType;
}
public override string ToString()
{
return _mediaType + NameValueHeaderValue.ToString(_parameters, ';', true);
}
public override bool Equals(object obj)
{
MediaTypeHeaderValue other = obj as MediaTypeHeaderValue;
if (other == null)
{
return false;
}
return string.Equals(_mediaType, other._mediaType, StringComparison.OrdinalIgnoreCase) &&
HeaderUtilities.AreEqualCollections(_parameters, other._parameters);
}
public override int GetHashCode()
{
// The media-type string is case-insensitive.
return StringComparer.OrdinalIgnoreCase.GetHashCode(_mediaType) ^ NameValueHeaderValue.GetHashCode(_parameters);
}
public static MediaTypeHeaderValue Parse(string input)
{
int index = 0;
return (MediaTypeHeaderValue)MediaTypeHeaderParser.SingleValueParser.ParseValue(input, null, ref index);
}
public static bool TryParse(string input, out MediaTypeHeaderValue parsedValue)
{
int index = 0;
object output;
parsedValue = null;
if (MediaTypeHeaderParser.SingleValueParser.TryParseValue(input, null, ref index, out output))
{
parsedValue = (MediaTypeHeaderValue)output;
return true;
}
return false;
}
internal static int GetMediaTypeLength(string input, int startIndex,
Func<MediaTypeHeaderValue> mediaTypeCreator, out MediaTypeHeaderValue parsedValue)
{
Debug.Assert(mediaTypeCreator != null);
Debug.Assert(startIndex >= 0);
parsedValue = null;
if (string.IsNullOrEmpty(input) || (startIndex >= input.Length))
{
return 0;
}
// Caller must remove leading whitespace. If not, we'll return 0.
string mediaType = null;
int mediaTypeLength = MediaTypeHeaderValue.GetMediaTypeExpressionLength(input, startIndex, out mediaType);
if (mediaTypeLength == 0)
{
return 0;
}
int current = startIndex + mediaTypeLength;
current = current + HttpRuleParser.GetWhitespaceLength(input, current);
MediaTypeHeaderValue mediaTypeHeader = null;
// If we're not done and we have a parameter delimiter, then we have a list of parameters.
if ((current < input.Length) && (input[current] == ';'))
{
mediaTypeHeader = mediaTypeCreator();
mediaTypeHeader._mediaType = mediaType;
current++; // skip delimiter.
int parameterLength = NameValueHeaderValue.GetNameValueListLength(input, current, ';',
(ObjectCollection<NameValueHeaderValue>)mediaTypeHeader.Parameters);
if (parameterLength == 0)
{
return 0;
}
parsedValue = mediaTypeHeader;
return current + parameterLength - startIndex;
}
// We have a media type without parameters.
mediaTypeHeader = mediaTypeCreator();
mediaTypeHeader._mediaType = mediaType;
parsedValue = mediaTypeHeader;
return current - startIndex;
}
private static int GetMediaTypeExpressionLength(string input, int startIndex, out string mediaType)
{
Debug.Assert((input != null) && (input.Length > 0) && (startIndex < input.Length));
// This method just parses the "type/subtype" string, it does not parse parameters.
mediaType = null;
// Parse the type, i.e. <type> in media type string "<type>/<subtype>; param1=value1; param2=value2"
int typeLength = HttpRuleParser.GetTokenLength(input, startIndex);
if (typeLength == 0)
{
return 0;
}
int current = startIndex + typeLength;
current = current + HttpRuleParser.GetWhitespaceLength(input, current);
// Parse the separator between type and subtype
if ((current >= input.Length) || (input[current] != '/'))
{
return 0;
}
current++; // skip delimiter.
current = current + HttpRuleParser.GetWhitespaceLength(input, current);
// Parse the subtype, i.e. <subtype> in media type string "<type>/<subtype>; param1=value1; param2=value2"
int subtypeLength = HttpRuleParser.GetTokenLength(input, current);
if (subtypeLength == 0)
{
return 0;
}
// If there are no whitespace between <type> and <subtype> in <type>/<subtype> get the media type using
// one Substring call. Otherwise get substrings for <type> and <subtype> and combine them.
int mediatTypeLength = current + subtypeLength - startIndex;
if (typeLength + subtypeLength + 1 == mediatTypeLength)
{
mediaType = input.Substring(startIndex, mediatTypeLength);
}
else
{
mediaType = input.Substring(startIndex, typeLength) + "/" + input.Substring(current, subtypeLength);
}
return mediatTypeLength;
}
private static void CheckMediaTypeFormat(string mediaType, string parameterName)
{
if (string.IsNullOrEmpty(mediaType))
{
throw new ArgumentException("The value cannot be null or empty.", parameterName);
}
// When adding values using strongly typed objects, no leading/trailing LWS (whitespace) are allowed.
// Also no LWS between type and subtype are allowed.
string tempMediaType;
int mediaTypeLength = GetMediaTypeExpressionLength(mediaType, 0, out tempMediaType);
if ((mediaTypeLength == 0) || (tempMediaType.Length != mediaType.Length))
{
throw new FormatException(string.Format(System.Globalization.CultureInfo.InvariantCulture, "The format of value '{0}' is invalid.", mediaType));
}
}
// Implement ICloneable explicitly to allow derived types to "override" the implementation.
object ICloneable.Clone()
{
return new MediaTypeHeaderValue(this);
}
}
}
| |
using System;
using System.IO;
using System.Reflection;
using log4net;
using log4net.Config;
namespace RLToolkit.Logger
{
/// <summary>
/// Log4Net implementing the ILogger interface.
/// </summary>
public class Log4NetLogger : ILogger
{
#region Variables
private readonly ILog log;
#endregion
#region Constants
/// <summary>The default config file for log4net.</summary>
public const string defaultConfigFile = @"logger.config";
#endregion
#region Init
/// <summary>Report that the system if functional on firat usage</summary>
static Log4NetLogger ()
{
string filePath = Path.Combine (AppDomain.CurrentDomain.BaseDirectory, defaultConfigFile);
if (File.Exists (filePath)) {
Console.WriteLine("Using the following configuration file for Log4Net:\n" + filePath);
XmlConfigurator.ConfigureAndWatch (new FileInfo (filePath));
} else {
// file not found!
Console.WriteLine("Configuration file for Log4Net not found:\n" + filePath);
XmlConfigurator.Configure();
}
LogManager.Instance.Log().Info("Logging system ready.");
}
/// <summary>
/// Constructor that initialiuze the internal logger
/// </summary>
/// <param name="logIn">Logger input</param>
public Log4NetLogger (ILog logIn)
{
log = logIn;
}
#endregion
#region Logger-Trace
/// <summary>
/// Log an entry under the trace level
/// </summary>
/// <param name="message">Message.</param>
public void Trace (string message)
{
if (log.IsDebugEnabled && message != null) {
log.Debug("TRACE-" + message);
}
}
/// <summary>
/// Log an entry under the trace level
/// </summary>
/// <param name="message">Message.</param>
/// <param name="param">Parameter for the string.Format</param>
public void Trace (string message, object[] param)
{
if (log.IsDebugEnabled && message != null) {
log.Debug(string.Format ("TRACE-" + message, param));
}
}
/// <summary>
/// Log an entry under the trace level
/// </summary>
/// <param name="message">Message.</param>
/// <param name="e">E.</param>
public void Trace (string message, Exception e)
{
if (log.IsDebugEnabled && message != null && e != null) {
log.Debug("TRACE-Exception thrown: " + message + Environment.NewLine + e.ToString());
}
}
#endregion
#region Logger-Debug
/// <summary>
/// Log an entry under the debug level
/// </summary>
/// <param name="message">Message.</param>
public void Debug (string message)
{
if (log.IsDebugEnabled && message != null) {
log.Debug(message);
}
}
/// <summary>
/// Log an entry under the debug level
/// </summary>
/// <param name="message">Message.</param>
/// <param name="param">Parameter for the string.Format</param>
public void Debug (string message, object[] param)
{
if (log.IsDebugEnabled && message != null) {
log.Debug(string.Format (message, param));
}
}
/// <summary>
/// Log an entry under the debug level
/// </summary>
/// <param name="message">Message.</param>
/// <param name="e">E.</param>
public void Debug (string message, Exception e)
{
if (log.IsDebugEnabled && message != null && e != null) {
log.Debug("Exception thrown: " + message + Environment.NewLine + e.ToString());
}
}
#endregion
#region Logger-Info
/// <summary>
/// Log an entry under the info level
/// </summary>
/// <param name="message">Message.</param>
public void Info (string message)
{
if (log.IsInfoEnabled && message != null) {
log.Info(message);
}
}
/// <summary>
/// Log an entry under the info level
/// </summary>
/// <param name="message">Message.</param>
/// <param name="param">Parameter for the string.Format</param>
public void Info (string message, object[] param)
{
if (log.IsInfoEnabled && message != null) {
log.Info(string.Format (message, param));
}
}
/// <summary>
/// Log an entry under the info level
/// </summary>
/// <param name="message">Message.</param>
/// <param name="e">E.</param>
public void Info (string message, Exception e)
{
if (log.IsInfoEnabled && message != null && e != null) {
log.Info("Exception thrown: " + message + Environment.NewLine + e.ToString());
}
}
#endregion
#region Logger-Warn
/// <summary>
/// Log an entry under the warn level
/// </summary>
/// <param name="message">Message.</param>
public void Warn (string message)
{
if (log.IsWarnEnabled && message != null) {
log.Warn(message);
}
}
/// <summary>
/// Log an entry under the warn level
/// </summary>
/// <param name="message">Message.</param>
/// <param name="param">Parameter for the string.Format</param>
public void Warn (string message, object[] param)
{
if (log.IsWarnEnabled && message != null) {
log.Warn(string.Format (message, param));
}
}
/// <summary>
/// Log an entry under the warn level
/// </summary>
/// <param name="message">Message.</param>
/// <param name="e">E.</param>
public void Warn (string message, Exception e)
{
if (log.IsWarnEnabled && message != null && e != null) {
log.Warn("Exception thrown: " + message + Environment.NewLine + e.ToString());
}
}
#endregion
#region Logger-Fatal
/// <summary>
/// Log an entry under the fatal level
/// </summary>
/// <param name="message">Message.</param>
public void Fatal (string message)
{
if (log.IsFatalEnabled && message != null) {
log.Fatal(message);
}
}
/// <summary>
/// Log an entry under the fatal level
/// </summary>
/// <param name="message">Message.</param>
/// <param name="param">Parameter for the string.Format</param>
public void Fatal (string message, object[] param)
{
if (log.IsFatalEnabled && message != null) {
log.Fatal(string.Format (message, param));
}
}
/// <summary>
/// Log an entry under the fatal level
/// </summary>
/// <param name="message">Message.</param>
/// <param name="e">E.</param>
public void Fatal (string message, Exception e)
{
if (log.IsFatalEnabled && message != null && e != null) {
log.Fatal("Exception thrown: " + message + Environment.NewLine + e.ToString());
}
}
#endregion
}
}
| |
// SNMP message extension class.
// Copyright (C) 2008-2010 Malcolm Crowe, Lex Li, and other contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Net;
using System.Net.Sockets;
#if NETSTANDARD2_0
using System.Runtime.InteropServices;
#endif
using System.Threading;
using System.Threading.Tasks;
using GSF.Net.Snmp.Security;
namespace GSF.Net.Snmp.Messaging
{
/// <summary>
/// Extension methods for <see cref="ISnmpMessage"/>.
/// </summary>
public static class SnmpMessageExtension
{
/// <summary>
/// Gets the <see cref="SnmpType"/>.
/// </summary>
/// <param name="message">The <see cref="ISnmpMessage"/>.</param>
/// <returns></returns>
public static SnmpType TypeCode(this ISnmpMessage message)
{
if (message == null)
{
throw new ArgumentNullException(nameof(message));
}
return message.Pdu().TypeCode;
}
/// <summary>
/// Variables.
/// </summary>
/// <param name="message">The <see cref="ISnmpMessage"/>.</param>
public static IList<Variable> Variables(this ISnmpMessage message)
{
if (message == null)
{
throw new ArgumentNullException(nameof(message));
}
SnmpType code = message.TypeCode();
return code == SnmpType.Unknown ? new List<Variable>(0) : message.Scope.Pdu.Variables;
}
/// <summary>
/// Request ID.
/// </summary>
/// <param name="message">The <see cref="ISnmpMessage"/>.</param>
public static int RequestId(this ISnmpMessage message)
{
if (message == null)
{
throw new ArgumentNullException(nameof(message));
}
return message.Scope.Pdu.RequestId.ToInt32();
}
/// <summary>
/// Gets the message ID.
/// </summary>
/// <value>The message ID.</value>
/// <param name="message">The <see cref="ISnmpMessage"/>.</param>
/// <remarks>For v3, message ID is different from request ID. For v1 and v2c, they are the same.</remarks>
public static int MessageId(this ISnmpMessage message)
{
if (message == null)
{
throw new ArgumentNullException(nameof(message));
}
return message.Header == Header.Empty ? message.RequestId() : message.Header.MessageId;
}
/// <summary>
/// PDU.
/// </summary>
/// <param name="message">The <see cref="ISnmpMessage"/>.</param>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Pdu")]
public static ISnmpPdu Pdu(this ISnmpMessage message)
{
if (message == null)
{
throw new ArgumentNullException(nameof(message));
}
return message.Scope.Pdu;
}
/// <summary>
/// Community name.
/// </summary>
/// <param name="message">The <see cref="ISnmpMessage"/>.</param>
public static OctetString Community(this ISnmpMessage message)
{
if (message == null)
{
throw new ArgumentNullException(nameof(message));
}
return message.Parameters.UserName;
}
#region sync methods
/// <summary>
/// Sends an <see cref="ISnmpMessage"/>.
/// </summary>
/// <param name="message">The <see cref="ISnmpMessage"/>.</param>
/// <param name="manager">Manager</param>
public static void Send(this ISnmpMessage message, EndPoint manager)
{
if (message == null)
{
throw new ArgumentNullException(nameof(message));
}
if (manager == null)
{
throw new ArgumentNullException(nameof(manager));
}
SnmpType code = message.TypeCode();
if ((code != SnmpType.TrapV1Pdu && code != SnmpType.TrapV2Pdu) && code != SnmpType.ReportPdu)
{
throw new InvalidOperationException(string.Format(
CultureInfo.InvariantCulture,
"not a trap message: {0}",
code));
}
using (Socket socket = manager.GetSocket())
{
message.Send(manager, socket);
}
}
/// <summary>
/// Sends an <see cref="ISnmpMessage"/>.
/// </summary>
/// <param name="message">The <see cref="ISnmpMessage"/>.</param>
/// <param name="manager">Manager</param>
/// <param name="socket">The socket.</param>
public static void Send(this ISnmpMessage message, EndPoint manager, Socket socket)
{
if (message == null)
{
throw new ArgumentNullException(nameof(message));
}
if (socket == null)
{
throw new ArgumentNullException(nameof(socket));
}
if (manager == null)
{
throw new ArgumentNullException(nameof(manager));
}
SnmpType code = message.TypeCode();
if ((code != SnmpType.TrapV1Pdu && code != SnmpType.TrapV2Pdu) && code != SnmpType.ReportPdu)
{
throw new InvalidOperationException(string.Format(
CultureInfo.InvariantCulture,
"not a trap message: {0}",
code));
}
byte[] bytes = message.ToBytes();
socket.SendTo(bytes, 0, bytes.Length, SocketFlags.None, manager);
}
/// <summary>
/// Sends this <see cref="ISnmpMessage"/> and handles the response from agent.
/// </summary>
/// <param name="request">The <see cref="ISnmpMessage"/>.</param>
/// <param name="timeout">The time-out value, in milliseconds. The default value is 0, which indicates an infinite time-out period. Specifying -1 also indicates an infinite time-out period.</param>
/// <param name="receiver">Port number.</param>
/// <param name="registry">User registry.</param>
/// <returns></returns>
public static ISnmpMessage GetResponse(this ISnmpMessage request, int timeout, IPEndPoint receiver, UserRegistry registry)
{
// TODO: make more usage of UserRegistry.
if (request == null)
{
throw new ArgumentNullException(nameof(request));
}
if (receiver == null)
{
throw new ArgumentNullException(nameof(receiver));
}
SnmpType code = request.TypeCode();
if (code == SnmpType.TrapV1Pdu || code == SnmpType.TrapV2Pdu || code == SnmpType.ReportPdu)
{
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "not a request message: {0}", code));
}
using (Socket socket = receiver.GetSocket())
{
return request.GetResponse(timeout, receiver, registry, socket);
}
}
/// <summary>
/// Sends this <see cref="ISnmpMessage"/> and handles the response from agent.
/// </summary>
/// <param name="request">The <see cref="ISnmpMessage"/>.</param>
/// <param name="timeout">The time-out value, in milliseconds. The default value is 0, which indicates an infinite time-out period. Specifying -1 also indicates an infinite time-out period.</param>
/// <param name="receiver">Port number.</param>
/// <returns></returns>
public static ISnmpMessage GetResponse(this ISnmpMessage request, int timeout, IPEndPoint receiver)
{
if (request == null)
{
throw new ArgumentNullException(nameof(request));
}
if (receiver == null)
{
throw new ArgumentNullException(nameof(receiver));
}
SnmpType code = request.TypeCode();
if (code == SnmpType.TrapV1Pdu || code == SnmpType.TrapV2Pdu || code == SnmpType.ReportPdu)
{
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "not a request message: {0}", code));
}
using (Socket socket = receiver.GetSocket())
{
return request.GetResponse(timeout, receiver, socket);
}
}
/// <summary>
/// Sends this <see cref="ISnmpMessage"/> and handles the response from agent.
/// </summary>
/// <param name="request">The <see cref="ISnmpMessage"/>.</param>
/// <param name="timeout">The time-out value, in milliseconds. The default value is 0, which indicates an infinite time-out period. Specifying -1 also indicates an infinite time-out period.</param>
/// <param name="receiver">Agent.</param>
/// <param name="udpSocket">The UDP <see cref="Socket"/> to use to send/receive.</param>
/// <returns></returns>
public static ISnmpMessage GetResponse(this ISnmpMessage request, int timeout, IPEndPoint receiver, Socket udpSocket)
{
if (request == null)
{
throw new ArgumentNullException(nameof(request));
}
if (receiver == null)
{
throw new ArgumentNullException(nameof(receiver));
}
if (udpSocket == null)
{
throw new ArgumentNullException(nameof(udpSocket));
}
UserRegistry registry = new UserRegistry();
if (request.Version == VersionCode.V3)
{
registry.Add(request.Parameters.UserName, request.Privacy);
}
return request.GetResponse(timeout, receiver, registry, udpSocket);
}
/// <summary>
/// Sends an <see cref="ISnmpMessage"/> and handles the response from agent.
/// </summary>
/// <param name="request">The <see cref="ISnmpMessage"/>.</param>
/// <param name="timeout">The time-out value, in milliseconds. The default value is 0, which indicates an infinite time-out period. Specifying -1 also indicates an infinite time-out period.</param>
/// <param name="receiver">Agent.</param>
/// <param name="udpSocket">The UDP <see cref="Socket"/> to use to send/receive.</param>
/// <param name="registry">The user registry.</param>
/// <returns></returns>
public static ISnmpMessage GetResponse(this ISnmpMessage request, int timeout, IPEndPoint receiver, UserRegistry registry, Socket udpSocket)
{
if (request == null)
{
throw new ArgumentNullException(nameof(request));
}
if (udpSocket == null)
{
throw new ArgumentNullException(nameof(udpSocket));
}
if (receiver == null)
{
throw new ArgumentNullException(nameof(receiver));
}
if (registry == null)
{
throw new ArgumentNullException(nameof(registry));
}
SnmpType requestCode = request.TypeCode();
if (requestCode == SnmpType.TrapV1Pdu || requestCode == SnmpType.TrapV2Pdu || requestCode == SnmpType.ReportPdu)
{
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "not a request message: {0}", requestCode));
}
byte[] bytes = request.ToBytes();
int bufSize = udpSocket.ReceiveBufferSize = Messenger.MaxMessageSize;
byte[] reply = new byte[bufSize];
// Whatever you change, try to keep the Send and the Receive close to each other.
udpSocket.SendTo(bytes, receiver);
udpSocket.ReceiveTimeout = timeout;
int count;
try
{
count = udpSocket.Receive(reply, 0, bufSize, SocketFlags.None);
}
catch (SocketException ex)
{
// IMPORTANT: Mono behavior.
if (IsRunningOnMono && ex.SocketErrorCode == SocketError.WouldBlock)
{
throw TimeoutException.Create(receiver.Address, timeout);
}
if (ex.SocketErrorCode == SocketError.TimedOut)
{
throw TimeoutException.Create(receiver.Address, timeout);
}
throw;
}
// Passing 'count' is not necessary because ParseMessages should ignore it, but it offer extra safety (and would avoid an issue if parsing >1 response).
ISnmpMessage response = MessageFactory.ParseMessages(reply, 0, count, registry)[0];
SnmpType responseCode = response.TypeCode();
if (responseCode == SnmpType.ResponsePdu || responseCode == SnmpType.ReportPdu)
{
int requestId = request.MessageId();
int responseId = response.MessageId();
if (responseId != requestId)
{
throw OperationException.Create(string.Format(CultureInfo.InvariantCulture, "wrong response sequence: expected {0}, received {1}", requestId, responseId), receiver.Address);
}
return response;
}
throw OperationException.Create(string.Format(CultureInfo.InvariantCulture, "wrong response type: {0}", responseCode), receiver.Address);
}
#endregion
#region async methods
#if NET471
/// <summary>
/// Ends a pending asynchronous read.
/// </summary>
/// <param name="request">The <see cref="ISnmpMessage"/>.</param>
/// <param name="asyncResult">An <see cref="IAsyncResult"/> that stores state information and any user defined data for this asynchronous operation.</param>
/// <returns></returns>
[Obsolete("Please use GetResponseAsync and await on it.")]
public static ISnmpMessage EndGetResponse(this ISnmpMessage request, IAsyncResult asyncResult)
{
if (asyncResult == null)
{
throw new ArgumentNullException(nameof(asyncResult));
}
if (request == null)
{
throw new ArgumentNullException(nameof(request));
}
SnmpMessageAsyncResult ar = (SnmpMessageAsyncResult)asyncResult;
Socket s = ar.WorkSocket;
int count = s.EndReceive(ar.Inner);
// Passing 'count' is not necessary because ParseMessages should ignore it, but it offer extra safety (and would avoid an issue if parsing >1 response).
ISnmpMessage response = MessageFactory.ParseMessages(ar.GetBuffer(), 0, count, ar.Users)[0];
SnmpType responseCode = response.TypeCode();
if (responseCode == SnmpType.ResponsePdu || responseCode == SnmpType.ReportPdu)
{
int requestId = request.MessageId();
int responseId = response.MessageId();
if (responseId != requestId)
{
throw OperationException.Create(string.Format(CultureInfo.InvariantCulture, "wrong response sequence: expected {0}, received {1}", requestId, responseId), ar.Receiver.Address);
}
return response;
}
throw OperationException.Create(string.Format(CultureInfo.InvariantCulture, "wrong response type: {0}", responseCode), ar.Receiver.Address);
}
/// <summary>
/// Begins to asynchronously send an <see cref="ISnmpMessage"/> to an <see cref="IPEndPoint"/>.
/// </summary>
/// <param name="request">The <see cref="ISnmpMessage"/>.</param>
/// <param name="receiver">Agent.</param>
/// <param name="registry">The user registry.</param>
/// <param name="udpSocket">The UDP <see cref="Socket"/> to use to send/receive.</param>
/// <param name="callback">The callback.</param>
/// <param name="state">The state object.</param>
/// <returns></returns>
[Obsolete("Please use GetResponseAsync and await on it.")]
public static IAsyncResult BeginGetResponse(this ISnmpMessage request, IPEndPoint receiver, UserRegistry registry, Socket udpSocket, AsyncCallback callback, object state)
{
if (request == null)
{
throw new ArgumentNullException(nameof(request));
}
if (udpSocket == null)
{
throw new ArgumentNullException(nameof(udpSocket));
}
if (receiver == null)
{
throw new ArgumentNullException(nameof(receiver));
}
if (registry == null)
{
throw new ArgumentNullException(nameof(registry));
}
SnmpType requestCode = request.TypeCode();
if (requestCode == SnmpType.TrapV1Pdu || requestCode == SnmpType.TrapV2Pdu || requestCode == SnmpType.ReportPdu)
{
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "not a request message: {0}", requestCode));
}
// Whatever you change, try to keep the Send and the Receive close to each other.
udpSocket.SendTo(request.ToBytes(), receiver);
int bufferSize = udpSocket.ReceiveBufferSize = Messenger.MaxMessageSize;
byte[] buffer = new byte[bufferSize];
// https://sharpsnmplib.codeplex.com/workitem/7234
if (callback != null)
{
AsyncCallback wrapped = callback;
callback = asyncResult =>
{
SnmpMessageAsyncResult result = new SnmpMessageAsyncResult(asyncResult, udpSocket, registry, receiver, buffer);
wrapped(result);
};
}
IAsyncResult ar = udpSocket.BeginReceive(buffer, 0, bufferSize, SocketFlags.None, callback, state);
return new SnmpMessageAsyncResult(ar, udpSocket, registry, receiver, buffer);
}
#endif
/// <summary>
/// Sends an <see cref="ISnmpMessage"/>.
/// </summary>
/// <param name="message">The <see cref="ISnmpMessage"/>.</param>
/// <param name="manager">Manager</param>
public static async Task SendAsync(this ISnmpMessage message, EndPoint manager)
{
if (message == null)
{
throw new ArgumentNullException(nameof(message));
}
if (manager == null)
{
throw new ArgumentNullException(nameof(manager));
}
SnmpType code = message.TypeCode();
if ((code != SnmpType.TrapV1Pdu && code != SnmpType.TrapV2Pdu) && code != SnmpType.ReportPdu)
{
throw new InvalidOperationException(string.Format(
CultureInfo.InvariantCulture,
"not a trap message: {0}",
code));
}
using (Socket socket = manager.GetSocket())
{
await message.SendAsync(manager, socket).ConfigureAwait(false);
}
}
/// <summary>
/// Sends an <see cref="ISnmpMessage"/>.
/// </summary>
/// <param name="message">The <see cref="ISnmpMessage"/>.</param>
/// <param name="manager">Manager</param>
/// <param name="socket">The socket.</param>
public static async Task SendAsync(this ISnmpMessage message, EndPoint manager, Socket socket)
{
if (message == null)
{
throw new ArgumentNullException(nameof(message));
}
if (socket == null)
{
throw new ArgumentNullException(nameof(socket));
}
if (manager == null)
{
throw new ArgumentNullException(nameof(manager));
}
SnmpType code = message.TypeCode();
if ((code != SnmpType.TrapV1Pdu && code != SnmpType.TrapV2Pdu) && code != SnmpType.ReportPdu)
{
throw new InvalidOperationException(string.Format(
CultureInfo.InvariantCulture,
"not a trap message: {0}",
code));
}
byte[] bytes = message.ToBytes();
SocketAsyncEventArgs info = SocketExtension.EventArgsFactory.Create();
info.RemoteEndPoint = manager;
info.SetBuffer(bytes, 0, bytes.Length);
using (SocketAwaitable awaitable1 = new SocketAwaitable(info))
{
await socket.SendToAsync(awaitable1);
}
}
/// <summary>
/// Sends this <see cref="ISnmpMessage"/> and handles the response from agent.
/// </summary>
/// <param name="request">The <see cref="ISnmpMessage"/>.</param>
/// <param name="receiver">Port number.</param>
/// <param name="registry">User registry.</param>
/// <returns></returns>
public static async Task<ISnmpMessage> GetResponseAsync(this ISnmpMessage request, IPEndPoint receiver, UserRegistry registry)
{
// TODO: make more usage of UserRegistry.
if (request == null)
{
throw new ArgumentNullException(nameof(request));
}
if (receiver == null)
{
throw new ArgumentNullException(nameof(receiver));
}
SnmpType code = request.TypeCode();
if (code == SnmpType.TrapV1Pdu || code == SnmpType.TrapV2Pdu || code == SnmpType.ReportPdu)
{
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "not a request message: {0}", code));
}
using (Socket socket = receiver.GetSocket())
{
return await request.GetResponseAsync(receiver, registry, socket).ConfigureAwait(false);
}
}
/// <summary>
/// Sends this <see cref="ISnmpMessage"/> and handles the response from agent.
/// </summary>
/// <param name="request">The <see cref="ISnmpMessage"/>.</param>
/// <param name="receiver">Port number.</param>
/// <returns></returns>
public static async Task<ISnmpMessage> GetResponseAsync(this ISnmpMessage request, IPEndPoint receiver)
{
if (request == null)
{
throw new ArgumentNullException(nameof(request));
}
if (receiver == null)
{
throw new ArgumentNullException(nameof(receiver));
}
SnmpType code = request.TypeCode();
if (code == SnmpType.TrapV1Pdu || code == SnmpType.TrapV2Pdu || code == SnmpType.ReportPdu)
{
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "not a request message: {0}", code));
}
using (Socket socket = receiver.GetSocket())
{
return await request.GetResponseAsync(receiver, socket).ConfigureAwait(false);
}
}
/// <summary>
/// Sends this <see cref="ISnmpMessage"/> and handles the response from agent.
/// </summary>
/// <param name="request">The <see cref="ISnmpMessage"/>.</param>
/// <param name="receiver">Agent.</param>
/// <param name="udpSocket">The UDP <see cref="Socket"/> to use to send/receive.</param>
/// <returns></returns>
public static async Task<ISnmpMessage> GetResponseAsync(this ISnmpMessage request, IPEndPoint receiver, Socket udpSocket)
{
if (request == null)
{
throw new ArgumentNullException(nameof(request));
}
if (receiver == null)
{
throw new ArgumentNullException(nameof(receiver));
}
if (udpSocket == null)
{
throw new ArgumentNullException(nameof(udpSocket));
}
UserRegistry registry = new UserRegistry();
if (request.Version == VersionCode.V3)
{
registry.Add(request.Parameters.UserName, request.Privacy);
}
return await request.GetResponseAsync(receiver, registry, udpSocket).ConfigureAwait(false);
}
/// <summary>
/// Sends an <see cref="ISnmpMessage"/> and handles the response from agent.
/// </summary>
/// <param name="request">The <see cref="ISnmpMessage"/>.</param>
/// <param name="receiver">Agent.</param>
/// <param name="udpSocket">The UDP <see cref="Socket"/> to use to send/receive.</param>
/// <param name="registry">The user registry.</param>
/// <returns></returns>
public static async Task<ISnmpMessage> GetResponseAsync(this ISnmpMessage request, IPEndPoint receiver, UserRegistry registry, Socket udpSocket)
{
if (request == null)
{
throw new ArgumentNullException(nameof(request));
}
if (udpSocket == null)
{
throw new ArgumentNullException(nameof(udpSocket));
}
if (registry == null)
{
throw new ArgumentNullException(nameof(registry));
}
SnmpType requestCode = request.TypeCode();
if (requestCode == SnmpType.TrapV1Pdu || requestCode == SnmpType.TrapV2Pdu || requestCode == SnmpType.ReportPdu)
{
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "not a request message: {0}", requestCode));
}
byte[] bytes = request.ToBytes();
int bufSize = udpSocket.ReceiveBufferSize = Messenger.MaxMessageSize;
// Whatever you change, try to keep the Send and the Receive close to each other.
SocketAsyncEventArgs info = SocketExtension.EventArgsFactory.Create();
info.RemoteEndPoint = receiver ?? throw new ArgumentNullException(nameof(receiver));
info.SetBuffer(bytes, 0, bytes.Length);
using (SocketAwaitable awaitable1 = new SocketAwaitable(info))
{
await udpSocket.SendToAsync(awaitable1);
}
int count;
byte[] reply = new byte[bufSize];
// IMPORTANT: follow http://blogs.msdn.com/b/pfxteam/archive/2011/12/15/10248293.aspx
SocketAsyncEventArgs args = SocketExtension.EventArgsFactory.Create();
IPAddress remoteAddress = udpSocket.AddressFamily == AddressFamily.InterNetworkV6 ? IPAddress.IPv6Any : IPAddress.Any;
EndPoint remote = new IPEndPoint(remoteAddress, 0);
try
{
args.RemoteEndPoint = remote;
args.SetBuffer(reply, 0, bufSize);
using (SocketAwaitable awaitable = new SocketAwaitable(args))
{
count = await udpSocket.ReceiveMessageFromAsync(awaitable);
}
}
catch (SocketException ex)
{
// IMPORTANT: Mono behavior (https://bugzilla.novell.com/show_bug.cgi?id=599488)
if (IsRunningOnMono && ex.SocketErrorCode == SocketError.WouldBlock)
{
throw TimeoutException.Create(receiver.Address, 0);
}
if (ex.SocketErrorCode == SocketError.TimedOut)
{
throw TimeoutException.Create(receiver.Address, 0);
}
throw;
}
// Passing 'count' is not necessary because ParseMessages should ignore it, but it offer extra safety (and would avoid an issue if parsing >1 response).
ISnmpMessage response = MessageFactory.ParseMessages(reply, 0, count, registry)[0];
SnmpType responseCode = response.TypeCode();
if (responseCode == SnmpType.ResponsePdu || responseCode == SnmpType.ReportPdu)
{
int requestId = request.MessageId();
int responseId = response.MessageId();
if (responseId != requestId)
{
throw OperationException.Create(string.Format(CultureInfo.InvariantCulture, "wrong response sequence: expected {0}, received {1}", requestId, responseId), receiver.Address);
}
return response;
}
throw OperationException.Create(string.Format(CultureInfo.InvariantCulture, "wrong response type: {0}", responseCode), receiver.Address);
}
#endregion
/// <summary>
/// Tests if running on Mono.
/// </summary>
/// <returns></returns>
public static bool IsRunningOnMono
{
get { return Type.GetType("Mono.Runtime") != null; }
}
/// <summary>
/// Gets a value indicating whether it is
/// running on Windows.
/// </summary>
/// <value><c>true</c> if is running on Windows; otherwise, <c>false</c>.</value>
public static bool IsRunningOnWindows
{
get
{
#if NET471
return !IsRunningOnMono;
#elif NETSTANDARD2_0
return RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
#else
return false;
#endif
}
}
/// <summary>
/// Gets a value indicating whether it is running on macOS.
/// </summary>
/// <value><c>true</c> if is running on macOS; otherwise, <c>false</c>.</value>
public static bool IsRunningOnMac
{
get
{
#if NET471
return IsRunningOnMono;
#elif NETSTANDARD2_0
return RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
#else
return false;
#endif
}
}
/// <summary>
/// Gets a value indicating whether it is running on iOS.
/// </summary>
/// <value><c>true</c> if is running on iOS; otherwise, <c>false</c>.</value>
public static bool IsRunningOnIOS
{
get
{
#if NET471
return false;
#elif NETSTANDARD2_0
return RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
#elif XAMARINIOS1_0
return true;
#else
return false;
#endif
}
}
/// <summary>
/// Packs up the <see cref="ISnmpMessage"/>.
/// </summary>
/// <param name="message">The <see cref="ISnmpMessage"/>.</param>
/// <param name="length">The length bytes.</param>
/// <returns></returns>
internal static Sequence PackMessage(this ISnmpMessage message, byte[] length)
{
if (message == null)
{
throw new ArgumentNullException(nameof(message));
}
return ByteTool.PackMessage(
length,
message.Version,
message.Header,
message.Parameters,
message.Privacy.GetScopeData(message.Header, message.Parameters, message.Scope.GetData(message.Version)));
}
private sealed class SnmpMessageAsyncResult : IAsyncResult
{
private readonly byte[] _buffer;
public SnmpMessageAsyncResult(IAsyncResult inner, Socket socket, UserRegistry users, IPEndPoint receiver, byte[] buffer)
{
_buffer = buffer;
WorkSocket = socket;
Users = users;
Receiver = receiver;
Inner = inner;
}
public IAsyncResult Inner { get; private set; }
public Socket WorkSocket { get; private set; }
public UserRegistry Users { get; private set; }
public byte[] GetBuffer()
{
return _buffer;
}
public IPEndPoint Receiver { get; private set; }
public bool IsCompleted
{
get { return Inner.IsCompleted; }
}
public WaitHandle AsyncWaitHandle
{
get { return Inner.AsyncWaitHandle; }
}
public object AsyncState
{
get { return Inner.AsyncState; }
}
public bool CompletedSynchronously
{
get { return Inner.CompletedSynchronously; }
}
}
}
}
| |
namespace Irony.Parsing
{
/// <summary>
/// Reduces list created by MakePlusRule or MakeListRule methods.
/// </summary>
public class ReduceListBuilderParserAction : ReduceParserAction
{
public ReduceListBuilderParserAction(Production production) : base(production)
{ }
protected override ParseTreeNode GetResultNode(ParsingContext context)
{
var childCount = Production.RValues.Count;
var firstChildIndex = context.ParserStack.Count - childCount;
// Get the list already created - it is the first child node
var listNode = context.ParserStack[firstChildIndex];
listNode.Span = context.ComputeStackRangeSpan(childCount);
// Next list member is the last child - at the top of the stack
var listMember = context.ParserStack.Top;
if (listMember.IsPunctuationOrEmptyTransient())
return listNode;
listNode.ChildNodes.Add(listMember);
return listNode;
}
}
/// <summary>
/// List container is an artificial non-terminal created by MakeStarRule method; the actual list is a direct child.
/// </summary>
public class ReduceListContainerParserAction : ReduceParserAction
{
public ReduceListContainerParserAction(Production production) : base(production)
{ }
protected override ParseTreeNode GetResultNode(ParsingContext context)
{
var childCount = this.Production.RValues.Count;
var firstChildIndex = context.ParserStack.Count - childCount;
var span = context.ComputeStackRangeSpan(childCount);
var newNode = new ParseTreeNode(this.Production.LValue, span);
// If it is not empty production - might happen for MakeStarRule
if (childCount > 0)
{
// Get the transient list with all members - it is the first child node
var listNode = context.ParserStack[firstChildIndex];
// Copy all list members
newNode.ChildNodes.AddRange(listNode.ChildNodes);
}
return newNode;
}
}
/// <summary>
/// Base class for more specific reduce actions.
/// </summary>
public partial class ReduceParserAction : ParserAction
{
public readonly Production Production;
public ReduceParserAction(Production production)
{
this.Production = production;
}
/// <summary>
/// Factory method for creating a proper type of reduce parser action.
/// </summary>
/// <param name="production">A Production to reduce.</param>
/// <returns>Reduce action.</returns>
public static ReduceParserAction Create(Production production)
{
var nonTerm = production.LValue;
// List builder (non-empty production for list non-terminal) is a special case
var isList = nonTerm.Flags.IsSet(TermFlags.IsList);
var isListBuilderProduction = isList && production.RValues.Count > 0 && production.RValues[0] == production.LValue;
if (isListBuilderProduction)
return new ReduceListBuilderParserAction(production);
else if (nonTerm.Flags.IsSet(TermFlags.IsListContainer))
return new ReduceListContainerParserAction(production);
else if (nonTerm.Flags.IsSet(TermFlags.IsTransient))
return new ReduceTransientParserAction(production);
else
return new ReduceParserAction(production);
}
public override void Execute(ParsingContext context)
{
var savedParserInput = context.CurrentParserInput;
context.CurrentParserInput = this.GetResultNode(context);
this.CompleteReduce(context);
context.CurrentParserInput = savedParserInput;
}
public override string ToString()
{
return string.Format(Resources.LabelActionReduce, this.Production.ToStringQuoted());
}
/// <summary>
/// Completes reduce: pops child nodes from the stack and pushes result node into the stack
/// </summary>
/// <param name="context"></param>
protected void CompleteReduce(ParsingContext context)
{
var resultNode = context.CurrentParserInput;
var childCount = Production.RValues.Count;
// Pop stack
context.ParserStack.Pop(childCount);
// Copy comment block from first child; if comments precede child node, they precede the parent as well.
if (resultNode.ChildNodes.Count > 0)
resultNode.Comments = resultNode.ChildNodes[0].Comments;
// Inherit precedence and associativity, to cover a standard case: BinOp->+|-|*|/;
// BinOp node should inherit precedence from underlying operator symbol.
// TODO: this special case will be handled differently. A ToTerm method should be expanded to allow "combined" terms like "NOT LIKE".
// OLD COMMENT: A special case is SQL operator "NOT LIKE" which consists of 2 tokens. We therefore inherit "max" precedence from any children
if (this.Production.LValue.Flags.IsSet(TermFlags.InheritPrecedence))
this.InheritPrecedence(resultNode);
// Push new node into stack and move to new state
// First read the state from top of the stack
context.CurrentParserState = context.ParserStack.Top.State;
if (context.TracingEnabled)
context.AddTrace(Resources.MsgTracePoppedState, this.Production.LValue.Name);
#region comments on special case
// Special case: if a non-terminal is Transient (ex: BinOp), then result node is not this NonTerminal, but its its child (ex: symbol).
// Shift action will invoke OnShifting on actual term being shifted (symbol); we need to invoke Shifting even on NonTerminal itself
// - this would be more expected behavior in general. ImpliedPrecHint relies on this
#endregion comments on special case
// Special case
if (resultNode.Term != this.Production.LValue)
this.Production.LValue.OnShifting(context.SharedParsingEventArgs);
// Shift to new state - execute shift over the non-terminal of the production.
var shift = context.CurrentParserState.Actions[this.Production.LValue];
// Execute shift to new state
shift.Execute(context);
// Invoke Reduce event
this.Production.LValue.OnReduced(context, this.Production, resultNode);
}
protected virtual ParseTreeNode GetResultNode(ParsingContext context)
{
var childCount = Production.RValues.Count;
var firstChildIndex = context.ParserStack.Count - childCount;
var span = context.ComputeStackRangeSpan(childCount);
var newNode = new ParseTreeNode(Production.LValue, span);
for (int i = 0; i < childCount; i++)
{
var childNode = context.ParserStack[firstChildIndex + i];
// Skip punctuation or empty transient nodes
if (childNode.IsPunctuationOrEmptyTransient())
continue;
newNode.ChildNodes.Add(childNode);
}
return newNode;
}
/// <summary>
/// This operation helps in situation when Bin expression is declared as BinExpr.Rule = expr + BinOp + expr;
/// where BinOp is an OR-combination of operators.
/// During parsing, when 'expr, BinOp, expr' is on the top of the stack,
/// and incoming symbol is operator, we need to use precedence rule for deciding on the action.
/// </summary>
/// <param name="node"></param>
private void InheritPrecedence(ParseTreeNode node)
{
for (int i = 0; i < node.ChildNodes.Count; i++)
{
var child = node.ChildNodes[i];
if (child.Precedence == Terminal.NoPrecedence)
continue;
node.Precedence = child.Precedence;
node.Associativity = child.Associativity;
return;
}
}
}
/// <summary>
/// Reduces non-terminal marked as Transient by MarkTransient method.
/// </summary>
public class ReduceTransientParserAction : ReduceParserAction
{
public ReduceTransientParserAction(Production production) : base(production)
{ }
protected override ParseTreeNode GetResultNode(ParsingContext context)
{
var topIndex = context.ParserStack.Count - 1;
var childCount = Production.RValues.Count;
for (int i = 0; i < childCount; i++)
{
var child = context.ParserStack[topIndex - i];
if (child.IsPunctuationOrEmptyTransient())
continue;
return child;
}
// Otherwise return an empty transient node;
// if it is part of the list, the list will skip it
var span = context.ComputeStackRangeSpan(childCount);
return new ParseTreeNode(Production.LValue, span);
}
}
}
| |
//
// System.Net.CookieContainerTest - CookieContainer tests
//
// Authors:
// Gonzalo Paniagua Javier ([email protected])
//
// (c) Copyright 2004 Novell, Inc. (http://www.novell.com)
//
using NUnit.Framework;
using System;
using System.Net;
using System.Reflection;
namespace MonoTests.System.Net
{
[TestFixture]
public class CookieContainerTest : Assertion
{
[Test]
public void TestCtor1 ()
{
CookieContainer c = new CookieContainer (234);
AssertEquals ("#01", 234, c.Capacity);
bool passed = false;
try {
new CookieContainer (0);
passed = false;
} catch (ArgumentException) {
passed = true;
}
AssertEquals ("#02", true, passed);
try {
new CookieContainer (-10);
passed = false;
} catch (ArgumentException) {
passed = true;
}
AssertEquals ("#03", true, passed);
}
[Test]
public void TestCtor3 ()
{
CookieContainer c = new CookieContainer (100, 50, 1000);
AssertEquals ("#01", 100, c.Capacity);
AssertEquals ("#02", 50, c.PerDomainCapacity);
AssertEquals ("#03", 1000, c.MaxCookieSize);
bool passed = false;
try {
new CookieContainer (100, 0, 1000);
passed = false;
} catch (ArgumentException) {
passed = true;
}
AssertEquals ("#04", true, passed);
try {
new CookieContainer (100, -1, 1000);
passed = false;
} catch (ArgumentException) {
passed = true;
}
AssertEquals ("#05", true, passed);
try {
new CookieContainer (100, Int32.MaxValue, 1000);
passed = true;
} catch (ArgumentException) {
passed = false;
}
AssertEquals ("#06", true, passed);
try {
new CookieContainer (100, 50, 0);
passed = false;
} catch (ArgumentException) {
passed = true;
}
AssertEquals ("#07", true, passed);
try {
new CookieContainer (100, 500, -4);
passed = false;
} catch (ArgumentException) {
passed = true;
}
AssertEquals ("#08", true, passed);
}
[Test]
public void TestDefaultLimits ()
{
AssertEquals ("#01", CookieContainer.DefaultCookieLengthLimit, 4096);
AssertEquals ("#02", CookieContainer.DefaultCookieLimit, 300);
AssertEquals ("#03", CookieContainer.DefaultPerDomainCookieLimit, 20);
}
[Test]
public void TestCapacity ()
{
CookieContainer c = new CookieContainer ();
AssertEquals ("#01", c.Capacity, 300);
c.Capacity = 200;
AssertEquals ("#02", c.Capacity, 200);
bool passed = false;
try {
c.Capacity = -5;
passed = false;
} catch (ArgumentOutOfRangeException) {
passed = true;
}
AssertEquals ("#03", true, passed);
try {
c.Capacity = 5; // must be >= PerDomainCapacity if PerDomainCapacity != Int32.MaxValue
passed = false;
} catch (ArgumentOutOfRangeException) {
passed = true;
}
AssertEquals ("#04", true, passed);
passed = false;
}
[Test]
public void TestMaxCookieSize ()
{
CookieContainer c = new CookieContainer ();
AssertEquals ("#01", c.MaxCookieSize, 4096);
bool passed = false;
try {
c.MaxCookieSize = -5;
passed = false;
} catch (ArgumentOutOfRangeException) {
passed = true;
}
AssertEquals ("#02", true, passed);
try {
c.MaxCookieSize = -1;
passed = false;
} catch (ArgumentOutOfRangeException) {
passed = true;
}
AssertEquals ("#03", true, passed);
c.MaxCookieSize = 80000;
AssertEquals ("#04", 80000, c.MaxCookieSize);
c.MaxCookieSize = Int32.MaxValue;
AssertEquals ("#04", Int32.MaxValue, c.MaxCookieSize);
}
[Test]
public void TestAdd_Args ()
{
CookieContainer cc = new CookieContainer ();
bool passed = false;
try {
cc.Add ((Cookie) null);
passed = false;
} catch (ArgumentNullException) {
passed = true;
}
AssertEquals ("#01", true, passed);
try {
cc.Add ((CookieCollection) null);
passed = false;
} catch (ArgumentNullException) {
passed = true;
}
AssertEquals ("#02", true, passed);
try {
cc.Add (null, (Cookie) null);
passed = false;
} catch (ArgumentNullException) {
passed = true;
}
AssertEquals ("#03", true, passed);
try {
cc.Add (null, (CookieCollection) null);
passed = false;
} catch (ArgumentNullException) {
passed = true;
}
AssertEquals ("#04", true, passed);
try {
cc.Add (new Uri ("http://www.contoso.com"), (Cookie) null);
passed = false;
} catch (ArgumentNullException) {
passed = true;
}
AssertEquals ("#05", true, passed);
try {
cc.Add (new Uri ("http://www.contoso.com"), (CookieCollection) null);
passed = false;
} catch (ArgumentNullException) {
passed = true;
}
AssertEquals ("#06", true, passed);
}
[Test]
public void TestAdd_Cookie ()
{
CookieContainer cc = new CookieContainer ();
Uri uri = new Uri ("http://www.contoso.com");
cc.Add (uri, new CookieCollection ());
DateTime timestamp = DateTime.Now;
cc.Add (uri, new Cookie ("hola", "Adios"));
CookieCollection coll = cc.GetCookies (uri);
Cookie cookie = coll [0];
AssertEquals ("#07", "", cookie.Comment);
AssertEquals ("#08", null, cookie.CommentUri);
AssertEquals ("#09", "www.contoso.com", cookie.Domain);
AssertEquals ("#10", false, cookie.Expired);
AssertEquals ("#11", DateTime.MinValue, cookie.Expires);
AssertEquals ("#12", "hola", cookie.Name);
AssertEquals ("#13", "/", cookie.Path);
AssertEquals ("#14", "", cookie.Port);
AssertEquals ("#15", false, cookie.Secure);
// FIX the next test
TimeSpan ts = cookie.TimeStamp - timestamp;
if (ts.TotalMilliseconds > 500)
AssertEquals ("#16 timestamp", true, false);
AssertEquals ("#17", "Adios", cookie.Value);
AssertEquals ("#18", 0, cookie.Version);
}
[Test]
public void TestGetCookies_Args ()
{
CookieContainer cc = new CookieContainer ();
try {
cc.GetCookies (null);
AssertEquals ("#01", true, false);
} catch (ArgumentNullException) {
}
}
[Test]
public void TestSetCookies_Args ()
{
CookieContainer cc = new CookieContainer ();
try {
cc.SetCookies (null, "");
AssertEquals ("#01", true, false);
} catch (ArgumentNullException) {
}
try {
cc.SetCookies (new Uri ("http://www.contoso.com"), null);
AssertEquals ("#02", true, false);
} catch (ArgumentNullException) {
}
try {
cc.SetCookies (new Uri ("http://www.contoso.com"), "=lalala");
AssertEquals ("#03", true, false);
} catch (CookieException) {
}
try {
cc.SetCookies (new Uri ("http://www.contoso.com"), "");
} catch (CookieException) {
AssertEquals ("#04", true, false);
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
namespace Ink.Runtime
{
internal class Container : Runtime.Object, INamedContent
{
public string name { get; set; }
public List<Runtime.Object> content {
get {
return _content;
}
set {
AddContent (value);
}
}
List<Runtime.Object> _content;
public Dictionary<string, INamedContent> namedContent { get; set; }
public Dictionary<string, Runtime.Object> namedOnlyContent {
get {
var namedOnlyContentDict = new Dictionary<string, Runtime.Object>();
foreach (var kvPair in namedContent) {
namedOnlyContentDict [kvPair.Key] = (Runtime.Object)kvPair.Value;
}
foreach (var c in content) {
var named = c as INamedContent;
if (named != null && named.hasValidName) {
namedOnlyContentDict.Remove (named.name);
}
}
if (namedOnlyContentDict.Count == 0)
namedOnlyContentDict = null;
return namedOnlyContentDict;
}
set {
var existingNamedOnly = namedOnlyContent;
if (existingNamedOnly != null) {
foreach (var kvPair in existingNamedOnly) {
namedContent.Remove (kvPair.Key);
}
}
if (value == null)
return;
foreach (var kvPair in value) {
var named = kvPair.Value as INamedContent;
if( named != null )
AddToNamedContentOnly (named);
}
}
}
public bool visitsShouldBeCounted { get; set; }
public bool turnIndexShouldBeCounted { get; set; }
public bool countingAtStartOnly { get; set; }
[Flags]
public enum CountFlags
{
Visits = 1,
Turns = 2,
CountStartOnly = 4
}
public int countFlags
{
get {
CountFlags flags = 0;
if (visitsShouldBeCounted) flags |= CountFlags.Visits;
if (turnIndexShouldBeCounted) flags |= CountFlags.Turns;
if (countingAtStartOnly) flags |= CountFlags.CountStartOnly;
// If we're only storing CountStartOnly, it serves no purpose,
// since it's dependent on the other two to be used at all.
// (e.g. for setting the fact that *if* a gather or choice's
// content is counted, then is should only be counter at the start)
// So this is just an optimisation for storage.
if (flags == CountFlags.CountStartOnly) {
flags = 0;
}
return (int)flags;
}
set {
var flag = (CountFlags)value;
if ((flag & CountFlags.Visits) > 0) visitsShouldBeCounted = true;
if ((flag & CountFlags.Turns) > 0) turnIndexShouldBeCounted = true;
if ((flag & CountFlags.CountStartOnly) > 0) countingAtStartOnly = true;
}
}
public bool hasValidName
{
get { return name != null && name.Length > 0; }
}
public Path pathToFirstLeafContent
{
get {
if( _pathToFirstLeafContent == null )
_pathToFirstLeafContent = path.PathByAppendingPath (internalPathToFirstLeafContent);
return _pathToFirstLeafContent;
}
}
Path _pathToFirstLeafContent;
Path internalPathToFirstLeafContent
{
get {
var components = new List<Path.Component>();
var container = this;
while (container != null) {
if (container.content.Count > 0) {
components.Add (new Path.Component (0));
container = container.content [0] as Container;
}
}
return new Path(components);
}
}
public Container ()
{
_content = new List<Runtime.Object> ();
namedContent = new Dictionary<string, INamedContent> ();
}
public void AddContent(Runtime.Object contentObj)
{
content.Add (contentObj);
if (contentObj.parent) {
throw new System.Exception ("content is already in " + contentObj.parent);
}
contentObj.parent = this;
TryAddNamedContent (contentObj);
}
public void AddContent(IList<Runtime.Object> contentList)
{
foreach (var c in contentList) {
AddContent (c);
}
}
public void InsertContent(Runtime.Object contentObj, int index)
{
content.Insert (index, contentObj);
if (contentObj.parent) {
throw new System.Exception ("content is already in " + contentObj.parent);
}
contentObj.parent = this;
TryAddNamedContent (contentObj);
}
public void TryAddNamedContent(Runtime.Object contentObj)
{
var namedContentObj = contentObj as INamedContent;
if (namedContentObj != null && namedContentObj.hasValidName) {
AddToNamedContentOnly (namedContentObj);
}
}
public void AddToNamedContentOnly(INamedContent namedContentObj)
{
Debug.Assert (namedContentObj is Runtime.Object, "Can only add Runtime.Objects to a Runtime.Container");
var runtimeObj = (Runtime.Object)namedContentObj;
runtimeObj.parent = this;
namedContent [namedContentObj.name] = namedContentObj;
}
public void AddContentsOfContainer(Container otherContainer)
{
content.AddRange (otherContainer.content);
foreach (var obj in otherContainer.content) {
obj.parent = this;
TryAddNamedContent (obj);
}
}
protected Runtime.Object ContentWithPathComponent(Path.Component component)
{
if (component.isIndex) {
if (component.index >= 0 && component.index < content.Count) {
return content [component.index];
}
// When path is out of range, quietly return nil
// (useful as we step/increment forwards through content)
else {
return null;
}
}
else if (component.isParent) {
return this.parent;
}
else {
INamedContent foundContent = null;
if (namedContent.TryGetValue (component.name, out foundContent)) {
return (Runtime.Object)foundContent;
} else {
return null;
}
}
}
public SearchResult ContentAtPath(Path path, int partialPathStart = 0, int partialPathLength = -1)
{
if (partialPathLength == -1)
partialPathLength = path.length;
var result = new SearchResult ();
result.approximate = false;
Container currentContainer = this;
Runtime.Object currentObj = this;
for (int i = partialPathStart; i < partialPathLength; ++i) {
var comp = path.GetComponent(i);
// Path component was wrong type
if (currentContainer == null) {
result.approximate = true;
break;
}
var foundObj = currentContainer.ContentWithPathComponent(comp);
// Couldn't resolve entire path?
if (foundObj == null) {
result.approximate = true;
break;
}
currentObj = foundObj;
currentContainer = foundObj as Container;
}
result.obj = currentObj;
return result;
}
public void BuildStringOfHierarchy(StringBuilder sb, int indentation, Runtime.Object pointedObj)
{
Action appendIndentation = () => {
const int spacesPerIndent = 4;
for(int i=0; i<spacesPerIndent*indentation;++i) {
sb.Append(" ");
}
};
appendIndentation ();
sb.Append("[");
if (this.hasValidName) {
sb.AppendFormat (" ({0})", this.name);
}
if (this == pointedObj) {
sb.Append (" <---");
}
sb.AppendLine ();
indentation++;
for (int i=0; i<content.Count; ++i) {
var obj = content [i];
if (obj is Container) {
var container = (Container)obj;
container.BuildStringOfHierarchy (sb, indentation, pointedObj);
} else {
appendIndentation ();
if (obj is StringValue) {
sb.Append ("\"");
sb.Append (obj.ToString ().Replace ("\n", "\\n"));
sb.Append ("\"");
} else {
sb.Append (obj.ToString ());
}
}
if (i != content.Count - 1) {
sb.Append (",");
}
if ( !(obj is Container) && obj == pointedObj ) {
sb.Append (" <---");
}
sb.AppendLine ();
}
var onlyNamed = new Dictionary<string, INamedContent> ();
foreach (var objKV in namedContent) {
if (content.Contains ((Runtime.Object)objKV.Value)) {
continue;
} else {
onlyNamed.Add (objKV.Key, objKV.Value);
}
}
if (onlyNamed.Count > 0) {
appendIndentation ();
sb.AppendLine ("-- named: --");
foreach (var objKV in onlyNamed) {
Debug.Assert (objKV.Value is Container, "Can only print out named Containers");
var container = (Container)objKV.Value;
container.BuildStringOfHierarchy (sb, indentation, pointedObj);
sb.AppendLine ();
}
}
indentation--;
appendIndentation ();
sb.Append ("]");
}
public virtual string BuildStringOfHierarchy()
{
var sb = new StringBuilder ();
BuildStringOfHierarchy (sb, 0, null);
return sb.ToString ();
}
}
}
| |
/*=============================================================================
* Examples.cs
* Use-case examples.
*==============================================================================
*
* Tested with .NET Framework 4.6
*
* Copyright (c) 2015, Exosite LLC
* All rights reserved.
*/
using System;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Threading;
namespace clronep.examples
{
/// <summary>
/// Contains methods that are used to demonstrate use-case examples for
/// the clronep library
/// </summary>
class Example
{
/// <summary>
/// Main method - calls into example sequences for layer 1 API (raw)
/// and layer 2 API (buffered, batch)
/// </summary>
public static void Main(string[] args)
{
//NOTE: The easiest way to get a Client Interface Key (CIK) the first time is probably from Exosite Portals https://portals.exosite.com
string cik;
OnePV1Form frm = new OnePV1Form();
frm.ShowDialog();
cik = frm.cik;
OnepV1Examples(cik); //Layer 1 (low level) examples
ClientOnepV1Examples(cik); //Layer 2 (batched/overloaded) examples
}
/// <summary>
/// Worker function for wait threading in OnepV1Examples
/// </summary>
public static void waitFunction(string cik, string rid, OnepV1 oneConn)
{
Dictionary<string, int> waitOptions = new Dictionary<string, int>();
waitOptions.Add("timeout", 30000);
Console.WriteLine("Waiting on dataport with RID " + rid);
Result result = oneConn.wait(cik, rid, waitOptions);
if (result.status == Result.OK)
{
Console.WriteLine("\r\nWait output: ");
Console.WriteLine(result.message);
Console.WriteLine("\r\n");
}
}
/// <summary>
/// Worker function for write threading in OnepV1Examples
/// </summary>
public static void waitWrite(string cik, string rid, OnepV1 oneConn)
{
Thread.Sleep(10000);
int val = new Random().Next(1, 100);
Result result = oneConn.write(cik, rid, val);
if (result.status == Result.OK)
{
Console.WriteLine(val+10 +" is the expected output of the wait");
}
}
/// <summary>
/// OnepV1Examples method - example sequence for layer 1 calls. Layer 1
/// calls are direct bindings to the 1P API.
/// </summary>
public static void OnepV1Examples(string cik)
{
//OnepV1(url, timeout)
OnepV1 oneConn = new OnepV1("https://m2.exosite.com/onep:v1/rpc/process", 35);
Result result;
try
{
// Get resource id of dataport given its alias name 'X1'
string alias_name = "X1";
result = oneConn.lookup(cik, "alias", alias_name);
string rid = null;
if (result.status == Result.OK)
{
rid = result.message;
} else {
// If dataport with alias 'X1' didn't exist, we will create it
Console.WriteLine("Could not find Dataport with alias " + alias_name + ", creating...");
result = oneConn.create(cik, "dataport", getDescObject());
if (result.status == Result.OK)
{
rid = result.message;
result = oneConn.map(cik, rid, alias_name);
Console.WriteLine("Dataport: " + rid + " (" + alias_name + ") is created.");
}
}
// Write data to dataport
int val = new Random().Next(1, 100);
result = oneConn.write(cik, rid, val);
if (result.status == Result.OK)
{
Console.WriteLine("Dataport " + rid + " is written with raw value " + val + ".");
}
// Read data from dataport
result = oneConn.read(cik, rid, EmptyOption.Instance);
if (result.status == Result.OK)
{
object[][] read = JsonConvert.DeserializeObject<object[][]>(result.message);
val = Int32.Parse(read[0][1].ToString());
Console.WriteLine("Dataport " + rid + " is read back as: " + val + " (value stored is different from raw write value due to pre-process rule).");
}
// Create and then drop a dataport (note - a client can have many dataports w/ same name, but alias & RID must be unique)
object desc = getDescObject();
result = oneConn.create(cik, "dataport", desc);
if (result.status == Result.OK)
{
rid = result.message;
Console.WriteLine("\r\nDataport: " + rid + " is created.");
alias_name = "test_alias";
// map/unmap alias to dataport
result = oneConn.map(cik, rid, alias_name);
if (result.status == Result.OK)
{
Console.WriteLine("Dataport: " + rid + " is mapped to alias '" + alias_name + "'");
// Un-map the alias from the dataport
result = oneConn.unmap(cik, alias_name);
if (result.status == Result.OK)
{
Console.WriteLine("Dataport: " + rid + " is unmapped from alias '" + alias_name + "'");
}
}
result = oneConn.drop(cik, rid);
if (result.status == Result.OK)
{
Console.WriteLine("Dataport: " + rid + " is dropped.");
}
}
// List a client's dataports
string[] options = new string[] { "dataport" };
result = oneConn.listing(cik, options);
if (result.status == Result.OK)
{
Console.WriteLine("\r\nList of all Dataport RIDs for client CIK " + cik + ":");
Console.WriteLine(result.message);
}
/* Get all mapping alias information for dataports */
// Get resource id of device given device key
result = oneConn.lookup(cik, "alias", "");
rid = result.message;
// Get the alias information of given device
Dictionary<string, object> option = new Dictionary<string, object>();
option.Add("aliases", true);
result = oneConn.info(cik, rid, option);
if (result.status == Result.OK)
{
Console.WriteLine("\r\nList of all Dataports with an alias for client CIK " + cik + ":");
Console.WriteLine(result.message);
Console.WriteLine("\r\n");
}
//wait example
rid = oneConn.lookup(cik, "alias", "X1").message;
ThreadStart starter = delegate { waitFunction(cik, rid, oneConn); };
Thread thread = new Thread(starter);
ThreadStart starter2 = delegate { waitWrite(cik, rid, oneConn); };
Thread thread2 = new Thread(starter2);
thread.Start();
thread2.Start();
Console.WriteLine("Waiting with timeout of 30 seconds for a write that will occur in 10 seconds");
thread2.Join(Timeout.Infinite);
thread.Join(Timeout.Infinite);
}
catch (OneException e)
{
Console.WriteLine("\r\nOnepV1Examples sequence exception:");
Console.WriteLine(e.Message);
}
}
/// <summary>
/// ClientOnepV1Examples method - example sequence for Layer 2 calls.
/// Layer 2 uses Layer 1, but add some function overloading and batch
/// sequences to simplify common use cases
/// </summary>
public static void ClientOnepV1Examples(string cik)
{
//ClientOnepV1(url, timeout, cik)
ClientOnepV1 conn = new ClientOnepV1("https://m2.exosite.com/onep:v1/rpc/process", 3, cik);
int val = new Random().Next(1, 100);
string alias_name = "X1";
string alias2_name = "X2";
Result result;
//write data to alias
try
{
Console.WriteLine("Writing to alias " + alias_name + ":");
result = conn.write(alias_name, val);
if (result.status == Result.OK)
{
Console.WriteLine("Successfully wrote value: " + val + ".\r\n");
}
}
catch(OnePlatformException e)
{
Console.WriteLine("ClientOnepV1Examples, write exception:");
Console.WriteLine(e.Message + "\r\n");
}
// read data from alias
try
{
Console.WriteLine("Reading from alias " + alias_name + ":");
result = conn.read(alias_name);
if (result.status == Result.OK)
{
object[][] read = JsonConvert.DeserializeObject<object[][]>(result.message);
val = Int32.Parse(read[0][1].ToString());
Console.WriteLine("Successfully read value: " + val + ".\r\n");
}
}
catch (OneException e)
{
Console.WriteLine("ClientOnepV1Examples, read exception:");
Console.WriteLine(e.Message + "\r\n");
}
//create dataport
try
{
Console.WriteLine("Creating a new dataport named " + alias2_name + ":");
DataportDescription desc = new DataportDescription("integer");//integer format
desc.retention.count = 10; // only allow 10 data points to be stored to the resource
desc.retention.duration = 1; // only allow the platform to keep the data points for 1 hour
desc.visibility = "parent";
desc.name = "Friendly Name";
result = conn.create(alias2_name, desc);
if (result.status == Result.OK)
{
Console.WriteLine("Success.\r\n");
}
else Console.WriteLine("Unsuccessful: " + result.status + ".\r\n");
}
catch (OneException e)
{
Console.WriteLine("ClientOnepV1Examples, create dataport exception:");
Console.WriteLine(e.Message + "\r\n");
}
//write group data
try
{
val = new Random().Next(1, 100);
Console.WriteLine("Writing value " + val + " to aliases " + alias_name + ", " + alias2_name + " as a group:");
Dictionary<string, object> entries = new Dictionary<string, object>();
entries.Add(alias_name, val);
entries.Add(alias2_name, val);
result = conn.writegroup(entries);
//NOTE: this call returns Result.OK regardless if _any_ of the writes were successful or not
if (result.status == Result.OK)
{
Console.WriteLine("Wrote a value of " + val + " to dataports.\r\n");
}
}
catch (OneException e)
{
Console.WriteLine("ClientOnepV1Examples, group write exception:");
Console.WriteLine(e.Message + "\r\n");
}
//get all aliases information
Console.WriteLine("Listing all alias information for client:");
Dictionary<string,string> aliasDict = conn.getAllAliasesInfo();
foreach( string alias in aliasDict.Keys){
string rid = aliasDict[alias];
Console.WriteLine(alias + "," + rid);
}
Console.WriteLine("\r\n");
/* The comment function has been deprecated in One Platform. The unit parameter is
* now stored in the meta field of clients by Portals.
// comment
try
{
Console.WriteLine("Adding \"unit\" parameter to dataport comment field:");
Dictionary<string, string> unit = new Dictionary<string, string>();
unit.Add("unit", "%");
string unitstr = JsonConvert.SerializeObject(unit);
//add "unit" using 'comment' method
conn.comment(alias_name, "public", unitstr);
//get "unit" using 'info' method
Dictionary<string, object> option = new Dictionary<string, object>();
option.Add("comments", true);
result = conn.info(alias_name, option);
//Console.WriteLine(res.message);
Dictionary<string, object[][]> a = JsonConvert.DeserializeObject<Dictionary<string, object[][]>>(result.message);
Dictionary<string, string> b = JsonConvert.DeserializeObject<Dictionary<string, string>>(a["comments"][0][1].ToString());
Console.WriteLine("Read back from comment field for parameter \"unit\" as: " + b["unit"] + ".\r\n");
}
catch (OneException e)
{
Console.WriteLine("ClientOnepV1Examples, comment exception:");
Console.WriteLine(e.Message + "\r\n");
}
*
*
*/
}
/// <summary>
/// Describes the setup of a dataport. Used when calling "create"
/// </summary>
public static object getDescObject()
{
Dictionary<string, object> desc = new Dictionary<string, object>();
desc.Add("format","integer");
desc.Add("name","X1");
desc.Add("visibility","parent");
Dictionary<string, object> retention = new Dictionary<string, object>();
retention.Add("count","infinity");
retention.Add("duration","infinity");
desc.Add("retention",retention);
object[] p1 = new object[]{"add",10};
object[] preprocess = new object[]{p1};
desc.Add("preprocess",preprocess);
return desc;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Runtime.Serialization.Formatters;
using System.Security.Authentication;
using System.Text;
using Halibut.Diagnostics;
using Newtonsoft.Json;
using Newtonsoft.Json.Bson;
namespace Halibut.Transport.Protocol
{
public class MessageExchangeStream : IMessageExchangeStream
{
readonly Stream stream;
readonly ILog log;
readonly StreamWriter streamWriter;
readonly StreamReader streamReader;
readonly JsonSerializer serializer;
readonly Version currentVersion = new Version(1, 0);
public MessageExchangeStream(Stream stream, ILog log)
{
this.stream = stream;
this.log = log;
streamWriter = new StreamWriter(stream, new UTF8Encoding(false));
streamReader = new StreamReader(stream, new UTF8Encoding(false));
serializer = Serializer();
SetNormalTimeouts();
}
public static Func<JsonSerializer> Serializer = CreateDefault;
public void IdentifyAsClient()
{
log.Write(EventType.Diagnostic, "Identifying as a client");
streamWriter.Write("MX-CLIENT ");
streamWriter.Write(currentVersion);
streamWriter.WriteLine();
streamWriter.WriteLine();
streamWriter.Flush();
ExpectServerIdentity();
}
public void SendNext()
{
SetShortTimeouts();
streamWriter.Write("NEXT");
streamWriter.WriteLine();
streamWriter.Flush();
SetNormalTimeouts();
}
public void SendProceed()
{
streamWriter.Write("PROCEED");
streamWriter.WriteLine();
streamWriter.Flush();
}
public bool ExpectNextOrEnd()
{
var line = ReadLine();
switch (line)
{
case "NEXT":
return true;
case null:
case "END":
return false;
default:
throw new ProtocolException("Expected NEXT or END, got: " + line);
}
}
public void ExpectProceeed()
{
SetShortTimeouts();
var line = ReadLine();
if (line == null)
throw new AuthenticationException("XYZ");
if (line != "PROCEED")
throw new ProtocolException("Expected PROCEED, got: " + line);
SetNormalTimeouts();
}
string ReadLine()
{
var line = streamReader.ReadLine();
while (line == string.Empty)
{
line = streamReader.ReadLine();
}
return line;
}
public void IdentifyAsSubscriber(string subscriptionId)
{
streamWriter.Write("MX-SUBSCRIBER ");
streamWriter.Write(currentVersion);
streamWriter.Write(" ");
streamWriter.Write(subscriptionId);
streamWriter.WriteLine();
streamWriter.WriteLine();
streamWriter.Flush();
ExpectServerIdentity();
}
public void IdentifyAsServer()
{
streamWriter.Write("MX-SERVER ");
streamWriter.Write(currentVersion);
streamWriter.WriteLine();
streamWriter.WriteLine();
streamWriter.Flush();
}
public RemoteIdentity ReadRemoteIdentity()
{
var line = streamReader.ReadLine();
if (string.IsNullOrEmpty(line)) throw new ProtocolException("Unable to receive the remote identity; the identity line was empty.");
var parts = line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
var identityType = ParseIdentityType(parts[0]);
if (identityType == RemoteIdentityType.Subscriber)
{
if (parts.Length < 3) throw new ProtocolException("Unable to receive the remote identity; the client identified as a subscriber, but did not supply a subscription ID.");
var subscriptionId = new Uri(parts[2]);
return new RemoteIdentity(identityType, subscriptionId);
}
return new RemoteIdentity(identityType);
}
public void Send<T>(T message)
{
using (var capture = StreamCapture.New())
{
WriteBsonMessage(message);
WriteEachStream(capture.SerializedStreams);
}
log.Write(EventType.Diagnostic, "Sent: {0}", message);
}
public T Receive<T>()
{
using (var capture = StreamCapture.New())
{
var result = ReadBsonMessage<T>();
ReadStreams(capture);
log.Write(EventType.Diagnostic, "Received: {0}", result);
return result;
}
}
static JsonSerializer CreateDefault()
{
var serializer = JsonSerializer.Create();
serializer.Formatting = Formatting.None;
serializer.ContractResolver = new HalibutContractResolver();
serializer.TypeNameHandling = TypeNameHandling.Auto;
serializer.TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple;
serializer.DateFormatHandling = DateFormatHandling.IsoDateFormat;
return serializer;
}
static RemoteIdentityType ParseIdentityType(string identityType)
{
switch (identityType)
{
case "MX-CLIENT":
return RemoteIdentityType.Client;
case "MX-SERVER":
return RemoteIdentityType.Server;
case "MX-SUBSCRIBER":
return RemoteIdentityType.Subscriber;
default:
throw new ProtocolException("Unable to process remote identity; unknown identity type: '" + identityType + "'");
}
}
void ExpectServerIdentity()
{
var identity = ReadRemoteIdentity();
if (identity.IdentityType != RemoteIdentityType.Server)
throw new ProtocolException("Expected the remote endpoint to identity as a server. Instead, it identified as: " + identity.IdentityType);
}
T ReadBsonMessage<T>()
{
using (var zip = new DeflateStream(stream, CompressionMode.Decompress, true))
using (var buffer = new BufferedStream(zip, 8192))
using (var bson = new BsonReader(buffer) { CloseInput = false })
{
return (T)serializer.Deserialize<MessageEnvelope>(bson).Message;
}
}
void ReadStreams(StreamCapture capture)
{
var expected = capture.DeserializedStreams.Count;
for (var i = 0; i < expected; i++)
{
ReadStream(capture);
}
}
void ReadStream(StreamCapture capture)
{
var reader = new BinaryReader(stream);
var id = new Guid(reader.ReadBytes(16));
var length = reader.ReadInt64();
var dataStream = FindStreamById(capture, id);
var tempFile = CopyStreamToFile(id, length, reader);
var lengthAgain = reader.ReadInt64();
if (lengthAgain != length)
{
throw new ProtocolException("There was a problem receiving a file stream: the length of the file was expected to be: " + length + " but less data was actually sent. This can happen if the remote party is sending a stream but the stream had already been partially read, or if the stream was being reused between calls.");
}
((IDataStreamInternal)dataStream).Received(tempFile);
}
static TemporaryFileStream CopyStreamToFile(Guid id, long length, BinaryReader reader)
{
var path = Path.Combine(Path.GetTempPath(), id.ToString());
using (var fileStream = new FileStream(path, FileMode.Create, FileAccess.Write))
{
var buffer = new byte[1024 * 128];
while (length > 0)
{
var read = reader.Read(buffer, 0, (int)Math.Min(buffer.Length, length));
length -= read;
fileStream.Write(buffer, 0, read);
}
}
return new TemporaryFileStream(path);
}
static DataStream FindStreamById(StreamCapture capture, Guid id)
{
var dataStream = capture.DeserializedStreams.FirstOrDefault(d => d.Id == id);
if (dataStream == null) throw new Exception("Unexpected stream!");
return dataStream;
}
void WriteBsonMessage<T>(T messages)
{
using (var zip = new DeflateStream(stream, CompressionMode.Compress, true))
using (var buffer = new BufferedStream(zip))
using (var bson = new BsonWriter(buffer) { CloseOutput = false })
{
serializer.Serialize(bson, new MessageEnvelope { Message = messages });
bson.Flush();
}
}
void WriteEachStream(IEnumerable<DataStream> streams)
{
foreach (var dataStream in streams)
{
var writer = new BinaryWriter(stream);
writer.Write(dataStream.Id.ToByteArray());
writer.Write(dataStream.Length);
writer.Flush();
var buffer = new BufferedStream(stream, 8192);
((IDataStreamInternal)dataStream).Transmit(buffer);
buffer.Flush();
writer.Write(dataStream.Length);
writer.Flush();
}
}
class MessageEnvelope
{
public object Message { get; set; }
}
void SetNormalTimeouts()
{
stream.WriteTimeout = (int)HalibutLimits.TcpClientSendTimeout.TotalMilliseconds;
stream.ReadTimeout = (int)HalibutLimits.TcpClientReceiveTimeout.TotalMilliseconds;
}
void SetShortTimeouts()
{
stream.WriteTimeout = (int)HalibutLimits.TcpClientHeartbeatSendTimeout.TotalMilliseconds;
stream.ReadTimeout = (int)HalibutLimits.TcpClientHeartbeatReceiveTimeout.TotalMilliseconds;
}
}
}
| |
// 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>
/// ApiVersionLocalOperations operations.
/// </summary>
internal partial class ApiVersionLocalOperations : IServiceOperations<AutoRestAzureSpecialParametersTestClient>, IApiVersionLocalOperations
{
/// <summary>
/// Initializes a new instance of the ApiVersionLocalOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal ApiVersionLocalOperations(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>
/// Get method with api-version modeled in the method. pass in api-version =
/// '2.0' to succeed
/// </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>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> GetMethodLocalValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
string apiVersion = "2.0";
// 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, "GetMethodLocalValid", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/apiVersion/method/string/none/query/local/2.0").ToString();
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new 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>
/// Get method with api-version modeled in the method. pass in api-version =
/// null to succeed
/// </summary>
/// <param name='apiVersion'>
/// This should appear as a method parameter, use value null, this should
/// result in no serialized parameter
/// </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>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> GetMethodLocalNullWithHttpMessagesAsync(string apiVersion = default(string), 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("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetMethodLocalNull", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/apiVersion/method/string/none/query/local/null").ToString();
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new 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>
/// Get method with api-version modeled in the method. pass in api-version =
/// '2.0' to succeed
/// </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>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> GetPathLocalValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
string apiVersion = "2.0";
// 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, "GetPathLocalValid", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/apiVersion/path/string/none/query/local/2.0").ToString();
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new 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>
/// Get method with api-version modeled in the method. pass in api-version =
/// '2.0' to succeed
/// </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>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> GetSwaggerLocalValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
string apiVersion = "2.0";
// 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, "GetSwaggerLocalValid", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/apiVersion/swagger/string/none/query/local/2.0").ToString();
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new 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;
}
}
}
| |
// ****************************************************************
// This is free software licensed under the NUnit license. You
// may obtain a copy of the license as well as information regarding
// copyright ownership at http://nunit.org/?p=license&r=2.4.
// ****************************************************************
using System;
using System.Text.RegularExpressions;
namespace NUnit.Framework.Tests
{
[TestFixture]
public class EqualsFixture : MessageChecker
{
[Test]
public void Equals()
{
string nunitString = "Hello NUnit";
string expected = nunitString;
string actual = nunitString;
Assert.IsTrue(expected == actual);
Assert.AreEqual(expected, actual);
}
[Test]
public void EqualsNull()
{
Assert.AreEqual(null, null);
}
[Test]
public void Bug575936Int32Int64Comparison()
{
long l64 = 0;
int i32 = 0;
Assert.AreEqual(i32, l64);
}
[Test]
public void IntegerLongComparison()
{
Assert.AreEqual(1, 1L);
Assert.AreEqual(1L, 1);
}
[Test]
public void IntegerEquals()
{
int val = 42;
Assert.AreEqual(val, 42);
}
[Test,ExpectedException(typeof(AssertionException))]
public void EqualsFail()
{
string junitString = "Goodbye JUnit";
string expected = "Hello NUnit";
expectedMessage =
" Expected string length 11 but was 13. Strings differ at index 0." + Environment.NewLine +
" Expected: \"Hello NUnit\"" + Environment.NewLine +
" But was: \"Goodbye JUnit\"" + Environment.NewLine +
" -----------^" + Environment.NewLine;
Assert.AreEqual(expected, junitString);
}
[Test,ExpectedException(typeof(AssertionException))]
public void EqualsNaNFails()
{
expectedMessage =
" Expected: 1.234d" + Environment.NewLine +
" But was: NaN" + Environment.NewLine;
Assert.AreEqual(1.234, Double.NaN, 0.0);
}
[Test]
[ExpectedException(typeof(AssertionException))]
public void NanEqualsFails()
{
expectedMessage =
" Expected: NaN" + Environment.NewLine +
" But was: 1.234d" + Environment.NewLine;
Assert.AreEqual(Double.NaN, 1.234, 0.0);
}
[Test]
public void NanEqualsNaNSucceeds()
{
Assert.AreEqual(Double.NaN, Double.NaN, 0.0);
}
[Test]
public void NegInfinityEqualsInfinity()
{
Assert.AreEqual(Double.NegativeInfinity, Double.NegativeInfinity, 0.0);
}
[Test]
public void PosInfinityEqualsInfinity()
{
Assert.AreEqual(Double.PositiveInfinity, Double.PositiveInfinity, 0.0);
}
[Test,ExpectedException(typeof(AssertionException))]
public void PosInfinityNotEquals()
{
expectedMessage =
" Expected: Infinity" + Environment.NewLine +
" But was: 1.23d" + Environment.NewLine;
Assert.AreEqual(Double.PositiveInfinity, 1.23, 0.0);
}
[Test,ExpectedException(typeof(AssertionException))]
public void PosInfinityNotEqualsNegInfinity()
{
expectedMessage =
" Expected: Infinity" + Environment.NewLine +
" But was: -Infinity" + Environment.NewLine;
Assert.AreEqual(Double.PositiveInfinity, Double.NegativeInfinity, 0.0);
}
[Test,ExpectedException(typeof(AssertionException))]
public void SinglePosInfinityNotEqualsNegInfinity()
{
expectedMessage =
" Expected: Infinity" + Environment.NewLine +
" But was: -Infinity" + Environment.NewLine;
Assert.AreEqual(float.PositiveInfinity, float.NegativeInfinity, (float)0.0);
}
[Test,ExpectedException(typeof(AssertionException))]
public void EqualsThrowsException()
{
object o = new object();
Assert.Equals(o, o);
}
[Test,ExpectedException(typeof(AssertionException))]
public void ReferenceEqualsThrowsException()
{
object o = new object();
Assert.ReferenceEquals(o, o);
}
[Test]
public void Float()
{
float val = (float)1.0;
float expected = val;
float actual = val;
Assert.IsTrue(expected == actual);
Assert.AreEqual(expected, actual, (float)0.0);
}
[Test]
public void Byte()
{
byte val = 1;
byte expected = val;
byte actual = val;
Assert.IsTrue(expected == actual);
Assert.AreEqual(expected, actual);
}
[Test]
public void String()
{
string s1 = "test";
string s2 = new System.Text.StringBuilder(s1).ToString();
Assert.IsTrue(s1.Equals(s2));
Assert.AreEqual(s1,s2);
}
[Test]
public void Short()
{
short val = 1;
short expected = val;
short actual = val;
Assert.IsTrue(expected == actual);
Assert.AreEqual(expected, actual);
}
[Test]
public void Int()
{
int val = 1;
int expected = val;
int actual = val;
Assert.IsTrue(expected == actual);
Assert.AreEqual(expected, actual);
}
[Test]
public void UInt()
{
uint val = 1;
uint expected = val;
uint actual = val;
Assert.IsTrue(expected == actual);
Assert.AreEqual(expected, actual);
}
[Test]
public void Decimal()
{
decimal expected = 100m;
decimal actual = 100.0m;
int integer = 100;
Assert.IsTrue( expected == actual );
Assert.AreEqual(expected, actual);
Assert.IsTrue(expected == integer);
Assert.AreEqual(expected, integer);
Assert.IsTrue(actual == integer);
Assert.AreEqual(actual, integer);
}
/// <summary>
/// Checks to see that a value comparison works with all types.
/// Current version has problems when value is the same but the
/// types are different...C# is not like Java, and doesn't automatically
/// perform value type conversion to simplify this type of comparison.
///
/// Related to Bug575936Int32Int64Comparison, but covers all numeric
/// types.
/// </summary>
[Test]
public void EqualsSameTypes()
{
byte b1 = 35;
sbyte sb2 = 35;
decimal d4 = 35;
double d5 = 35;
float f6 = 35;
int i7 = 35;
uint u8 = 35;
long l9 = 35;
short s10 = 35;
ushort us11 = 35;
System.Byte b12 = 35;
System.SByte sb13 = 35;
System.Decimal d14 = 35;
System.Double d15 = 35;
System.Single s16 = 35;
System.Int32 i17 = 35;
System.UInt32 ui18 = 35;
System.Int64 i19 = 35;
System.UInt64 ui20 = 35;
System.Int16 i21 = 35;
System.UInt16 i22 = 35;
Assert.AreEqual( 35, b1 );
Assert.AreEqual( 35, sb2 );
Assert.AreEqual( 35, d4 );
Assert.AreEqual( 35, d5 );
Assert.AreEqual( 35, f6 );
Assert.AreEqual( 35, i7 );
Assert.AreEqual( 35, u8 );
Assert.AreEqual( 35, l9 );
Assert.AreEqual( 35, s10 );
Assert.AreEqual( 35, us11 );
Assert.AreEqual( 35, b12 );
Assert.AreEqual( 35, sb13 );
Assert.AreEqual( 35, d14 );
Assert.AreEqual( 35, d15 );
Assert.AreEqual( 35, s16 );
Assert.AreEqual( 35, i17 );
Assert.AreEqual( 35, ui18 );
Assert.AreEqual( 35, i19 );
Assert.AreEqual( 35, ui20 );
Assert.AreEqual( 35, i21 );
Assert.AreEqual( 35, i22 );
}
[Test]
public void EnumsEqual()
{
MyEnum actual = MyEnum.a;
Assert.AreEqual( MyEnum.a, actual );
}
[Test, ExpectedException( typeof(AssertionException) )]
public void EnumsNotEqual()
{
MyEnum actual = MyEnum.a;
expectedMessage =
" Expected: c" + Environment.NewLine +
" But was: a" + Environment.NewLine;
Assert.AreEqual( MyEnum.c, actual );
}
[Test]
public void DateTimeEqual()
{
DateTime dt1 = new DateTime( 2005, 6, 1, 7, 0, 0 );
DateTime dt2 = new DateTime( 2005, 6, 1, 0, 0, 0 ) + TimeSpan.FromHours( 7.0 );
Assert.AreEqual( dt1, dt2 );
}
[Test, ExpectedException( typeof (AssertionException) )]
public void DateTimeNotEqual()
{
DateTime dt1 = new DateTime( 2005, 6, 1, 7, 0, 0 );
DateTime dt2 = new DateTime( 2005, 6, 1, 0, 0, 0 );
expectedMessage = string.Format(
" Expected: {0}" + Environment.NewLine +
" But was: {1}" + Environment.NewLine, dt1, dt2);
Assert.AreEqual(dt1, dt2);
}
private enum MyEnum
{
a, b, c
}
[Test]
public void DoubleNotEqualMessageDisplaysAllDigits()
{
string message = "";
try
{
double d1 = 36.1;
double d2 = 36.099999999999994;
Assert.AreEqual( d1, d2 );
}
catch(AssertionException ex)
{
message = ex.Message;
}
if ( message == "" )
Assert.Fail( "Should have thrown an AssertionException" );
int i = message.IndexOf('3');
int j = message.IndexOf( 'd', i );
string expected = message.Substring( i, j - i + 1 );
i = message.IndexOf( '3', j );
j = message.IndexOf( 'd', i );
string actual = message.Substring( i , j - i + 1 );
Assert.AreNotEqual( expected, actual );
}
[Test]
public void FloatNotEqualMessageDisplaysAllDigits()
{
string message = "";
try
{
float f1 = 36.125F;
float f2 = 36.125004F;
Assert.AreEqual( f1, f2 );
}
catch(AssertionException ex)
{
message = ex.Message;
}
if ( message == "" )
Assert.Fail( "Should have thrown an AssertionException" );
int i = message.IndexOf( '3' );
int j = message.IndexOf( 'f', i );
string expected = message.Substring( i, j - i + 1 );
i = message.IndexOf( '3', j );
j = message.IndexOf( 'f', i );
string actual = message.Substring( i, j - i + 1 );
Assert.AreNotEqual( expected, actual );
}
[Test]
public void DoubleNotEqualMessageDisplaysTolerance()
{
string message = "";
try
{
double d1 = 0.15;
double d2 = 0.12;
double tol = 0.005;
Assert.AreEqual( d1, d2, tol );
}
catch( AssertionException ex )
{
message = ex.Message;
}
if ( message == "" )
Assert.Fail( "Should have thrown an AssertionException" );
StringAssert.Contains( "+/- 0.005", message );
}
[Test]
public void FloatNotEqualMessageDisplaysTolerance()
{
string message = "";
try
{
float f1 = 0.15F;
float f2 = 0.12F;
float tol = 0.001F;
Assert.AreEqual( f1, f2, tol );
}
catch( AssertionException ex )
{
message = ex.Message;
}
if ( message == "" )
Assert.Fail( "Should have thrown an AssertionException" );
StringAssert.Contains( "+/- 0.001", message );
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Web.Http;
using Swank.Description;
namespace TestHarness.Default
{
public class AnotherController : ApiController
{
[Comments("Type comments. Raw denim aesthetic synth nesciunt. :trollface:")]
public class Model
{
[Comments("Member comments. Raw denim aesthetic synth nesciunt. :trollface:")]
public string Value { get; set; }
[Comments("Member comments. Raw denim aesthetic synth nesciunt. :trollface:")]
[DefaultValue("fark")]
public string DefaultValue { get; set; }
[Comments("Member comments. Raw denim aesthetic synth nesciunt. :trollface:")]
public Options OptionValue { get; set; }
[Comments("Member comments. Raw denim aesthetic synth nesciunt. :trollface:")]
[Obsolete("Obsolete comments. Raw denim aesthetic synth nesciunt. :trollface:")]
public string DepricatedValue { get; set; }
[Comments("Member comments. Raw denim aesthetic synth nesciunt. :trollface:")]
public int NumericValue { get; set; }
[Comments("Member comments. Raw denim aesthetic synth nesciunt. :trollface:")]
public bool BooleanValue { get; set; }
[Comments("Member comments. Raw denim aesthetic synth nesciunt. :trollface:")]
public DateTime DateValue { get; set; }
[Comments("Member comments. Raw denim aesthetic synth nesciunt. :trollface:")]
public TimeSpan DurationValue { get; set; }
[Comments("Member comments. Raw denim aesthetic synth nesciunt. :trollface:")]
public Guid GuidValue { get; set; }
[Comments("Member comments. Raw denim aesthetic synth nesciunt. :trollface:")]
public ChildModel ComplexValue { get; set; }
[Comments("Member comments. Raw denim aesthetic synth nesciunt. :trollface:")]
public List<int> SimpleList { get; set; }
[Comments("Member comments. Raw denim aesthetic synth nesciunt. :trollface:")]
public List<ChildModel> ComplexList { get; set; }
[Comments("Member comments. Raw denim aesthetic synth nesciunt. :trollface:")]
public List<List<ChildModel>> ListOfList { get; set; }
[Comments("Member comments. Raw denim aesthetic synth nesciunt. :trollface:")]
public List<Dictionary<string, ChildModel>> ListOfDictionary { get; set; }
[Comments("Member comments. Raw denim aesthetic synth nesciunt. :trollface:")]
[DictionaryDescription(comments: "Dictionary comments. Raw denim aesthetic synth nesciunt. :trollface:",
keyName: "key-name", keyComments: "Key comments. Raw denim aesthetic synth nesciunt. :trollface:",
valueComments: "Value comments. Raw denim aesthetic synth nesciunt. :trollface:")]
public Dictionary<string, int> SimpleTypeDictionary { get; set; }
[Comments("Member comments. Raw denim aesthetic synth nesciunt. :trollface:")]
[DictionaryDescription(comments: "Dictionary comments. Raw denim aesthetic synth nesciunt. :trollface:",
keyName: "key-name", keyComments: "Key comments. Raw denim aesthetic synth nesciunt. :trollface:",
valueComments: "Value comments. Raw denim aesthetic synth nesciunt. :trollface:")]
public Dictionary<string, ChildModel> ComplexTypeDictionary { get; set; }
[Comments("Member comments. Raw denim aesthetic synth nesciunt. :trollface:")]
[DictionaryDescription(comments: "Dictionary comments. Raw denim aesthetic synth nesciunt. :trollface:",
keyName: "key-name", keyComments: "Key comments. Raw denim aesthetic synth nesciunt. :trollface:",
valueComments: "Value comments. Raw denim aesthetic synth nesciunt. :trollface:")]
public Dictionary<Options, Options> OptionsDictionary { get; set; }
[Comments("Member comments. Raw denim aesthetic synth nesciunt. :trollface:")]
[DictionaryDescription(comments: "Dictionary comments. Raw denim aesthetic synth nesciunt. :trollface:",
keyName: "key-name", keyComments: "Key comments. Raw denim aesthetic synth nesciunt. :trollface:",
valueComments: "Value comments. Raw denim aesthetic synth nesciunt. :trollface:")]
public Dictionary<Options, List<ChildModel>> DictionaryOfLists { get; set; }
[Comments("Member comments. Raw denim aesthetic synth nesciunt. :trollface:")]
[DictionaryDescription(comments: "Dictionary comments. Raw denim aesthetic synth nesciunt. :trollface:",
keyName: "key-name", keyComments: "Key comments. Raw denim aesthetic synth nesciunt. :trollface:",
valueComments: "Value comments. Raw denim aesthetic synth nesciunt. :trollface:")]
public Dictionary<Options, Dictionary<string, ChildModel>> DictionaryOfDictionaries { get; set; }
}
[Comments("Type comments. Raw denim aesthetic synth nesciunt. :trollface:")]
public class ChildModel
{
[Comments("Member comments. Raw denim aesthetic synth nesciunt. :trollface:")]
public string Value { get; set; }
[Comments("Member comments. Raw denim aesthetic synth nesciunt. :trollface:")]
public int NumericValue { get; set; }
[Comments("Member comments. Raw denim aesthetic synth nesciunt. :trollface:")]
public bool BooleanValue { get; set; }
[Comments("Member comments. Raw denim aesthetic synth nesciunt. :trollface:")]
public DateTime DateValue { get; set; }
[Comments("Member comments. Raw denim aesthetic synth nesciunt. :trollface:")]
public TimeSpan DurationValue { get; set; }
[Comments("Member comments. Raw denim aesthetic synth nesciunt. :trollface:")]
public Guid GuidValue { get; set; }
}
[Comments("Enum comments. Raw denim aesthetic synth nesciunt. :trollface:")]
public enum Options
{
[Comments("Enum option 1 comments. Raw denim aesthetic synth nesciunt. :trollface:")]
Option1,
[Comments("Enum option 2 comments. Raw denim aesthetic synth nesciunt. :trollface:")]
Option2
}
[Secure]
[Route("another/controller/{id}/{option}")]
[Description("Endpoint Name", "Endpoint remarks. Anim pariatur cliche reprehenderit. :trollface:")]
[RequestHeader("request-header-1", "Request header 1. You probably haven't heard of them. :trollface:")]
[RequestHeader("request-header-2", "Request header 2. Leggings occaecat craft beer farm-to-table. :trollface:", true)]
[ResponseHeader("response-header-1", "Response header 1. Vegan excepteur butcher vice lomo. :trollface:")]
[ResponseHeader("response-header-2", "Response header 2. Raw denim aesthetic synth nesciunt. :trollface:")]
[StatusCode(HttpStatusCode.Created, "Status code 1. Vegan excepteur butcher vice lomo. :trollface:")]
[StatusCode(HttpStatusCode.BadGateway, "Status code 2. Raw denim aesthetic synth nesciunt. :trollface:")]
[ResponseComments("Response description. Raw denim aesthetic synth nesciunt. :trollface:")]
public Model Get(
[Comments("Request parameter. Vegan excepteur butcher vice lomo. :trollface:")] Model model,
[Comments("Url parameter 1. Enim eiusmod high life accusamus. :trollface:")] Guid id,
[Comments("Option url parameter 2. 3 wolf moon officia aute sunt aliqua. :trollface:")] Options option,
[Comments("Required, options query string 1. Leggings occaecat craft beer farm-to-table. :trollface:"), Required] Options requiredOption,
[Comments("Required, multiple querystring 2. Leggings occaecat craft beer farm-to-table. :trollface:"), Required, Multiple] int requiredMultiple,
[Comments("Optional, default querystring 3. Raw denim aesthetic synth nesciunt. :trollface:"), DefaultValue(5)] int? optionalDefault = null)
{
return null;
}
[Secure]
[Route("another/controller/{id}/{option}")]
[Description("Endpoint Name", "Endpoint remarks. Anim pariatur cliche reprehenderit. :trollface:")]
[RequestHeader("request-header-1", "Request header 1. You probably haven't heard of them. :trollface:")]
[RequestHeader("request-header-2", "Request header 2. Leggings occaecat craft beer farm-to-table. :trollface:", true)]
[ResponseHeader("response-header-1", "Response header 1. Vegan excepteur butcher vice lomo. :trollface:")]
[ResponseHeader("response-header-2", "Response header 2. Raw denim aesthetic synth nesciunt. :trollface:")]
[StatusCode(HttpStatusCode.Created, "Status code 1. Vegan excepteur butcher vice lomo. :trollface:")]
[StatusCode(HttpStatusCode.BadGateway, "Status code 2. Raw denim aesthetic synth nesciunt. :trollface:")]
[ResponseComments("Response description. Raw denim aesthetic synth nesciunt. :trollface:")]
public Model Post(
[Comments("Request parameter. Vegan excepteur butcher vice lomo. :trollface:")] Model model,
[Comments("Url parameter 1. Enim eiusmod high life accusamus. :trollface:")] Guid id,
[Comments("Option url parameter 2. 3 wolf moon officia aute sunt aliqua. :trollface:")] Options option,
[Comments("Required, options query string 1. Leggings occaecat craft beer farm-to-table. :trollface:"), Required] Options requiredOption,
[Comments("Required, multiple querystring 2. Leggings occaecat craft beer farm-to-table. :trollface:"), Required, Multiple] int requiredMultiple,
[Comments("Optional, default querystring 3. Raw denim aesthetic synth nesciunt. :trollface:"), DefaultValue(5)] int? optionalDefault = null)
{
return null;
}
[Secure]
[Route("another/controller/{id}/{option}")]
[Description("Endpoint Name", "Endpoint remarks. Anim pariatur cliche reprehenderit. :trollface:")]
[RequestHeader("request-header-1", "Request header 1. You probably haven't heard of them. :trollface:")]
[RequestHeader("request-header-2", "Request header 2. Leggings occaecat craft beer farm-to-table. :trollface:", true)]
[ResponseHeader("response-header-1", "Response header 1. Vegan excepteur butcher vice lomo. :trollface:")]
[ResponseHeader("response-header-2", "Response header 2. Raw denim aesthetic synth nesciunt. :trollface:")]
[StatusCode(HttpStatusCode.Created, "Status code 1. Vegan excepteur butcher vice lomo. :trollface:")]
[StatusCode(HttpStatusCode.BadGateway, "Status code 2. Raw denim aesthetic synth nesciunt. :trollface:")]
[ResponseComments("Response description. Raw denim aesthetic synth nesciunt. :trollface:")]
public Model Put(
[Comments("Request parameter. Vegan excepteur butcher vice lomo. :trollface:")] Model model,
[Comments("Url parameter 1. Enim eiusmod high life accusamus. :trollface:")] Guid id,
[Comments("Option url parameter 2. 3 wolf moon officia aute sunt aliqua. :trollface:")] Options option,
[Comments("Required, options query string 1. Leggings occaecat craft beer farm-to-table. :trollface:"), Required] Options requiredOption,
[Comments("Required, multiple querystring 2. Leggings occaecat craft beer farm-to-table. :trollface:"), Required, Multiple] int requiredMultiple,
[Comments("Optional, default querystring 3. Raw denim aesthetic synth nesciunt. :trollface:"), DefaultValue(5)] int? optionalDefault = null)
{
return null;
}
[Secure]
[Route("another/controller/{id}/{option}")]
[Description("Endpoint Name", "Endpoint remarks. Anim pariatur cliche reprehenderit. :trollface:")]
[RequestHeader("request-header-1", "Request header 1. You probably haven't heard of them. :trollface:")]
[RequestHeader("request-header-2", "Request header 2. Leggings occaecat craft beer farm-to-table. :trollface:", true)]
[ResponseHeader("response-header-1", "Response header 1. Vegan excepteur butcher vice lomo. :trollface:")]
[ResponseHeader("response-header-2", "Response header 2. Raw denim aesthetic synth nesciunt. :trollface:")]
[StatusCode(HttpStatusCode.Created, "Status code 1. Vegan excepteur butcher vice lomo. :trollface:")]
[StatusCode(HttpStatusCode.BadGateway, "Status code 2. Raw denim aesthetic synth nesciunt. :trollface:")]
[ResponseComments("Response description. Raw denim aesthetic synth nesciunt. :trollface:")]
public void Delete(
[Comments("Request parameter. Vegan excepteur butcher vice lomo. :trollface:")] Model model,
[Comments("Url parameter 1. Enim eiusmod high life accusamus. :trollface:")] Guid id,
[Comments("Option url parameter 2. 3 wolf moon officia aute sunt aliqua. :trollface:")] Options option,
[Comments("Required, options query string 1. Leggings occaecat craft beer farm-to-table. :trollface:"), Required] Options requiredOption,
[Comments("Required, multiple querystring 2. Leggings occaecat craft beer farm-to-table. :trollface:"), Required, Multiple] int requiredMultiple,
[Comments("Optional, default querystring 3. Raw denim aesthetic synth nesciunt. :trollface:"), DefaultValue(5)] int? optionalDefault = null)
{
}
[BinaryRequest, BinaryResponse]
[Route("another/controller/file/{*filename}")]
public Stream PostFile(string filename, Stream stream)
{
return null;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.