context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.Extensions.Logging;
using CPV.Models;
using CPV.Models.AccountViewModels;
using CPV.Services;
namespace CPV.Controllers
{
[Authorize]
public class AccountController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly IEmailSender _emailSender;
private readonly ISmsSender _smsSender;
private readonly ILogger _logger;
public AccountController(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
IEmailSender emailSender,
ISmsSender smsSender,
ILoggerFactory loggerFactory)
{
_userManager = userManager;
_signInManager = signInManager;
_emailSender = emailSender;
_smsSender = smsSender;
_logger = loggerFactory.CreateLogger<AccountController>();
}
//
// GET: /Account/Login
[HttpGet]
[AllowAnonymous]
public IActionResult Login(string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
return View();
}
//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
if (ModelState.IsValid)
{
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, set lockoutOnFailure: true
var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
_logger.LogInformation(1, "User logged in.");
return RedirectToLocal(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
}
if (result.IsLockedOut)
{
_logger.LogWarning(2, "User account locked out.");
return View("Lockout");
}
else
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return View(model);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// GET: /Account/Register
[HttpGet]
[AllowAnonymous]
public IActionResult Register(string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
return View();
}
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
// For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713
// Send an email with this link
//var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
//var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
//await _emailSender.SendEmailAsync(model.Email, "Confirm your account",
// $"Please confirm your account by clicking this link: <a href='{callbackUrl}'>link</a>");
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(3, "User created a new account with password.");
return RedirectToLocal(returnUrl);
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// POST: /Account/LogOff
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> LogOff()
{
await _signInManager.SignOutAsync();
_logger.LogInformation(4, "User logged out.");
return RedirectToAction(nameof(HomeController.Index), "Home");
}
//
// POST: /Account/ExternalLogin
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public IActionResult ExternalLogin(string provider, string returnUrl = null)
{
// Request a redirect to the external login provider.
var redirectUrl = Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl });
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
return Challenge(properties, provider);
}
//
// GET: /Account/ExternalLoginCallback
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
{
if (remoteError != null)
{
ModelState.AddModelError(string.Empty, $"Error from external provider: {remoteError}");
return View(nameof(Login));
}
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
return RedirectToAction(nameof(Login));
}
// Sign in the user with this external login provider if the user already has a login.
var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false);
if (result.Succeeded)
{
_logger.LogInformation(5, "User logged in with {Name} provider.", info.LoginProvider);
return RedirectToLocal(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl });
}
if (result.IsLockedOut)
{
return View("Lockout");
}
else
{
// If the user does not have an account, then ask the user to create an account.
ViewData["ReturnUrl"] = returnUrl;
ViewData["LoginProvider"] = info.LoginProvider;
var email = info.Principal.FindFirstValue(ClaimTypes.Email);
return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = email });
}
}
//
// POST: /Account/ExternalLoginConfirmation
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl = null)
{
if (ModelState.IsValid)
{
// Get the information about the user from the external login provider
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
return View("ExternalLoginFailure");
}
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await _userManager.CreateAsync(user);
if (result.Succeeded)
{
result = await _userManager.AddLoginAsync(user, info);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(6, "User created an account using {Name} provider.", info.LoginProvider);
return RedirectToLocal(returnUrl);
}
}
AddErrors(result);
}
ViewData["ReturnUrl"] = returnUrl;
return View(model);
}
// GET: /Account/ConfirmEmail
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> ConfirmEmail(string userId, string code)
{
if (userId == null || code == null)
{
return View("Error");
}
var user = await _userManager.FindByIdAsync(userId);
if (user == null)
{
return View("Error");
}
var result = await _userManager.ConfirmEmailAsync(user, code);
return View(result.Succeeded ? "ConfirmEmail" : "Error");
}
//
// GET: /Account/ForgotPassword
[HttpGet]
[AllowAnonymous]
public IActionResult ForgotPassword()
{
return View();
}
//
// POST: /Account/ForgotPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ForgotPassword(ForgotPasswordViewModel model)
{
if (ModelState.IsValid)
{
var user = await _userManager.FindByNameAsync(model.Email);
if (user == null || !(await _userManager.IsEmailConfirmedAsync(user)))
{
// Don't reveal that the user does not exist or is not confirmed
return View("ForgotPasswordConfirmation");
}
// For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713
// Send an email with this link
//var code = await _userManager.GeneratePasswordResetTokenAsync(user);
//var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
//await _emailSender.SendEmailAsync(model.Email, "Reset Password",
// $"Please reset your password by clicking here: <a href='{callbackUrl}'>link</a>");
//return View("ForgotPasswordConfirmation");
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// GET: /Account/ForgotPasswordConfirmation
[HttpGet]
[AllowAnonymous]
public IActionResult ForgotPasswordConfirmation()
{
return View();
}
//
// GET: /Account/ResetPassword
[HttpGet]
[AllowAnonymous]
public IActionResult ResetPassword(string code = null)
{
return code == null ? View("Error") : View();
}
//
// POST: /Account/ResetPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ResetPassword(ResetPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await _userManager.FindByNameAsync(model.Email);
if (user == null)
{
// Don't reveal that the user does not exist
return RedirectToAction(nameof(AccountController.ResetPasswordConfirmation), "Account");
}
var result = await _userManager.ResetPasswordAsync(user, model.Code, model.Password);
if (result.Succeeded)
{
return RedirectToAction(nameof(AccountController.ResetPasswordConfirmation), "Account");
}
AddErrors(result);
return View();
}
//
// GET: /Account/ResetPasswordConfirmation
[HttpGet]
[AllowAnonymous]
public IActionResult ResetPasswordConfirmation()
{
return View();
}
//
// GET: /Account/SendCode
[HttpGet]
[AllowAnonymous]
public async Task<ActionResult> SendCode(string returnUrl = null, bool rememberMe = false)
{
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return View("Error");
}
var userFactors = await _userManager.GetValidTwoFactorProvidersAsync(user);
var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList();
return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
//
// POST: /Account/SendCode
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SendCode(SendCodeViewModel model)
{
if (!ModelState.IsValid)
{
return View();
}
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return View("Error");
}
// Generate the token and send it
var code = await _userManager.GenerateTwoFactorTokenAsync(user, model.SelectedProvider);
if (string.IsNullOrWhiteSpace(code))
{
return View("Error");
}
var message = "Your security code is: " + code;
if (model.SelectedProvider == "Email")
{
await _emailSender.SendEmailAsync(await _userManager.GetEmailAsync(user), "Security Code", message);
}
else if (model.SelectedProvider == "Phone")
{
await _smsSender.SendSmsAsync(await _userManager.GetPhoneNumberAsync(user), message);
}
return RedirectToAction(nameof(VerifyCode), new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe });
}
//
// GET: /Account/VerifyCode
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> VerifyCode(string provider, bool rememberMe, string returnUrl = null)
{
// Require that the user has already logged in via username/password or external login
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return View("Error");
}
return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
//
// POST: /Account/VerifyCode
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> VerifyCode(VerifyCodeViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// The following code protects for brute force attacks against the two factor codes.
// If a user enters incorrect codes for a specified amount of time then the user account
// will be locked out for a specified amount of time.
var result = await _signInManager.TwoFactorSignInAsync(model.Provider, model.Code, model.RememberMe, model.RememberBrowser);
if (result.Succeeded)
{
return RedirectToLocal(model.ReturnUrl);
}
if (result.IsLockedOut)
{
_logger.LogWarning(7, "User account locked out.");
return View("Lockout");
}
else
{
ModelState.AddModelError(string.Empty, "Invalid code.");
return View(model);
}
}
#region Helpers
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
private Task<ApplicationUser> GetCurrentUserAsync()
{
return _userManager.GetUserAsync(HttpContext.User);
}
private IActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction(nameof(HomeController.Index), "Home");
}
}
#endregion
}
}
| |
// ****************************************************************
// Copyright 2009, Charlie Poole
// This is free software licensed under the NUnit license. You may
// obtain a copy of the license at http://nunit.org
// ****************************************************************
// ****************************************************************
// Generated by the NUnit Syntax Generator
//
// Command Line: GenSyntax.exe SyntaxElements.txt
//
// DO NOT MODIFY THIS FILE DIRECTLY
// ****************************************************************
using System;
using System.Collections;
using NAssert.Constraints;
namespace NAssert
{
/// <summary>
/// Helper class with properties and methods that supply
/// a number of constraints used in Asserts.
/// </summary>
public class Is
{
#region Not
/// <summary>
/// Returns a ConstraintExpression that negates any
/// following constraint.
/// </summary>
public static ConstraintExpression Not
{
get { return new ConstraintExpression().Not; }
}
#endregion
#region All
/// <summary>
/// Returns a ConstraintExpression, which will apply
/// the following constraint to all members of a collection,
/// succeeding if all of them succeed.
/// </summary>
public static ConstraintExpression All
{
get { return new ConstraintExpression().All; }
}
#endregion
#region Null
/// <summary>
/// Returns a constraint that tests for null
/// </summary>
public static NullConstraint Null
{
get { return new NullConstraint(); }
}
#endregion
#region True
/// <summary>
/// Returns a constraint that tests for True
/// </summary>
public static TrueConstraint True
{
get { return new TrueConstraint(); }
}
#endregion
#region False
/// <summary>
/// Returns a constraint that tests for False
/// </summary>
public static FalseConstraint False
{
get { return new FalseConstraint(); }
}
#endregion
#region NaN
/// <summary>
/// Returns a constraint that tests for NaN
/// </summary>
public static NaNConstraint NaN
{
get { return new NaNConstraint(); }
}
#endregion
#region Empty
/// <summary>
/// Returns a constraint that tests for empty
/// </summary>
public static EmptyConstraint Empty
{
get { return new EmptyConstraint(); }
}
#endregion
#region Unique
/// <summary>
/// Returns a constraint that tests whether a collection
/// contains all unique items.
/// </summary>
public static UniqueItemsConstraint Unique
{
get { return new UniqueItemsConstraint(); }
}
#endregion
#region BinarySerializable
/// <summary>
/// Returns a constraint that tests whether an object graph is serializable in binary format.
/// </summary>
public static BinarySerializableConstraint BinarySerializable
{
get { return new BinarySerializableConstraint(); }
}
#endregion
#region XmlSerializable
/// <summary>
/// Returns a constraint that tests whether an object graph is serializable in xml format.
/// </summary>
public static XmlSerializableConstraint XmlSerializable
{
get { return new XmlSerializableConstraint(); }
}
#endregion
#region EqualTo
/// <summary>
/// Returns a constraint that tests two items for equality
/// </summary>
public static EqualConstraint EqualTo(object expected)
{
return new EqualConstraint(expected);
}
#endregion
#region SameAs
/// <summary>
/// Returns a constraint that tests that two references are the same object
/// </summary>
public static SameAsConstraint SameAs(object expected)
{
return new SameAsConstraint(expected);
}
#endregion
#region GreaterThan
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is greater than the suppled argument
/// </summary>
public static GreaterThanConstraint GreaterThan(object expected)
{
return new GreaterThanConstraint(expected);
}
#endregion
#region GreaterThanOrEqualTo
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is greater than or equal to the suppled argument
/// </summary>
public static GreaterThanOrEqualConstraint GreaterThanOrEqualTo(object expected)
{
return new GreaterThanOrEqualConstraint(expected);
}
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is greater than or equal to the suppled argument
/// </summary>
public static GreaterThanOrEqualConstraint AtLeast(object expected)
{
return new GreaterThanOrEqualConstraint(expected);
}
#endregion
#region LessThan
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is less than the suppled argument
/// </summary>
public static LessThanConstraint LessThan(object expected)
{
return new LessThanConstraint(expected);
}
#endregion
#region LessThanOrEqualTo
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is less than or equal to the suppled argument
/// </summary>
public static LessThanOrEqualConstraint LessThanOrEqualTo(object expected)
{
return new LessThanOrEqualConstraint(expected);
}
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is less than or equal to the suppled argument
/// </summary>
public static LessThanOrEqualConstraint AtMost(object expected)
{
return new LessThanOrEqualConstraint(expected);
}
#endregion
#region TypeOf
/// <summary>
/// Returns a constraint that tests whether the actual
/// value is of the exact type supplied as an argument.
/// </summary>
public static ExactTypeConstraint TypeOf(Type expectedType)
{
return new ExactTypeConstraint(expectedType);
}
#if NET_2_0
/// <summary>
/// Returns a constraint that tests whether the actual
/// value is of the exact type supplied as an argument.
/// </summary>
public static ExactTypeConstraint TypeOf<T>()
{
return new ExactTypeConstraint(typeof(T));
}
#endif
#endregion
#region InstanceOf
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is of the type supplied as an argument or a derived type.
/// </summary>
public static InstanceOfTypeConstraint InstanceOf(Type expectedType)
{
return new InstanceOfTypeConstraint(expectedType);
}
#if NET_2_0
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is of the type supplied as an argument or a derived type.
/// </summary>
public static InstanceOfTypeConstraint InstanceOf<T>()
{
return new InstanceOfTypeConstraint(typeof(T));
}
#endif
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is of the type supplied as an argument or a derived type.
/// </summary>
[Obsolete("Use InstanceOf(expectedType)")]
public static InstanceOfTypeConstraint InstanceOfType(Type expectedType)
{
return new InstanceOfTypeConstraint(expectedType);
}
#if NET_2_0
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is of the type supplied as an argument or a derived type.
/// </summary>
[Obsolete("Use InstanceOf<T>()")]
public static InstanceOfTypeConstraint InstanceOfType<T>()
{
return new InstanceOfTypeConstraint(typeof(T));
}
#endif
#endregion
#region AssignableFrom
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is assignable from the type supplied as an argument.
/// </summary>
public static AssignableFromConstraint AssignableFrom(Type expectedType)
{
return new AssignableFromConstraint(expectedType);
}
#if NET_2_0
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is assignable from the type supplied as an argument.
/// </summary>
public static AssignableFromConstraint AssignableFrom<T>()
{
return new AssignableFromConstraint(typeof(T));
}
#endif
#endregion
#region AssignableTo
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is assignable from the type supplied as an argument.
/// </summary>
public static AssignableToConstraint AssignableTo(Type expectedType)
{
return new AssignableToConstraint(expectedType);
}
#if NET_2_0
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is assignable from the type supplied as an argument.
/// </summary>
public static AssignableToConstraint AssignableTo<T>()
{
return new AssignableToConstraint(typeof(T));
}
#endif
#endregion
#region EquivalentTo
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is a collection containing the same elements as the
/// collection supplied as an argument.
/// </summary>
public static CollectionEquivalentConstraint EquivalentTo(IEnumerable expected)
{
return new CollectionEquivalentConstraint(expected);
}
#endregion
#region SubsetOf
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is a subset of the collection supplied as an argument.
/// </summary>
public static CollectionSubsetConstraint SubsetOf(IEnumerable expected)
{
return new CollectionSubsetConstraint(expected);
}
#endregion
#region Ordered
/// <summary>
/// Returns a constraint that tests whether a collection is ordered
/// </summary>
public static CollectionOrderedConstraint Ordered
{
get { return new CollectionOrderedConstraint(); }
}
#endregion
#region StringContaining
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value contains the substring supplied as an argument.
/// </summary>
public static SubstringConstraint StringContaining(string expected)
{
return new SubstringConstraint(expected);
}
#endregion
#region StringStarting
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value starts with the substring supplied as an argument.
/// </summary>
public static StartsWithConstraint StringStarting(string expected)
{
return new StartsWithConstraint(expected);
}
#endregion
#region StringEnding
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value ends with the substring supplied as an argument.
/// </summary>
public static EndsWithConstraint StringEnding(string expected)
{
return new EndsWithConstraint(expected);
}
#endregion
#region StringMatching
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value matches the Regex pattern supplied as an argument.
/// </summary>
public static RegexConstraint StringMatching(string pattern)
{
return new RegexConstraint(pattern);
}
#endregion
#region SamePath
/// <summary>
/// Returns a constraint that tests whether the path provided
/// is the same as an expected path after canonicalization.
/// </summary>
public static SamePathConstraint SamePath(string expected)
{
return new SamePathConstraint(expected);
}
#endregion
#region SubPath
/// <summary>
/// Returns a constraint that tests whether the path provided
/// is the same path or under an expected path after canonicalization.
/// </summary>
public static SubPathConstraint SubPath(string expected)
{
return new SubPathConstraint(expected);
}
#endregion
#region SamePathOrUnder
/// <summary>
/// Returns a constraint that tests whether the path provided
/// is the same path or under an expected path after canonicalization.
/// </summary>
public static SamePathOrUnderConstraint SamePathOrUnder(string expected)
{
return new SamePathOrUnderConstraint(expected);
}
#endregion
#region InRange
/// <summary>
/// Returns a constraint that tests whether the actual value falls
/// within a specified range.
/// </summary>
public static RangeConstraint InRange(IComparable from, IComparable to)
{
return new RangeConstraint(from, to);
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.CoreModules
{
public class SunModule : ISunModule
{
/// <summary>
/// Note: Sun Hour can be a little deceaving. Although it's based on a 24 hour clock
/// it is not based on ~06:00 == Sun Rise. Rather it is based on 00:00 being sun-rise.
/// </summary>
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
//
// Global Constants used to determine where in the sky the sun is
//
private const double m_SeasonalTilt = 0.03 * Math.PI; // A daily shift of approximately 1.7188 degrees
private const double m_AverageTilt = -0.25 * Math.PI; // A 45 degree tilt
private const double m_SunCycle = 2.0D * Math.PI; // A perfect circle measured in radians
private const double m_SeasonalCycle = 2.0D * Math.PI; // Ditto
//
// Per Region Values
//
private bool ready = false;
// This solves a chick before the egg problem
// the local SunFixedHour and SunFixed variables MUST be updated
// at least once with the proper Region Settings before we start
// updating those region settings in GenSunPos()
private bool receivedEstateToolsSunUpdate = false;
// Configurable values
private string m_RegionMode = "SL";
// Sun's position information is updated and sent to clients every m_UpdateInterval frames
private int m_UpdateInterval = 0;
// Number of real time hours per virtual day
private double m_DayLengthHours = 0;
// Number of virtual days to a virtual year
private int m_YearLengthDays = 0;
// Ratio of Daylight hours to Night time hours. This is accomplished by shifting the
// sun's orbit above the horizon
private double m_HorizonShift = 0;
// Used to scale current and positional time to adjust length of an hour during day vs night.
private double m_DayTimeSunHourScale;
// private double m_longitude = 0;
// private double m_latitude = 0;
// Configurable defaults Defaults close to SL
private string d_mode = "SL";
private int d_frame_mod = 100; // Every 10 seconds (actually less)
private double d_day_length = 4; // A VW day is 4 RW hours long
private int d_year_length = 60; // There are 60 VW days in a VW year
private double d_day_night = 0.5; // axis offset: Default Hoizon shift to try and closely match the sun model in LL Viewer
private double d_DayTimeSunHourScale = 0.5; // Day/Night hours are equal
// private double d_longitude = -73.53;
// private double d_latitude = 41.29;
// Frame counter
private uint m_frame = 0;
// Cached Scene reference
private Scene m_scene = null;
// Calculated Once in the lifetime of a region
private long TicksToEpoch; // Elapsed time for 1/1/1970
private uint SecondsPerSunCycle; // Length of a virtual day in RW seconds
private uint SecondsPerYear; // Length of a virtual year in RW seconds
private double SunSpeed; // Rate of passage in radians/second
private double SeasonSpeed; // Rate of change for seasonal effects
// private double HoursToRadians; // Rate of change for seasonal effects
private long TicksUTCOffset = 0; // seconds offset from UTC
// Calculated every update
private float OrbitalPosition; // Orbital placement at a point in time
private double HorizonShift; // Axis offset to skew day and night
private double TotalDistanceTravelled; // Distance since beginning of time (in radians)
private double SeasonalOffset; // Seaonal variation of tilt
private float Magnitude; // Normal tilt
// private double VWTimeRatio; // VW time as a ratio of real time
// Working values
private Vector3 Position = Vector3.Zero;
private Vector3 Velocity = Vector3.Zero;
private Quaternion Tilt = new Quaternion(1.0f, 0.0f, 0.0f, 0.0f);
// Used to fix the sun in the sky so it doesn't move based on current time
private bool m_SunFixed = false;
private float m_SunFixedHour = 0f;
private const int TICKS_PER_SECOND = 10000000;
// Current time in elapsed seconds since Jan 1st 1970
private ulong CurrentTime
{
get
{
return (ulong)(((DateTime.Now.Ticks) - TicksToEpoch + TicksUTCOffset) / TICKS_PER_SECOND);
}
}
// Time in seconds since UTC to use to calculate sun position.
ulong PosTime = 0;
/// <summary>
/// Calculate the sun's orbital position and its velocity.
/// </summary>
private void GenSunPos()
{
// Time in seconds since UTC to use to calculate sun position.
PosTime = CurrentTime;
if (m_SunFixed)
{
// SunFixedHour represents the "hour of day" we would like
// It's represented in 24hr time, with 0 hour being sun-rise
// Because our day length is probably not 24hrs {LL is 6} we need to do a bit of math
// Determine the current "day" from current time, so we can use "today"
// to determine Seasonal Tilt and what'not
// Integer math rounded is on purpose to drop fractional day, determines number
// of virtual days since Epoch
PosTime = CurrentTime / SecondsPerSunCycle;
// Since we want number of seconds since Epoch, multiply back up
PosTime *= SecondsPerSunCycle;
// Then offset by the current Fixed Sun Hour
// Fixed Sun Hour needs to be scaled to reflect the user configured Seconds Per Sun Cycle
PosTime += (ulong)((m_SunFixedHour / 24.0) * (ulong)SecondsPerSunCycle);
}
else
{
if (m_DayTimeSunHourScale != 0.5f)
{
ulong CurDaySeconds = CurrentTime % SecondsPerSunCycle;
double CurDayPercentage = (double)CurDaySeconds / SecondsPerSunCycle;
ulong DayLightSeconds = (ulong)(m_DayTimeSunHourScale * SecondsPerSunCycle);
ulong NightSeconds = SecondsPerSunCycle - DayLightSeconds;
PosTime = CurrentTime / SecondsPerSunCycle;
PosTime *= SecondsPerSunCycle;
if (CurDayPercentage < 0.5)
{
PosTime += (ulong)((CurDayPercentage / .5) * DayLightSeconds);
}
else
{
PosTime += DayLightSeconds;
PosTime += (ulong)(((CurDayPercentage - 0.5) / .5) * NightSeconds);
}
}
}
TotalDistanceTravelled = SunSpeed * PosTime; // distance measured in radians
OrbitalPosition = (float)(TotalDistanceTravelled % m_SunCycle); // position measured in radians
// TotalDistanceTravelled += HoursToRadians-(0.25*Math.PI)*Math.Cos(HoursToRadians)-OrbitalPosition;
// OrbitalPosition = (float) (TotalDistanceTravelled%SunCycle);
SeasonalOffset = SeasonSpeed * PosTime; // Present season determined as total radians travelled around season cycle
Tilt.W = (float)(m_AverageTilt + (m_SeasonalTilt * Math.Sin(SeasonalOffset))); // Calculate seasonal orbital N/S tilt
// m_log.Debug("[SUN] Total distance travelled = "+TotalDistanceTravelled+", present position = "+OrbitalPosition+".");
// m_log.Debug("[SUN] Total seasonal progress = "+SeasonalOffset+", present tilt = "+Tilt.W+".");
// The sun rotates about the Z axis
Position.X = (float)Math.Cos(-TotalDistanceTravelled);
Position.Y = (float)Math.Sin(-TotalDistanceTravelled);
Position.Z = 0;
// For interest we rotate it slightly about the X access.
// Celestial tilt is a value that ranges .025
Position *= Tilt;
// Finally we shift the axis so that more of the
// circle is above the horizon than below. This
// makes the nights shorter than the days.
Position = Vector3.Normalize(Position);
Position.Z = Position.Z + (float)HorizonShift;
Position = Vector3.Normalize(Position);
// m_log.Debug("[SUN] Position("+Position.X+","+Position.Y+","+Position.Z+")");
Velocity.X = 0;
Velocity.Y = 0;
Velocity.Z = (float)SunSpeed;
// Correct angular velocity to reflect the seasonal rotation
Magnitude = Position.Length();
if (m_SunFixed)
{
Velocity.X = 0;
Velocity.Y = 0;
Velocity.Z = 0;
}
else
{
Velocity = (Velocity * Tilt) * (1.0f / Magnitude);
}
// TODO: Decouple this, so we can get rid of Linden Hour info
// Update Region infor with new Sun Position and Hour
// set estate settings for region access to sun position
if (receivedEstateToolsSunUpdate)
{
m_scene.RegionInfo.RegionSettings.SunVector = Position;
m_scene.RegionInfo.RegionSettings.SunPosition = GetCurrentTimeAsLindenSunHour();
}
}
private float GetCurrentTimeAsLindenSunHour()
{
if (m_SunFixed)
{
return m_SunFixedHour + 6;
}
return GetCurrentSunHour() + 6.0f;
}
#region IRegion Methods
// Called immediately after the module is loaded for a given region
// i.e. Immediately after instance creation.
public void Initialise(Scene scene, IConfigSource config)
{
m_scene = scene;
m_frame = 0;
// This one puts an entry in the main help screen
m_scene.AddCommand(this, String.Empty, "sun", "Usage: sun [param] [value] - Get or Update Sun module paramater", null);
// This one enables the ability to type just "sun" without any parameters
m_scene.AddCommand(this, "sun", "", "", HandleSunConsoleCommand);
foreach (KeyValuePair<string, string> kvp in GetParamList())
{
m_scene.AddCommand(this, String.Format("sun {0}", kvp.Key), String.Format("{0} - {1}", kvp.Key, kvp.Value), "", HandleSunConsoleCommand);
}
TimeZone local = TimeZone.CurrentTimeZone;
TicksUTCOffset = local.GetUtcOffset(local.ToLocalTime(DateTime.Now)).Ticks;
m_log.Debug("[SUN]: localtime offset is " + TicksUTCOffset);
// Align ticks with Second Life
TicksToEpoch = new DateTime(1970, 1, 1).Ticks;
// Just in case they don't have the stanzas
try
{
// Mode: determines how the sun is handled
m_RegionMode = config.Configs["Sun"].GetString("mode", d_mode);
// Mode: determines how the sun is handled
// m_latitude = config.Configs["Sun"].GetDouble("latitude", d_latitude);
// Mode: determines how the sun is handled
// m_longitude = config.Configs["Sun"].GetDouble("longitude", d_longitude);
// Year length in days
m_YearLengthDays = config.Configs["Sun"].GetInt("year_length", d_year_length);
// Day length in decimal hours
m_DayLengthHours = config.Configs["Sun"].GetDouble("day_length", d_day_length);
// Horizon shift, this is used to shift the sun's orbit, this affects the day / night ratio
// must hard code to ~.5 to match sun position in LL based viewers
m_HorizonShift = config.Configs["Sun"].GetDouble("day_night_offset", d_day_night);
// Scales the sun hours 0...12 vs 12...24, essentially makes daylight hours longer/shorter vs nighttime hours
m_DayTimeSunHourScale = config.Configs["Sun"].GetDouble("day_time_sun_hour_scale", d_DayTimeSunHourScale);
// Update frequency in frames
m_UpdateInterval = config.Configs["Sun"].GetInt("update_interval", d_frame_mod);
}
catch (Exception e)
{
m_log.Debug("[SUN]: Configuration access failed, using defaults. Reason: " + e.Message);
m_RegionMode = d_mode;
m_YearLengthDays = d_year_length;
m_DayLengthHours = d_day_length;
m_HorizonShift = d_day_night;
m_UpdateInterval = d_frame_mod;
m_DayTimeSunHourScale = d_DayTimeSunHourScale;
// m_latitude = d_latitude;
// m_longitude = d_longitude;
}
switch (m_RegionMode)
{
case "T1":
default:
case "SL":
// Time taken to complete a cycle (day and season)
SecondsPerSunCycle = (uint) (m_DayLengthHours * 60 * 60);
SecondsPerYear = (uint) (SecondsPerSunCycle*m_YearLengthDays);
// Ration of real-to-virtual time
// VWTimeRatio = 24/m_day_length;
// Speed of rotation needed to complete a cycle in the
// designated period (day and season)
SunSpeed = m_SunCycle/SecondsPerSunCycle;
SeasonSpeed = m_SeasonalCycle/SecondsPerYear;
// Horizon translation
HorizonShift = m_HorizonShift; // Z axis translation
// HoursToRadians = (SunCycle/24)*VWTimeRatio;
// Insert our event handling hooks
scene.EventManager.OnFrame += SunUpdate;
scene.EventManager.OnAvatarEnteringNewParcel += AvatarEnteringParcel;
scene.EventManager.OnEstateToolsSunUpdate += EstateToolsSunUpdate;
scene.EventManager.OnGetCurrentTimeAsLindenSunHour += GetCurrentTimeAsLindenSunHour;
ready = true;
m_log.Debug("[SUN]: Mode is " + m_RegionMode);
m_log.Debug("[SUN]: Initialization completed. Day is " + SecondsPerSunCycle + " seconds, and year is " + m_YearLengthDays + " days");
m_log.Debug("[SUN]: Axis offset is " + m_HorizonShift);
m_log.Debug("[SUN]: Percentage of time for daylight " + m_DayTimeSunHourScale);
m_log.Debug("[SUN]: Positional data updated every " + m_UpdateInterval + " frames");
break;
}
scene.RegisterModuleInterface<ISunModule>(this);
}
public void PostInitialise()
{
}
public void Close()
{
ready = false;
// Remove our hooks
m_scene.EventManager.OnFrame -= SunUpdate;
m_scene.EventManager.OnAvatarEnteringNewParcel -= AvatarEnteringParcel;
m_scene.EventManager.OnEstateToolsSunUpdate -= EstateToolsSunUpdate;
m_scene.EventManager.OnGetCurrentTimeAsLindenSunHour -= GetCurrentTimeAsLindenSunHour;
}
public string Name
{
get { return "SunModule"; }
}
public bool IsSharedModule
{
get { return false; }
}
#endregion
#region EventManager Events
public void SunToClient(IClientAPI client)
{
if (m_RegionMode != "T1")
{
if (ready)
{
if (m_SunFixed)
{
// m_log.DebugFormat("[SUN]: SunHour {0}, Position {1}, PosTime {2}, OrbitalPosition : {3} ", m_SunFixedHour, Position.ToString(), PosTime.ToString(), OrbitalPosition.ToString());
client.SendSunPos(Position, Velocity, PosTime, SecondsPerSunCycle, SecondsPerYear, OrbitalPosition);
}
else
{
// m_log.DebugFormat("[SUN]: SunHour {0}, Position {1}, PosTime {2}, OrbitalPosition : {3} ", m_SunFixedHour, Position.ToString(), PosTime.ToString(), OrbitalPosition.ToString());
client.SendSunPos(Position, Velocity, CurrentTime, SecondsPerSunCycle, SecondsPerYear, OrbitalPosition);
}
}
}
}
public void SunUpdate()
{
if (((m_frame++ % m_UpdateInterval) != 0) || !ready || m_SunFixed || !receivedEstateToolsSunUpdate)
{
return;
}
GenSunPos(); // Generate shared values once
SunUpdateToAllClients();
}
/// <summary>
/// When an avatar enters the region, it's probably a good idea to send them the current sun info
/// </summary>
/// <param name="avatar"></param>
/// <param name="localLandID"></param>
/// <param name="regionID"></param>
private void AvatarEnteringParcel(ScenePresence avatar, int localLandID, UUID regionID)
{
SunToClient(avatar.ControllingClient);
}
/// <summary>
///
/// </summary>
/// <param name="regionHandle"></param>
/// <param name="FixedTime">Is the sun's position fixed?</param>
/// <param name="useEstateTime">Use the Region or Estate Sun hour?</param>
/// <param name="FixedSunHour">What hour of the day is the Sun Fixed at?</param>
public void EstateToolsSunUpdate(ulong regionHandle, bool FixedSun, bool useEstateTime, float FixedSunHour)
{
if (m_scene.RegionInfo.RegionHandle == regionHandle)
{
// Must limit the Sun Hour to 0 ... 24
while (FixedSunHour > 24.0f)
FixedSunHour -= 24;
while (FixedSunHour < 0)
FixedSunHour += 24;
m_SunFixedHour = FixedSunHour;
m_SunFixed = FixedSun;
m_log.DebugFormat("[SUN]: Sun Settings Update: Fixed Sun? : {0}", m_SunFixed.ToString());
m_log.DebugFormat("[SUN]: Sun Settings Update: Sun Hour : {0}", m_SunFixedHour.ToString());
receivedEstateToolsSunUpdate = true;
// Generate shared values
GenSunPos();
// When sun settings are updated, we should update all clients with new settings.
SunUpdateToAllClients();
m_log.DebugFormat("[SUN]: PosTime : {0}", PosTime.ToString());
}
}
#endregion
private void SunUpdateToAllClients()
{
m_scene.ForEachScenePresence(delegate(ScenePresence sp)
{
if (!sp.IsChildAgent)
{
SunToClient(sp.ControllingClient);
}
});
}
#region ISunModule Members
public double GetSunParameter(string param)
{
switch (param.ToLower())
{
case "year_length":
return m_YearLengthDays;
case "day_length":
return m_DayLengthHours;
case "day_night_offset":
return m_HorizonShift;
case "day_time_sun_hour_scale":
return m_DayTimeSunHourScale;
case "update_interval":
return m_UpdateInterval;
default:
throw new Exception("Unknown sun parameter.");
}
}
public void SetSunParameter(string param, double value)
{
HandleSunConsoleCommand("sun", new string[] {param, value.ToString() });
}
public float GetCurrentSunHour()
{
float ticksleftover = CurrentTime % SecondsPerSunCycle;
return (24.0f * (ticksleftover / SecondsPerSunCycle));
}
#endregion
public void HandleSunConsoleCommand(string module, string[] cmdparams)
{
if (m_scene.ConsoleScene() == null)
{
// FIXME: If console region is root then this will be printed by every module. Currently, there is no
// way to prevent this, short of making the entire module shared (which is complete overkill).
// One possibility is to return a bool to signal whether the module has completely handled the command
m_log.InfoFormat("[Sun]: Please change to a specific region in order to set Sun parameters.");
return;
}
if (m_scene.ConsoleScene() != m_scene)
{
m_log.InfoFormat("[Sun]: Console Scene is not my scene.");
return;
}
m_log.InfoFormat("[Sun]: Processing command.");
foreach (string output in ParseCmdParams(cmdparams))
{
m_log.Info("[SUN] " + output);
}
}
private Dictionary<string, string> GetParamList()
{
Dictionary<string, string> Params = new Dictionary<string, string>();
Params.Add("year_length", "number of days to a year");
Params.Add("day_length", "number of seconds to a day");
Params.Add("day_night_offset", "induces a horizon shift");
Params.Add("update_interval", "how often to update the sun's position in frames");
Params.Add("day_time_sun_hour_scale", "scales day light vs nite hours to change day/night ratio");
return Params;
}
private List<string> ParseCmdParams(string[] args)
{
List<string> Output = new List<string>();
if ((args.Length == 1) || (args[1].ToLower() == "help") || (args[1].ToLower() == "list"))
{
Output.Add("The following parameters can be changed or viewed:");
foreach (KeyValuePair<string, string> kvp in GetParamList())
{
Output.Add(String.Format("{0} - {1}",kvp.Key, kvp.Value));
}
return Output;
}
if (args.Length == 2)
{
try
{
double value = GetSunParameter(args[1]);
Output.Add(String.Format("Parameter {0} is {1}.", args[1], value.ToString()));
}
catch (Exception)
{
Output.Add(String.Format("Unknown parameter {0}.", args[1]));
}
}
else if (args.Length == 3)
{
float value = 0.0f;
if (!float.TryParse(args[2], out value))
{
Output.Add(String.Format("The parameter value {0} is not a valid number.", args[2]));
}
switch (args[1].ToLower())
{
case "year_length":
m_YearLengthDays = (int)value;
break;
case "day_length":
m_DayLengthHours = value;
break;
case "day_night_offset":
m_HorizonShift = value;
break;
case "day_time_sun_hour_scale":
m_DayTimeSunHourScale = value;
break;
case "update_interval":
m_UpdateInterval = (int)value;
break;
default:
Output.Add(String.Format("Unknown parameter {0}.", args[1]));
return Output;
}
Output.Add(String.Format("Parameter {0} set to {1}.", args[1], value.ToString()));
// Generate shared values
GenSunPos();
// When sun settings are updated, we should update all clients with new settings.
SunUpdateToAllClients();
}
return Output;
}
}
}
| |
using Android.App;
using Android.Content;
using PushNotification.Plugin.Abstractions;
using System;
using System.Threading.Tasks;
using Android.Gms.Common;
using Java.Util.Logging;
using Android.Gms.Gcm;
using Android.Util;
using Java.Lang;
using Android.Content.PM;
using Android.OS;
using System.Collections.Generic;
using Android.Preferences;
using Android.Support.V4.App;
using Android.Media;
using Android;
using Android.Gms.Iid;
using System.Threading;
using Java.IO;
namespace PushNotification.Plugin
{
/// <summary>
/// Implementation for Feature
/// </summary>
public class PushNotificationImplementation : IPushNotification
{
private const string GcmPreferencesKey = "GCMPreferences";
private int DefaultBackOffMilliseconds = 3000;
const string Tag = "PushNotification";
/// <summary>
/// Push Notification Listener
/// </summary>
internal static IPushNotificationListener Listener { get; set; }
/// <summary>
/// GCM Token
/// </summary>
public string Token { get { return GetRegistrationId(); } }
/// <summary>
/// Register for Push Notifications
/// </summary>
public void Register()
{
System.Diagnostics.Debug.WriteLine($"{PushNotificationKey.DomainName} - Register - Registering push notifications");
if (string.IsNullOrEmpty(CrossPushNotification.SenderId))
{
System.Diagnostics.Debug.WriteLine($"{PushNotificationKey.DomainName} - Register - SenderId is missing.");
CrossPushNotification.PushNotificationListener.OnError($"{PushNotificationKey.DomainName} - Register - Sender Id is missing.", DeviceType.Android);
}
else //if (string.IsNullOrEmpty(Token))
{
System.Diagnostics.Debug.WriteLine($"{PushNotificationKey.DomainName} - Register - Registering for Push Notifications");
//ResetBackoff();
ThreadPool.QueueUserWorkItem(state =>
{
try
{
Intent intent = new Intent(Android.App.Application.Context, typeof(PushNotificationRegistrationIntentService));
Android.App.Application.Context.StartService(intent);
}
catch (System.Exception ex)
{
System.Diagnostics.Debug.WriteLine($"{Tag} - Error : {ex.Message}");
CrossPushNotification.PushNotificationListener.OnError($"{Tag} - Register - {ex.Message}", DeviceType.Android);
}
});
}
//else
//{
// System.Diagnostics.Debug.WriteLine(string.Format("{0} - Register - Already Registered for Push Notifications", PushNotificationKey.DomainName));
//}
}
/// <summary>
/// Unregister push notifications
/// </summary>
public void Unregister()
{
ThreadPool.QueueUserWorkItem(state =>
{
System.Diagnostics.Debug.WriteLine($"{PushNotificationKey.DomainName} - Unregister - Unregistering push notifications");
try
{
InstanceID instanceID = InstanceID.GetInstance(Android.App.Application.Context);
instanceID.DeleteToken(CrossPushNotification.SenderId, GoogleCloudMessaging.InstanceIdScope);
CrossPushNotification.PushNotificationListener.OnUnregistered(DeviceType.Android);
PushNotificationImplementation.StoreRegistrationId(Android.App.Application.Context, string.Empty);
}
catch (IOException ex)
{
System.Diagnostics.Debug.WriteLine($"{Tag} - Error : {ex.Message}");
CrossPushNotification.PushNotificationListener.OnError($"{Tag} - Unregister - {ex.Message}", DeviceType.Android);
}
});
}
private string GetRegistrationId()
{
string retVal = "";
Context context = Android.App.Application.Context;
ISharedPreferences prefs = GetGCMPreferences(context);
string registrationId = prefs.GetString(PushNotificationKey.Token, string.Empty);
if (string.IsNullOrEmpty(registrationId))
{
System.Diagnostics.Debug.WriteLine($"{PushNotificationKey.DomainName} - Registration not found.");
return retVal;
}
// Check if app was updated; if so, it must clear the registration ID
// since the existing registration ID is not guaranteed to work with
// the new app version.
int registeredVersion = prefs.GetInt(PushNotificationKey.AppVersion, Integer.MinValue);
int currentVersion = GetAppVersion(context);
if (registeredVersion != currentVersion)
{
System.Diagnostics.Debug.WriteLine($"{PushNotificationKey.DomainName} - App version changed.");
return retVal;
}
retVal = registrationId;
return retVal;
}
internal static ISharedPreferences GetGCMPreferences(Context context)
{
// This sample app persists the registration ID in shared preferences, but
// how you store the registration ID in your app is up to you.
return context.GetSharedPreferences(GcmPreferencesKey, FileCreationMode.Private);
}
internal static int GetAppVersion(Context context)
{
try
{
PackageInfo packageInfo = context.PackageManager.GetPackageInfo(context.PackageName, 0);
return packageInfo.VersionCode;
}
catch (Android.Content.PM.PackageManager.NameNotFoundException e)
{
// should never happen
throw new RuntimeException("Could not get package name: " + e);
}
}
internal static void StoreRegistrationId(Context context, string regId)
{
ISharedPreferences prefs = GetGCMPreferences(context);
int appVersion = GetAppVersion(context);
System.Diagnostics.Debug.WriteLine($"{PushNotificationKey.DomainName} - Saving token on app version {appVersion}");
ISharedPreferencesEditor editor = prefs.Edit();
editor.PutString(PushNotificationKey.Token, regId);
editor.PutInt(PushNotificationKey.AppVersion, appVersion);
editor.Commit();
}
/* internal void ResetBackoff()
{
// Logger.Debug("resetting backoff for " + context.PackageName);
Context context = Android.App.Application.Context;
SetBackoff(DefaultBackOffMilliseconds);
}
internal int GetBackoff()
{
Context context = Android.App.Application.Context;
var prefs = GetGCMPreferences(context);
return prefs.GetInt(PushNotificationKey.BackOffMilliseconds, DefaultBackOffMilliseconds);
}
internal void SetBackoff(int backoff)
{
Context context = Android.App.Application.Context;
var prefs = GetGCMPreferences(context);
var editor = prefs.Edit();
editor.PutInt(PushNotificationKey.BackOffMilliseconds, backoff);
editor.Commit();
}*/
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Pathfinding.Serialization.JsonFx;
using Pathfinding.Serialization;
namespace Pathfinding {
/** Basic point graph.
* \ingroup graphs
* The List graph is the most basic graph structure, it consists of a number of interconnected points in space, waypoints or nodes.\n
* The list graph takes a Transform object as "root", this Transform will be searched for child objects, every child object will be treated as a node.
* It will then check if any connections between the nodes can be made, first it will check if the distance between the nodes isn't too large ( #maxDistance )
* and then it will check if the axis aligned distance isn't too high. The axis aligned distance, named #limits,
* is useful because usually an AI cannot climb very high, but linking nodes far away from each other,
* but on the same Y level should still be possible. #limits and #maxDistance won't affect anything if the values are 0 (zero) though. \n
* Lastly it will check if there are any obstructions between the nodes using
* <a href="http://unity3d.com/support/documentation/ScriptReference/Physics.Raycast.html">raycasting</a> which can optionally be thick.\n
* One thing to think about when using raycasting is to either place the nodes a small
* distance above the ground in your scene or to make sure that the ground is not in the raycast \a mask to avoid the raycast from hitting the ground.\n
* \note Does not support linecast because of obvious reasons.
*
\shadowimage{pointgraph_graph.png}
\shadowimage{pointgraph_inspector.png}
*/
[JsonOptIn]
public class PointGraph : NavGraph
,IUpdatableGraph
{
[JsonMember]
/** Childs of this transform are treated as nodes */
public Transform root;
[JsonMember]
/** If no #root is set, all nodes with the tag is used as nodes */
public string searchTag;
[JsonMember]
/** Max distance for a connection to be valid.
* The value 0 (zero) will be read as infinity and thus all nodes not restricted by
* other constraints will be added as connections.
*
* A negative value will disable any neighbours to be added.
* It will completely stop the connection processing to be done, so it can save you processing
* power if you don't these connections.
*/
public float maxDistance = 0;
[JsonMember]
/** Max distance along the axis for a connection to be valid. 0 = infinity */
public Vector3 limits;
[JsonMember]
/** Use raycasts to check connections */
public bool raycast = true;
[JsonMember]
/** Use thick raycast */
public bool thickRaycast = false;
[JsonMember]
/** Thick raycast radius */
public float thickRaycastRadius = 1;
[JsonMember]
/** Recursively search for childnodes to the #root */
public bool recursive = true;
[JsonMember]
public bool autoLinkNodes = true;
[JsonMember]
/** Layer mask to use for raycast */
public LayerMask mask;
[JsonMember]
/** Optimizes the graph for sparse graphs.
*
* This can reduce calculation times for both scanning and for normal path requests by huge amounts.
*
* You should enable this when your #maxDistance and/or #limits variables are set relatively low compared to the world
* size. It reduces the number of node-node checks that need to be done during scan, and can also optimize getting the nearest node from the graph (such as when querying for a path).
*
* Try enabling and disabling this option, check the scan times logged when you scan the graph to see if your graph is suited for this optimization
* or if it makes it slower.
*
* The gain of using this optimization increases with larger graphs, the default scan algorithm is brute force an requires O(n^2) checks, this optimization
* along with a graph suited for it, requires only O(n) checks during scan.
*
* \note
* When you have this enabled, you will not be able to move nodes around using scripting unless you recalculate the lookup structure at the same time.
* \see RebuildNodeLookup
*
* \astarpro
*/
public bool optimizeForSparseGraph = false;
[JsonMember]
/** Optimizes for when the graph is mostly spread out in the XZ plane.
* Requires #optimizeForSparseGraph.
*
* When your graph is mostly spread out in the XZ plane instead of equally in all directions,
* you can tick this toggle to speed up some calculations.
* If you do not have a graph which is spread out mostly on the XZ plane, enabling this option
* will most likely degrade the performance of the graph instead of improve it.
*
* \astarpro
*/
public bool optimizeFor2D = false;
private static readonly Int3[] ThreeDNeighbours = new Int3[] {
new Int3 ( -1, 0, -1),
new Int3 ( 0, 0, -1),
new Int3 ( 1, 0, -1),
new Int3 ( -1, 0, 0),
new Int3 ( 0, 0, 0),
new Int3 ( 1, 0, 0),
new Int3 ( -1, 0, 1),
new Int3 ( 0, 0, 1),
new Int3 ( 1, 0, 1),
new Int3 ( -1, -1, -1),
new Int3 ( 0, -1, -1),
new Int3 ( 1, -1, -1),
new Int3 ( -1, -1, 0),
new Int3 ( 0, -1, 0),
new Int3 ( 1, -1, 0),
new Int3 ( -1, -1, 1),
new Int3 ( 0, -1, 1),
new Int3 ( 1, -1, 1),
new Int3 ( -1, 1, -1),
new Int3 ( 0, 1, -1),
new Int3 ( 1, 1, -1),
new Int3 ( -1, 1, 0),
new Int3 ( 0, 1, 0),
new Int3 ( 1, 1, 0),
new Int3 ( -1, 1, 1),
new Int3 ( 0, 1, 1),
new Int3 ( 1, 1, 1),
};
Dictionary<Int3, PointNode> nodeLookup;
Int3 minLookup, maxLookup;
Int3 lookupCellSize;
/** GameObjects which defined the node in the #nodes array.
* Entries are permitted to be null in case no GameObject was used to define a node.
*
* \note Set, but not used at the moment. Does not work after deserialization.
*/
GameObject[] nodeGameObjects;
/** All nodes in this graph.
* Note that only the first #nodeCount will be non-null.
*
* You can also use the GetNodes method to get all nodes.
*/
public PointNode[] nodes;
/** Number of nodes in this graph.
*
* \warning Do not edit directly
*/
public int nodeCount;
Int3 WorldToLookupSpace ( Int3 p ) {
Int3 lp = Int3.zero;
lp.x = lookupCellSize.x != 0 ? p.x/lookupCellSize.x : 0;
lp.y = lookupCellSize.y != 0 ? p.y/lookupCellSize.y : 0;
lp.z = lookupCellSize.z != 0 ? p.z/lookupCellSize.z : 0;
return lp;
}
public override void GetNodes (GraphNodeDelegateCancelable del) {
if (nodes == null) return;
for (int i=0;i<nodeCount && del (nodes[i]);i++) {}
}
public override NNInfo GetNearest (Vector3 position, NNConstraint constraint, GraphNode hint) {
return GetNearestForce (position, constraint);
}
public override NNInfo GetNearestForce (Vector3 position, NNConstraint constraint)
{
//Debug.LogError ("This function (GetNearest) is not implemented in the navigation graph generator : Type "+this.GetType ().Name);
if (nodes == null) return new NNInfo();
float maxDistSqr = constraint.constrainDistance ? AstarPath.active.maxNearestNodeDistanceSqr : float.PositiveInfinity;
float minDist = float.PositiveInfinity;
GraphNode minNode = null;
float minConstDist = float.PositiveInfinity;
GraphNode minConstNode = null;
if ( optimizeForSparseGraph ) {
Int3 lookupStart = WorldToLookupSpace ( (Int3)position );
Int3 size = lookupStart-minLookup;
int mw = 0;
mw = System.Math.Max (mw, System.Math.Abs (size.x) );
mw = System.Math.Max (mw, System.Math.Abs (size.y) );
mw = System.Math.Max (mw, System.Math.Abs (size.z) );
size = lookupStart-maxLookup;
mw = System.Math.Max (mw, System.Math.Abs (size.x) );
mw = System.Math.Max (mw, System.Math.Abs (size.y) );
mw = System.Math.Max (mw, System.Math.Abs (size.z) );
PointNode node = null;
if ( nodeLookup.TryGetValue (lookupStart, out node) ) {
while ( node != null ) {
float dist = (position-(Vector3)node.position).sqrMagnitude;
if (dist < minDist) { minDist = dist; minNode = node; }
if (constraint == null || (dist < minConstDist && dist < maxDistSqr && constraint.Suitable (node))) { minConstDist = dist; minConstNode = node; }
node = node.next;
}
}
for ( int w = 1; w <= mw; w++ ) {
if ( w >= 20 ) {
Debug.LogWarning ("Aborting GetNearest call at maximum distance because it has iterated too many times.\n" +
"If you get this regularly, check your settings for PointGraph -> <b>Optimize For Sparse Graph</b> and " +
"PointGraph -> <b>Optimize For 2D</b>.\nThis happens when the closest node was very far away (20*link distance between nodes). " +
"When optimizing for sparse graphs, getting the nearest node from far away positions is <b>very slow</b>.\n");
break;
}
if ( lookupCellSize.y == 0 ) {
Int3 reference = lookupStart + new Int3(-w,0,-w);
for ( int x=0; x <= 2*w; x++ ) {
if ( nodeLookup.TryGetValue (reference + new Int3 ( x, 0, 0 ), out node) ) {
while ( node != null ) {
float dist = (position-(Vector3)node.position).sqrMagnitude;
if (dist < minDist) { minDist = dist; minNode = node; }
if (constraint == null || (dist < minConstDist && dist < maxDistSqr && constraint.Suitable (node))) { minConstDist = dist; minConstNode = node; }
node = node.next;
}
}
if ( nodeLookup.TryGetValue (reference + new Int3 ( x, 0, 2*w ), out node) ) {
while ( node != null ) {
float dist = (position-(Vector3)node.position).sqrMagnitude;
if (dist < minDist) { minDist = dist; minNode = node; }
if (constraint == null || (dist < minConstDist && dist < maxDistSqr && constraint.Suitable (node))) { minConstDist = dist; minConstNode = node; }
node = node.next;
}
}
}
for ( int x=1; x < 2*w; x++ ) {
if ( nodeLookup.TryGetValue (reference + new Int3 ( 0, 0, x ), out node) ) {
while ( node != null ) {
float dist = (position-(Vector3)node.position).sqrMagnitude;
if (dist < minDist) { minDist = dist; minNode = node; }
if (constraint == null || (dist < minConstDist && dist < maxDistSqr && constraint.Suitable (node))) { minConstDist = dist; minConstNode = node; }
node = node.next;
}
}
if ( nodeLookup.TryGetValue (reference + new Int3 ( 2*w, 0, x ), out node) ) {
while ( node != null ) {
float dist = (position-(Vector3)node.position).sqrMagnitude;
if (dist < minDist) { minDist = dist; minNode = node; }
if (constraint == null || (dist < minConstDist && dist < maxDistSqr && constraint.Suitable (node))) { minConstDist = dist; minConstNode = node; }
node = node.next;
}
}
}
} else {
Int3 reference = lookupStart + new Int3(-w,-w,-w);
for ( int x=0; x <= 2*w; x++ ) {
for ( int y=0; y <= 2*w; y++ ) {
if ( nodeLookup.TryGetValue (reference + new Int3 ( x, y, 0 ), out node) ) {
while ( node != null ) {
float dist = (position-(Vector3)node.position).sqrMagnitude;
if (dist < minDist) { minDist = dist; minNode = node; }
if (constraint == null || (dist < minConstDist && dist < maxDistSqr && constraint.Suitable (node))) { minConstDist = dist; minConstNode = node; }
node = node.next;
}
}
if ( nodeLookup.TryGetValue (reference + new Int3 ( x, y, 2*w ), out node) ) {
while ( node != null ) {
float dist = (position-(Vector3)node.position).sqrMagnitude;
if (dist < minDist) { minDist = dist; minNode = node; }
if (constraint == null || (dist < minConstDist && dist < maxDistSqr && constraint.Suitable (node))) { minConstDist = dist; minConstNode = node; }
node = node.next;
}
}
}
}
for ( int x=1; x < 2*w; x++ ) {
for ( int y=0; y <= 2*w; y++ ) {
if ( nodeLookup.TryGetValue (reference + new Int3 ( 0, y, x ), out node) ) {
while ( node != null ) {
float dist = (position-(Vector3)node.position).sqrMagnitude;
if (dist < minDist) { minDist = dist; minNode = node; }
if (constraint == null || (dist < minConstDist && dist < maxDistSqr && constraint.Suitable (node))) { minConstDist = dist; minConstNode = node; }
node = node.next;
}
}
if ( nodeLookup.TryGetValue (reference + new Int3 ( 2*w, y, x ), out node) ) {
while ( node != null ) {
float dist = (position-(Vector3)node.position).sqrMagnitude;
if (dist < minDist) { minDist = dist; minNode = node; }
if (constraint == null || (dist < minConstDist && dist < maxDistSqr && constraint.Suitable (node))) { minConstDist = dist; minConstNode = node; }
node = node.next;
}
}
}
}
for ( int x=1; x < 2*w; x++ ) {
for ( int y=1; y < 2*w; y++ ) {
if ( nodeLookup.TryGetValue (reference + new Int3 ( x, 0, y ), out node) ) {
while ( node != null ) {
float dist = (position-(Vector3)node.position).sqrMagnitude;
if (dist < minDist) { minDist = dist; minNode = node; }
if (constraint == null || (dist < minConstDist && dist < maxDistSqr && constraint.Suitable (node))) { minConstDist = dist; minConstNode = node; }
node = node.next;
}
}
if ( nodeLookup.TryGetValue (reference + new Int3 ( x, 2*w, y ), out node) ) {
while ( node != null ) {
float dist = (position-(Vector3)node.position).sqrMagnitude;
if (dist < minDist) { minDist = dist; minNode = node; }
if (constraint == null || (dist < minConstDist && dist < maxDistSqr && constraint.Suitable (node))) { minConstDist = dist; minConstNode = node; }
node = node.next;
}
}
}
}
}
if ( minConstNode != null ) {
// Only search one more layer
mw = System.Math.Min (mw, w+1);
}
}
} else {
for (int i=0;i<nodeCount;i++) {
PointNode node = nodes[i];
float dist = (position-(Vector3)node.position).sqrMagnitude;
if (dist < minDist) {
minDist = dist;
minNode = node;
}
if (constraint == null || (dist < minConstDist && dist < maxDistSqr && constraint.Suitable (node))) {
minConstDist = dist;
minConstNode = node;
}
}
}
NNInfo nnInfo = new NNInfo (minNode);
nnInfo.constrainedNode = minConstNode;
if (minConstNode != null) {
nnInfo.constClampedPosition = (Vector3)minConstNode.position;
} else if (minNode != null) {
nnInfo.constrainedNode = minNode;
nnInfo.constClampedPosition = (Vector3)minNode.position;
}
return nnInfo;
}
/** Add a node to the graph at the specified position.
* \note Vector3 can be casted to Int3 using (Int3)myVector.
*/
public PointNode AddNode (Int3 position) {
return AddNode ( new PointNode (active), position );
}
/** Add a node with the specified type to the graph at the specified position.
* \note Vector3 can be casted to Int3 using (Int3)myVector.
*
* \param nd This must be a node created using T(AstarPath.active) right before the call to this method.
* The node parameter is only there because there is no new(AstarPath) constraint on
* generic type parameters.
*/
public T AddNode<T> (T nd, Int3 position) where T : PointNode {
if ( nodes == null || nodeCount == nodes.Length ) {
PointNode[] nds = new PointNode[nodes != null ? System.Math.Max (nodes.Length+4, nodes.Length*2) : 4];
for ( int i = 0; i < nodeCount; i++ ) nds[i] = nodes[i];
nodes = nds;
}
//T nd = new T( active );//new PointNode ( active );
nd.SetPosition (position);
nd.GraphIndex = graphIndex;
nd.Walkable = true;
nodes[nodeCount] = nd;
nodeCount++;
AddToLookup ( nd );
return nd;
}
/** Recursively counds children of a transform */
public static int CountChildren (Transform tr) {
int c = 0;
foreach (Transform child in tr) {
c++;
c+= CountChildren (child);
}
return c;
}
/** Recursively adds childrens of a transform as nodes */
public void AddChildren (ref int c, Transform tr) {
foreach (Transform child in tr) {
(nodes[c] as PointNode).SetPosition ((Int3)child.position);
nodes[c].Walkable = true;
nodeGameObjects[c] = child.gameObject;
#if !AstarRelease && FALSE
NodeObject nobj = child.GetComponent<NodeObject>();
if (nobj != null) nodes[c].Walkable = nobj.walkable;
#endif
c++;
AddChildren (ref c,child);
}
}
/** Rebuilds the lookup structure for nodes.
*
* This is used when #optimizeForSparseGraph is enabled.
*
* You should call this method every time you move a node in the graph manually and
* you are using #optimizeForSparseGraph, otherwise pathfinding might not work correctly.
*
* \astarpro
*/
public void RebuildNodeLookup () {
if ( !optimizeForSparseGraph ) return;
if ( maxDistance == 0 ) {
lookupCellSize = (Int3)limits;
} else {
lookupCellSize.x = Mathf.CeilToInt(Int3.Precision*(limits.x != 0 ? Mathf.Min(maxDistance, limits.x) : maxDistance));
lookupCellSize.y = Mathf.CeilToInt(Int3.Precision*(limits.y != 0 ? Mathf.Min(maxDistance, limits.y) : maxDistance));
lookupCellSize.z = Mathf.CeilToInt(Int3.Precision*(limits.z != 0 ? Mathf.Min(maxDistance, limits.z) : maxDistance));
}
if ( optimizeFor2D ) {
lookupCellSize.y = 0;
}
if ( nodeLookup == null ) nodeLookup = new Dictionary<Int3, PointNode>();
nodeLookup.Clear ();
for ( int i = 0; i < nodeCount; i++ ) {
PointNode node = nodes[i];
AddToLookup ( node );
}
}
public void AddToLookup ( PointNode node ) {
if ( nodeLookup == null ) return;
Int3 p = WorldToLookupSpace ( node.position );
if ( nodeLookup.Count == 0 ) {
minLookup = p;
maxLookup = p;
} else {
minLookup = new Int3(System.Math.Min (minLookup.x,p.x),System.Math.Min (minLookup.y,p.y),System.Math.Min (minLookup.z,p.z));
maxLookup = new Int3(System.Math.Max (minLookup.x,p.x),System.Math.Max (minLookup.y,p.y),System.Math.Max (minLookup.z,p.z));
}
// Does not cover all cases, but at least some of them
if ( node.next != null ) throw new System.Exception ( "This node has already been added to the lookup structure" );
PointNode root;
if (nodeLookup.TryGetValue ( p, out root )){
// Insert in between
node.next = root.next;
root.next = node;
} else {
nodeLookup[p] = node;
}
}
public override void ScanInternal (OnScanStatus statusCallback) {
if (root == null) {
//If there is no root object, try to find nodes with the specified tag instead
GameObject[] gos = GameObject.FindGameObjectsWithTag (searchTag);
nodeGameObjects = gos;
if (gos == null) {
nodes = new PointNode[0];
nodeCount = 0;
return;
}
//Create and set up the found nodes
nodes = new PointNode[gos.Length];
nodeCount = nodes.Length;
for (int i=0;i<nodes.Length;i++) nodes[i] = new PointNode(active);
//CreateNodes (gos.Length);
for (int i=0;i<gos.Length;i++) {
(nodes[i] as PointNode).SetPosition ((Int3)gos[i].transform.position);
nodes[i].Walkable = true;
#if !AstarRelease && FALSE
NodeObject nobj = gos[i].GetComponent<NodeObject>();
if (nobj != null) nodes[i].Walkable = nobj.walkable;
#endif
}
} else {
//Search the root for children and create nodes for them
if (!recursive) {
nodes = new PointNode[root.childCount];
nodeCount = nodes.Length;
for (int i=0;i<nodes.Length;i++) nodes[i] = new PointNode(active);
nodeGameObjects = new GameObject[nodes.Length];
int c = 0;
foreach (Transform child in root) {
(nodes[c] as PointNode).SetPosition ((Int3)child.position);
nodes[c].Walkable = true;
nodeGameObjects[c] = child.gameObject;
#if !AstarRelease && FALSE
NodeObject nobj = child.GetComponent<NodeObject>();
if (nobj != null) nodes[c].Walkable = nobj.walkable;
#endif
c++;
}
} else {
nodes = new PointNode[CountChildren(root)];
nodeCount = nodes.Length;
for (int i=0;i<nodes.Length;i++) nodes[i] = new PointNode(active);
//CreateNodes (CountChildren (root));
nodeGameObjects = new GameObject[nodes.Length];
int startID = 0;
AddChildren (ref startID,root);
}
}
if ( optimizeForSparseGraph ) {
RebuildNodeLookup ();
}
if (maxDistance >= 0) {
//To avoid too many allocations, these lists are reused for each node
List<PointNode> connections = new List<PointNode>(3);
List<uint> costs = new List<uint>(3);
//Loop through all nodes and add connections to other nodes
for (int i=0;i<nodes.Length;i++) {
connections.Clear ();
costs.Clear ();
PointNode node = nodes[i];
if ( optimizeForSparseGraph ) {
Int3 p = WorldToLookupSpace ( node.position );
int l = lookupCellSize.y == 0 ? 9 : ThreeDNeighbours.Length;
for ( int j = 0; j < l; j++ ) {
Int3 np = p + ThreeDNeighbours[j];
PointNode other;
if ( nodeLookup.TryGetValue ( np, out other ) ) {
while ( other != null ) {
float dist = 0;
if (IsValidConnection (node,other,out dist)) {
connections.Add (other);
/** \todo Is this equal to .costMagnitude */
costs.Add ((uint)Mathf.RoundToInt (dist*Int3.FloatPrecision));
}
other = other.next;
}
}
}
} else {
// Only brute force is available in the free version
for (int j=0;j<nodes.Length;j++) {
if (i == j) continue;
PointNode other = nodes[j];
float dist = 0;
if (IsValidConnection (node,other,out dist)) {
connections.Add (other);
/** \todo Is this equal to .costMagnitude */
costs.Add ((uint)Mathf.RoundToInt (dist*Int3.FloatPrecision));
}
}
}
node.connections = connections.ToArray();
node.connectionCosts = costs.ToArray();
}
}
//GC can clear this up now.
nodeGameObjects = null;
}
/** Returns if the connection between \a a and \a b is valid.
* Checks for obstructions using raycasts (if enabled) and checks for height differences.\n
* As a bonus, it outputs the distance between the nodes too if the connection is valid */
public virtual bool IsValidConnection (GraphNode a, GraphNode b, out float dist) {
dist = 0;
if (!a.Walkable || !b.Walkable) return false;
Vector3 dir = (Vector3)(a.position-b.position);
if (
(!Mathf.Approximately (limits.x,0) && Mathf.Abs (dir.x) > limits.x) ||
(!Mathf.Approximately (limits.y,0) && Mathf.Abs (dir.y) > limits.y) ||
(!Mathf.Approximately (limits.z,0) && Mathf.Abs (dir.z) > limits.z))
{
return false;
}
dist = dir.magnitude;
if (maxDistance == 0 || dist < maxDistance) {
if (raycast) {
Ray ray = new Ray ((Vector3)a.position,(Vector3)(b.position-a.position));
Ray invertRay = new Ray ((Vector3)b.position,(Vector3)(a.position-b.position));
if (thickRaycast) {
if (!Physics.SphereCast (ray,thickRaycastRadius,dist,mask) && !Physics.SphereCast (invertRay,thickRaycastRadius,dist,mask)) {
return true;
}
} else {
if (!Physics.Raycast (ray,dist,mask) && !Physics.Raycast (invertRay,dist,mask)) {
return true;
}
}
} else {
return true;
}
}
return false;
}
public GraphUpdateThreading CanUpdateAsync (GraphUpdateObject o) {
return GraphUpdateThreading.UnityThread;
}
public void UpdateAreaInit (GraphUpdateObject o) {}
/** Updates an area in the list graph.
* Recalculates possibly affected connections, i.e all connectionlines passing trough the bounds of the \a guo will be recalculated
* \astarpro */
public void UpdateArea (GraphUpdateObject guo) {
if (nodes == null) {
return;
}
for (int i=0;i<nodeCount;i++) {
if (guo.bounds.Contains ((Vector3)nodes[i].position)) {
guo.WillUpdateNode (nodes[i]);
guo.Apply (nodes[i]);
}
}
if (guo.updatePhysics) {
//Use a copy of the bounding box, we should not change the GUO's bounding box since it might be used for other graph updates
Bounds bounds = guo.bounds;
if (thickRaycast) {
//Expand the bounding box to account for the thick raycast
bounds.Expand (thickRaycastRadius*2);
}
//Create two temporary arrays used for holding new connections and costs
List<GraphNode> tmp_arr = Pathfinding.Util.ListPool<GraphNode>.Claim ();
List<uint> tmp_arr2 = Pathfinding.Util.ListPool<uint>.Claim ();
for (int i=0;i<nodeCount;i++) {
PointNode node = nodes[i] as PointNode;
Vector3 a = (Vector3)node.position;
List<GraphNode> conn = null;
List<uint> costs = null;
for (int j=0;j<nodeCount;j++) {
if (j==i) continue;
Vector3 b = (Vector3)nodes[j].position;
if (Polygon.LineIntersectsBounds (bounds,a,b)) {
float dist;
PointNode other = nodes[j] as PointNode;
bool contains = node.ContainsConnection (other);
//Note, the IsValidConnection test will actually only be done once
//no matter what,so there is no performance penalty there
if (!contains && IsValidConnection (node,other, out dist)) {
//Debug.DrawLine (a+Vector3.up*0.1F,b+Vector3.up*0.1F,Color.green);
if (conn == null) {
tmp_arr.Clear();
tmp_arr2.Clear ();
conn = tmp_arr;
costs = tmp_arr2;
conn.AddRange (node.connections);
costs.AddRange (node.connectionCosts);
}
uint cost = (uint)Mathf.RoundToInt (dist*Int3.FloatPrecision);
conn.Add (other);
costs.Add (cost);
} else if (contains && !IsValidConnection (node,other, out dist)) {
//Debug.DrawLine (a+Vector3.up*0.5F*Random.value,b+Vector3.up*0.5F*Random.value,Color.red);
if (conn == null) {
tmp_arr.Clear();
tmp_arr2.Clear ();
conn = tmp_arr;
costs = tmp_arr2;
conn.AddRange (node.connections);
costs.AddRange (node.connectionCosts);
}
int p = conn.IndexOf (other);
//Shouldn't have to check for it, but who knows what might go wrong
if (p != -1) {
conn.RemoveAt (p);
costs.RemoveAt (p);
}
}
}
}
if (conn != null) {
node.connections = conn.ToArray ();
node.connectionCosts = costs.ToArray ();
}
}
Pathfinding.Util.ListPool<GraphNode>.Release (tmp_arr);
Pathfinding.Util.ListPool<uint>.Release (tmp_arr2);
}
}
public override void PostDeserialization ()
{
RebuildNodeLookup ();
}
public override void RelocateNodes (Matrix4x4 oldMatrix, Matrix4x4 newMatrix)
{
base.RelocateNodes (oldMatrix, newMatrix);
RebuildNodeLookup ();
}
public override void SerializeExtraInfo (GraphSerializationContext ctx)
{
if (nodes == null) ctx.writer.Write (-1);
ctx.writer.Write (nodeCount);
for (int i=0;i<nodeCount;i++) {
if (nodes[i] == null) ctx.writer.Write (-1);
else {
ctx.writer.Write (0);
nodes[i].SerializeNode(ctx);
}
}
}
public override void DeserializeExtraInfo (GraphSerializationContext ctx) {
int count = ctx.reader.ReadInt32();
if (count == -1) {
nodes = null;
return;
}
nodes = new PointNode[count];
nodeCount = count;
for (int i=0;i<nodes.Length;i++) {
if (ctx.reader.ReadInt32() == -1) continue;
nodes[i] = new PointNode(active);
nodes[i].DeserializeNode(ctx);
}
}
}
}
| |
//
// 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.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Hyak.Common;
using Microsoft.WindowsAzure.Management.RecoveryServices;
using Microsoft.WindowsAzure.Management.RecoveryServices.Models;
namespace Microsoft.WindowsAzure.Management.RecoveryServices
{
/// <summary>
/// Definition of vault operations for the Site Recovery extension.
/// </summary>
internal partial class VaultOperations : IServiceOperations<RecoveryServicesManagementClient>, IVaultOperations
{
/// <summary>
/// Initializes a new instance of the VaultOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal VaultOperations(RecoveryServicesManagementClient client)
{
this._client = client;
}
private RecoveryServicesManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.WindowsAzure.Management.RecoveryServices.RecoveryServicesManagementClient.
/// </summary>
public RecoveryServicesManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Creates a vault
/// </summary>
/// <param name='cloudServiceName'>
/// Required. The name of the cloud service containing the job
/// collection.
/// </param>
/// <param name='vaultName'>
/// Required. The name of the vault to create.
/// </param>
/// <param name='vaultCreationInput'>
/// Required. Vault object to be created
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the Vm group object.
/// </returns>
public async Task<VaultCreateResponse> BeginCreatingAsync(string cloudServiceName, string vaultName, VaultCreateArgs vaultCreationInput, CancellationToken cancellationToken)
{
// Validate
if (cloudServiceName == null)
{
throw new ArgumentNullException("cloudServiceName");
}
if (vaultName == null)
{
throw new ArgumentNullException("vaultName");
}
if (vaultCreationInput == null)
{
throw new ArgumentNullException("vaultCreationInput");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cloudServiceName", cloudServiceName);
tracingParameters.Add("vaultName", vaultName);
tracingParameters.Add("vaultCreationInput", vaultCreationInput);
TracingAdapter.Enter(invocationId, this, "BeginCreatingAsync", tracingParameters);
}
// Construct URL
string url = "";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/cloudservices/";
url = url + Uri.EscapeDataString(cloudServiceName);
url = url + "/resources/";
url = url + "WAHyperVRecoveryManager";
url = url + "/";
url = url + "HyperVRecoveryManagerVault";
url = url + "/";
url = url + Uri.EscapeDataString(vaultName);
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/xml");
httpRequest.Headers.Add("x-ms-version", "2013-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
XDocument requestDoc = new XDocument();
XElement resourceElement = new XElement(XName.Get("Resource", "http://schemas.microsoft.com/windowsazure"));
requestDoc.Add(resourceElement);
if (vaultCreationInput.ResourceProviderNamespace != null)
{
XElement resourceProviderNamespaceElement = new XElement(XName.Get("ResourceProviderNamespace", "http://schemas.microsoft.com/windowsazure"));
resourceProviderNamespaceElement.Value = vaultCreationInput.ResourceProviderNamespace;
resourceElement.Add(resourceProviderNamespaceElement);
}
if (vaultCreationInput.Type != null)
{
XElement typeElement = new XElement(XName.Get("Type", "http://schemas.microsoft.com/windowsazure"));
typeElement.Value = vaultCreationInput.Type;
resourceElement.Add(typeElement);
}
if (vaultCreationInput.Name != null)
{
XElement nameElement = new XElement(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
nameElement.Value = vaultCreationInput.Name;
resourceElement.Add(nameElement);
}
if (vaultCreationInput.Plan != null)
{
XElement planElement = new XElement(XName.Get("Plan", "http://schemas.microsoft.com/windowsazure"));
planElement.Value = vaultCreationInput.Plan;
resourceElement.Add(planElement);
}
if (vaultCreationInput.SchemaVersion != null)
{
XElement schemaVersionElement = new XElement(XName.Get("SchemaVersion", "http://schemas.microsoft.com/windowsazure"));
schemaVersionElement.Value = vaultCreationInput.SchemaVersion;
resourceElement.Add(schemaVersionElement);
}
if (vaultCreationInput.ETag != null)
{
XElement eTagElement = new XElement(XName.Get("ETag", "http://schemas.microsoft.com/windowsazure"));
eTagElement.Value = vaultCreationInput.ETag;
resourceElement.Add(eTagElement);
}
if (vaultCreationInput.Label != null)
{
XElement labelElement = new XElement(XName.Get("Label", "http://schemas.microsoft.com/windowsazure"));
labelElement.Value = vaultCreationInput.Label;
resourceElement.Add(labelElement);
}
requestContent = requestDoc.ToString();
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
VaultCreateResponse result = null;
// Deserialize Response
result = new VaultCreateResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("ETag"))
{
result.ETag = httpResponse.Headers.GetValues("ETag").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Deletes a vault
/// </summary>
/// <param name='cloudServiceName'>
/// Required. The name of the cloud service containing the job
/// collection.
/// </param>
/// <param name='vaultName'>
/// Required. The name of the vault to delete.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public async Task<RecoveryServicesOperationStatusResponse> BeginDeletingAsync(string cloudServiceName, string vaultName, CancellationToken cancellationToken)
{
// Validate
if (cloudServiceName == null)
{
throw new ArgumentNullException("cloudServiceName");
}
if (vaultName == null)
{
throw new ArgumentNullException("vaultName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cloudServiceName", cloudServiceName);
tracingParameters.Add("vaultName", vaultName);
TracingAdapter.Enter(invocationId, this, "BeginDeletingAsync", tracingParameters);
}
// Construct URL
string url = "";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/cloudservices/";
url = url + Uri.EscapeDataString(cloudServiceName);
url = url + "/resources/";
url = url + "WAHyperVRecoveryManager";
url = url + "/";
url = url + "HyperVRecoveryManagerVault";
url = url + "/";
url = url + Uri.EscapeDataString(vaultName);
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/xml");
httpRequest.Headers.Add("x-ms-version", "2013-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
RecoveryServicesOperationStatusResponse result = null;
// Deserialize Response
result = new RecoveryServicesOperationStatusResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Creates a vault
/// </summary>
/// <param name='cloudServiceName'>
/// Required. The name of the cloud service containing the job
/// collection.
/// </param>
/// <param name='vaultName'>
/// Required. The name of the vault to create.
/// </param>
/// <param name='vaultCreationInput'>
/// Required. Vault object to be created
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public async Task<RecoveryServicesOperationStatusResponse> CreateAsync(string cloudServiceName, string vaultName, VaultCreateArgs vaultCreationInput, CancellationToken cancellationToken)
{
RecoveryServicesManagementClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cloudServiceName", cloudServiceName);
tracingParameters.Add("vaultName", vaultName);
tracingParameters.Add("vaultCreationInput", vaultCreationInput);
TracingAdapter.Enter(invocationId, this, "CreateAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
VaultCreateResponse response = await client.Vaults.BeginCreatingAsync(cloudServiceName, vaultName, vaultCreationInput, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
RecoveryServicesOperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 15;
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while ((result.Status != RecoveryServicesOperationStatus.InProgress) == false)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
delayInSeconds = 10;
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
if (result.Status != RecoveryServicesOperationStatus.Succeeded)
{
if (result.Error != null)
{
CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message);
ex.Error = new CloudError();
ex.Error.Code = result.Error.Code;
ex.Error.Message = result.Error.Message;
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
else
{
CloudException ex = new CloudException("");
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
}
result.ETag = response.ETag;
return result;
}
/// <summary>
/// Deletes a vault
/// </summary>
/// <param name='cloudServiceName'>
/// Required. The name of the cloud service containing the job
/// collection.
/// </param>
/// <param name='vaultName'>
/// Required. The name of the vault to delete.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public async Task<RecoveryServicesOperationStatusResponse> DeleteAsync(string cloudServiceName, string vaultName, CancellationToken cancellationToken)
{
RecoveryServicesManagementClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cloudServiceName", cloudServiceName);
tracingParameters.Add("vaultName", vaultName);
TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
RecoveryServicesOperationStatusResponse response = await client.Vaults.BeginDeletingAsync(cloudServiceName, vaultName, cancellationToken).ConfigureAwait(false);
if (response.Status == RecoveryServicesOperationStatus.Succeeded)
{
return response;
}
cancellationToken.ThrowIfCancellationRequested();
RecoveryServicesOperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 15;
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while ((result.Status != RecoveryServicesOperationStatus.InProgress) == false)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
delayInSeconds = 10;
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
if (result.Status != RecoveryServicesOperationStatus.Succeeded)
{
if (result.Error != null)
{
CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message);
ex.Error = new CloudError();
ex.Error.Code = result.Error.Code;
ex.Error.Message = result.Error.Message;
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
else
{
CloudException ex = new CloudException("");
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
}
return result;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Timers;
using System.Text.RegularExpressions;
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.OptionalModules.World.AutoBackup
{
/// <summary>
/// Choose between ways of naming the backup files that are generated.
/// </summary>
/// <remarks>Time: OARs are named by a timestamp.
/// Sequential: OARs are named by counting (Region_1.oar, Region_2.oar, etc.)
/// Overwrite: Only one file per region is created; it's overwritten each time a backup is made.</remarks>
public enum NamingType
{
Time,
Sequential,
Overwrite
}
///<summary>
/// AutoBackupModule: save OAR region backups to disk periodically
/// </summary>
/// <remarks>
/// Config Settings Documentation.
/// Each configuration setting can be specified in two places: OpenSim.ini or Regions.ini.
/// If specified in Regions.ini, the settings should be within the region's section name.
/// If specified in OpenSim.ini, the settings should be within the [AutoBackupModule] section.
/// Region-specific settings take precedence.
///
/// AutoBackupModuleEnabled: True/False. Default: False. If True, use the auto backup module. This setting does not support per-region basis.
/// All other settings under [AutoBackupModule] are ignored if AutoBackupModuleEnabled is false, even per-region settings!
/// AutoBackup: True/False. Default: False. If True, activate auto backup functionality.
/// This is the only required option for enabling auto-backup; the other options have sane defaults.
/// If False for a particular region, the auto-backup module becomes a no-op for the region, and all other AutoBackup* settings are ignored.
/// If False globally (the default), only regions that specifically override it in Regions.ini will get AutoBackup functionality.
/// AutoBackupInterval: Double, non-negative value. Default: 720 (12 hours).
/// The number of minutes between each backup attempt.
/// If a negative or zero value is given, it is equivalent to setting AutoBackup = False.
/// AutoBackupBusyCheck: True/False. Default: True.
/// If True, we will only take an auto-backup if a set of conditions are met.
/// These conditions are heuristics to try and avoid taking a backup when the sim is busy.
/// AutoBackupSkipAssets
/// If true, assets are not saved to the oar file. Considerably reduces impact on simulator when backing up. Intended for when assets db is backed up separately
/// AutoBackupScript: String. Default: not specified (disabled).
/// File path to an executable script or binary to run when an automatic backup is taken.
/// The file should really be (Windows) an .exe or .bat, or (Linux/Mac) a shell script or binary.
/// Trying to "run" directories, or things with weird file associations on Win32, might cause unexpected results!
/// argv[1] of the executed file/script will be the file name of the generated OAR.
/// If the process can't be spawned for some reason (file not found, no execute permission, etc), write a warning to the console.
/// AutoBackupNaming: string. Default: Time.
/// One of three strings (case insensitive):
/// "Time": Current timestamp is appended to file name. An existing file will never be overwritten.
/// "Sequential": A number is appended to the file name. So if RegionName_x.oar exists, we'll save to RegionName_{x+1}.oar next. An existing file will never be overwritten.
/// "Overwrite": Always save to file named "${AutoBackupDir}/RegionName.oar", even if we have to overwrite an existing file.
/// AutoBackupDir: String. Default: "." (the current directory).
/// A directory (absolute or relative) where backups should be saved.
/// AutoBackupDilationThreshold: float. Default: 0.5. Lower bound on time dilation required for BusyCheck heuristics to pass.
/// If the time dilation is below this value, don't take a backup right now.
/// AutoBackupAgentThreshold: int. Default: 10. Upper bound on # of agents in region required for BusyCheck heuristics to pass.
/// If the number of agents is greater than this value, don't take a backup right now
/// Save memory by setting low initial capacities. Minimizes impact in common cases of all regions using same interval, and instances hosting 1 ~ 4 regions.
/// Also helps if you don't want AutoBackup at all.
/// </remarks>
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "AutoBackupModule")]
public class AutoBackupModule : ISharedRegionModule
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private readonly Dictionary<Guid, IScene> m_pendingSaves = new Dictionary<Guid, IScene>(1);
private readonly AutoBackupModuleState m_defaultState = new AutoBackupModuleState();
private readonly Dictionary<IScene, AutoBackupModuleState> m_states =
new Dictionary<IScene, AutoBackupModuleState>(1);
private readonly Dictionary<Timer, List<IScene>> m_timerMap =
new Dictionary<Timer, List<IScene>>(1);
private readonly Dictionary<double, Timer> m_timers = new Dictionary<double, Timer>(1);
private delegate T DefaultGetter<T>(string settingName, T defaultValue);
private bool m_enabled;
/// <summary>
/// Whether the shared module should be enabled at all. NOT the same as m_Enabled in AutoBackupModuleState!
/// </summary>
private bool m_closed;
private IConfigSource m_configSource;
/// <summary>
/// Required by framework.
/// </summary>
public bool IsSharedModule
{
get { return true; }
}
#region ISharedRegionModule Members
/// <summary>
/// Identifies the module to the system.
/// </summary>
string IRegionModuleBase.Name
{
get { return "AutoBackupModule"; }
}
/// <summary>
/// We don't implement an interface, this is a single-use module.
/// </summary>
Type IRegionModuleBase.ReplaceableInterface
{
get { return null; }
}
/// <summary>
/// Called once in the lifetime of the module at startup.
/// </summary>
/// <param name="source">The input config source for OpenSim.ini.</param>
void IRegionModuleBase.Initialise(IConfigSource source)
{
// Determine if we have been enabled at all in OpenSim.ini -- this is part and parcel of being an optional module
this.m_configSource = source;
IConfig moduleConfig = source.Configs["AutoBackupModule"];
if (moduleConfig == null)
{
this.m_enabled = false;
return;
}
else
{
this.m_enabled = moduleConfig.GetBoolean("AutoBackupModuleEnabled", false);
if (this.m_enabled)
{
m_log.Info("[AUTO BACKUP]: AutoBackupModule enabled");
}
else
{
return;
}
}
Timer defTimer = new Timer(43200000);
this.m_defaultState.Timer = defTimer;
this.m_timers.Add(43200000, defTimer);
defTimer.Elapsed += this.HandleElapsed;
defTimer.AutoReset = true;
defTimer.Start();
AutoBackupModuleState abms = this.ParseConfig(null, true);
m_log.Debug("[AUTO BACKUP]: Here is the default config:");
m_log.Debug(abms.ToString());
}
/// <summary>
/// Called once at de-init (sim shutting down).
/// </summary>
void IRegionModuleBase.Close()
{
if (!this.m_enabled)
{
return;
}
// We don't want any timers firing while the sim's coming down; strange things may happen.
this.StopAllTimers();
}
/// <summary>
/// Currently a no-op for AutoBackup because we have to wait for region to be fully loaded.
/// </summary>
/// <param name="scene"></param>
void IRegionModuleBase.AddRegion(Scene scene)
{
}
/// <summary>
/// Here we just clean up some resources and stop the OAR backup (if any) for the given scene.
/// </summary>
/// <param name="scene">The scene (region) to stop performing AutoBackup on.</param>
void IRegionModuleBase.RemoveRegion(Scene scene)
{
if (!this.m_enabled)
{
return;
}
if (this.m_states.ContainsKey(scene))
{
AutoBackupModuleState abms = this.m_states[scene];
// Remove this scene out of the timer map list
Timer timer = abms.Timer;
List<IScene> list = this.m_timerMap[timer];
list.Remove(scene);
// Shut down the timer if this was the last scene for the timer
if (list.Count == 0)
{
this.m_timerMap.Remove(timer);
this.m_timers.Remove(timer.Interval);
timer.Close();
}
this.m_states.Remove(scene);
}
}
/// <summary>
/// Most interesting/complex code paths in AutoBackup begin here.
/// We read lots of Nini config, maybe set a timer, add members to state tracking Dictionaries, etc.
/// </summary>
/// <param name="scene">The scene to (possibly) perform AutoBackup on.</param>
void IRegionModuleBase.RegionLoaded(Scene scene)
{
if (!this.m_enabled)
{
return;
}
// This really ought not to happen, but just in case, let's pretend it didn't...
if (scene == null)
{
return;
}
AutoBackupModuleState abms = this.ParseConfig(scene, false);
m_log.Debug("[AUTO BACKUP]: Config for " + scene.RegionInfo.RegionName);
m_log.Debug((abms == null ? "DEFAULT" : abms.ToString()));
m_states.Add(scene, abms);
}
/// <summary>
/// Currently a no-op.
/// </summary>
void ISharedRegionModule.PostInitialise()
{
}
#endregion
/// <summary>
/// Set up internal state for a given scene. Fairly complex code.
/// When this method returns, we've started auto-backup timers, put members in Dictionaries, and created a State object for this scene.
/// </summary>
/// <param name="scene">The scene to look at.</param>
/// <param name="parseDefault">Whether this call is intended to figure out what we consider the "default" config (applied to all regions unless overridden by per-region settings).</param>
/// <returns>An AutoBackupModuleState contains most information you should need to know relevant to auto-backup, as applicable to a single region.</returns>
private AutoBackupModuleState ParseConfig(IScene scene, bool parseDefault)
{
string sRegionName;
string sRegionLabel;
// string prepend;
AutoBackupModuleState state;
if (parseDefault)
{
sRegionName = null;
sRegionLabel = "DEFAULT";
// prepend = "";
state = this.m_defaultState;
}
else
{
sRegionName = scene.RegionInfo.RegionName;
sRegionLabel = sRegionName;
// prepend = sRegionName + ".";
state = null;
}
// Read the config settings and set variables.
IConfig regionConfig = (scene != null ? scene.Config.Configs[sRegionName] : null);
IConfig config = this.m_configSource.Configs["AutoBackupModule"];
if (config == null)
{
// defaultState would be disabled too if the section doesn't exist.
state = this.m_defaultState;
return state;
}
bool tmpEnabled = ResolveBoolean("AutoBackup", this.m_defaultState.Enabled, config, regionConfig);
if (state == null && tmpEnabled != this.m_defaultState.Enabled)
//Varies from default state
{
state = new AutoBackupModuleState();
}
if (state != null)
{
state.Enabled = tmpEnabled;
}
// If you don't want AutoBackup, we stop.
if ((state == null && !this.m_defaultState.Enabled) || (state != null && !state.Enabled))
{
return state;
}
else
{
m_log.Info("[AUTO BACKUP]: Region " + sRegionLabel + " is AutoBackup ENABLED.");
}
// Borrow an existing timer if one exists for the same interval; otherwise, make a new one.
double interval =
this.ResolveDouble("AutoBackupInterval", this.m_defaultState.IntervalMinutes,
config, regionConfig) * 60000.0;
if (state == null && interval != this.m_defaultState.IntervalMinutes * 60000.0)
{
state = new AutoBackupModuleState();
}
if (this.m_timers.ContainsKey(interval))
{
if (state != null)
{
state.Timer = this.m_timers[interval];
}
m_log.Debug("[AUTO BACKUP]: Reusing timer for " + interval + " msec for region " +
sRegionLabel);
}
else
{
// 0 or negative interval == do nothing.
if (interval <= 0.0 && state != null)
{
state.Enabled = false;
return state;
}
if (state == null)
{
state = new AutoBackupModuleState();
}
Timer tim = new Timer(interval);
state.Timer = tim;
//Milliseconds -> minutes
this.m_timers.Add(interval, tim);
tim.Elapsed += this.HandleElapsed;
tim.AutoReset = true;
tim.Start();
}
// Add the current region to the list of regions tied to this timer.
if (scene != null)
{
if (state != null)
{
if (this.m_timerMap.ContainsKey(state.Timer))
{
this.m_timerMap[state.Timer].Add(scene);
}
else
{
List<IScene> scns = new List<IScene>(1);
scns.Add(scene);
this.m_timerMap.Add(state.Timer, scns);
}
}
else
{
if (this.m_timerMap.ContainsKey(this.m_defaultState.Timer))
{
this.m_timerMap[this.m_defaultState.Timer].Add(scene);
}
else
{
List<IScene> scns = new List<IScene>(1);
scns.Add(scene);
this.m_timerMap.Add(this.m_defaultState.Timer, scns);
}
}
}
bool tmpBusyCheck = ResolveBoolean("AutoBackupBusyCheck",
this.m_defaultState.BusyCheck, config, regionConfig);
if (state == null && tmpBusyCheck != this.m_defaultState.BusyCheck)
{
state = new AutoBackupModuleState();
}
if (state != null)
{
state.BusyCheck = tmpBusyCheck;
}
// Included Option To Skip Assets
bool tmpSkipAssets = ResolveBoolean("AutoBackupSkipAssets",
this.m_defaultState.SkipAssets, config, regionConfig);
if (state == null && tmpSkipAssets != this.m_defaultState.SkipAssets)
{
state = new AutoBackupModuleState();
}
if (state != null)
{
state.SkipAssets = tmpSkipAssets;
}
// Set file naming algorithm
string stmpNamingType = ResolveString("AutoBackupNaming",
this.m_defaultState.NamingType.ToString(), config, regionConfig);
NamingType tmpNamingType;
if (stmpNamingType.Equals("Time", StringComparison.CurrentCultureIgnoreCase))
{
tmpNamingType = NamingType.Time;
}
else if (stmpNamingType.Equals("Sequential", StringComparison.CurrentCultureIgnoreCase))
{
tmpNamingType = NamingType.Sequential;
}
else if (stmpNamingType.Equals("Overwrite", StringComparison.CurrentCultureIgnoreCase))
{
tmpNamingType = NamingType.Overwrite;
}
else
{
m_log.Warn("Unknown naming type specified for region " + sRegionLabel + ": " +
stmpNamingType);
tmpNamingType = NamingType.Time;
}
if (state == null && tmpNamingType != this.m_defaultState.NamingType)
{
state = new AutoBackupModuleState();
}
if (state != null)
{
state.NamingType = tmpNamingType;
}
string tmpScript = ResolveString("AutoBackupScript",
this.m_defaultState.Script, config, regionConfig);
if (state == null && tmpScript != this.m_defaultState.Script)
{
state = new AutoBackupModuleState();
}
if (state != null)
{
state.Script = tmpScript;
}
string tmpBackupDir = ResolveString("AutoBackupDir", ".", config, regionConfig);
if (state == null && tmpBackupDir != this.m_defaultState.BackupDir)
{
state = new AutoBackupModuleState();
}
if (state != null)
{
state.BackupDir = tmpBackupDir;
// Let's give the user some convenience and auto-mkdir
if (state.BackupDir != ".")
{
try
{
DirectoryInfo dirinfo = new DirectoryInfo(state.BackupDir);
if (!dirinfo.Exists)
{
dirinfo.Create();
}
}
catch (Exception e)
{
m_log.Warn(
"BAD NEWS. You won't be able to save backups to directory " +
state.BackupDir +
" because it doesn't exist or there's a permissions issue with it. Here's the exception.",
e);
}
}
}
if(state == null)
return m_defaultState;
return state;
}
/// <summary>
/// Helper function for ParseConfig.
/// </summary>
/// <param name="settingName"></param>
/// <param name="defaultValue"></param>
/// <param name="global"></param>
/// <param name="local"></param>
/// <returns></returns>
private bool ResolveBoolean(string settingName, bool defaultValue, IConfig global, IConfig local)
{
if(local != null)
{
return local.GetBoolean(settingName, global.GetBoolean(settingName, defaultValue));
}
else
{
return global.GetBoolean(settingName, defaultValue);
}
}
/// <summary>
/// Helper function for ParseConfig.
/// </summary>
/// <param name="settingName"></param>
/// <param name="defaultValue"></param>
/// <param name="global"></param>
/// <param name="local"></param>
/// <returns></returns>
private double ResolveDouble(string settingName, double defaultValue, IConfig global, IConfig local)
{
if (local != null)
{
return local.GetDouble(settingName, global.GetDouble(settingName, defaultValue));
}
else
{
return global.GetDouble(settingName, defaultValue);
}
}
/// <summary>
/// Helper function for ParseConfig.
/// </summary>
/// <param name="settingName"></param>
/// <param name="defaultValue"></param>
/// <param name="global"></param>
/// <param name="local"></param>
/// <returns></returns>
private int ResolveInt(string settingName, int defaultValue, IConfig global, IConfig local)
{
if (local != null)
{
return local.GetInt(settingName, global.GetInt(settingName, defaultValue));
}
else
{
return global.GetInt(settingName, defaultValue);
}
}
/// <summary>
/// Helper function for ParseConfig.
/// </summary>
/// <param name="settingName"></param>
/// <param name="defaultValue"></param>
/// <param name="global"></param>
/// <param name="local"></param>
/// <returns></returns>
private string ResolveString(string settingName, string defaultValue, IConfig global, IConfig local)
{
if (local != null)
{
return local.GetString(settingName, global.GetString(settingName, defaultValue));
}
else
{
return global.GetString(settingName, defaultValue);
}
}
/// <summary>
/// Called when any auto-backup timer expires. This starts the code path for actually performing a backup.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void HandleElapsed(object sender, ElapsedEventArgs e)
{
// TODO: heuristic thresholds are per-region, so we should probably run heuristics once per region
// XXX: Running heuristics once per region could add undue performance penalty for something that's supposed to
// check whether the region is too busy! Especially on sims with LOTS of regions.
// Alternative: make heuristics thresholds global to the module rather than per-region. Less flexible,
// but would allow us to be semantically correct while being easier on perf.
// Alternative 2: Run heuristics once per unique set of heuristics threshold parameters! Ay yi yi...
// Alternative 3: Don't support per-region heuristics at all; just accept them as a global only parameter.
// Since this is pretty experimental, I haven't decided which alternative makes the most sense.
if (this.m_closed)
{
return;
}
bool heuristicsRun = false;
bool heuristicsPassed = false;
if (!this.m_timerMap.ContainsKey((Timer) sender))
{
m_log.Debug("Code-up error: timerMap doesn't contain timer " + sender);
}
List<IScene> tmap = this.m_timerMap[(Timer) sender];
if (tmap != null && tmap.Count > 0)
{
foreach (IScene scene in tmap)
{
AutoBackupModuleState state = this.m_states[scene];
bool heuristics = state.BusyCheck;
// Fast path: heuristics are on; already ran em; and sim is fine; OR, no heuristics for the region.
if ((heuristics && heuristicsRun && heuristicsPassed) || !heuristics)
{
this.DoRegionBackup(scene);
// Heuristics are on; ran but we're too busy -- keep going. Maybe another region will have heuristics off!
}
else if (heuristicsRun)
{
m_log.Info("[AUTO BACKUP]: Heuristics: too busy to backup " +
scene.RegionInfo.RegionName + " right now.");
continue;
// Logical Deduction: heuristics are on but haven't been run
}
else
{
heuristicsPassed = this.RunHeuristics(scene);
heuristicsRun = true;
if (!heuristicsPassed)
{
m_log.Info("[AUTO BACKUP]: Heuristics: too busy to backup " +
scene.RegionInfo.RegionName + " right now.");
continue;
}
this.DoRegionBackup(scene);
}
}
}
}
/// <summary>
/// Save an OAR, register for the callback for when it's done, then call the AutoBackupScript (if applicable).
/// </summary>
/// <param name="scene"></param>
private void DoRegionBackup(IScene scene)
{
if (!scene.Ready)
{
// We won't backup a region that isn't operating normally.
m_log.Warn("[AUTO BACKUP]: Not backing up region " + scene.RegionInfo.RegionName +
" because its status is " + scene.RegionStatus);
return;
}
AutoBackupModuleState state = this.m_states[scene];
IRegionArchiverModule iram = scene.RequestModuleInterface<IRegionArchiverModule>();
string savePath = BuildOarPath(scene.RegionInfo.RegionName,
state.BackupDir,
state.NamingType);
if (savePath == null)
{
m_log.Warn("[AUTO BACKUP]: savePath is null in HandleElapsed");
return;
}
Guid guid = Guid.NewGuid();
m_pendingSaves.Add(guid, scene);
state.LiveRequests.Add(guid, savePath);
((Scene) scene).EventManager.OnOarFileSaved += new EventManager.OarFileSaved(EventManager_OnOarFileSaved);
m_log.Info("[AUTO BACKUP]: Backing up region " + scene.RegionInfo.RegionName);
// Must pass options, even if dictionary is empty!
Dictionary<string, object> options = new Dictionary<string, object>();
if (state.SkipAssets)
options["noassets"] = true;
iram.ArchiveRegion(savePath, guid, options);
}
/// <summary>
/// Called by the Event Manager when the OnOarFileSaved event is fired.
/// </summary>
/// <param name="guid"></param>
/// <param name="message"></param>
void EventManager_OnOarFileSaved(Guid guid, string message)
{
// Ignore if the OAR save is being done by some other part of the system
if (m_pendingSaves.ContainsKey(guid))
{
AutoBackupModuleState abms = m_states[(m_pendingSaves[guid])];
ExecuteScript(abms.Script, abms.LiveRequests[guid]);
m_pendingSaves.Remove(guid);
abms.LiveRequests.Remove(guid);
}
}
/// <summary>This format may turn out to be too unwieldy to keep...
/// Besides, that's what ctimes are for. But then how do I name each file uniquely without using a GUID?
/// Sequential numbers, right? We support those, too!</summary>
private static string GetTimeString()
{
StringWriter sw = new StringWriter();
sw.Write("_");
DateTime now = DateTime.Now;
sw.Write(now.Year);
sw.Write("y_");
sw.Write(now.Month);
sw.Write("M_");
sw.Write(now.Day);
sw.Write("d_");
sw.Write(now.Hour);
sw.Write("h_");
sw.Write(now.Minute);
sw.Write("m_");
sw.Write(now.Second);
sw.Write("s");
sw.Flush();
string output = sw.ToString();
sw.Close();
return output;
}
/// <summary>Return value of true ==> not too busy; false ==> too busy to backup an OAR right now, or error.</summary>
private bool RunHeuristics(IScene region)
{
try
{
return this.RunTimeDilationHeuristic(region) && this.RunAgentLimitHeuristic(region);
}
catch (Exception e)
{
m_log.Warn("[AUTO BACKUP]: Exception in RunHeuristics", e);
return false;
}
}
/// <summary>
/// If the time dilation right at this instant is less than the threshold specified in AutoBackupDilationThreshold (default 0.5),
/// then we return false and trip the busy heuristic's "too busy" path (i.e. don't save an OAR).
/// AutoBackupDilationThreshold is a _LOWER BOUND_. Lower Time Dilation is bad, so if you go lower than our threshold, it's "too busy".
/// </summary>
/// <param name="region"></param>
/// <returns>Returns true if we're not too busy; false means we've got worse time dilation than the threshold.</returns>
private bool RunTimeDilationHeuristic(IScene region)
{
string regionName = region.RegionInfo.RegionName;
return region.TimeDilation >=
this.m_configSource.Configs["AutoBackupModule"].GetFloat(
regionName + ".AutoBackupDilationThreshold", 0.5f);
}
/// <summary>
/// If the root agent count right at this instant is less than the threshold specified in AutoBackupAgentThreshold (default 10),
/// then we return false and trip the busy heuristic's "too busy" path (i.e., don't save an OAR).
/// AutoBackupAgentThreshold is an _UPPER BOUND_. Higher Agent Count is bad, so if you go higher than our threshold, it's "too busy".
/// </summary>
/// <param name="region"></param>
/// <returns>Returns true if we're not too busy; false means we've got more agents on the sim than the threshold.</returns>
private bool RunAgentLimitHeuristic(IScene region)
{
string regionName = region.RegionInfo.RegionName;
try
{
Scene scene = (Scene) region;
// TODO: Why isn't GetRootAgentCount() a method in the IScene interface? Seems generally useful...
return scene.GetRootAgentCount() <=
this.m_configSource.Configs["AutoBackupModule"].GetInt(
regionName + ".AutoBackupAgentThreshold", 10);
}
catch (InvalidCastException ice)
{
m_log.Debug(
"[AUTO BACKUP]: I NEED MAINTENANCE: IScene is not a Scene; can't get root agent count!",
ice);
return true;
// Non-obstructionist safest answer...
}
}
/// <summary>
/// Run the script or executable specified by the "AutoBackupScript" config setting.
/// Of course this is a security risk if you let anyone modify OpenSim.ini and they want to run some nasty bash script.
/// But there are plenty of other nasty things that can be done with an untrusted OpenSim.ini, such as running high threat level scripting functions.
/// </summary>
/// <param name="scriptName"></param>
/// <param name="savePath"></param>
private static void ExecuteScript(string scriptName, string savePath)
{
// Do nothing if there's no script.
if (scriptName == null || scriptName.Length <= 0)
{
return;
}
try
{
FileInfo fi = new FileInfo(scriptName);
if (fi.Exists)
{
ProcessStartInfo psi = new ProcessStartInfo(scriptName);
psi.Arguments = savePath;
psi.CreateNoWindow = true;
Process proc = Process.Start(psi);
proc.ErrorDataReceived += HandleProcErrorDataReceived;
}
}
catch (Exception e)
{
m_log.Warn(
"Exception encountered when trying to run script for oar backup " + savePath, e);
}
}
/// <summary>
/// Called if a running script process writes to stderr.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void HandleProcErrorDataReceived(object sender, DataReceivedEventArgs e)
{
m_log.Warn("ExecuteScript hook " + ((Process) sender).ProcessName +
" is yacking on stderr: " + e.Data);
}
/// <summary>
/// Quickly stop all timers from firing.
/// </summary>
private void StopAllTimers()
{
foreach (Timer t in this.m_timerMap.Keys)
{
t.Close();
}
this.m_closed = true;
}
/// <summary>
/// Determine the next unique filename by number, for "Sequential" AutoBackupNamingType.
/// </summary>
/// <param name="dirName"></param>
/// <param name="regionName"></param>
/// <returns></returns>
private static string GetNextFile(string dirName, string regionName)
{
FileInfo uniqueFile = null;
long biggestExistingFile = GetNextOarFileNumber(dirName, regionName);
biggestExistingFile++;
// We don't want to overwrite the biggest existing file; we want to write to the NEXT biggest.
uniqueFile =
new FileInfo(dirName + Path.DirectorySeparatorChar + regionName + "_" +
biggestExistingFile + ".oar");
return uniqueFile.FullName;
}
/// <summary>
/// Top-level method for creating an absolute path to an OAR backup file based on what naming scheme the user wants.
/// </summary>
/// <param name="regionName">Name of the region to save.</param>
/// <param name="baseDir">Absolute or relative path to the directory where the file should reside.</param>
/// <param name="naming">The naming scheme for the file name.</param>
/// <returns></returns>
private static string BuildOarPath(string regionName, string baseDir, NamingType naming)
{
FileInfo path = null;
switch (naming)
{
case NamingType.Overwrite:
path = new FileInfo(baseDir + Path.DirectorySeparatorChar + regionName + ".oar");
return path.FullName;
case NamingType.Time:
path =
new FileInfo(baseDir + Path.DirectorySeparatorChar + regionName +
GetTimeString() + ".oar");
return path.FullName;
case NamingType.Sequential:
// All codepaths in GetNextFile should return a file name ending in .oar
path = new FileInfo(GetNextFile(baseDir, regionName));
return path.FullName;
default:
m_log.Warn("VERY BAD: Unhandled case element " + naming);
break;
}
return null;
}
/// <summary>
/// Helper function for Sequential file naming type (see BuildOarPath and GetNextFile).
/// </summary>
/// <param name="dirName"></param>
/// <param name="regionName"></param>
/// <returns></returns>
private static long GetNextOarFileNumber(string dirName, string regionName)
{
long retval = 1;
DirectoryInfo di = new DirectoryInfo(dirName);
FileInfo[] fi = di.GetFiles(regionName, SearchOption.TopDirectoryOnly);
Array.Sort(fi, (f1, f2) => StringComparer.CurrentCultureIgnoreCase.Compare(f1.Name, f2.Name));
if (fi.LongLength > 0)
{
long subtract = 1L;
bool worked = false;
Regex reg = new Regex(regionName + "_([0-9])+" + ".oar");
while (!worked && subtract <= fi.LongLength)
{
// Pick the file with the last natural ordering
string biggestFileName = fi[fi.LongLength - subtract].Name;
MatchCollection matches = reg.Matches(biggestFileName);
long l = 1;
if (matches.Count > 0 && matches[0].Groups.Count > 0)
{
try
{
long.TryParse(matches[0].Groups[1].Value, out l);
retval = l;
worked = true;
}
catch (FormatException fe)
{
m_log.Warn(
"[AUTO BACKUP]: Error: Can't parse long value from file name to determine next OAR backup file number!",
fe);
subtract++;
}
}
else
{
subtract++;
}
}
}
return retval;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
// Copyright (c) 2004 Mainsoft Co.
//
// 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 Xunit;
using System.Collections;
using System.ComponentModel;
namespace System.Data.Tests
{
public class DataTableCollectionTest2
{
private int _counter = 0;
[Fact]
public void Add()
{
// Adding computed column to a data set
var ds = new DataSet();
ds.Tables.Add(new DataTable("Table"));
ds.Tables[0].Columns.Add(new DataColumn("EmployeeNo", typeof(string)));
ds.Tables[0].Rows.Add(new object[] { "Maciek" });
ds.Tables[0].Columns.Add("ComputedColumn", typeof(object), "EmployeeNo");
Assert.Equal("EmployeeNo", ds.Tables[0].Columns["ComputedColumn"].Expression);
}
[Fact]
public void AddTwoTables()
{
var ds = new DataSet();
ds.Tables.Add();
Assert.Equal("Table1", ds.Tables[0].TableName);
//Assert.Equal(ds.Tables[0].TableName,"Table1");
ds.Tables.Add();
Assert.Equal("Table2", ds.Tables[1].TableName);
//Assert.Equal(ds.Tables[1].TableName,"Table2");
}
[Fact]
public void AddRange()
{
var ds = new DataSet();
DataTable[] arr = new DataTable[2];
arr[0] = new DataTable("NewTable1");
arr[1] = new DataTable("NewTable2");
ds.Tables.AddRange(arr);
Assert.Equal("NewTable1", ds.Tables[0].TableName);
Assert.Equal("NewTable2", ds.Tables[1].TableName);
}
[Fact]
public void AddRange_NullValue()
{
var ds = new DataSet();
ds.Tables.AddRange(null);
}
[Fact]
public void AddRange_ArrayWithNull()
{
var ds = new DataSet();
DataTable[] arr = new DataTable[2];
arr[0] = new DataTable("NewTable1");
arr[1] = null;
ds.Tables.AddRange(arr);
Assert.Equal("NewTable1", ds.Tables[0].TableName);
Assert.Equal(1, ds.Tables.Count);
}
[Fact]
public void CanRemove()
{
var ds = new DataSet();
ds.Tables.Add();
Assert.True(ds.Tables.CanRemove(ds.Tables[0]));
}
[Fact]
public void CanRemove_NullValue()
{
var ds = new DataSet();
Assert.False(ds.Tables.CanRemove(null));
}
[Fact]
public void CanRemove_TableDoesntBelong()
{
var ds = new DataSet();
DataSet ds1 = new DataSet();
ds1.Tables.Add();
Assert.False(ds.Tables.CanRemove(ds1.Tables[0]));
}
[Fact]
public void CanRemove_PartOfRelation()
{
var ds = new DataSet();
ds.Tables.Add(DataProvider.CreateParentDataTable());
ds.Tables.Add(DataProvider.CreateChildDataTable());
ds.Relations.Add("rel", ds.Tables[0].Columns["ParentId"], ds.Tables[1].Columns["ParentId"], false);
Assert.False(ds.Tables.CanRemove(ds.Tables[0]));
Assert.False(ds.Tables.CanRemove(ds.Tables[1]));
}
[Fact]
public void CanRemove_PartOfConstraint()
{
DataSet ds = DataProvider.CreateForeignConstraint();
Assert.False(ds.Tables.CanRemove(ds.Tables[0]));
Assert.False(ds.Tables.CanRemove(ds.Tables[1]));
}
[Fact]
public void CollectionChanged()
{
_counter = 0;
var ds = new DataSet();
ds.Tables.CollectionChanged += new CollectionChangeEventHandler(Tables_CollectionChanged);
ds.Tables.Add();
ds.Tables.Add();
Assert.Equal(2, _counter);
ds.Tables.Remove(ds.Tables[0]);
ds.Tables.Remove(ds.Tables[0]);
Assert.Equal(4, _counter);
}
private void Tables_CollectionChanged(object sender, CollectionChangeEventArgs e)
{
_counter++;
}
[Fact]
public void CollectionChanging()
{
_counter = 0;
var ds = new DataSet();
ds.Tables.CollectionChanging += new CollectionChangeEventHandler(Tables_CollectionChanging);
ds.Tables.Add();
ds.Tables.Add();
Assert.Equal(2, _counter);
ds.Tables.Remove(ds.Tables[0]);
ds.Tables.Remove(ds.Tables[0]);
Assert.Equal(4, _counter);
}
private void Tables_CollectionChanging(object sender, CollectionChangeEventArgs e)
{
_counter++;
}
[Fact]
public void Contains()
{
var ds = new DataSet();
ds.Tables.Add("NewTable1");
ds.Tables.Add("NewTable2");
Assert.True(ds.Tables.Contains("NewTable1"));
Assert.True(ds.Tables.Contains("NewTable2"));
Assert.False(ds.Tables.Contains("NewTable3"));
ds.Tables["NewTable1"].TableName = "Tbl1";
Assert.False(ds.Tables.Contains("NewTable1"));
Assert.True(ds.Tables.Contains("Tbl1"));
}
[Fact]
public void CopyTo()
{
var ds = new DataSet();
ds.Tables.Add();
ds.Tables.Add();
DataTable[] arr = new DataTable[2];
ds.Tables.CopyTo(arr, 0);
Assert.Equal("Table1", arr[0].TableName);
Assert.Equal("Table2", arr[1].TableName);
}
[Fact]
public void Count()
{
var ds = new DataSet();
Assert.Equal(0, ds.Tables.Count);
ds.Tables.Add();
Assert.Equal(1, ds.Tables.Count);
ds.Tables.Add();
Assert.Equal(2, ds.Tables.Count);
ds.Tables.Remove("Table1");
Assert.Equal(1, ds.Tables.Count);
ds.Tables.Remove("Table2");
Assert.Equal(0, ds.Tables.Count);
}
[Fact]
public void GetEnumerator()
{
var ds = new DataSet();
ds.Tables.Add();
ds.Tables.Add();
int count = 0;
IEnumerator myEnumerator = ds.Tables.GetEnumerator();
while (myEnumerator.MoveNext())
{
Assert.Equal("Table", ((DataTable)myEnumerator.Current).TableName.Substring(0, 5));
count++;
}
Assert.Equal(2, count);
}
[Fact]
public void IndexOf_ByDataTable()
{
var ds = new DataSet();
DataTable dt = new DataTable("NewTable1");
DataTable dt1 = new DataTable("NewTable2");
ds.Tables.AddRange(new DataTable[] { dt, dt1 });
Assert.Equal(0, ds.Tables.IndexOf(dt));
Assert.Equal(1, ds.Tables.IndexOf(dt1));
ds.Tables.IndexOf((DataTable)null);
DataTable dt2 = new DataTable("NewTable2");
Assert.Equal(-1, ds.Tables.IndexOf(dt2));
}
[Fact]
public void IndexOf_ByName()
{
var ds = new DataSet();
DataTable dt = new DataTable("NewTable1");
DataTable dt1 = new DataTable("NewTable2");
ds.Tables.AddRange(new DataTable[] { dt, dt1 });
Assert.Equal(0, ds.Tables.IndexOf("NewTable1"));
Assert.Equal(1, ds.Tables.IndexOf("NewTable2"));
ds.Tables.IndexOf((string)null);
Assert.Equal(-1, ds.Tables.IndexOf("NewTable3"));
}
[Fact]
public void Item()
{
var ds = new DataSet();
DataTable dt = new DataTable("NewTable1");
DataTable dt1 = new DataTable("NewTable2");
ds.Tables.AddRange(new DataTable[] { dt, dt1 });
Assert.Equal(dt, ds.Tables[0]);
Assert.Equal(dt1, ds.Tables[1]);
Assert.Equal(dt, ds.Tables["NewTable1"]);
Assert.Equal(dt1, ds.Tables["NewTable2"]);
}
[Fact]
public void DataTableCollection_Add_D1()
{
var ds = new DataSet();
DataTable dt = new DataTable("NewTable1");
ds.Tables.Add(dt);
Assert.Equal("NewTable1", ds.Tables[0].TableName);
}
[Fact]
public void DataTableCollection_Add_D2()
{
var ds = new DataSet();
Assert.Throws<ArgumentNullException>(() =>
{
ds.Tables.Add((DataTable)null);
});
}
[Fact]
public void DataTableCollection_Add_D3()
{
var ds = new DataSet();
DataSet ds1 = new DataSet();
ds1.Tables.Add();
AssertExtensions.Throws<ArgumentException>(null, () => ds.Tables.Add(ds1.Tables[0]));
}
[Fact]
public void DataTableCollection_Add_D4()
{
var ds = new DataSet();
ds.Tables.Add();
DataTable dt = new DataTable("Table1");
Assert.Throws<DuplicateNameException>(() => ds.Tables.Add(dt));
}
[Fact]
public void DataTableCollection_Add_S1()
{
var ds = new DataSet();
ds.Tables.Add("NewTable1");
Assert.Equal("NewTable1", ds.Tables[0].TableName);
ds.Tables.Add("NewTable2");
Assert.Equal("NewTable2", ds.Tables[1].TableName);
}
[Fact]
public void DataTableCollection_Add_S2()
{
var ds = new DataSet();
ds.Tables.Add("NewTable1");
Assert.Throws<DuplicateNameException>(() => ds.Tables.Add("NewTable1"));
}
[Fact]
public void DataTableCollection_Clear1()
{
var ds = new DataSet();
ds.Tables.Add();
ds.Tables.Add();
ds.Tables.Clear();
Assert.Equal(0, ds.Tables.Count);
}
[Fact]
public void DataTableCollection_Clear2()
{
var ds = new DataSet();
ds.Tables.Add();
ds.Tables.Add();
ds.Tables.Clear();
Assert.Throws<IndexOutOfRangeException>(() => ds.Tables[0].TableName = "Error");
}
[Fact]
public void DataTableCollection_Remove_D1()
{
var ds = new DataSet();
DataTable dt = new DataTable("NewTable1");
DataTable dt1 = new DataTable("NewTable2");
ds.Tables.AddRange(new DataTable[] { dt, dt1 });
ds.Tables.Remove(dt);
Assert.Equal(1, ds.Tables.Count);
Assert.Equal(dt1, ds.Tables[0]);
ds.Tables.Remove(dt1);
Assert.Equal(0, ds.Tables.Count);
}
[Fact]
public void DataTableCollection_Remove_D2()
{
var ds = new DataSet();
DataTable dt = new DataTable("NewTable1");
AssertExtensions.Throws<ArgumentException>(null, () => ds.Tables.Remove(dt));
}
[Fact]
public void DataTableCollection_Remove_D3()
{
var ds = new DataSet();
Assert.Throws<ArgumentNullException>(() => ds.Tables.Remove((DataTable)null));
}
[Fact]
public void DataTableCollection_Remove_S1()
{
var ds = new DataSet();
DataTable dt = new DataTable("NewTable1");
DataTable dt1 = new DataTable("NewTable2");
ds.Tables.AddRange(new DataTable[] { dt, dt1 });
ds.Tables.Remove("NewTable1");
Assert.Equal(1, ds.Tables.Count);
Assert.Equal(dt1, ds.Tables[0]);
ds.Tables.Remove("NewTable2");
Assert.Equal(0, ds.Tables.Count);
}
[Fact]
public void DataTableCollection_Remove_S2()
{
var ds = new DataSet();
AssertExtensions.Throws<ArgumentException>(null, () => ds.Tables.Remove("NewTable2"));
}
[Fact]
public void DataTableCollection_Remove_S3()
{
var ds = new DataSet();
AssertExtensions.Throws<ArgumentException>(null, () => ds.Tables.Remove((string)null));
}
[Fact]
public void DataTableCollection_RemoveAt_I1()
{
var ds = new DataSet();
DataTable dt = new DataTable("NewTable1");
DataTable dt1 = new DataTable("NewTable2");
ds.Tables.AddRange(new DataTable[] { dt, dt1 });
ds.Tables.RemoveAt(1);
Assert.Equal(dt, ds.Tables[0]);
ds.Tables.RemoveAt(0);
Assert.Equal(0, ds.Tables.Count);
}
[Fact]
public void DataTableCollection_RemoveAt_I2()
{
var ds = new DataSet();
Assert.Throws<IndexOutOfRangeException>(() => ds.Tables.RemoveAt(-1));
}
[Fact]
public void DataTableCollection_RemoveAt_I3()
{
DataSet ds = DataProvider.CreateForeignConstraint();
AssertExtensions.Throws<ArgumentException>(null, () => ds.Tables.RemoveAt(0)); //Parent table
}
[Fact]
public void AddTable_DiffNamespaceTest()
{
var ds = new DataSet();
ds.Tables.Add("table", "namespace1");
ds.Tables.Add("table", "namespace2");
Assert.Equal(2, ds.Tables.Count);
try
{
ds.Tables.Add("table", "namespace1");
Assert.False(true);
}
catch (DuplicateNameException e) { }
ds.Tables.Add("table");
try
{
ds.Tables.Add("table", null);
Assert.False(true);
}
catch (DuplicateNameException e) { }
}
[Fact]
public void Contains_DiffNamespaceTest()
{
var ds = new DataSet();
ds.Tables.Add("table");
Assert.True(ds.Tables.Contains("table"));
ds.Tables.Add("table", "namespace1");
ds.Tables.Add("table", "namespace2");
// Should fail if it cannot be resolved to a single table
Assert.False(ds.Tables.Contains("table"));
try
{
ds.Tables.Contains("table", null);
Assert.False(true);
}
catch (ArgumentNullException e) { }
Assert.True(ds.Tables.Contains("table", "namespace1"));
Assert.False(ds.Tables.Contains("table", "namespace3"));
}
[Fact]
public void IndexOf_DiffNamespaceTest()
{
var ds = new DataSet();
ds.Tables.Add("table");
Assert.Equal(0, ds.Tables.IndexOf("table"));
ds.Tables.Add("table", "namespace1");
ds.Tables.Add("table", "namespace2");
Assert.Equal(-1, ds.Tables.IndexOf("table"));
Assert.Equal(2, ds.Tables.IndexOf("table", "namespace2"));
Assert.Equal(1, ds.Tables.IndexOf("table", "namespace1"));
}
[Fact]
public void Remove_DiffNamespaceTest()
{
var ds = new DataSet();
ds.Tables.Add("table");
ds.Tables.Add("table", "namespace1");
ds.Tables.Add("table", "namespace2");
try
{
ds.Tables.Remove("table");
Assert.False(true);
}
catch (ArgumentException e) { }
ds.Tables.Remove("table", "namespace2");
Assert.Equal(2, ds.Tables.Count);
Assert.Equal("namespace1", ds.Tables[1].Namespace);
try
{
ds.Tables.Remove("table", "namespace2");
Assert.False(true);
}
catch (ArgumentException e) { }
}
}
}
| |
using Blogifier.Core.Data;
using Blogifier.Core.Extensions;
using Blogifier.Shared;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.ServiceModel.Syndication;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
namespace Blogifier.Core.Providers
{
public interface ISyndicationProvider
{
Task<List<Post>> GetPosts(string feedUrl, int userId, Uri baseUrl, string webRoot = "/");
Task<bool> ImportPost(Post post);
}
public class SyndicationProvider : ISyndicationProvider
{
private readonly AppDbContext _dbContext;
private readonly IStorageProvider _storageProvider;
private static int _userId;
private static string _webRoot;
private static Uri _baseUrl;
public SyndicationProvider(AppDbContext dbContext, IStorageProvider storageProvider)
{
_dbContext = dbContext;
_storageProvider = storageProvider;
}
public async Task<List<Post>> GetPosts(string feedUrl, int userId, Uri baseUrl, string webRoot = "/")
{
_userId = userId;
_webRoot = webRoot;
_baseUrl = baseUrl;
List<Post> posts = new List<Post>();
try
{
SyndicationFeed feed = SyndicationFeed.Load(XmlReader.Create(feedUrl));
foreach (var item in feed.Items)
{
posts.Add(await GetPost(item));
}
}
catch (Exception ex)
{
Serilog.Log.Error($"Error parsing feed URL: {ex.Message}");
}
return posts;
}
public async Task<bool> ImportPost(Post post)
{
try
{
await ImportImages(post);
await ImportFiles(post);
var converter = new ReverseMarkdown.Converter();
post.Description = GetDescription(converter.Convert(post.Description));
post.Content = converter.Convert(post.Content);
post.Selected = false;
await _dbContext.Posts.AddAsync(post);
if (await _dbContext.SaveChangesAsync() == 0)
{
Serilog.Log.Error($"Error saving post {post.Title}");
return false;
}
Post savedPost = await _dbContext.Posts.SingleAsync(p => p.Slug == post.Slug);
if(savedPost == null)
{
Serilog.Log.Error($"Error finding saved post - {post.Title}");
return false;
}
savedPost.Blog = await _dbContext.Blogs.FirstOrDefaultAsync();
return await _dbContext.SaveChangesAsync() > 0;
}
catch (Exception ex)
{
Serilog.Log.Error($"Error importing post {post.Title}: {ex.Message}");
return false;
}
}
#region Private members
async Task<Post> GetPost(SyndicationItem syndicationItem)
{
Post post = new Post()
{
AuthorId = _userId,
PostType = PostType.Post,
Title = syndicationItem.Title.Text,
Slug = await GetSlug(syndicationItem.Title.Text),
Description = GetDescription(syndicationItem.Title.Text),
Content = syndicationItem.Summary.Text,
Cover = Constants.DefaultCover,
Published = syndicationItem.PublishDate.DateTime,
DateCreated = syndicationItem.PublishDate.DateTime,
DateUpdated = syndicationItem.LastUpdatedTime.DateTime
};
if (syndicationItem.ElementExtensions != null)
{
foreach (SyndicationElementExtension ext in syndicationItem.ElementExtensions)
{
if (ext.GetObject<XElement>().Name.LocalName == "summary")
post.Description = GetDescription(ext.GetObject<XElement>().Value);
if (ext.GetObject<XElement>().Name.LocalName == "cover")
post.Cover = ext.GetObject<XElement>().Value;
}
}
if (syndicationItem.Categories != null)
{
if (post.PostCategories == null)
post.PostCategories = new List<PostCategory>();
foreach (var category in syndicationItem.Categories)
{
post.PostCategories.Add(new PostCategory()
{
Category = new Category
{
Content = category.Name,
DateCreated = DateTime.UtcNow,
DateUpdated = DateTime.UtcNow
}
});
}
}
return post;
}
async Task ImportImages(Post post)
{
string rgx = @"<img[^>]*?src\s*=\s*[""']?([^'"" >]+?)[ '""][^>]*?>";
if (string.IsNullOrEmpty(post.Content))
return;
if(post.Cover != Constants.DefaultCover)
{
var path = string.Format("{0}/{1}/{2}", post.AuthorId, post.Published.Year, post.Published.Month);
var mdTag = await _storageProvider.UploadFromWeb(new Uri(post.Cover), _webRoot, path);
if (mdTag.Length > 0 && mdTag.IndexOf("(") > 2)
post.Cover = mdTag.Substring(mdTag.IndexOf("(") + 2).Replace(")", "");
}
var matches = Regex.Matches(post.Content, rgx, RegexOptions.IgnoreCase | RegexOptions.Singleline);
if (matches == null)
return;
foreach (Match m in matches)
{
try
{
var tag = m.Groups[0].Value;
var path = string.Format("{0}/{1}/{2}", post.AuthorId, post.Published.Year, post.Published.Month);
var uri = Regex.Match(tag, "<img.+?src=[\"'](.+?)[\"'].+?>", RegexOptions.IgnoreCase).Groups[1].Value;
uri = ValidateUrl(uri);
var mdTag = "";
if (uri.Contains("data:image"))
mdTag = await _storageProvider.UploadBase64Image(uri, _webRoot, path);
else
{
try
{
mdTag = await _storageProvider.UploadFromWeb(new Uri(uri), _webRoot, path);
}
catch
{
if (uri.StartsWith("https:"))
{
mdTag = await _storageProvider.UploadFromWeb(new Uri(uri.Replace("https:", "http:")), _webRoot, path);
}
}
}
post.Content = post.Content.ReplaceIgnoreCase(tag, mdTag);
}
catch (Exception ex)
{
Serilog.Log.Error($"Error importing images: {ex.Message}");
}
}
}
async Task ImportFiles(Post post)
{
var rgx = @"(?i)<a\b[^>]*?>(?<text>.*?)</a>";
string[] exts = new string[] { "zip", "7z", "xml", "pdf", "doc", "docx", "xls", "xlsx", "mp3", "mp4", "avi" };
if (string.IsNullOrEmpty(post.Content))
return;
MatchCollection matches = Regex.Matches(post.Content, rgx, RegexOptions.IgnoreCase | RegexOptions.Singleline);
if (matches != null)
{
foreach (Match m in matches)
{
try
{
var tag = m.Value;
var src = XElement.Parse(tag).Attribute("href").Value;
var mdTag = "";
foreach (var ext in exts)
{
if (src.ToLower().EndsWith($".{ext}"))
{
var uri = ValidateUrl(src);
var path = string.Format("{0}/{1}/{2}", post.AuthorId, post.Published.Year, post.Published.Month);
mdTag = await _storageProvider.UploadFromWeb(new Uri(uri), _webRoot, path);
if (mdTag.StartsWith("!"))
mdTag = mdTag.Substring(1);
post.Content = post.Content.ReplaceIgnoreCase(m.Value, mdTag);
}
}
}
catch (Exception ex)
{
Serilog.Log.Error($"Error importing files: {ex.Message}");
}
}
}
}
async Task<string> GetSlug(string title)
{
string slug = title.ToSlug();
Post post = await _dbContext.Posts.SingleOrDefaultAsync(p => p.Slug == slug);
if (post == null)
return slug;
for (int i = 2; i < 100; i++)
{
post = await _dbContext.Posts.AsNoTracking()
.SingleAsync(p => p.Slug == $"{slug}{i}");
if (post == null)
return await Task.FromResult(slug + i.ToString());
}
return slug;
}
string ValidateUrl(string link)
{
var url = link;
var baseUrl = _baseUrl.ToString();
if (baseUrl.EndsWith("/"))
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
if (url.StartsWith("~"))
url = url.Replace("~", baseUrl);
if (url.StartsWith("/"))
url = $"{baseUrl}{url}";
if (!(url.StartsWith("http:") || url.StartsWith("https:")))
url = $"{baseUrl}/{url}";
return url;
}
string GetDescription(string description)
{
description = description.StripHtml();
if (description.Length > 450)
description = description.Substring(0, 446) + "...";
return description;
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Globalization;
using Xunit;
namespace System.Globalization.CalendarTests
{
// GregorianCalendar.GetDaysInMonth(Int32, Int32)
public class GregorianCalendarGetDaysInMonth
{
private readonly RandomDataGenerator _generator = new RandomDataGenerator();
private static readonly int[] s_daysInMonth365 =
{
0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
};
private static readonly int[] s_daysInMonth366 =
{
0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
};
#region Positive tests
// PosTest1: leap year, any month other than February
[Fact]
public void PosTest1()
{
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
int year, month;
int expectedDays, actualDays;
year = GetALeapYear(myCalendar);
//Get a random value beween 1 and 12 not including 2.
do
{
month = _generator.GetInt32(-55) % 12 + 1;
} while (2 == month);
expectedDays = s_daysInMonth366[month];
actualDays = myCalendar.GetDaysInMonth(year, month);
Assert.Equal(expectedDays, actualDays);
}
// PosTest2: leap year, February
[Fact]
public void PosTest2()
{
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
int year, month;
int expectedDays, actualDays;
year = GetALeapYear(myCalendar);
month = 2;
expectedDays = s_daysInMonth366[month];
actualDays = myCalendar.GetDaysInMonth(year, month);
Assert.Equal(expectedDays, actualDays);
}
// PosTest3: common year, February
[Fact]
public void PosTest3()
{
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
int year, month;
int expectedDays, actualDays;
year = GetACommonYear(myCalendar);
month = 2;
expectedDays = s_daysInMonth365[month];
actualDays = myCalendar.GetDaysInMonth(year, month);
Assert.Equal(expectedDays, actualDays);
}
// PosTest4: common year, any month other than February
[Fact]
public void PosTest4()
{
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
int year, month;
int expectedDays, actualDays;
year = GetACommonYear(myCalendar);
//Get a random value beween 1 and 12 not including 2.
do
{
month = _generator.GetInt32(-55) % 12 + 1;
} while (2 == month);
expectedDays = s_daysInMonth365[month];
actualDays = myCalendar.GetDaysInMonth(year, month);
Assert.Equal(expectedDays, actualDays);
}
// PosTest5: Maximum supported year, any month
[Fact]
public void PosTest5()
{
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
int year, month;
int expectedDays, actualDays;
year = myCalendar.MaxSupportedDateTime.Year;
//Get a random month whose value is beween 1 and 12
month = _generator.GetInt32(-55) % 12 + 1;
expectedDays = (IsLeapYear(year)) ? s_daysInMonth366[month] : s_daysInMonth365[month];
actualDays = myCalendar.GetDaysInMonth(year, month);
Assert.Equal(expectedDays, actualDays);
}
// PosTest6: Minimum supported year, any month
[Fact]
public void PosTest6()
{
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
int year, month;
int expectedDays, actualDays;
year = myCalendar.MaxSupportedDateTime.Year;
//Get a random month whose value is beween 1 and 12
month = _generator.GetInt32(-55) % 12 + 1;
expectedDays = (IsLeapYear(year)) ? s_daysInMonth366[month] : s_daysInMonth365[month];
actualDays = myCalendar.GetDaysInMonth(year, month);
Assert.Equal(expectedDays, actualDays);
}
// PosTest7: Any year, any month
[Fact]
public void PosTest7()
{
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
int year, month;
int expectedDays, actualDays;
year = GetAYear(myCalendar);
//Get a random month whose value is beween 1 and 12
month = _generator.GetInt32(-55) % 12 + 1;
expectedDays = (IsLeapYear(year)) ? s_daysInMonth366[month] : s_daysInMonth365[month];
actualDays = myCalendar.GetDaysInMonth(year, month);
Assert.Equal(expectedDays, actualDays);
}
// PosTest8: Any year, the minimum month
[Fact]
public void PosTest8()
{
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
int year, month;
int expectedDays, actualDays;
year = myCalendar.MaxSupportedDateTime.Year;
month = 1;
expectedDays = (IsLeapYear(year)) ? s_daysInMonth366[month] : s_daysInMonth365[month];
actualDays = myCalendar.GetDaysInMonth(year, month);
Assert.Equal(expectedDays, actualDays);
}
// PosTest9: Any year, the maximum month
[Fact]
public void PosTest9()
{
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
int year, month;
int expectedDays, actualDays;
year = myCalendar.MaxSupportedDateTime.Year;
month = 12;
expectedDays = (IsLeapYear(year)) ? s_daysInMonth366[month] : s_daysInMonth365[month];
actualDays = myCalendar.GetDaysInMonth(year, month);
Assert.Equal(expectedDays, actualDays);
}
#endregion
#region Negative Tests
// NegTest1: year is greater than maximum supported value
[Fact]
public void NegTest1()
{
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
int year, month;
year = myCalendar.MaxSupportedDateTime.Year + 100;
month = _generator.GetInt32(-55) % 12 + 1;
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
myCalendar.GetDaysInMonth(year, month);
});
}
// NegTest2: year is less than maximum supported value
[Fact]
public void NegTest2()
{
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
int year, month;
year = myCalendar.MinSupportedDateTime.Year - 100;
month = _generator.GetInt32(-55) % 12 + 1;
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
myCalendar.GetDaysInMonth(year, month);
});
}
// NegTest3: month is greater than maximum supported value
[Fact]
public void NegTest3()
{
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
int year, month;
year = GetAYear(myCalendar);
month = 13 + _generator.GetInt32(-55) % (int.MaxValue - 12);
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
myCalendar.GetDaysInMonth(year, month);
});
}
// NegTest4: month is less than maximum supported value
[Fact]
public void NegTest4()
{
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
int year, month;
year = myCalendar.MinSupportedDateTime.Year - 100;
month = -1 * _generator.GetInt32(-55);
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
myCalendar.GetDaysInMonth(year, month);
});
}
#endregion
#region Helper methods for all the tests
//Indicate whether the specified year is leap year or not
private bool IsLeapYear(int year)
{
if (0 == year % 400 || (0 != year % 100 && 0 == (year & 0x3)))
{
return true;
}
return false;
}
//Get a random year beween minmum supported year and maximum supported year of the specified calendar
private int GetAYear(Calendar calendar)
{
int retVal;
int maxYear, minYear;
maxYear = calendar.MaxSupportedDateTime.Year;
minYear = calendar.MinSupportedDateTime.Year;
retVal = minYear + _generator.GetInt32(-55) % (maxYear + 1 - minYear);
return retVal;
}
//Get a leap year of the specified calendar
private int GetALeapYear(Calendar calendar)
{
int retVal;
// A leap year is any year divisible by 4 except for centennial years(those ending in 00)
// which are only leap years if they are divisible by 400.
retVal = ~(~GetAYear(calendar) | 0x3); // retVal will be divisible by 4 since the 2 least significant bits will be 0
retVal = (0 != retVal % 100) ? retVal : (retVal - retVal % 400); // if retVal is divisible by 100 subtract years from it to make it divisible by 400
// if retVal was 100, 200, or 300 the above logic will result in 0
if (0 == retVal)
{
retVal = 400;
}
return retVal;
}
//Get a common year of the specified calendar
private int GetACommonYear(Calendar calendar)
{
int retVal;
do
{
retVal = GetAYear(calendar);
}
while ((0 == (retVal & 0x3) && 0 != retVal % 100) || 0 == retVal % 400);
return retVal;
}
//Get text represntation of the input parmeters
private string GetParamsInfo(int year, int month)
{
string str;
str = string.Format("\nThe specified month is in {0}-{1}(year-month).", year, month);
return str;
}
#endregion
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using Microsoft.Scripting;
using Microsoft.Scripting.Runtime;
using System.Text;
using IronPython.Runtime.Binding;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
namespace IronPython.Runtime {
/// <summary>
/// Provides both helpers for implementing Python dictionaries as well
/// as providing public methods that should be exposed on all dictionary types.
///
/// Currently these are published on IDictionary<object, object>
/// </summary>
public static class DictionaryOps {
#region Dictionary Public API Surface
// Dictionary has an odd not-implemented check to support custom dictionaries and therefore
// needs a custom __eq__ / __ne__ implementation.
public static string/*!*/ __repr__(CodeContext/*!*/ context, IDictionary<object, object> self) {
List<object> infinite = PythonOps.GetAndCheckInfinite(self);
if (infinite == null) {
return "{...}";
}
int index = infinite.Count;
infinite.Add(self);
try {
StringBuilder buf = new StringBuilder();
buf.Append("{");
bool first = true;
foreach (KeyValuePair<object, object> kv in self) {
if (first) first = false;
else buf.Append(", ");
if (CustomStringDictionary.IsNullObject(kv.Key))
buf.Append("None");
else
buf.Append(PythonOps.Repr(context, kv.Key));
buf.Append(": ");
buf.Append(PythonOps.Repr(context, kv.Value));
}
buf.Append("}");
return buf.ToString();
} finally {
System.Diagnostics.Debug.Assert(index == infinite.Count - 1);
infinite.RemoveAt(index);
}
}
public static object get(PythonDictionary self, object key) {
return get(self, key, null);
}
public static object get(PythonDictionary self, object key, object defaultValue) {
object ret;
if (self.TryGetValueNoMissing(key, out ret)) return ret;
return defaultValue;
}
public static List items(IDictionary<object, object> self) {
List ret = PythonOps.MakeEmptyList(self.Count);
foreach (KeyValuePair<object, object> kv in self) {
ret.AddNoLock(PythonTuple.MakeTuple(kv.Key, kv.Value));
}
return ret;
}
public static IEnumerator iteritems(IDictionary<object, object> self) {
return ((IEnumerable)items(self)).GetEnumerator();
}
public static IEnumerator iterkeys(IDictionary<object, object> self) {
return ((IEnumerable)keys(self)).GetEnumerator();
}
public static List keys(IDictionary<object, object> self) {
return PythonOps.MakeListFromSequence(self.Keys);
}
public static object pop(PythonDictionary self, object key) {
//??? perf won't match expected Python perf
object ret;
if (self.TryGetValueNoMissing(key, out ret)) {
self.RemoveDirect(key);
return ret;
} else {
throw PythonOps.KeyError(key);
}
}
public static object pop(PythonDictionary self, object key, object defaultValue) {
//??? perf won't match expected Python perf
object ret;
if (self.TryGetValueNoMissing(key, out ret)) {
self.RemoveDirect(key);
return ret;
} else {
return defaultValue;
}
}
public static PythonTuple popitem(IDictionary<object, object> self) {
IEnumerator<KeyValuePair<object, object>> ie = self.GetEnumerator();
if (ie.MoveNext()) {
object key = ie.Current.Key;
object val = ie.Current.Value;
self.Remove(key);
return PythonTuple.MakeTuple(key, val);
}
throw PythonOps.KeyError("dictionary is empty");
}
public static object setdefault(PythonDictionary self, object key) {
return setdefault(self, key, null);
}
public static object setdefault(PythonDictionary self, object key, object defaultValue) {
object ret;
if (self.TryGetValueNoMissing(key, out ret)) return ret;
self.SetItem(key, defaultValue);
return defaultValue;
}
public static void update(CodeContext/*!*/ context, PythonDictionary/*!*/ self, object other) {
PythonDictionary pyDict;
if ((pyDict = other as PythonDictionary) != null) {
pyDict._storage.CopyTo(ref self._storage);
} else {
SlowUpdate(context, self, other);
}
}
private static void SlowUpdate(CodeContext/*!*/ context, PythonDictionary/*!*/ self, object other) {
object keysFunc;
DictProxy dictProxy;
IDictionary dict;
if ((dictProxy = other as DictProxy) != null) {
update(context, self, dictProxy.Type.GetMemberDictionary(context, false));
} else if ((dict = other as IDictionary) != null) {
IDictionaryEnumerator e = dict.GetEnumerator();
while (e.MoveNext()) {
self._storage.Add(ref self._storage, e.Key, e.Value);
}
} else if (PythonOps.TryGetBoundAttr(other, "keys", out keysFunc)) {
// user defined dictionary
IEnumerator i = PythonOps.GetEnumerator(PythonCalls.Call(context, keysFunc));
while (i.MoveNext()) {
self._storage.Add(ref self._storage, i.Current, PythonOps.GetIndex(context, other, i.Current));
}
} else {
// list of lists (key/value pairs), list of tuples,
// tuple of tuples, etc...
IEnumerator i = PythonOps.GetEnumerator(other);
int index = 0;
while (i.MoveNext()) {
if (!AddKeyValue(self, i.Current)) {
throw PythonOps.ValueError("dictionary update sequence element #{0} has bad length; 2 is required", index);
}
index++;
}
}
}
#endregion
#region Dictionary Helper APIs
internal static bool TryGetValueVirtual(CodeContext context, PythonDictionary self, object key, ref object DefaultGetItem, out object value) {
IPythonObject sdo = self as IPythonObject;
if (sdo != null) {
Debug.Assert(sdo != null);
PythonType myType = sdo.PythonType;
object ret;
PythonTypeSlot dts;
if (DefaultGetItem == null) {
// lazy init our cached DefaultGetItem
TypeCache.Dict.TryLookupSlot(context, "__getitem__", out dts);
bool res = dts.TryGetValue(context, self, TypeCache.Dict, out DefaultGetItem);
Debug.Assert(res);
}
// check and see if it's overridden
if (myType.TryLookupSlot(context, "__getitem__", out dts)) {
dts.TryGetValue(context, self, myType, out ret);
if (ret != DefaultGetItem) {
// subtype of dict that has overridden __getitem__
// we need to call the user's versions, and handle
// any exceptions.
try {
value = self[key];
return true;
} catch (KeyNotFoundException) {
value = null;
return false;
}
}
}
}
value = null;
return false;
}
internal static bool AddKeyValue(PythonDictionary self, object o) {
IEnumerator i = PythonOps.GetEnumerator(o); //c.GetEnumerator();
if (i.MoveNext()) {
object key = i.Current;
if (i.MoveNext()) {
object value = i.Current;
self._storage.Add(ref self._storage, key, value);
return !i.MoveNext();
}
}
return false;
}
internal static int CompareTo(CodeContext/*!*/ context, IDictionary<object, object> left, IDictionary<object, object> right) {
int lcnt = left.Count;
int rcnt = right.Count;
if (lcnt != rcnt) return lcnt > rcnt ? 1 : -1;
List ritems = DictionaryOps.items(right);
return CompareToWorker(context, left, ritems);
}
internal static int CompareToWorker(CodeContext/*!*/ context, IDictionary<object, object> left, List ritems) {
List litems = DictionaryOps.items(left);
litems.sort(context);
ritems.sort(context);
return litems.CompareToWorker(ritems);
}
#endregion
}
}
| |
/*
Copyright 2019 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
//Author: Nick Kramer [MSFT]
//Source: http://blogs.msdn.com/b/nickkramer/archive/2006/09/22/766934.aspx
using System.Collections.Generic;
using System.Diagnostics;
namespace Xceed.Wpf.Toolkit.LiveExplorer.Core.CodeFormatting
{
// XML tokenizer, tokens are designed to match Visual Studio syntax highlighting
class XmlTokenizer
{
private string input;
private int position = 0;
private XmlTokenizerMode mode = XmlTokenizerMode.OutsideElement;
public static List<XmlToken> Tokenize( string input )
{
XmlTokenizerMode mode = XmlTokenizerMode.OutsideElement;
XmlTokenizer tokenizer = new XmlTokenizer();
return tokenizer.Tokenize( input, ref mode );
}
public List<XmlToken> Tokenize( string input, ref XmlTokenizerMode _mode )
{
this.input = input;
this.mode = _mode;
this.position = 0;
List<XmlToken> result = Tokenize();
_mode = this.mode;
return result;
}
private List<XmlToken> Tokenize()
{
List<XmlToken> list = new List<XmlToken>();
XmlToken token;
do
{
int previousPosition = position;
token = NextToken();
string tokenText = input.Substring( previousPosition, token.Length );
list.Add( token );
}
while( token.Kind != XmlTokenKind.EOF );
List<string> strings = TokensToStrings( list, input );
return list;
}
private List<string> TokensToStrings( List<XmlToken> list, string input )
{
List<string> output = new List<string>();
int position = 0;
foreach( XmlToken token in list )
{
output.Add( input.Substring( position, token.Length ) );
position += token.Length;
}
return output;
}
// debugging function
public string RemainingText
{
get
{
return input.Substring( position );
}
}
private XmlToken NextToken()
{
if( position >= input.Length )
return new XmlToken( XmlTokenKind.EOF, 0 );
XmlToken token;
switch( mode )
{
case XmlTokenizerMode.AfterAttributeEquals:
token = TokenizeAttributeValue();
break;
case XmlTokenizerMode.AfterAttributeName:
token = TokenizeSimple( "=", XmlTokenKind.Equals, XmlTokenizerMode.AfterAttributeEquals );
break;
case XmlTokenizerMode.AfterOpen:
token = TokenizeName( XmlTokenKind.ElementName, XmlTokenizerMode.InsideElement );
break;
case XmlTokenizerMode.InsideCData:
token = TokenizeInsideCData();
break;
case XmlTokenizerMode.InsideComment:
token = TokenizeInsideComment();
break;
case XmlTokenizerMode.InsideElement:
token = TokenizeInsideElement();
break;
case XmlTokenizerMode.InsideProcessingInstruction:
token = TokenizeInsideProcessingInstruction();
break;
case XmlTokenizerMode.OutsideElement:
token = TokenizeOutsideElement();
break;
default:
token = new XmlToken( XmlTokenKind.EOF, 0 );
Debug.Fail( "missing case" );
break;
}
return token;
}
private bool IsNameCharacter( char character )
{
// XML rule: Letter | Digit | '.' | '-' | '_' | ':' | CombiningChar | Extender
bool result = char.IsLetterOrDigit( character ) || character == '.' | character == '-' | character == '_' | character == ':';
return result;
}
private XmlToken TokenizeAttributeValue()
{
Debug.Assert( mode == XmlTokenizerMode.AfterAttributeEquals );
int closePosition = input.IndexOf( input[ position ], position + 1 );
XmlToken token = new XmlToken( XmlTokenKind.AttributeValue, closePosition + 1 - position );
position = closePosition + 1;
mode = XmlTokenizerMode.InsideElement;
return token;
}
private XmlToken TokenizeName( XmlTokenKind kind, XmlTokenizerMode nextMode )
{
Debug.Assert( mode == XmlTokenizerMode.AfterOpen || mode == XmlTokenizerMode.InsideElement );
int i;
for( i = position; i < input.Length; i++ )
if( !IsNameCharacter( input[ i ] ) )
break;
XmlToken token = new XmlToken( kind, i - position );
mode = nextMode;
position = i;
return token;
}
private XmlToken TokenizeElementWhitespace()
{
int i;
for( i = position; i < input.Length; i++ )
if( !char.IsWhiteSpace( input[ i ] ) )
break;
XmlToken token = new XmlToken( XmlTokenKind.ElementWhitespace, i - position );
position = i;
return token;
}
private bool StartsWith( string text )
{
if( position + text.Length > input.Length )
return false;
else
return input.Substring( position, text.Length ) == text;
}
private XmlToken TokenizeInsideElement()
{
if( char.IsWhiteSpace( input[ position ] ) )
return TokenizeElementWhitespace();
else
if( StartsWith( "/>" ) )
return TokenizeSimple( "/>", XmlTokenKind.SelfClose, XmlTokenizerMode.OutsideElement );
else
if( StartsWith( ">" ) )
return TokenizeSimple( ">", XmlTokenKind.Close, XmlTokenizerMode.OutsideElement );
else
return TokenizeName( XmlTokenKind.AttributeName, XmlTokenizerMode.AfterAttributeName );
}
private XmlToken TokenizeText()
{
Debug.Assert( input[ position ] != '<' );
Debug.Assert( input[ position ] != '&' );
Debug.Assert( mode == XmlTokenizerMode.OutsideElement );
int i;
for( i = position; i < input.Length; i++ )
if( input[ i ] == '<' || input[ i ] == '&' )
break;
XmlToken token = new XmlToken( XmlTokenKind.TextContent, i - position );
position = i;
return token;
}
private XmlToken TokenizeOutsideElement()
{
Debug.Assert( mode == XmlTokenizerMode.OutsideElement );
if( position >= input.Length )
return new XmlToken( XmlTokenKind.EOF, 0 );
switch( input[ position ] )
{
case '<':
return TokenizeOpen();
case '&':
return TokenizeEntity();
default:
return TokenizeText();
}
}
private XmlToken TokenizeSimple( string text, XmlTokenKind kind, XmlTokenizerMode nextMode )
{
XmlToken token = new XmlToken( kind, text.Length );
position += text.Length;
mode = nextMode;
return token;
}
private XmlToken TokenizeOpen()
{
Debug.Assert( input[ position ] == '<' );
if( StartsWith( "<!--" ) )
return TokenizeSimple( "<!--", XmlTokenKind.CommentBegin, XmlTokenizerMode.InsideComment );
else
if( StartsWith( "<![CDATA[" ) )
return TokenizeSimple( "<![CDATA[", XmlTokenKind.CDataBegin, XmlTokenizerMode.InsideCData );
else
if( StartsWith( "<?" ) )
return TokenizeSimple( "<?", XmlTokenKind.OpenProcessingInstruction, XmlTokenizerMode.InsideProcessingInstruction );
else
if( StartsWith( "</" ) )
return TokenizeSimple( "</", XmlTokenKind.OpenClose, XmlTokenizerMode.AfterOpen );
else
return TokenizeSimple( "<", XmlTokenKind.Open, XmlTokenizerMode.AfterOpen );
}
private XmlToken TokenizeEntity()
{
Debug.Assert( mode == XmlTokenizerMode.OutsideElement );
Debug.Assert( input[ position ] == '&' );
XmlToken token = new XmlToken( XmlTokenKind.Entity, input.IndexOf( ';', position ) - position );
position += token.Length;
return token;
}
private XmlToken TokenizeInsideProcessingInstruction()
{
Debug.Assert( mode == XmlTokenizerMode.InsideProcessingInstruction );
int tokenend = input.IndexOf( "?>", position );
if( position == tokenend )
{
position += "?>".Length;
mode = XmlTokenizerMode.OutsideElement;
return new XmlToken( XmlTokenKind.CloseProcessingInstruction, "?>".Length );
}
else
{
XmlToken token = new XmlToken( XmlTokenKind.TextContent, tokenend - position );
position = tokenend;
return token;
}
}
private XmlToken TokenizeInsideCData()
{
Debug.Assert( mode == XmlTokenizerMode.InsideCData );
int tokenend = input.IndexOf( "]]>", position );
if( position == tokenend )
{
position += "]]>".Length;
mode = XmlTokenizerMode.OutsideElement;
return new XmlToken( XmlTokenKind.CDataEnd, "]]>".Length );
}
else
{
XmlToken token = new XmlToken( XmlTokenKind.TextContent, tokenend - position );
position = tokenend;
return token;
}
}
private XmlToken TokenizeInsideComment()
{
Debug.Assert( mode == XmlTokenizerMode.InsideComment );
int tokenend = input.IndexOf( "-->", position );
if( position == tokenend )
{
position += "-->".Length;
mode = XmlTokenizerMode.OutsideElement;
return new XmlToken( XmlTokenKind.CommentEnd, "-->".Length );
}
else
{
XmlToken token = new XmlToken( XmlTokenKind.CommentText, tokenend - position );
position = tokenend;
return token;
}
}
}
// Used so you can restart the tokenizer for the next line of XML
enum XmlTokenizerMode
{
InsideComment,
InsideProcessingInstruction,
AfterOpen,
AfterAttributeName,
AfterAttributeEquals,
InsideElement,
// after element name, before attribute or />
OutsideElement,
InsideCData
}
struct XmlToken
{
public XmlTokenKind Kind;
public short Length;
public XmlToken( XmlTokenKind kind, int length )
{
Kind = kind;
Length = ( short )length;
}
}
/*
* this file implements a mostly correct XML tokenizer. The token boundaries
* have been chosen to match Visual Studio syntax highlighting, so a few of
* the boundaries are little weird. (Especially comments) known issues:
*
* Doesn't handle DTD's
* mediocre handling of processing instructions <? ?> -- it won't crash,
* but the token boundaries are wrong
* Doesn't enforce correct XML
* there's probably a few cases where it will die if given in valid XML
*
*
* This tokenizer has been designed to be restartable, so you can tokenize
* one line of XML at a time.
*/
enum XmlTokenKind
{
Open,
// <
Close,
//>
SelfClose,
// />
OpenClose,
// </
ElementName,
ElementWhitespace,
//whitespace between attributes
AttributeName,
Equals,
// inside attribute
AttributeValue,
// attribute value
CommentBegin,
// <!--
CommentText,
CommentEnd,
// -->
Entity,
// >
OpenProcessingInstruction,
// <?
CloseProcessingInstruction,
// ?>
CDataBegin,
// <![CDATA[
CDataEnd,
// ]]>
TextContent,
//WhitespaceContent, // text content that's whitespace. Space is embedded inside
EOF,
// end of file
}
}
| |
/*
* Copyright (c) 2006-2008, openmetaverse.org
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the openmetaverse.org nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using OpenMetaverse.Packets;
using System.Collections.Generic;
namespace OpenMetaverse
{
/// <summary>
/// Estate level administration and utilities
/// </summary>
public class EstateTools
{
private GridClient Client;
public GroundTextureSettings GroundTextures;
/// <summary>
/// Triggered on LandStatReply when the report type is for "top colliders"
/// </summary>
/// <param name="objectCount"></param>
/// <param name="Tasks"></param>
public delegate void GetTopCollidersReply(int objectCount, List<EstateTask> Tasks);
/// <summary>
/// Triggered on LandStatReply when the report type is for "top scripts"
/// </summary>
/// <param name="objectCount"></param>
/// <param name="Tasks"></param>
public delegate void GetTopScriptsReply(int objectCount, List<EstateTask> Tasks);
/// <summary>
/// Triggered when the list of estate managers is received for the current estate
/// </summary>
/// <param name="managers"></param>
/// <param name="count"></param>
/// <param name="estateID"></param>
public delegate void EstateManagersReply(uint estateID, int count, List<UUID> managers);
/// <summary>
/// FIXME - Enumerate all params from EstateOwnerMessage packet
/// </summary>
/// <param name="denyNoPaymentInfo"></param>
/// <param name="estateID"></param>
/// <param name="estateName"></param>
/// <param name="estateOwner"></param>
public delegate void EstateUpdateInfoReply(string estateName, UUID estateOwner, uint estateID, bool denyNoPaymentInfo);
public delegate void EstateManagersListReply(uint estateID, List<UUID> managers);
public delegate void EstateBansReply(uint estateID, int count, List<UUID> banned);
public delegate void EstateUsersReply(uint estateID, int count, List<UUID> allowedUsers);
public delegate void EstateGroupsReply(uint estateID, int count, List<UUID> allowedGroups);
public delegate void EstateCovenantReply(UUID covenantID, long timestamp, string estateName, UUID estateOwnerID);
// <summary>Callback for LandStatReply packets</summary>
//public event LandStatReply OnLandStatReply;
/// <summary>Triggered upon a successful .GetTopColliders()</summary>
public event GetTopCollidersReply OnGetTopColliders;
/// <summary>Triggered upon a successful .GetTopScripts()</summary>
public event GetTopScriptsReply OnGetTopScripts;
/// <summary>Returned, along with other info, upon a successful .GetInfo()</summary>
public event EstateUpdateInfoReply OnGetEstateUpdateInfo;
/// <summary>Returned, along with other info, upon a successful .GetInfo()</summary>
public event EstateManagersReply OnGetEstateManagers;
/// <summary>Returned, along with other info, upon a successful .GetInfo()</summary>
public event EstateBansReply OnGetEstateBans;
/// <summary>Returned, along with other info, upon a successful .GetInfo()</summary>
public event EstateGroupsReply OnGetAllowedGroups;
/// <summary>Returned, along with other info, upon a successful .GetInfo()</summary>
public event EstateUsersReply OnGetAllowedUsers;
/// <summary>Triggered upon a successful .RequestCovenant()</summary>
public event EstateCovenantReply OnGetCovenant;
/// <summary>
/// Constructor for EstateTools class
/// </summary>
/// <param name="client"></param>
public EstateTools(GridClient client)
{
Client = client;
Client.Network.RegisterCallback(PacketType.LandStatReply, new NetworkManager.PacketCallback(LandStatReplyHandler));
Client.Network.RegisterCallback(PacketType.EstateOwnerMessage, new NetworkManager.PacketCallback(EstateOwnerMessageHandler));
Client.Network.RegisterCallback(PacketType.EstateCovenantReply, new NetworkManager.PacketCallback(EstateCovenantReplyHandler));
}
/// <summary>Describes tasks returned in LandStatReply</summary>
public class EstateTask
{
public Vector3 Position;
public float Score;
public UUID TaskID;
public uint TaskLocalID;
public string TaskName;
public string OwnerName;
}
/// <summary>Used in the ReportType field of a LandStatRequest</summary>
public enum LandStatReportType
{
TopScripts = 0,
TopColliders = 1
}
/// <summary>Used by EstateOwnerMessage packets</summary>
public enum EstateAccessDelta
{
BanUser = 64,
BanUserAllEstates = 66,
UnbanUser = 128,
UnbanUserAllEstates = 130
}
public enum EstateAccessReplyDelta : uint
{
AllowedUsers = 17,
AllowedGroups = 18,
EstateBans = 20,
EstateManagers = 24
}
/// <summary>Used by GroundTextureSettings</summary>
public class GroundTextureRegion
{
public UUID TextureID;
public float Low;
public float High;
}
/// <summary>Ground texture settings for each corner of the region</summary>
public class GroundTextureSettings
{
public GroundTextureRegion Southwest;
public GroundTextureRegion Northwest;
public GroundTextureRegion Southeast;
public GroundTextureRegion Northeast;
}
/// <summary>
/// Requests estate information such as top scripts and colliders
/// </summary>
/// <param name="parcelLocalID"></param>
/// <param name="reportType"></param>
/// <param name="requestFlags"></param>
/// <param name="filter"></param>
public void LandStatRequest(int parcelLocalID, LandStatReportType reportType, uint requestFlags, string filter)
{
LandStatRequestPacket p = new LandStatRequestPacket();
p.AgentData.AgentID = Client.Self.AgentID;
p.AgentData.SessionID = Client.Self.SessionID;
p.RequestData.Filter = Utils.StringToBytes(filter);
p.RequestData.ParcelLocalID = parcelLocalID;
p.RequestData.ReportType = (uint)reportType;
p.RequestData.RequestFlags = requestFlags;
Client.Network.SendPacket(p);
}
/// <summary>Requests estate settings, including estate manager and access/ban lists</summary>
public void GetInfo()
{
EstateOwnerMessage("getinfo", "");
}
/// <summary>Requests the "Top Scripts" list for the current region</summary>
public void GetTopScripts()
{
//EstateOwnerMessage("scripts", "");
LandStatRequest(0, LandStatReportType.TopScripts, 0, "");
}
/// <summary>Requests the "Top Colliders" list for the current region</summary>
public void GetTopColliders()
{
//EstateOwnerMessage("colliders", "");
LandStatRequest(0, LandStatReportType.TopColliders, 0, "");
}
private void EstateCovenantReplyHandler(Packet packet, Simulator simulator)
{
EstateCovenantReplyPacket reply = (EstateCovenantReplyPacket)packet;
if (OnGetCovenant != null)
{
try
{
OnGetCovenant(
reply.Data.CovenantID,
reply.Data.CovenantTimestamp,
Utils.BytesToString(reply.Data.EstateName),
reply.Data.EstateOwnerID);
}
catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); }
}
}
/// <summary></summary>
/// <param name="packet"></param>
/// <param name="simulator"></param>
private void EstateOwnerMessageHandler(Packet packet, Simulator simulator)
{
EstateOwnerMessagePacket message = (EstateOwnerMessagePacket)packet;
uint estateID;
string method = Utils.BytesToString(message.MethodData.Method);
//List<string> parameters = new List<string>();
if (method == "estateupdateinfo")
{
string estateName = Utils.BytesToString(message.ParamList[0].Parameter);
UUID estateOwner = new UUID(Utils.BytesToString(message.ParamList[1].Parameter));
estateID = Utils.BytesToUInt(message.ParamList[2].Parameter);
/*
foreach (EstateOwnerMessagePacket.ParamListBlock param in message.ParamList)
{
parameters.Add(Utils.BytesToString(param.Parameter));
}
*/
bool denyNoPaymentInfo;
if (Utils.BytesToUInt(message.ParamList[8].Parameter) == 0) denyNoPaymentInfo = true;
else denyNoPaymentInfo = false;
if (OnGetEstateUpdateInfo != null)
{
try
{
OnGetEstateUpdateInfo(estateName, estateOwner, estateID, denyNoPaymentInfo);
}
catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); }
}
}
else if (method == "setaccess")
{
int count;
estateID = Utils.BytesToUInt(message.ParamList[0].Parameter);
if (message.ParamList.Length > 1)
{
//param comes in as a string for some reason
uint param;
if (!uint.TryParse(Utils.BytesToString(message.ParamList[1].Parameter), out param)) return;
EstateAccessReplyDelta accessType = (EstateAccessReplyDelta)param;
switch (accessType)
{
case EstateAccessReplyDelta.EstateManagers:
if (OnGetEstateManagers != null)
{
if (message.ParamList.Length > 5)
{
if (!int.TryParse(Utils.BytesToString(message.ParamList[5].Parameter), out count)) return;
List<UUID> managers = new List<UUID>();
for (int i = 6; i < message.ParamList.Length; i++)
{
try
{
UUID managerID = new UUID(message.ParamList[i].Parameter, 0);
managers.Add(managerID);
}
catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); }
}
try { OnGetEstateManagers(estateID, count, managers); }
catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); }
}
}
break;
case EstateAccessReplyDelta.EstateBans:
if (OnGetEstateBans != null)
{
if (message.ParamList.Length > 6)
{
if (!int.TryParse(Utils.BytesToString(message.ParamList[4].Parameter), out count)) return;
List<UUID> bannedUsers = new List<UUID>();
for (int i = 7; i < message.ParamList.Length; i++)
{
try
{
UUID bannedID = new UUID(message.ParamList[i].Parameter, 0);
bannedUsers.Add(bannedID);
}
catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); }
}
try { OnGetEstateBans(estateID, count, bannedUsers); }
catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); }
}
}
break;
case EstateAccessReplyDelta.AllowedUsers:
if (OnGetAllowedUsers != null)
{
if (message.ParamList.Length > 5)
{
if (!int.TryParse(Utils.BytesToString(message.ParamList[2].Parameter), out count)) return;
List<UUID> allowedUsers = new List<UUID>();
for (int i = 6; i < message.ParamList.Length; i++)
{
try
{
UUID allowedID = new UUID(message.ParamList[i].Parameter, 0);
allowedUsers.Add(allowedID);
}
catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); }
}
try { OnGetAllowedUsers(estateID, count, allowedUsers); }
catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); }
}
}
break;
case EstateAccessReplyDelta.AllowedGroups:
if (OnGetAllowedGroups != null)
{
if (message.ParamList.Length > 5)
{
if (!int.TryParse(Utils.BytesToString(message.ParamList[3].Parameter), out count)) return;
List<UUID> allowedGroups = new List<UUID>();
for (int i = 5; i < message.ParamList.Length; i++)
{
try
{
UUID groupID = new UUID(message.ParamList[i].Parameter, 0);
allowedGroups.Add(groupID);
}
catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); }
}
try { OnGetAllowedGroups(estateID, count, allowedGroups); }
catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); }
}
}
break;
}
}
}
/*
Console.WriteLine("--- " + method + " ---");
foreach (EstateOwnerMessagePacket.ParamListBlock block in message.ParamList)
{
Console.WriteLine(Utils.BytesToString(block.Parameter));
}
Console.WriteLine("------");
*/
}
/// <summary></summary>
/// <param name="packet"></param>
/// <param name="simulator"></param>
private void LandStatReplyHandler(Packet packet, Simulator simulator)
{
//if (OnLandStatReply != null || OnGetTopScripts != null || OnGetTopColliders != null)
if (OnGetTopScripts != null || OnGetTopColliders != null)
{
LandStatReplyPacket p = (LandStatReplyPacket)packet;
List<EstateTask> Tasks = new List<EstateTask>();
foreach (LandStatReplyPacket.ReportDataBlock rep in p.ReportData)
{
EstateTask task = new EstateTask();
task.Position = new Vector3(rep.LocationX, rep.LocationY, rep.LocationZ);
task.Score = rep.Score;
task.TaskID = rep.TaskID;
task.TaskLocalID = rep.TaskLocalID;
task.TaskName = Utils.BytesToString(rep.TaskName);
task.OwnerName = Utils.BytesToString(rep.OwnerName);
Tasks.Add(task);
}
LandStatReportType type = (LandStatReportType)p.RequestData.ReportType;
if (OnGetTopScripts != null && type == LandStatReportType.TopScripts)
{
try { OnGetTopScripts((int)p.RequestData.TotalObjectCount, Tasks); }
catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); }
}
else if (OnGetTopColliders != null && type == LandStatReportType.TopColliders)
{
try { OnGetTopColliders((int)p.RequestData.TotalObjectCount, Tasks); }
catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); }
}
/*
if (OnGetTopColliders != null)
{
//FIXME - System.UnhandledExceptionEventArgs
OnLandStatReply(
type,
p.RequestData.RequestFlags,
(int)p.RequestData.TotalObjectCount,
Tasks
);
}
*/
}
}
public void EstateOwnerMessage(string method, string param)
{
List<string> listParams = new List<string>();
listParams.Add(param);
EstateOwnerMessage(method, listParams);
}
/// <summary>
/// Used for setting and retrieving various estate panel settings
/// </summary>
/// <param name="method">EstateOwnerMessage Method field</param>
/// <param name="listParams">List of parameters to include</param>
public void EstateOwnerMessage(string method, List<string>listParams)
{
EstateOwnerMessagePacket estate = new EstateOwnerMessagePacket();
estate.AgentData.AgentID = Client.Self.AgentID;
estate.AgentData.SessionID = Client.Self.SessionID;
estate.AgentData.TransactionID = UUID.Zero;
estate.MethodData.Invoice = UUID.Random();
estate.MethodData.Method = Utils.StringToBytes(method);
estate.ParamList = new EstateOwnerMessagePacket.ParamListBlock[listParams.Count];
for (int i = 0; i < listParams.Count; i++)
{
estate.ParamList[i] = new EstateOwnerMessagePacket.ParamListBlock();
estate.ParamList[i].Parameter = Utils.StringToBytes(listParams[i]);
}
Client.Network.SendPacket((Packet)estate);
}
/// <summary>
/// Kick an avatar from an estate
/// </summary>
/// <param name="userID">Key of Agent to remove</param>
public void KickUser(UUID userID)
{
EstateOwnerMessage("kickestate", userID.ToString());
}
/// <summary>
/// Ban an avatar from an estate</summary>
/// <param name="userID">Key of Agent to remove</param>
/// <param name="allEstates">Ban user from this estate and all others owned by the estate owner</param>
public void BanUser(UUID userID, bool allEstates)
{
List<string> listParams = new List<string>();
uint flag = allEstates ? (uint)EstateAccessDelta.BanUserAllEstates : (uint)EstateAccessDelta.BanUser;
listParams.Add(Client.Self.AgentID.ToString());
listParams.Add(flag.ToString());
listParams.Add(userID.ToString());
EstateOwnerMessage("estateaccessdelta", listParams);
}
/// <summary>Unban an avatar from an estate</summary>
/// <param name="userID">Key of Agent to remove</param>
/// /// <param name="allEstates">Unban user from this estate and all others owned by the estate owner</param>
public void UnbanUser(UUID userID, bool allEstates)
{
List<string> listParams = new List<string>();
uint flag = allEstates ? (uint)EstateAccessDelta.UnbanUserAllEstates : (uint)EstateAccessDelta.UnbanUser;
listParams.Add(Client.Self.AgentID.ToString());
listParams.Add(flag.ToString());
listParams.Add(userID.ToString());
EstateOwnerMessage("estateaccessdelta", listParams);
}
/// <summary>
/// Send a message dialog to everyone in an entire estate
/// </summary>
/// <param name="message">Message to send all users in the estate</param>
public void EstateMessage(string message)
{
List<string> listParams = new List<string>();
listParams.Add(Client.Self.FirstName + " " + Client.Self.LastName);
listParams.Add(message);
EstateOwnerMessage("instantmessage", listParams);
}
/// <summary>
/// Send a message dialog to everyone in a simulator
/// </summary>
/// <param name="message">Message to send all users in the simulator</param>
public void SimulatorMessage(string message)
{
List<string> listParams = new List<string>();
listParams.Add("-1");
listParams.Add("-1");
listParams.Add(Client.Self.AgentID.ToString());
listParams.Add(Client.Self.FirstName + " " + Client.Self.LastName);
listParams.Add(message);
EstateOwnerMessage("simulatormessage", listParams);
}
/// <summary>
/// Send an avatar back to their home location
/// </summary>
/// <param name="pest">Key of avatar to send home</param>
public void TeleportHomeUser(UUID pest)
{
List<string> listParams = new List<string>();
listParams.Add(Client.Self.AgentID.ToString());
listParams.Add(pest.ToString());
EstateOwnerMessage("teleporthomeuser", listParams);
}
/// <summary>
/// Begin the region restart process
/// </summary>
public void RestartRegion()
{
EstateOwnerMessage("restart", "120");
}
/// <summary>
/// Cancels a region restart
/// </summary>
public void CancelRestart()
{
EstateOwnerMessage("restart", "-1");
}
/// <summary>Estate panel "Region" tab settings</summary>
public void SetRegionInfo(bool blockTerraform, bool blockFly, bool allowDamage, bool allowLandResell, bool restrictPushing, bool allowParcelJoinDivide, float agentLimit, float objectBonus, bool mature)
{
List<string> listParams = new List<string>();
if (blockTerraform) listParams.Add("Y"); else listParams.Add("N");
if (blockFly) listParams.Add("Y"); else listParams.Add("N");
if (allowDamage) listParams.Add("Y"); else listParams.Add("N");
if (allowLandResell) listParams.Add("Y"); else listParams.Add("N");
listParams.Add(agentLimit.ToString());
listParams.Add(objectBonus.ToString());
if (mature) listParams.Add("21"); else listParams.Add("13"); //FIXME - enumerate these settings
if (restrictPushing) listParams.Add("Y"); else listParams.Add("N");
if (allowParcelJoinDivide) listParams.Add("Y"); else listParams.Add("N");
EstateOwnerMessage("setregioninfo", listParams);
}
/// <summary>Estate panel "Debug" tab settings</summary>
public void SetRegionDebug(bool disableScripts, bool disableCollisions, bool disablePhysics)
{
List<string> listParams = new List<string>();
if (disableScripts) listParams.Add("Y"); else listParams.Add("N");
if (disableCollisions) listParams.Add("Y"); else listParams.Add("N");
if (disablePhysics) listParams.Add("Y"); else listParams.Add("N");
EstateOwnerMessage("setregiondebug", listParams);
}
public void RequestCovenant()
{
EstateCovenantRequestPacket req = new EstateCovenantRequestPacket();
req.AgentData.AgentID = Client.Self.AgentID;
req.AgentData.SessionID = Client.Self.SessionID;
Client.Network.SendPacket(req);
}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the opsworks-2013-02-18.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.OpsWorks.Model
{
/// <summary>
/// Container for the parameters to the CloneStack operation.
/// Creates a clone of a specified stack. For more information, see <a href="http://docs.aws.amazon.com/opsworks/latest/userguide/workingstacks-cloning.html">Clone
/// a Stack</a>. By default, all parameters are set to the values used by the parent stack.
///
///
/// <para>
/// <b>Required Permissions</b>: To use this action, an IAM user must have an attached
/// policy that explicitly grants permissions. For more information on user permissions,
/// see <a href="http://docs.aws.amazon.com/opsworks/latest/userguide/opsworks-security-users.html">Managing
/// User Permissions</a>.
/// </para>
/// </summary>
public partial class CloneStackRequest : AmazonOpsWorksRequest
{
private string _agentVersion;
private Dictionary<string, string> _attributes = new Dictionary<string, string>();
private ChefConfiguration _chefConfiguration;
private List<string> _cloneAppIds = new List<string>();
private bool? _clonePermissions;
private StackConfigurationManager _configurationManager;
private Source _customCookbooksSource;
private string _customJson;
private string _defaultAvailabilityZone;
private string _defaultInstanceProfileArn;
private string _defaultOs;
private RootDeviceType _defaultRootDeviceType;
private string _defaultSshKeyName;
private string _defaultSubnetId;
private string _hostnameTheme;
private string _name;
private string _region;
private string _serviceRoleArn;
private string _sourceStackId;
private bool? _useCustomCookbooks;
private bool? _useOpsworksSecurityGroups;
private string _vpcId;
/// <summary>
/// Gets and sets the property AgentVersion.
/// <para>
/// The default AWS OpsWorks agent version. You have the following options:
/// </para>
/// <ul> <li>Auto-update - Set this parameter to <code>LATEST</code>. AWS OpsWorks automatically
/// installs new agent versions on the stack's instances as soon as they are available.</li>
/// <li>Fixed version - Set this parameter to your preferred agent version. To update
/// the agent version, you must edit the stack configuration and specify a new version.
/// AWS OpsWorks then automatically installs that version on the stack's instances.</li>
/// </ul>
/// <para>
/// The default setting is <code>LATEST</code>. To specify an agent version, you must
/// use the complete version number, not the abbreviated number shown on the console.
/// For a list of available agent version numbers, call <a>DescribeAgentVersions</a>.
/// </para>
/// <note>You can also specify an agent version when you create or update an instance,
/// which overrides the stack's default setting.</note>
/// </summary>
public string AgentVersion
{
get { return this._agentVersion; }
set { this._agentVersion = value; }
}
// Check to see if AgentVersion property is set
internal bool IsSetAgentVersion()
{
return this._agentVersion != null;
}
/// <summary>
/// Gets and sets the property Attributes.
/// <para>
/// A list of stack attributes and values as key/value pairs to be added to the cloned
/// stack.
/// </para>
/// </summary>
public Dictionary<string, string> Attributes
{
get { return this._attributes; }
set { this._attributes = value; }
}
// Check to see if Attributes property is set
internal bool IsSetAttributes()
{
return this._attributes != null && this._attributes.Count > 0;
}
/// <summary>
/// Gets and sets the property ChefConfiguration.
/// <para>
/// A <code>ChefConfiguration</code> object that specifies whether to enable Berkshelf
/// and the Berkshelf version on Chef 11.10 stacks. For more information, see <a href="http://docs.aws.amazon.com/opsworks/latest/userguide/workingstacks-creating.html">Create
/// a New Stack</a>.
/// </para>
/// </summary>
public ChefConfiguration ChefConfiguration
{
get { return this._chefConfiguration; }
set { this._chefConfiguration = value; }
}
// Check to see if ChefConfiguration property is set
internal bool IsSetChefConfiguration()
{
return this._chefConfiguration != null;
}
/// <summary>
/// Gets and sets the property CloneAppIds.
/// <para>
/// A list of source stack app IDs to be included in the cloned stack.
/// </para>
/// </summary>
public List<string> CloneAppIds
{
get { return this._cloneAppIds; }
set { this._cloneAppIds = value; }
}
// Check to see if CloneAppIds property is set
internal bool IsSetCloneAppIds()
{
return this._cloneAppIds != null && this._cloneAppIds.Count > 0;
}
/// <summary>
/// Gets and sets the property ClonePermissions.
/// <para>
/// Whether to clone the source stack's permissions.
/// </para>
/// </summary>
public bool ClonePermissions
{
get { return this._clonePermissions.GetValueOrDefault(); }
set { this._clonePermissions = value; }
}
// Check to see if ClonePermissions property is set
internal bool IsSetClonePermissions()
{
return this._clonePermissions.HasValue;
}
/// <summary>
/// Gets and sets the property ConfigurationManager.
/// <para>
/// The configuration manager. When you clone a Linux stack we recommend that you use
/// the configuration manager to specify the Chef version: 0.9, 11.4, or 11.10. The default
/// value is currently 11.10.
/// </para>
/// </summary>
public StackConfigurationManager ConfigurationManager
{
get { return this._configurationManager; }
set { this._configurationManager = value; }
}
// Check to see if ConfigurationManager property is set
internal bool IsSetConfigurationManager()
{
return this._configurationManager != null;
}
/// <summary>
/// Gets and sets the property CustomCookbooksSource.
/// </summary>
public Source CustomCookbooksSource
{
get { return this._customCookbooksSource; }
set { this._customCookbooksSource = value; }
}
// Check to see if CustomCookbooksSource property is set
internal bool IsSetCustomCookbooksSource()
{
return this._customCookbooksSource != null;
}
/// <summary>
/// Gets and sets the property CustomJson.
/// <para>
/// A string that contains user-defined, custom JSON. It is used to override the corresponding
/// default stack configuration JSON values. The string should be in the following format
/// and must escape characters such as '"':
/// </para>
///
/// <para>
/// <code>"{\"key1\": \"value1\", \"key2\": \"value2\",...}"</code>
/// </para>
///
/// <para>
/// For more information on custom JSON, see <a href="http://docs.aws.amazon.com/opsworks/latest/userguide/workingstacks-json.html">Use
/// Custom JSON to Modify the Stack Configuration Attributes</a>
/// </para>
/// </summary>
public string CustomJson
{
get { return this._customJson; }
set { this._customJson = value; }
}
// Check to see if CustomJson property is set
internal bool IsSetCustomJson()
{
return this._customJson != null;
}
/// <summary>
/// Gets and sets the property DefaultAvailabilityZone.
/// <para>
/// The cloned stack's default Availability Zone, which must be in the specified region.
/// For more information, see <a href="http://docs.aws.amazon.com/general/latest/gr/rande.html">Regions
/// and Endpoints</a>. If you also specify a value for <code>DefaultSubnetId</code>, the
/// subnet must be in the same zone. For more information, see the <code>VpcId</code>
/// parameter description.
/// </para>
/// </summary>
public string DefaultAvailabilityZone
{
get { return this._defaultAvailabilityZone; }
set { this._defaultAvailabilityZone = value; }
}
// Check to see if DefaultAvailabilityZone property is set
internal bool IsSetDefaultAvailabilityZone()
{
return this._defaultAvailabilityZone != null;
}
/// <summary>
/// Gets and sets the property DefaultInstanceProfileArn.
/// <para>
/// The Amazon Resource Name (ARN) of an IAM profile that is the default profile for all
/// of the stack's EC2 instances. For more information about IAM ARNs, see <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html">Using
/// Identifiers</a>.
/// </para>
/// </summary>
public string DefaultInstanceProfileArn
{
get { return this._defaultInstanceProfileArn; }
set { this._defaultInstanceProfileArn = value; }
}
// Check to see if DefaultInstanceProfileArn property is set
internal bool IsSetDefaultInstanceProfileArn()
{
return this._defaultInstanceProfileArn != null;
}
/// <summary>
/// Gets and sets the property DefaultOs.
/// <para>
/// The stack's operating system, which must be set to one of the following.
/// </para>
/// <ul> <li>A supported Linux operating system: An Amazon Linux version, such as <code>Amazon
/// Linux 2015.03</code>, <code>Red Hat Enterprise Linux 7</code>, <code>Ubuntu 12.04
/// LTS</code>, or <code>Ubuntu 14.04 LTS</code>.</li> <li> <code>Microsoft Windows Server
/// 2012 R2 Base</code>.</li> <li>A custom AMI: <code>Custom</code>. You specify the custom
/// AMI you want to use when you create instances. For more information on how to use
/// custom AMIs with OpsWorks, see <a href="http://docs.aws.amazon.com/opsworks/latest/userguide/workinginstances-custom-ami.html">Using
/// Custom AMIs</a>.</li> </ul>
/// <para>
/// The default option is the parent stack's operating system. For more information on
/// the supported operating systems, see <a href="http://docs.aws.amazon.com/opsworks/latest/userguide/workinginstances-os.html">AWS
/// OpsWorks Operating Systems</a>.
/// </para>
/// <note>You can specify a different Linux operating system for the cloned stack, but
/// you cannot change from Linux to Windows or Windows to Linux.</note>
/// </summary>
public string DefaultOs
{
get { return this._defaultOs; }
set { this._defaultOs = value; }
}
// Check to see if DefaultOs property is set
internal bool IsSetDefaultOs()
{
return this._defaultOs != null;
}
/// <summary>
/// Gets and sets the property DefaultRootDeviceType.
/// <para>
/// The default root device type. This value is used by default for all instances in the
/// cloned stack, but you can override it when you create an instance. For more information,
/// see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ComponentsAMIs.html#storage-for-the-root-device">Storage
/// for the Root Device</a>.
/// </para>
/// </summary>
public RootDeviceType DefaultRootDeviceType
{
get { return this._defaultRootDeviceType; }
set { this._defaultRootDeviceType = value; }
}
// Check to see if DefaultRootDeviceType property is set
internal bool IsSetDefaultRootDeviceType()
{
return this._defaultRootDeviceType != null;
}
/// <summary>
/// Gets and sets the property DefaultSshKeyName.
/// <para>
/// A default Amazon EC2 key pair name. The default value is none. If you specify a key
/// pair name, AWS OpsWorks installs the public key on the instance and you can use the
/// private key with an SSH client to log in to the instance. For more information, see
/// <a href="http://docs.aws.amazon.com/opsworks/latest/userguide/workinginstances-ssh.html">
/// Using SSH to Communicate with an Instance</a> and <a href="http://docs.aws.amazon.com/opsworks/latest/userguide/security-ssh-access.html">
/// Managing SSH Access</a>. You can override this setting by specifying a different key
/// pair, or no key pair, when you <a href="http://docs.aws.amazon.com/opsworks/latest/userguide/workinginstances-add.html">
/// create an instance</a>.
/// </para>
/// </summary>
public string DefaultSshKeyName
{
get { return this._defaultSshKeyName; }
set { this._defaultSshKeyName = value; }
}
// Check to see if DefaultSshKeyName property is set
internal bool IsSetDefaultSshKeyName()
{
return this._defaultSshKeyName != null;
}
/// <summary>
/// Gets and sets the property DefaultSubnetId.
/// <para>
/// The stack's default VPC subnet ID. This parameter is required if you specify a value
/// for the <code>VpcId</code> parameter. All instances are launched into this subnet
/// unless you specify otherwise when you create the instance. If you also specify a value
/// for <code>DefaultAvailabilityZone</code>, the subnet must be in that zone. For information
/// on default values and when this parameter is required, see the <code>VpcId</code>
/// parameter description.
/// </para>
/// </summary>
public string DefaultSubnetId
{
get { return this._defaultSubnetId; }
set { this._defaultSubnetId = value; }
}
// Check to see if DefaultSubnetId property is set
internal bool IsSetDefaultSubnetId()
{
return this._defaultSubnetId != null;
}
/// <summary>
/// Gets and sets the property HostnameTheme.
/// <para>
/// The stack's host name theme, with spaces are replaced by underscores. The theme is
/// used to generate host names for the stack's instances. By default, <code>HostnameTheme</code>
/// is set to <code>Layer_Dependent</code>, which creates host names by appending integers
/// to the layer's short name. The other themes are:
/// </para>
/// <ul> <li> <code>Baked_Goods</code> </li> <li> <code>Clouds</code> </li> <li> <code>Europe_Cities</code>
/// </li> <li> <code>Fruits</code> </li> <li> <code>Greek_Deities</code> </li> <li> <code>Legendary_creatures_from_Japan</code>
/// </li> <li> <code>Planets_and_Moons</code> </li> <li> <code>Roman_Deities</code> </li>
/// <li> <code>Scottish_Islands</code> </li> <li> <code>US_Cities</code> </li> <li> <code>Wild_Cats</code>
/// </li> </ul>
/// <para>
/// To obtain a generated host name, call <code>GetHostNameSuggestion</code>, which returns
/// a host name based on the current theme.
/// </para>
/// </summary>
public string HostnameTheme
{
get { return this._hostnameTheme; }
set { this._hostnameTheme = value; }
}
// Check to see if HostnameTheme property is set
internal bool IsSetHostnameTheme()
{
return this._hostnameTheme != null;
}
/// <summary>
/// Gets and sets the property Name.
/// <para>
/// The cloned stack name.
/// </para>
/// </summary>
public string Name
{
get { return this._name; }
set { this._name = value; }
}
// Check to see if Name property is set
internal bool IsSetName()
{
return this._name != null;
}
/// <summary>
/// Gets and sets the property Region.
/// <para>
/// The cloned stack AWS region, such as "us-east-1". For more information about AWS regions,
/// see <a href="http://docs.aws.amazon.com/general/latest/gr/rande.html">Regions and
/// Endpoints</a>.
/// </para>
/// </summary>
public string Region
{
get { return this._region; }
set { this._region = value; }
}
// Check to see if Region property is set
internal bool IsSetRegion()
{
return this._region != null;
}
/// <summary>
/// Gets and sets the property ServiceRoleArn.
/// <para>
/// The stack AWS Identity and Access Management (IAM) role, which allows AWS OpsWorks
/// to work with AWS resources on your behalf. You must set this parameter to the Amazon
/// Resource Name (ARN) for an existing IAM role. If you create a stack by using the AWS
/// OpsWorks console, it creates the role for you. You can obtain an existing stack's
/// IAM ARN programmatically by calling <a>DescribePermissions</a>. For more information
/// about IAM ARNs, see <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html">Using
/// Identifiers</a>.
/// </para>
/// <note>
/// <para>
/// You must set this parameter to a valid service role ARN or the action will fail; there
/// is no default value. You can specify the source stack's service role ARN, if you prefer,
/// but you must do so explicitly.
/// </para>
/// </note>
/// </summary>
public string ServiceRoleArn
{
get { return this._serviceRoleArn; }
set { this._serviceRoleArn = value; }
}
// Check to see if ServiceRoleArn property is set
internal bool IsSetServiceRoleArn()
{
return this._serviceRoleArn != null;
}
/// <summary>
/// Gets and sets the property SourceStackId.
/// <para>
/// The source stack ID.
/// </para>
/// </summary>
public string SourceStackId
{
get { return this._sourceStackId; }
set { this._sourceStackId = value; }
}
// Check to see if SourceStackId property is set
internal bool IsSetSourceStackId()
{
return this._sourceStackId != null;
}
/// <summary>
/// Gets and sets the property UseCustomCookbooks.
/// <para>
/// Whether to use custom cookbooks.
/// </para>
/// </summary>
public bool UseCustomCookbooks
{
get { return this._useCustomCookbooks.GetValueOrDefault(); }
set { this._useCustomCookbooks = value; }
}
// Check to see if UseCustomCookbooks property is set
internal bool IsSetUseCustomCookbooks()
{
return this._useCustomCookbooks.HasValue;
}
/// <summary>
/// Gets and sets the property UseOpsworksSecurityGroups.
/// <para>
/// Whether to associate the AWS OpsWorks built-in security groups with the stack's layers.
/// </para>
///
/// <para>
/// AWS OpsWorks provides a standard set of built-in security groups, one for each layer,
/// which are associated with layers by default. With <code>UseOpsworksSecurityGroups</code>
/// you can instead provide your own custom security groups. <code>UseOpsworksSecurityGroups</code>
/// has the following settings:
/// </para>
/// <ul> <li>True - AWS OpsWorks automatically associates the appropriate built-in security
/// group with each layer (default setting). You can associate additional security groups
/// with a layer after you create it but you cannot delete the built-in security group.
/// </li> <li>False - AWS OpsWorks does not associate built-in security groups with layers.
/// You must create appropriate Amazon Elastic Compute Cloud (Amazon EC2) security groups
/// and associate a security group with each layer that you create. However, you can still
/// manually associate a built-in security group with a layer on creation; custom security
/// groups are required only for those layers that need custom settings. </li> </ul>
/// <para>
/// For more information, see <a href="http://docs.aws.amazon.com/opsworks/latest/userguide/workingstacks-creating.html">Create
/// a New Stack</a>.
/// </para>
/// </summary>
public bool UseOpsworksSecurityGroups
{
get { return this._useOpsworksSecurityGroups.GetValueOrDefault(); }
set { this._useOpsworksSecurityGroups = value; }
}
// Check to see if UseOpsworksSecurityGroups property is set
internal bool IsSetUseOpsworksSecurityGroups()
{
return this._useOpsworksSecurityGroups.HasValue;
}
/// <summary>
/// Gets and sets the property VpcId.
/// <para>
/// The ID of the VPC that the cloned stack is to be launched into. It must be in the
/// specified region. All instances are launched into this VPC, and you cannot change
/// the ID later.
/// </para>
/// <ul> <li>If your account supports EC2 Classic, the default value is no VPC.</li>
/// <li>If your account does not support EC2 Classic, the default value is the default
/// VPC for the specified region.</li> </ul>
/// <para>
/// If the VPC ID corresponds to a default VPC and you have specified either the <code>DefaultAvailabilityZone</code>
/// or the <code>DefaultSubnetId</code> parameter only, AWS OpsWorks infers the value
/// of the other parameter. If you specify neither parameter, AWS OpsWorks sets these
/// parameters to the first valid Availability Zone for the specified region and the corresponding
/// default VPC subnet ID, respectively.
/// </para>
///
/// <para>
/// If you specify a nondefault VPC ID, note the following:
/// </para>
/// <ul> <li>It must belong to a VPC in your account that is in the specified region.</li>
/// <li>You must specify a value for <code>DefaultSubnetId</code>.</li> </ul>
/// <para>
/// For more information on how to use AWS OpsWorks with a VPC, see <a href="http://docs.aws.amazon.com/opsworks/latest/userguide/workingstacks-vpc.html">Running
/// a Stack in a VPC</a>. For more information on default VPC and EC2 Classic, see <a
/// href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-platforms.html">Supported
/// Platforms</a>.
/// </para>
/// </summary>
public string VpcId
{
get { return this._vpcId; }
set { this._vpcId = value; }
}
// Check to see if VpcId property is set
internal bool IsSetVpcId()
{
return this._vpcId != 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.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net.Security;
namespace System.Net
{
public sealed unsafe partial class HttpListener
{
public static bool IsSupported => true;
private Dictionary<HttpListenerContext, HttpListenerContext> _listenerContexts = new Dictionary<HttpListenerContext, HttpListenerContext>();
private List<HttpListenerContext> _contextQueue = new List<HttpListenerContext>();
private List<ListenerAsyncResult> _asyncWaitQueue = new List<ListenerAsyncResult>();
private Dictionary<HttpConnection, HttpConnection> _connections = new Dictionary<HttpConnection, HttpConnection>();
internal SslStream CreateSslStream(Stream innerStream, bool ownsStream, RemoteCertificateValidationCallback callback)
{
return new SslStream(innerStream, ownsStream, callback);
}
public HttpListenerTimeoutManager TimeoutManager
{
get
{
throw new PlatformNotSupportedException();
}
}
public HttpListenerPrefixCollection Prefixes
{
get
{
CheckDisposed();
return _prefixes;
}
}
public void Start()
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
lock (_internalLock)
{
try
{
CheckDisposed();
if (_state == State.Started)
return;
HttpEndPointManager.AddListener(this);
_state = State.Started;
}
catch (Exception exception)
{
_state = State.Closed;
if (NetEventSource.IsEnabled) NetEventSource.Error(this, $"Start {exception}");
throw;
}
finally
{
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
}
}
public bool UnsafeConnectionNtlmAuthentication
{
get
{
throw new PlatformNotSupportedException();
}
set
{
throw new PlatformNotSupportedException();
}
}
public void Stop()
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
try
{
lock (_internalLock)
{
CheckDisposed();
if (_state == State.Stopped)
{
return;
}
Close(false);
_state = State.Stopped;
}
}
catch (Exception exception)
{
if (NetEventSource.IsEnabled) NetEventSource.Error(this, $"Stop {exception}");
throw;
}
finally
{
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
}
public void Abort()
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
lock (_internalLock)
{
try
{
if (_state == State.Closed)
{
return;
}
// Just detach and free resources. Don't call Stop (which may throw).
if (_state == State.Started)
{
Close(true);
}
}
catch (Exception exception)
{
if (NetEventSource.IsEnabled) NetEventSource.Error(this, $"Abort {exception}");
throw;
}
finally
{
_state = State.Closed;
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
}
}
private void Dispose()
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
lock (_internalLock)
{
try
{
if (_state == State.Closed)
{
return;
}
Close(true);
}
catch (Exception exception)
{
if (NetEventSource.IsEnabled) NetEventSource.Error(this, $"Dispose {exception}");
throw;
}
finally
{
_state = State.Closed;
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
}
}
private void Close(bool force)
{
CheckDisposed();
HttpEndPointManager.RemoveListener(this);
Cleanup(force);
}
internal void UnregisterContext(HttpListenerContext context)
{
lock ((_listenerContexts as ICollection).SyncRoot)
{
_listenerContexts.Remove(context);
}
lock ((_contextQueue as ICollection).SyncRoot)
{
int idx = _contextQueue.IndexOf(context);
if (idx >= 0)
_contextQueue.RemoveAt(idx);
}
}
internal void AddConnection(HttpConnection cnc)
{
lock ((_connections as ICollection).SyncRoot)
{
_connections[cnc] = cnc;
}
}
internal void RemoveConnection(HttpConnection cnc)
{
lock ((_connections as ICollection).SyncRoot)
{
_connections.Remove(cnc);
}
}
internal void RegisterContext(HttpListenerContext context)
{
lock ((_listenerContexts as ICollection).SyncRoot)
{
_listenerContexts[context] = context;
}
ListenerAsyncResult ares = null;
lock ((_asyncWaitQueue as ICollection).SyncRoot)
{
if (_asyncWaitQueue.Count == 0)
{
lock ((_contextQueue as ICollection).SyncRoot)
_contextQueue.Add(context);
}
else
{
ares = _asyncWaitQueue[0];
_asyncWaitQueue.RemoveAt(0);
}
}
if (ares != null)
{
ares.Complete(context);
}
}
private void Cleanup(bool close_existing)
{
lock ((_listenerContexts as ICollection).SyncRoot)
{
if (close_existing)
{
// Need to copy this since closing will call UnregisterContext
ICollection keys = _listenerContexts.Keys;
var all = new HttpListenerContext[keys.Count];
keys.CopyTo(all, 0);
_listenerContexts.Clear();
for (int i = all.Length - 1; i >= 0; i--)
all[i].Connection.Close(true);
}
lock ((_connections as ICollection).SyncRoot)
{
ICollection keys = _connections.Keys;
var conns = new HttpConnection[keys.Count];
keys.CopyTo(conns, 0);
_connections.Clear();
for (int i = conns.Length - 1; i >= 0; i--)
conns[i].Close(true);
}
lock ((_contextQueue as ICollection).SyncRoot)
{
var ctxs = (HttpListenerContext[])_contextQueue.ToArray();
_contextQueue.Clear();
for (int i = ctxs.Length - 1; i >= 0; i--)
ctxs[i].Connection.Close(true);
}
lock ((_asyncWaitQueue as ICollection).SyncRoot)
{
Exception exc = new ObjectDisposedException("listener");
foreach (ListenerAsyncResult ares in _asyncWaitQueue)
{
ares.Complete(exc);
}
_asyncWaitQueue.Clear();
}
}
}
private HttpListenerContext GetContextFromQueue()
{
lock ((_contextQueue as ICollection).SyncRoot)
{
if (_contextQueue.Count == 0)
{
return null;
}
HttpListenerContext context = _contextQueue[0];
_contextQueue.RemoveAt(0);
return context;
}
}
public IAsyncResult BeginGetContext(AsyncCallback callback, Object state)
{
CheckDisposed();
if (_state != State.Started)
{
throw new InvalidOperationException(SR.Format(SR.net_listener_mustcall, "Start()"));
}
ListenerAsyncResult ares = new ListenerAsyncResult(callback, state);
// lock wait_queue early to avoid race conditions
lock ((_asyncWaitQueue as ICollection).SyncRoot)
{
lock ((_contextQueue as ICollection).SyncRoot)
{
HttpListenerContext ctx = GetContextFromQueue();
if (ctx != null)
{
ares.Complete(ctx, true);
return ares;
}
}
_asyncWaitQueue.Add(ares);
}
return ares;
}
public HttpListenerContext EndGetContext(IAsyncResult asyncResult)
{
CheckDisposed();
if (asyncResult == null)
{
throw new ArgumentNullException(nameof(asyncResult));
}
ListenerAsyncResult ares = asyncResult as ListenerAsyncResult;
if (ares == null)
{
throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
}
if (ares._endCalled)
{
throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, nameof(EndGetContext)));
}
ares._endCalled = true;
if (!ares.IsCompleted)
ares.AsyncWaitHandle.WaitOne();
lock ((_asyncWaitQueue as ICollection).SyncRoot)
{
int idx = _asyncWaitQueue.IndexOf(ares);
if (idx >= 0)
_asyncWaitQueue.RemoveAt(idx);
}
HttpListenerContext context = ares.GetContext();
context.ParseAuthentication(SelectAuthenticationScheme(context));
return context;
}
internal AuthenticationSchemes SelectAuthenticationScheme(HttpListenerContext context)
{
return AuthenticationSchemeSelectorDelegate != null ? AuthenticationSchemeSelectorDelegate(context.Request) : _authenticationScheme;
}
public HttpListenerContext GetContext()
{
if (_state == State.Stopped)
{
throw new InvalidOperationException(SR.Format(SR.net_listener_mustcall, "Start()"));
}
if (_prefixes.Count == 0)
{
throw new InvalidOperationException(SR.Format(SR.net_listener_mustcall, "AddPrefix()"));
}
ListenerAsyncResult ares = (ListenerAsyncResult)BeginGetContext(null, null);
ares._inGet = true;
return EndGetContext(ares);
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Instrumentation;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
public class CSharpCommandLineParser : CommandLineParser
{
public static readonly CSharpCommandLineParser Default = new CSharpCommandLineParser();
public static readonly CSharpCommandLineParser Interactive = new CSharpCommandLineParser(isInteractive: true);
internal CSharpCommandLineParser(bool isInteractive = false)
: base(CSharp.MessageProvider.Instance, isInteractive)
{
}
protected override string RegularFileExtension { get { return ".cs"; } }
protected override string ScriptFileExtension { get { return ".csx"; } }
internal sealed override CommandLineArguments CommonParse(IEnumerable<string> args, string baseDirectory, string additionalReferencePaths)
{
return Parse(args, baseDirectory, additionalReferencePaths);
}
public new CSharpCommandLineArguments Parse(IEnumerable<string> args, string baseDirectory, string additionalReferencePaths = null)
{
using (Logger.LogBlock(FunctionId.CSharp_CommandLineParser_Parse))
{
List<Diagnostic> diagnostics = new List<Diagnostic>();
List<string> flattenedArgs = new List<string>();
List<string> scriptArgs = IsInteractive ? new List<string>() : null;
FlattenArgs(args, diagnostics, flattenedArgs, scriptArgs, baseDirectory);
string appConfigPath = null;
bool displayLogo = true;
bool displayHelp = false;
bool optimize = false;
bool checkOverflow = false;
bool allowUnsafe = false;
bool concurrentBuild = true;
bool emitPdb = false;
string pdbPath = null;
bool noStdLib = false;
string outputDirectory = baseDirectory;
string outputFileName = null;
string documentationPath = null;
bool parseDocumentationComments = false; //Don't just null check documentationFileName because we want to do this even if the file name is invalid.
bool utf8output = false;
OutputKind outputKind = OutputKind.ConsoleApplication;
SubsystemVersion subsystemVersion = SubsystemVersion.None;
LanguageVersion languageVersion = CSharpParseOptions.Default.LanguageVersion;
string mainTypeName = null;
string win32ManifestFile = null;
string win32ResourceFile = null;
string win32IconFile = null;
bool noWin32Manifest = false;
Platform platform = Platform.AnyCpu;
ulong baseAddress = 0;
int fileAlignment = 0;
bool? delaySignSetting = null;
string keyFileSetting = null;
string keyContainerSetting = null;
List<ResourceDescription> managedResources = new List<ResourceDescription>();
List<CommandLineSourceFile> sourceFiles = new List<CommandLineSourceFile>();
List<CommandLineSourceFile> additionalFiles = new List<CommandLineSourceFile>();
bool sourceFilesSpecified = false;
bool resourcesOrModulesSpecified = false;
Encoding codepage = null;
var checksumAlgorithm = SourceHashAlgorithm.Sha1;
var defines = ArrayBuilder<string>.GetInstance();
List<CommandLineReference> metadataReferences = new List<CommandLineReference>();
List<CommandLineAnalyzerReference> analyzers = new List<CommandLineAnalyzerReference>();
List<string> libPaths = new List<string>();
List<string> keyFileSearchPaths = new List<string>();
List<string> usings = new List<string>();
var generalDiagnosticOption = ReportDiagnostic.Default;
var diagnosticOptions = new Dictionary<string, ReportDiagnostic>();
var noWarns = new Dictionary<string, ReportDiagnostic>();
var warnAsErrors = new Dictionary<string, ReportDiagnostic>();
int warningLevel = 4;
bool highEntropyVA = false;
bool printFullPaths = false;
string moduleAssemblyName = null;
string moduleName = null;
List<string> features = new List<string>();
string runtimeMetadataVersion = null;
bool errorEndLocation = false;
CultureInfo preferredUILang = null;
string touchedFilesPath = null;
var sqmSessionGuid = Guid.Empty;
// Process ruleset files first so that diagnostic severity settings specified on the command line via
// /nowarn and /warnaserror can override diagnostic severity settings specified in the ruleset file.
if (!IsInteractive)
{
foreach (string arg in flattenedArgs)
{
string name, value;
if (TryParseOption(arg, out name, out value) && (name == "ruleset"))
{
var unquoted = RemoveAllQuotes(value);
if (string.IsNullOrEmpty(unquoted))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name);
}
else
{
generalDiagnosticOption = GetDiagnosticOptionsFromRulesetFile(diagnosticOptions, diagnostics, unquoted, baseDirectory);
}
}
}
}
foreach (string arg in flattenedArgs)
{
Debug.Assert(!arg.StartsWith("@", StringComparison.Ordinal));
string name, value;
if (!TryParseOption(arg, out name, out value))
{
sourceFiles.AddRange(ParseFileArgument(arg, baseDirectory, diagnostics));
sourceFilesSpecified = true;
continue;
}
switch (name)
{
case "?":
case "help":
displayHelp = true;
continue;
case "r":
case "reference":
metadataReferences.AddRange(ParseAssemblyReferences(arg, value, diagnostics, embedInteropTypes: false));
continue;
case "a":
case "analyzer":
analyzers.AddRange(ParseAnalyzers(arg, value, diagnostics));
continue;
case "d":
case "define":
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", arg);
continue;
}
IEnumerable<Diagnostic> defineDiagnostics;
defines.AddRange(ParseConditionalCompilationSymbols(value, out defineDiagnostics));
diagnostics.AddRange(defineDiagnostics);
continue;
case "codepage":
if (value == null)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name);
continue;
}
var encoding = TryParseEncodingName(value);
if (encoding == null)
{
AddDiagnostic(diagnostics, ErrorCode.FTL_BadCodepage, value);
continue;
}
codepage = encoding;
continue;
case "checksumalgorithm":
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name);
continue;
}
var newChecksumAlgorithm = TryParseHashAlgorithmName(value);
if (newChecksumAlgorithm == SourceHashAlgorithm.None)
{
AddDiagnostic(diagnostics, ErrorCode.FTL_BadChecksumAlgorithm, value);
continue;
}
checksumAlgorithm = newChecksumAlgorithm;
continue;
case "checked":
case "checked+":
if (value != null)
{
break;
}
checkOverflow = true;
continue;
case "checked-":
if (value != null)
break;
checkOverflow = false;
continue;
case "features":
if (value == null)
{
features.Clear();
}
else
{
features.Add(value);
}
continue;
case "noconfig":
// It is already handled (see CommonCommandLineCompiler.cs).
continue;
case "sqmsessionguid":
if (value == null)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_MissingGuidForOption, "<text>", name);
}
else
{
if (!Guid.TryParse(value, out sqmSessionGuid))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidFormatForGuidForOption, value, name);
}
}
continue;
case "preferreduilang":
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", arg);
continue;
}
try
{
preferredUILang = new CultureInfo(value);
}
catch (CultureNotFoundException)
{
AddDiagnostic(diagnostics, ErrorCode.WRN_BadUILang, value);
}
continue;
#if DEBUG
case "attachdebugger":
Debugger.Launch();
continue;
#endif
}
if (IsInteractive)
{
switch (name)
{
// interactive:
case "rp":
case "referencepath":
// TODO: should it really go to libPaths?
ParseAndResolveReferencePaths(name, value, baseDirectory, libPaths, MessageID.IDS_REFERENCEPATH_OPTION, diagnostics);
continue;
case "u":
case "using":
usings.AddRange(ParseUsings(arg, value, diagnostics));
continue;
}
}
else
{
switch (name)
{
case "out":
if (string.IsNullOrWhiteSpace(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg);
}
else
{
ParseOutputFile(value, diagnostics, baseDirectory, out outputFileName, out outputDirectory);
}
continue;
case "t":
case "target":
if (value == null)
{
break; // force 'unrecognized option'
}
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.FTL_InvalidTarget);
}
else
{
outputKind = ParseTarget(value, diagnostics);
}
continue;
case "moduleassemblyname":
value = value != null ? value.Unquote() : null;
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", arg);
}
else if (!MetadataHelpers.IsValidAssemblyOrModuleName(value))
{
// Dev11 C# doesn't check the name (VB does)
AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidAssemblyName, "<text>", arg);
}
else
{
moduleAssemblyName = value;
}
continue;
case "modulename":
var unquotedModuleName = RemoveAllQuotes(value);
if (string.IsNullOrEmpty(unquotedModuleName))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "modulename");
continue;
}
else
{
moduleName = unquotedModuleName;
}
continue;
case "platform":
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<string>", arg);
}
else
{
platform = ParsePlatform(value, diagnostics);
}
continue;
case "recurse":
if (value == null)
{
break; // force 'unrecognized option'
}
else if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg);
}
else
{
int before = sourceFiles.Count;
sourceFiles.AddRange(ParseRecurseArgument(value, baseDirectory, diagnostics));
if (sourceFiles.Count > before)
{
sourceFilesSpecified = true;
}
}
continue;
case "doc":
parseDocumentationComments = true;
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), arg);
continue;
}
string unquoted = RemoveAllQuotes(value);
if (string.IsNullOrEmpty(unquoted))
{
// CONSIDER: This diagnostic exactly matches dev11, but it would be simpler (and more consistent with /out)
// if we just let the next case handle /doc:"".
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "/doc:"); // Different argument.
}
else
{
documentationPath = ParseGenericPathToFile(unquoted, diagnostics, baseDirectory);
}
continue;
case "addmodule":
if (value == null)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "/addmodule:");
}
else if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg);
}
else
{
// NOTE(tomat): Dev10 used to report CS1541: ERR_CantIncludeDirectory if the path was a directory.
// Since we now support /referencePaths option we would need to search them to see if the resolved path is a directory.
// An error will be reported by the assembly manager anyways.
metadataReferences.AddRange(ParseSeparatedPaths(value).Select(path => new CommandLineReference(path, MetadataReferenceProperties.Module)));
resourcesOrModulesSpecified = true;
}
continue;
case "l":
case "link":
metadataReferences.AddRange(ParseAssemblyReferences(arg, value, diagnostics, embedInteropTypes: true));
continue;
case "win32res":
win32ResourceFile = GetWin32Setting(arg, value, diagnostics);
continue;
case "win32icon":
win32IconFile = GetWin32Setting(arg, value, diagnostics);
continue;
case "win32manifest":
win32ManifestFile = GetWin32Setting(arg, value, diagnostics);
noWin32Manifest = false;
continue;
case "nowin32manifest":
noWin32Manifest = true;
win32ManifestFile = null;
continue;
case "res":
case "resource":
if (value == null)
{
break; // Dev11 reports inrecognized option
}
var embeddedResource = ParseResourceDescription(arg, value, baseDirectory, diagnostics, embedded: true);
if (embeddedResource != null)
{
managedResources.Add(embeddedResource);
resourcesOrModulesSpecified = true;
}
continue;
case "linkres":
case "linkresource":
if (value == null)
{
break; // Dev11 reports inrecognized option
}
var linkedResource = ParseResourceDescription(arg, value, baseDirectory, diagnostics, embedded: false);
if (linkedResource != null)
{
managedResources.Add(linkedResource);
resourcesOrModulesSpecified = true;
}
continue;
case "debug":
emitPdb = true;
// unused, parsed for backward compat only
if (value != null)
{
if (value.IsEmpty())
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), name);
}
else if (!string.Equals(value, "full", StringComparison.OrdinalIgnoreCase) &&
!string.Equals(value, "pdbonly", StringComparison.OrdinalIgnoreCase))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_BadDebugType, value);
}
}
continue;
case "debug+":
//guard against "debug+:xx"
if (value != null)
break;
emitPdb = true;
continue;
case "debug-":
if (value != null)
break;
emitPdb = false;
continue;
case "o":
case "optimize":
case "o+":
case "optimize+":
if (value != null)
break;
optimize = true;
continue;
case "o-":
case "optimize-":
if (value != null)
break;
optimize = false;
continue;
case "p":
case "parallel":
case "p+":
case "parallel+":
if (value != null)
break;
concurrentBuild = true;
continue;
case "p-":
case "parallel-":
if (value != null)
break;
concurrentBuild = false;
continue;
case "warnaserror":
case "warnaserror+":
if (value == null)
{
generalDiagnosticOption = ReportDiagnostic.Error;
// Clear specific warnaserror options (since last /warnaserror flag on the command line always wins).
warnAsErrors.Clear();
continue;
}
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name);
}
else
{
AddWarnings(warnAsErrors, ReportDiagnostic.Error, ParseWarnings(value));
}
continue;
case "warnaserror-":
if (value == null)
{
generalDiagnosticOption = ReportDiagnostic.Default;
// Clear specific warnaserror options (since last /warnaserror flag on the command line always wins).
warnAsErrors.Clear();
continue;
}
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name);
}
else
{
AddWarnings(warnAsErrors, ReportDiagnostic.Default, ParseWarnings(value));
}
continue;
case "w":
case "warn":
if (value == null)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name);
continue;
}
int newWarningLevel;
if (string.IsNullOrEmpty(value) ||
!int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out newWarningLevel))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name);
}
else if (newWarningLevel < 0 || newWarningLevel > 4)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_BadWarningLevel, name);
}
else
{
warningLevel = newWarningLevel;
}
continue;
case "nowarn":
if (value == null)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name);
continue;
}
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name);
}
else
{
AddWarnings(noWarns, ReportDiagnostic.Suppress, ParseWarnings(value));
}
continue;
case "unsafe":
case "unsafe+":
if (value != null)
break;
allowUnsafe = true;
continue;
case "unsafe-":
if (value != null)
break;
allowUnsafe = false;
continue;
case "langversion":
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "/langversion:");
}
else if (!TryParseLanguageVersion(value, CSharpParseOptions.Default.LanguageVersion, out languageVersion))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_BadCompatMode, value);
}
continue;
case "delaysign":
case "delaysign+":
if (value != null)
{
break;
}
delaySignSetting = true;
continue;
case "delaysign-":
if (value != null)
{
break;
}
delaySignSetting = false;
continue;
case "keyfile":
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, "keyfile");
}
else
{
keyFileSetting = RemoveAllQuotes(value);
}
// NOTE: Dev11/VB also clears "keycontainer", see also:
//
// MSDN: In case both /keyfile and /keycontainer are specified (either by command line option or by
// MSDN: custom attribute) in the same compilation, the compiler will first try the key container.
// MSDN: If that succeeds, then the assembly is signed with the information in the key container.
// MSDN: If the compiler does not find the key container, it will try the file specified with /keyfile.
// MSDN: If that succeeds, the assembly is signed with the information in the key file and the key
// MSDN: information will be installed in the key container (similar to sn -i) so that on the next
// MSDN: compilation, the key container will be valid.
continue;
case "keycontainer":
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "keycontainer");
}
else
{
keyContainerSetting = value;
}
// NOTE: Dev11/VB also clears "keyfile", see also:
//
// MSDN: In case both /keyfile and /keycontainer are specified (either by command line option or by
// MSDN: custom attribute) in the same compilation, the compiler will first try the key container.
// MSDN: If that succeeds, then the assembly is signed with the information in the key container.
// MSDN: If the compiler does not find the key container, it will try the file specified with /keyfile.
// MSDN: If that succeeds, the assembly is signed with the information in the key file and the key
// MSDN: information will be installed in the key container (similar to sn -i) so that on the next
// MSDN: compilation, the key container will be valid.
continue;
case "highentropyva":
case "highentropyva+":
if (value != null)
break;
highEntropyVA = true;
continue;
case "highentropyva-":
if (value != null)
break;
highEntropyVA = false;
continue;
case "nologo":
displayLogo = false;
continue;
case "baseaddress":
ulong newBaseAddress;
if (string.IsNullOrEmpty(value) || !TryParseUInt64(value, out newBaseAddress))
{
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name);
}
else
{
AddDiagnostic(diagnostics, ErrorCode.ERR_BadBaseNumber, value);
}
}
else
{
baseAddress = newBaseAddress;
}
continue;
case "subsystemversion":
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "subsystemversion");
continue;
}
// It seems VS 2012 just silently corrects invalid values and suppresses the error message
SubsystemVersion version = SubsystemVersion.None;
if (SubsystemVersion.TryParse(value, out version))
{
subsystemVersion = version;
}
else
{
AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidSubsystemVersion, value);
}
continue;
case "touchedfiles":
unquoted = RemoveAllQuotes(value);
if (string.IsNullOrEmpty(unquoted))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "touchedfiles");
continue;
}
else
{
touchedFilesPath = unquoted;
}
continue;
case "bugreport":
UnimplementedSwitch(diagnostics, name);
continue;
case "utf8output":
if (value != null)
break;
utf8output = true;
continue;
case "m":
case "main":
// Remove any quotes for consistent behaviour as MSBuild can return quoted or
// unquoted main.
unquoted = RemoveAllQuotes(value);
if (string.IsNullOrEmpty(unquoted))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name);
continue;
}
mainTypeName = unquoted;
continue;
case "fullpaths":
if (value != null)
break;
printFullPaths = true;
continue;
case "filealign":
ushort newAlignment;
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name);
}
else if (!TryParseUInt16(value, out newAlignment))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidFileAlignment, value);
}
else if (!CompilationOptions.IsValidFileAlignment(newAlignment))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidFileAlignment, value);
}
else
{
fileAlignment = newAlignment;
}
continue;
case "pdb":
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg);
}
else
{
pdbPath = ParsePdbPath(value, diagnostics, baseDirectory);
}
continue;
case "errorendlocation":
errorEndLocation = true;
continue;
case "nostdlib":
case "nostdlib+":
if (value != null)
break;
noStdLib = true;
continue;
case "lib":
ParseAndResolveReferencePaths(name, value, baseDirectory, libPaths, MessageID.IDS_LIB_OPTION, diagnostics);
continue;
case "nostdlib-":
if (value != null)
break;
noStdLib = false;
continue;
case "errorreport":
continue;
case "appconfig":
unquoted = RemoveAllQuotes(value);
if (string.IsNullOrEmpty(unquoted))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, ":<text>", RemoveAllQuotes(arg));
}
else
{
appConfigPath = ParseGenericPathToFile(
unquoted, diagnostics, baseDirectory);
}
continue;
case "runtimemetadataversion":
unquoted = RemoveAllQuotes(value);
if (string.IsNullOrEmpty(unquoted))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name);
continue;
}
runtimeMetadataVersion = unquoted;
continue;
case "ruleset":
// The ruleset arg has already been processed in a separate pass above.
continue;
case "additionalfile":
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<file list>", name);
continue;
}
additionalFiles.AddRange(ParseAdditionalFileArgument(value, baseDirectory, diagnostics));
continue;
}
}
AddDiagnostic(diagnostics, ErrorCode.ERR_BadSwitch, arg);
}
foreach (var o in warnAsErrors)
{
diagnosticOptions[o.Key] = o.Value;
}
// Specific nowarn options always override specific warnaserror options.
foreach (var o in noWarns)
{
diagnosticOptions[o.Key] = o.Value;
}
if (!IsInteractive && !sourceFilesSpecified && (outputKind.IsNetModule() || !resourcesOrModulesSpecified))
{
AddDiagnostic(diagnostics, diagnosticOptions, ErrorCode.WRN_NoSources);
}
if (!noStdLib)
{
metadataReferences.Insert(0, new CommandLineReference(typeof(object).Assembly.Location, MetadataReferenceProperties.Assembly));
}
if (!platform.Requires64Bit())
{
if (baseAddress > uint.MaxValue - 0x8000)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_BadBaseNumber, string.Format("0x{0:X}", baseAddress));
baseAddress = 0;
}
}
// add additional reference paths if specified
if (!string.IsNullOrWhiteSpace(additionalReferencePaths))
{
ParseAndResolveReferencePaths(null, additionalReferencePaths, baseDirectory, libPaths, MessageID.IDS_LIB_ENV, diagnostics);
}
ImmutableArray<string> referencePaths = BuildSearchPaths(libPaths);
ValidateWin32Settings(win32ResourceFile, win32IconFile, win32ManifestFile, outputKind, diagnostics);
// Dev11 searches for the key file in the current directory and assembly output directory.
// We always look to base directory and then examine the search paths.
keyFileSearchPaths.Add(baseDirectory);
if (baseDirectory != outputDirectory)
{
keyFileSearchPaths.Add(outputDirectory);
}
if (!emitPdb)
{
if (pdbPath != null)
{
// Can't give a PDB file name and turn off debug information
AddDiagnostic(diagnostics, ErrorCode.ERR_MissingDebugSwitch);
}
}
string compilationName;
GetCompilationAndModuleNames(diagnostics, outputKind, sourceFiles, sourceFilesSpecified, moduleAssemblyName, ref outputFileName, ref moduleName, out compilationName);
var parseOptions = new CSharpParseOptions
(
languageVersion: languageVersion,
preprocessorSymbols: defines.ToImmutableAndFree(),
documentationMode: parseDocumentationComments ? DocumentationMode.Diagnose : DocumentationMode.None,
kind: SourceCodeKind.Regular
);
var scriptParseOptions = parseOptions.WithKind(SourceCodeKind.Script);
var options = new CSharpCompilationOptions
(
outputKind: outputKind,
moduleName: moduleName,
mainTypeName: mainTypeName,
scriptClassName: WellKnownMemberNames.DefaultScriptClassName,
usings: usings,
optimizationLevel: optimize ? OptimizationLevel.Release : OptimizationLevel.Debug,
checkOverflow: checkOverflow,
allowUnsafe: allowUnsafe,
concurrentBuild: concurrentBuild,
cryptoKeyContainer: keyContainerSetting,
cryptoKeyFile: keyFileSetting,
delaySign: delaySignSetting,
platform: platform,
generalDiagnosticOption: generalDiagnosticOption,
warningLevel: warningLevel,
specificDiagnosticOptions: diagnosticOptions
).WithFeatures(features.AsImmutable());
var emitOptions = new EmitOptions
(
metadataOnly: false,
debugInformationFormat: DebugInformationFormat.Pdb,
pdbFilePath: null, // to be determined later
outputNameOverride: null, // to be determined later
baseAddress: baseAddress,
highEntropyVirtualAddressSpace: highEntropyVA,
fileAlignment: fileAlignment,
subsystemVersion: subsystemVersion,
runtimeMetadataVersion: runtimeMetadataVersion
);
// add option incompatibility errors if any
diagnostics.AddRange(options.Errors);
return new CSharpCommandLineArguments
{
IsInteractive = IsInteractive,
BaseDirectory = baseDirectory,
Errors = diagnostics.AsImmutable(),
Utf8Output = utf8output,
CompilationName = compilationName,
OutputFileName = outputFileName,
PdbPath = pdbPath,
EmitPdb = emitPdb,
OutputDirectory = outputDirectory,
DocumentationPath = documentationPath,
AppConfigPath = appConfigPath,
SourceFiles = sourceFiles.AsImmutable(),
Encoding = codepage,
ChecksumAlgorithm = checksumAlgorithm,
MetadataReferences = metadataReferences.AsImmutable(),
AnalyzerReferences = analyzers.AsImmutable(),
AdditionalFiles = additionalFiles.AsImmutable(),
ReferencePaths = referencePaths,
KeyFileSearchPaths = keyFileSearchPaths.AsImmutable(),
Win32ResourceFile = win32ResourceFile,
Win32Icon = win32IconFile,
Win32Manifest = win32ManifestFile,
NoWin32Manifest = noWin32Manifest,
DisplayLogo = displayLogo,
DisplayHelp = displayHelp,
ManifestResources = managedResources.AsImmutable(),
CompilationOptions = options,
ParseOptions = IsInteractive ? scriptParseOptions : parseOptions,
EmitOptions = emitOptions,
ScriptArguments = scriptArgs.AsImmutableOrEmpty(),
TouchedFilesPath = touchedFilesPath,
PrintFullPaths = printFullPaths,
ShouldIncludeErrorEndLocation = errorEndLocation,
PreferredUILang = preferredUILang,
SqmSessionGuid = sqmSessionGuid
};
}
}
private static void ParseAndResolveReferencePaths(string switchName, string switchValue, string baseDirectory, List<string> builder, MessageID origin, List<Diagnostic> diagnostics)
{
if (string.IsNullOrEmpty(switchValue))
{
Debug.Assert(!string.IsNullOrEmpty(switchName));
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_PathList.Localize(), switchName);
return;
}
foreach (string path in ParseSeparatedPaths(switchValue))
{
string resolvedPath = FileUtilities.ResolveRelativePath(path, baseDirectory);
if (resolvedPath == null)
{
AddDiagnostic(diagnostics, ErrorCode.WRN_InvalidSearchPathDir, path, origin.Localize(), MessageID.IDS_DirectoryHasInvalidPath.Localize());
}
else if (!Directory.Exists(resolvedPath))
{
AddDiagnostic(diagnostics, ErrorCode.WRN_InvalidSearchPathDir, path, origin.Localize(), MessageID.IDS_DirectoryDoesNotExist.Localize());
}
else
{
builder.Add(resolvedPath);
}
}
}
private static string GetWin32Setting(string arg, string value, List<Diagnostic> diagnostics)
{
if (value == null)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg);
}
else
{
string noQuotes = RemoveAllQuotes(value);
if (string.IsNullOrWhiteSpace(noQuotes))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg);
}
else
{
return noQuotes;
}
}
return null;
}
private void GetCompilationAndModuleNames(
List<Diagnostic> diagnostics,
OutputKind outputKind,
List<CommandLineSourceFile> sourceFiles,
bool sourceFilesSpecified,
string moduleAssemblyName,
ref string outputFileName,
ref string moduleName,
out string compilationName)
{
string simpleName;
if (outputFileName == null)
{
// In C#, if the output file name isn't specified explicitly, then executables take their
// names from the files containing their entrypoints and libraries derive their names from
// their first input files.
if (!IsInteractive && !sourceFilesSpecified)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_OutputNeedsName);
simpleName = null;
}
else if (outputKind.IsApplication())
{
simpleName = null;
}
else
{
simpleName = PathUtilities.RemoveExtension(PathUtilities.GetFileName(sourceFiles.FirstOrDefault().Path));
outputFileName = simpleName + outputKind.GetDefaultExtension();
if (simpleName.Length == 0 && !outputKind.IsNetModule())
{
AddDiagnostic(diagnostics, ErrorCode.FTL_InputFileNameTooLong, outputFileName);
outputFileName = simpleName = null;
}
}
}
else
{
simpleName = PathUtilities.RemoveExtension(outputFileName);
if (simpleName.Length == 0)
{
AddDiagnostic(diagnostics, ErrorCode.FTL_InputFileNameTooLong, outputFileName);
outputFileName = simpleName = null;
}
}
if (outputKind.IsNetModule())
{
Debug.Assert(!IsInteractive);
compilationName = moduleAssemblyName;
}
else
{
if (moduleAssemblyName != null)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_AssemblyNameOnNonModule);
}
compilationName = simpleName;
}
if (moduleName == null)
{
moduleName = outputFileName;
}
}
private static ImmutableArray<string> BuildSearchPaths(List<string> libPaths)
{
var builder = ArrayBuilder<string>.GetInstance();
// Match how Dev11 builds the list of search paths
// see PCWSTR LangCompiler::GetSearchPath()
// current folder first -- base directory is searched by default
// SDK path is specified or current runtime directory
builder.Add(RuntimeEnvironment.GetRuntimeDirectory());
// libpath
builder.AddRange(libPaths);
return builder.ToImmutableAndFree();
}
public static IEnumerable<string> ParseConditionalCompilationSymbols(string value, out IEnumerable<Diagnostic> diagnostics)
{
Diagnostic myDiagnostic = null;
value = value.TrimEnd(null);
// Allow a trailing semicolon or comma in the options
if (!value.IsEmpty() &&
(value.Last() == ';' || value.Last() == ','))
{
value = value.Substring(0, value.Length - 1);
}
string[] values = value.Split(new char[] { ';', ',' } /*, StringSplitOptions.RemoveEmptyEntries*/);
var defines = new ArrayBuilder<string>(values.Length);
foreach (string id in values)
{
string trimmedId = id.Trim();
if (SyntaxFacts.IsValidIdentifier(trimmedId))
{
defines.Add(trimmedId);
}
else if (myDiagnostic == null)
{
myDiagnostic = Diagnostic.Create(CSharp.MessageProvider.Instance, (int)ErrorCode.WRN_DefineIdentifierRequired, trimmedId);
}
}
diagnostics = myDiagnostic == null ? SpecializedCollections.EmptyEnumerable<Diagnostic>()
: SpecializedCollections.SingletonEnumerable(myDiagnostic);
return defines.AsEnumerable();
}
private static Platform ParsePlatform(string value, IList<Diagnostic> diagnostics)
{
switch (value.ToLowerInvariant())
{
case "x86":
return Platform.X86;
case "x64":
return Platform.X64;
case "itanium":
return Platform.Itanium;
case "anycpu":
return Platform.AnyCpu;
case "anycpu32bitpreferred":
return Platform.AnyCpu32BitPreferred;
case "arm":
return Platform.Arm;
default:
AddDiagnostic(diagnostics, ErrorCode.ERR_BadPlatformType, value);
return Platform.AnyCpu;
}
}
private static OutputKind ParseTarget(string value, IList<Diagnostic> diagnostics)
{
switch (value.ToLowerInvariant())
{
case "exe":
return OutputKind.ConsoleApplication;
case "winexe":
return OutputKind.WindowsApplication;
case "library":
return OutputKind.DynamicallyLinkedLibrary;
case "module":
return OutputKind.NetModule;
case "appcontainerexe":
return OutputKind.WindowsRuntimeApplication;
case "winmdobj":
return OutputKind.WindowsRuntimeMetadata;
default:
AddDiagnostic(diagnostics, ErrorCode.FTL_InvalidTarget);
return OutputKind.ConsoleApplication;
}
}
private static IEnumerable<string> ParseUsings(string arg, string value, IList<Diagnostic> diagnostics)
{
if (value.Length == 0)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Namespace1.Localize(), arg);
yield break;
}
foreach (var u in value.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
{
yield return u;
}
}
private IEnumerable<CommandLineAnalyzerReference> ParseAnalyzers(string arg, string value, List<Diagnostic> diagnostics)
{
if (value == null)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), arg);
yield break;
}
else if (value.Length == 0)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg);
yield break;
}
List<string> paths = ParseSeparatedPaths(value).Where((path) => !string.IsNullOrWhiteSpace(path)).ToList();
foreach (string path in paths)
{
yield return new CommandLineAnalyzerReference(path);
}
}
private IEnumerable<CommandLineReference> ParseAssemblyReferences(string arg, string value, IList<Diagnostic> diagnostics, bool embedInteropTypes)
{
if (value == null)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), arg);
yield break;
}
else if (value.Length == 0)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg);
yield break;
}
// /r:"reference"
// /r:alias=reference
// /r:alias="reference"
// /r:reference;reference
// /r:"path;containing;semicolons"
// /r:"unterminated_quotes
// /r:"quotes"in"the"middle
// /r:alias=reference;reference ... error 2034
// /r:nonidf=reference ... error 1679
int eqlOrQuote = value.IndexOfAny(new[] { '"', '=' });
string alias;
if (eqlOrQuote >= 0 && value[eqlOrQuote] == '=')
{
alias = value.Substring(0, eqlOrQuote);
value = value.Substring(eqlOrQuote + 1);
if (!SyntaxFacts.IsValidIdentifier(alias))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_BadExternIdentifier, alias);
yield break;
}
}
else
{
alias = null;
}
List<string> paths = ParseSeparatedPaths(value).Where((path) => !string.IsNullOrWhiteSpace(path)).ToList();
if (alias != null)
{
if (paths.Count > 1)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_OneAliasPerReference, value);
yield break;
}
if (paths.Count == 0)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_AliasMissingFile, alias);
yield break;
}
}
foreach (string path in paths)
{
// NOTE(tomat): Dev10 used to report CS1541: ERR_CantIncludeDirectory if the path was a directory.
// Since we now support /referencePaths option we would need to search them to see if the resolved path is a directory.
var aliases = (alias != null) ? ImmutableArray.Create(alias) : ImmutableArray<string>.Empty;
var properties = new MetadataReferenceProperties(MetadataImageKind.Assembly, aliases, embedInteropTypes);
yield return new CommandLineReference(path, properties);
}
}
private static void ValidateWin32Settings(string win32ResourceFile, string win32IconResourceFile, string win32ManifestFile, OutputKind outputKind, IList<Diagnostic> diagnostics)
{
if (win32ResourceFile != null)
{
if (win32IconResourceFile != null)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_CantHaveWin32ResAndIcon);
}
if (win32ManifestFile != null)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_CantHaveWin32ResAndManifest);
}
}
if (outputKind.IsNetModule() && win32ManifestFile != null)
{
AddDiagnostic(diagnostics, ErrorCode.WRN_CantHaveManifestForModule);
}
}
internal static ResourceDescription ParseResourceDescription(
string arg,
string resourceDescriptor,
string baseDirectory,
IList<Diagnostic> diagnostics,
bool embedded)
{
string filePath;
string fullPath;
string fileName;
string resourceName;
string accessibility;
ParseResourceDescription(
resourceDescriptor,
baseDirectory,
false,
out filePath,
out fullPath,
out fileName,
out resourceName,
out accessibility);
bool isPublic;
if (accessibility == null)
{
// If no accessibility is given, we default to "public".
// NOTE: Dev10 distinguishes between null and empty/whitespace-only.
isPublic = true;
}
else if (string.Equals(accessibility, "public", StringComparison.OrdinalIgnoreCase))
{
isPublic = true;
}
else if (string.Equals(accessibility, "private", StringComparison.OrdinalIgnoreCase))
{
isPublic = false;
}
else
{
AddDiagnostic(diagnostics, ErrorCode.ERR_BadResourceVis, accessibility);
return null;
}
if (string.IsNullOrEmpty(filePath))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg);
return null;
}
if (fullPath == null || string.IsNullOrWhiteSpace(fileName) || fileName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0)
{
AddDiagnostic(diagnostics, ErrorCode.FTL_InputFileNameTooLong, filePath);
return null;
}
Func<Stream> dataProvider = () =>
{
// Use FileShare.ReadWrite because the file could be opened by the current process.
// For example, it is an XML doc file produced by the build.
return new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
};
return new ResourceDescription(resourceName, fileName, dataProvider, isPublic, embedded, checkArgs: false);
}
private static bool TryParseLanguageVersion(string str, LanguageVersion defaultVersion, out LanguageVersion version)
{
if (str == null)
{
version = defaultVersion;
return true;
}
switch (str.ToLowerInvariant())
{
case "iso-1":
version = LanguageVersion.CSharp1;
return true;
case "iso-2":
version = LanguageVersion.CSharp2;
return true;
case "default":
version = defaultVersion;
return true;
default:
int versionNumber;
if (int.TryParse(str, NumberStyles.None, CultureInfo.InvariantCulture, out versionNumber) && ((LanguageVersion)versionNumber).IsValid())
{
version = (LanguageVersion)versionNumber;
return true;
}
version = defaultVersion;
return false;
}
}
private static IEnumerable<string> ParseWarnings(string value)
{
value = value.Unquote();
string[] values = value.Split(new char[] { ',', ';', ' ' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string id in values)
{
ushort number;
if (ushort.TryParse(id, NumberStyles.Integer, CultureInfo.InvariantCulture, out number) &&
ErrorFacts.IsWarning((ErrorCode)number))
{
// The id refers to a compiler warning.
yield return CSharp.MessageProvider.Instance.GetIdForErrorCode(number);
}
else
{
// Previous versions of the compiler used to report a warning (CS1691)
// whenever an unrecognized warning code was supplied in /nowarn or
// /warnaserror. We no longer generate a warning in such cases.
// Instead we assume that the unrecognized id refers to a custom diagnostic.
yield return id;
}
}
}
private static void AddWarnings(Dictionary<string, ReportDiagnostic> d, ReportDiagnostic kind, IEnumerable<string> items)
{
foreach (var id in items)
{
ReportDiagnostic existing;
if (d.TryGetValue(id, out existing))
{
// Rewrite the existing value with the latest one unless it is for /nowarn.
if (existing != ReportDiagnostic.Suppress)
d[id] = kind;
}
else
{
d.Add(id, kind);
}
}
}
private static void UnimplementedSwitch(IList<Diagnostic> diagnostics, string switchName)
{
AddDiagnostic(diagnostics, ErrorCode.WRN_UnimplementedCommandLineSwitch, "/" + switchName);
}
private static void UnimplementedSwitchValue(IList<Diagnostic> diagnostics, string switchName, string value)
{
AddDiagnostic(diagnostics, ErrorCode.WRN_UnimplementedCommandLineSwitch, "/" + switchName + ":" + value);
}
internal override void GenerateErrorForNoFilesFoundInRecurse(string path, IList<Diagnostic> diagnostics)
{
// no error in csc.exe
}
private static void AddDiagnostic(IList<Diagnostic> diagnostics, ErrorCode errorCode)
{
diagnostics.Add(Diagnostic.Create(CSharp.MessageProvider.Instance, (int)errorCode));
}
private static void AddDiagnostic(IList<Diagnostic> diagnostics, ErrorCode errorCode, params object[] arguments)
{
diagnostics.Add(Diagnostic.Create(CSharp.MessageProvider.Instance, (int)errorCode, arguments));
}
/// <summary>
/// Diagnostic for the errorCode added if the warningOptions does not mention suppressed for the errorCode.
/// </summary>
private static void AddDiagnostic(IList<Diagnostic> diagnostics, Dictionary<string, ReportDiagnostic> warningOptions, ErrorCode errorCode, params object[] arguments)
{
int code = (int)errorCode;
ReportDiagnostic value;
warningOptions.TryGetValue(CSharp.MessageProvider.Instance.GetIdForErrorCode(code), out value);
if (value != ReportDiagnostic.Suppress)
{
AddDiagnostic(diagnostics, errorCode, arguments);
}
}
}
}
| |
/*
* Copyright (c) 2006-2007, Second Life Reverse Engineering Team
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the Second Life Reverse Engineering Team nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using libsecondlife.Packets;
using System.Collections.Generic;
namespace libsecondlife
{
/// <summary>
/// Estate level administration and utilities
/// </summary>
public class EstateTools
{
private SecondLife Client;
public GroundTextureSettings GroundTextures;
/// <summary>
/// Triggered on LandStatReply when the report type is for "top colliders"
/// </summary>
/// <param name="objectCount"></param>
/// <param name="Tasks"></param>
public delegate void GetTopCollidersReply(int objectCount, List<EstateTask> Tasks);
/// <summary>
/// Triggered on LandStatReply when the report type is for "top scripts"
/// </summary>
/// <param name="objectCount"></param>
/// <param name="Tasks"></param>
public delegate void GetTopScriptsReply(int objectCount, List<EstateTask> Tasks);
/// <summary>
/// Triggered when the list of estate managers is received for the current estate
/// </summary>
/// <param name="managers"></param>
/// <param name="count"></param>
/// <param name="estateID"></param>
public delegate void EstateManagersReply(uint estateID, int count, List<LLUUID> managers);
/// <summary>
/// FIXME - Enumerate all params from EstateOwnerMessage packet
/// </summary>
/// <param name="denyNoPaymentInfo"></param>
/// <param name="estateID"></param>
/// <param name="estateName"></param>
/// <param name="estateOwner"></param>
public delegate void EstateUpdateInfoReply(string estateName, LLUUID estateOwner, uint estateID, bool denyNoPaymentInfo);
public delegate void EstateManagersListReply(uint estateID, List<LLUUID> managers);
public delegate void EstateBansReply(uint estateID, int count, List<LLUUID> banned);
public delegate void EstateUsersReply(uint estateID, int count, List<LLUUID> allowedUsers);
public delegate void EstateGroupsReply(uint estateID, int count, List<LLUUID> allowedGroups);
public delegate void EstateCovenantReply(LLUUID covenantID, long timestamp, string estateName, LLUUID estateOwnerID);
/// <summary>Callback for LandStatReply packets</summary>
//public event LandStatReply OnLandStatReply;
/// <summary>Triggered upon a successful .GetTopColliders()</summary>
public event GetTopCollidersReply OnGetTopColliders;
/// <summary>Triggered upon a successful .GetTopScripts()</summary>
public event GetTopScriptsReply OnGetTopScripts;
/// <summary>Returned, along with other info, upon a successful .GetInfo()</summary>
public event EstateUpdateInfoReply OnGetEstateUpdateInfo;
/// <summary>Returned, along with other info, upon a successful .GetInfo()</summary>
public event EstateManagersReply OnGetEstateManagers;
/// <summary>Returned, along with other info, upon a successful .GetInfo()</summary>
public event EstateBansReply OnGetEstateBans;
/// <summary>Returned, along with other info, upon a successful .GetInfo()</summary>
public event EstateGroupsReply OnGetAllowedGroups;
/// <summary>Returned, along with other info, upon a successful .GetInfo()</summary>
public event EstateUsersReply OnGetAllowedUsers;
/// <summary>Triggered upon a successful .RequestCovenant()</summary>
public event EstateCovenantReply OnGetCovenant;
/// <summary>
/// Constructor for EstateTools class
/// </summary>
/// <param name="client"></param>
public EstateTools(SecondLife client)
{
Client = client;
Client.Network.RegisterCallback(PacketType.LandStatReply, new NetworkManager.PacketCallback(LandStatReplyHandler));
Client.Network.RegisterCallback(PacketType.EstateOwnerMessage, new NetworkManager.PacketCallback(EstateOwnerMessageHandler));
Client.Network.RegisterCallback(PacketType.EstateCovenantReply, new NetworkManager.PacketCallback(EstateCovenantReplyHandler));
}
/// <summary>Describes tasks returned in LandStatReply</summary>
public class EstateTask
{
public LLVector3 Position;
public float Score;
public LLUUID TaskID;
public uint TaskLocalID;
public string TaskName;
public string OwnerName;
}
/// <summary>Used in the ReportType field of a LandStatRequest</summary>
public enum LandStatReportType
{
TopScripts = 0,
TopColliders = 1
}
/// <summary>Used by EstateOwnerMessage packets</summary>
public enum EstateAccessDelta
{
BanUser = 64,
UnbanUser = 128
}
public enum EstateAccessReplyDelta : uint
{
AllowedUsers = 17,
AllowedGroups = 18,
EstateBans = 20,
EstateManagers = 24
}
/// <summary>Used by GroundTextureSettings</summary>
public class GroundTextureRegion
{
public LLUUID TextureID;
public float Low;
public float High;
}
/// <summary>Ground texture settings for each corner of the region</summary>
public class GroundTextureSettings
{
public GroundTextureRegion Southwest;
public GroundTextureRegion Northwest;
public GroundTextureRegion Southeast;
public GroundTextureRegion Northeast;
}
/// <summary>
/// Requests estate information such as top scripts and colliders
/// </summary>
/// <param name="parcelLocalID"></param>
/// <param name="reportType"></param>
/// <param name="requestFlags"></param>
/// <param name="filter"></param>
public void LandStatRequest(int parcelLocalID, LandStatReportType reportType, uint requestFlags, string filter)
{
LandStatRequestPacket p = new LandStatRequestPacket();
p.AgentData.AgentID = Client.Self.AgentID;
p.AgentData.SessionID = Client.Self.SessionID;
p.RequestData.Filter = Helpers.StringToField(filter);
p.RequestData.ParcelLocalID = parcelLocalID;
p.RequestData.ReportType = (uint)reportType;
p.RequestData.RequestFlags = requestFlags;
Client.Network.SendPacket(p);
}
/// <summary>Requests estate settings, including estate manager and access/ban lists</summary>
public void GetInfo()
{
EstateOwnerMessage("getinfo", new List<string>());
}
/// <summary>Requests the "Top Scripts" list for the current region</summary>
public void GetTopScripts()
{
//EstateOwnerMessage("scripts", "");
LandStatRequest(0, LandStatReportType.TopScripts, 0, "");
}
/// <summary>Requests the "Top Colliders" list for the current region</summary>
public void GetTopColliders()
{
//EstateOwnerMessage("colliders", "");
LandStatRequest(0, LandStatReportType.TopColliders, 0, "");
}
private void EstateCovenantReplyHandler(Packet packet, Simulator simulator)
{
EstateCovenantReplyPacket reply = (EstateCovenantReplyPacket)packet;
if (OnGetCovenant != null)
{
try
{
OnGetCovenant(
reply.Data.CovenantID,
reply.Data.CovenantTimestamp,
Helpers.FieldToUTF8String(reply.Data.EstateName),
reply.Data.EstateOwnerID);
}
catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); }
}
}
/// <summary></summary>
/// <param name="packet"></param>
/// <param name="simulator"></param>
private void EstateOwnerMessageHandler(Packet packet, Simulator simulator)
{
EstateOwnerMessagePacket message = (EstateOwnerMessagePacket)packet;
uint estateID;
string method = Helpers.FieldToUTF8String(message.MethodData.Method);
List<string> parameters = new List<string>();
if (method == "estateupdateinfo")
{
string estateName = Helpers.FieldToUTF8String(message.ParamList[0].Parameter);
LLUUID estateOwner = new LLUUID(Helpers.FieldToUTF8String(message.ParamList[1].Parameter));
estateID = Helpers.BytesToUInt(message.ParamList[2].Parameter);
/*
foreach (EstateOwnerMessagePacket.ParamListBlock param in message.ParamList)
{
parameters.Add(Helpers.FieldToUTF8String(param.Parameter));
}
*/
bool denyNoPaymentInfo;
if (Helpers.BytesToUInt(message.ParamList[8].Parameter) == 0) denyNoPaymentInfo = true;
else denyNoPaymentInfo = false;
if (OnGetEstateUpdateInfo != null)
{
try
{
OnGetEstateUpdateInfo(estateName, estateOwner, estateID, denyNoPaymentInfo);
}
catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); }
}
}
else if (method == "setaccess")
{
int count;
estateID = Helpers.BytesToUInt(message.ParamList[0].Parameter);
if (message.ParamList.Length > 1)
{
EstateAccessReplyDelta accessType = (EstateAccessReplyDelta)Helpers.BytesToUInt(message.ParamList[1].Parameter);
switch (accessType)
{
case EstateAccessReplyDelta.EstateManagers:
if (OnGetEstateManagers != null)
{
count = (int)Helpers.BytesToUInt(message.ParamList[3].Parameter);
List<LLUUID> managers = new List<LLUUID>();
if (message.ParamList.Length > 5)
{
for (int i = 5; i < message.ParamList.Length; i++)
{
LLUUID managerID;
if (LLUUID.TryParse(Helpers.FieldToUTF8String(message.ParamList[i].Parameter), out managerID))
{
managers.Add(managerID);
}
}
try { OnGetEstateManagers(estateID, count, managers); }
catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); }
}
}
break;
case EstateAccessReplyDelta.EstateBans:
if (OnGetEstateBans != null)
{
count = (int)Helpers.BytesToUInt(message.ParamList[4].Parameter);
List<LLUUID> bannedUsers = new List<LLUUID>();
if (message.ParamList.Length > 5)
{
for (int i = 5; i < message.ParamList.Length; i++)
{
LLUUID bannedID;
if (LLUUID.TryParse(Helpers.FieldToUTF8String(message.ParamList[i].Parameter), out bannedID))
{
bannedUsers.Add(bannedID);
}
}
try { OnGetEstateBans(estateID, count, bannedUsers); }
catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); }
}
}
break;
case EstateAccessReplyDelta.AllowedUsers:
if (OnGetAllowedUsers != null)
{
count = (int)Helpers.BytesToUInt(message.ParamList[2].Parameter);
List<LLUUID> allowedUsers = new List<LLUUID>();
if (message.ParamList.Length > 5)
{
for (int i = 5; i < message.ParamList.Length; i++)
{
LLUUID userID;
if (LLUUID.TryParse(Helpers.FieldToUTF8String(message.ParamList[i].Parameter), out userID))
{
allowedUsers.Add(userID);
}
}
try { OnGetAllowedUsers(estateID, count, allowedUsers); }
catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); }
}
}
break;
case EstateAccessReplyDelta.AllowedGroups:
if (OnGetAllowedGroups != null)
{
count = (int)Helpers.BytesToUInt(message.ParamList[3].Parameter);
List<LLUUID> allowedGroups = new List<LLUUID>();
if (message.ParamList.Length > 5)
{
for (int i = 5; i < message.ParamList.Length; i++)
{
LLUUID groupID;
if (LLUUID.TryParse(Helpers.FieldToUTF8String(message.ParamList[i].Parameter), out groupID))
{
allowedGroups.Add(groupID);
}
}
try { OnGetAllowedGroups(estateID, count, allowedGroups); }
catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); }
}
}
break;
}
if (accessType == EstateAccessReplyDelta.EstateManagers)
{
if (OnGetEstateManagers != null)
{
count = (int)Helpers.BytesToUInt(message.ParamList[5].Parameter);
List<LLUUID> managers = new List<LLUUID>();
for (int i = 5; i < message.ParamList.Length; i++)
{
LLUUID managerID;
if (LLUUID.TryParse(Helpers.FieldToUTF8String(message.ParamList[i].Parameter), out managerID))
{
managers.Add(managerID);
}
}
try { OnGetEstateManagers(estateID, count, managers); }
catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); }
}
}
}
}
/*
Console.WriteLine("--- " + method + " ---");
foreach (EstateOwnerMessagePacket.ParamListBlock block in message.ParamList)
{
Console.WriteLine(Helpers.FieldToUTF8String(block.Parameter));
}
Console.WriteLine("------");
*/
}
/// <summary></summary>
/// <param name="packet"></param>
/// <param name="simulator"></param>
private void LandStatReplyHandler(Packet packet, Simulator simulator)
{
//if (OnLandStatReply != null || OnGetTopScripts != null || OnGetTopColliders != null)
if (OnGetTopScripts != null || OnGetTopColliders != null)
{
LandStatReplyPacket p = (LandStatReplyPacket)packet;
List<EstateTask> Tasks = new List<EstateTask>();
foreach (LandStatReplyPacket.ReportDataBlock rep in p.ReportData)
{
EstateTask task = new EstateTask();
task.Position = new LLVector3(rep.LocationX, rep.LocationY, rep.LocationZ);
task.Score = rep.Score;
task.TaskID = rep.TaskID;
task.TaskLocalID = rep.TaskLocalID;
task.TaskName = Helpers.FieldToUTF8String(rep.TaskName);
task.OwnerName = Helpers.FieldToUTF8String(rep.OwnerName);
Tasks.Add(task);
}
LandStatReportType type = (LandStatReportType)p.RequestData.ReportType;
if (OnGetTopScripts != null && type == LandStatReportType.TopScripts)
{
try { OnGetTopScripts((int)p.RequestData.TotalObjectCount, Tasks); }
catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); }
}
else if (OnGetTopColliders != null && type == LandStatReportType.TopColliders)
{
try { OnGetTopColliders((int)p.RequestData.TotalObjectCount, Tasks); }
catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); }
}
/*
if (OnGetTopColliders != null)
{
//FIXME - System.UnhandledExceptionEventArgs
OnLandStatReply(
type,
p.RequestData.RequestFlags,
(int)p.RequestData.TotalObjectCount,
Tasks
);
}
*/
}
}
public void EstateOwnerMessage(string method, string param)
{
List<string> listParams = new List<string>();
listParams.Add(param);
EstateOwnerMessage(method, listParams);
}
/// <summary>
/// Used for setting and retrieving various estate panel settings
/// </summary>
/// <param name="method">EstateOwnerMessage Method field</param>
/// <param name="listParams">List of parameters to include</param>
public void EstateOwnerMessage(string method, List<string>listParams)
{
EstateOwnerMessagePacket estate = new EstateOwnerMessagePacket();
estate.AgentData.AgentID = Client.Self.AgentID;
estate.AgentData.SessionID = Client.Self.SessionID;
estate.AgentData.TransactionID = LLUUID.Zero;
estate.MethodData.Invoice = LLUUID.Random();
estate.MethodData.Method = Helpers.StringToField(method);
estate.ParamList = new EstateOwnerMessagePacket.ParamListBlock[listParams.Count];
for (int i = 0; i < listParams.Count; i++)
{
estate.ParamList[i] = new EstateOwnerMessagePacket.ParamListBlock();
estate.ParamList[i].Parameter = Helpers.StringToField(listParams[i]);
}
Client.Network.SendPacket((Packet)estate);
}
/// <summary>
/// Kick an avatar from an estate
/// </summary>
/// <param name="userID">Key of Agent to remove</param>
public void KickUser(LLUUID userID)
{
EstateOwnerMessage("kickestate", userID.ToString());
}
/// <summary>Ban an avatar from an estate</summary>
/// <param name="userID">Key of Agent to remove</param>
public void BanUser(LLUUID userID)
{
List<string> listParams = new List<string>();
uint flag = (uint)EstateAccessDelta.BanUser;
listParams.Add(Client.Self.AgentID.ToString());
listParams.Add(flag.ToString());
listParams.Add(userID.ToString());
EstateOwnerMessage("estateaccessdelta", listParams);
}
/// <summary>Unban an avatar from an estate</summary>
/// <param name="userID">Key of Agent to remove</param>
public void UnbanUser(LLUUID userID)
{
List<string> listParams = new List<string>();
uint flag = (uint)EstateAccessDelta.UnbanUser;
listParams.Add(Client.Self.AgentID.ToString());
listParams.Add(flag.ToString());
listParams.Add(userID.ToString());
EstateOwnerMessage("estateaccessdelta", listParams);
}
/// <summary>
/// Send a message dialog to everyone in an entire estate
/// </summary>
/// <param name="message">Message to send all users in the estate</param>
public void EstateMessage(string message)
{
List<string> listParams = new List<string>();
listParams.Add(Client.Self.FirstName + " " + Client.Self.LastName);
listParams.Add(message);
EstateOwnerMessage("instantmessage", listParams);
}
/// <summary>
/// Send a message dialog to everyone in a simulator
/// </summary>
/// <param name="message">Message to send all users in the simulator</param>
public void SimulatorMessage(string message)
{
List<string> listParams = new List<string>();
listParams.Add("-1");
listParams.Add("-1");
listParams.Add(Client.Self.AgentID.ToString());
listParams.Add(Client.Self.FirstName + " " + Client.Self.LastName);
listParams.Add(message);
EstateOwnerMessage("simulatormessage", listParams);
}
/// <summary>
/// Send an avatar back to their home location
/// </summary>
/// <param name="pest">Key of avatar to send home</param>
public void TeleportHomeUser(LLUUID pest)
{
List<string> listParams = new List<string>();
listParams.Add(Client.Self.AgentID.ToString());
listParams.Add(pest.ToString());
EstateOwnerMessage("teleporthomeuser", listParams);
}
/// <summary>
/// Begin the region restart process
/// </summary>
public void RestartRegion()
{
EstateOwnerMessage("restart", "120");
}
/// <summary>
/// Cancels a region restart
/// </summary>
public void CancelRestart()
{
EstateOwnerMessage("restart", "-1");
}
/// <summary>Estate panel "Region" tab settings</summary>
public void SetRegionInfo(bool blockTerraform, bool blockFly, bool allowDamage, bool allowLandResell, bool restrictPushing, bool allowParcelJoinDivide, float agentLimit, float objectBonus, bool mature)
{
List<string> listParams = new List<string>();
if (blockTerraform) listParams.Add("Y"); else listParams.Add("N");
if (blockFly) listParams.Add("Y"); else listParams.Add("N");
if (allowDamage) listParams.Add("Y"); else listParams.Add("N");
if (allowLandResell) listParams.Add("Y"); else listParams.Add("N");
listParams.Add(agentLimit.ToString());
listParams.Add(objectBonus.ToString());
if (mature) listParams.Add("21"); else listParams.Add("13"); //FIXME - enumerate these settings
if (restrictPushing) listParams.Add("Y"); else listParams.Add("N");
if (allowParcelJoinDivide) listParams.Add("Y"); else listParams.Add("N");
EstateOwnerMessage("setregioninfo", listParams);
}
/// <summary>Estate panel "Debug" tab settings</summary>
public void SetRegionDebug(bool disableScripts, bool disableCollisions, bool disablePhysics)
{
List<string> listParams = new List<string>();
if (disableScripts) listParams.Add("Y"); else listParams.Add("N");
if (disableCollisions) listParams.Add("Y"); else listParams.Add("N");
if (disablePhysics) listParams.Add("Y"); else listParams.Add("N");
EstateOwnerMessage("setregiondebug", listParams);
}
public void RequestCovenant()
{
EstateCovenantRequestPacket req = new EstateCovenantRequestPacket();
req.AgentData.AgentID = Client.Self.AgentID;
req.AgentData.SessionID = Client.Self.SessionID;
Client.Network.SendPacket(req);
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;
using Microsoft.VisualStudio.Services.Agent.Util;
using System.IO;
using System.Runtime.Serialization;
using System.Security.Cryptography;
namespace Microsoft.VisualStudio.Services.Agent
{
public sealed class LinuxAgentCredentialStore : AgentService, IAgentCredentialStore
{
// 'msftvsts' 128 bits iv
private readonly byte[] iv = new byte[] { 0x36, 0x64, 0x37, 0x33, 0x36, 0x36, 0x37, 0x34, 0x37, 0x36, 0x37, 0x33, 0x37, 0x34, 0x37, 0x33 };
// 256 bits key
private byte[] _symmetricKey;
private string _credStoreFile;
private Dictionary<string, Credential> _credStore;
public override void Initialize(IHostContext hostContext)
{
base.Initialize(hostContext);
_credStoreFile = hostContext.GetConfigFile(WellKnownConfigFile.CredentialStore);
if (File.Exists(_credStoreFile))
{
_credStore = IOUtil.LoadObject<Dictionary<string, Credential>>(_credStoreFile);
}
else
{
_credStore = new Dictionary<string, Credential>(StringComparer.OrdinalIgnoreCase);
}
string machineId;
if (File.Exists("/etc/machine-id"))
{
// try use machine-id as encryption key
// this helps avoid accidental information disclosure, but isn't intended for true security
machineId = File.ReadAllLines("/etc/machine-id").FirstOrDefault();
Trace.Info($"machine-id length {machineId?.Length ?? 0}.");
// machine-id doesn't exist or machine-id is not 256 bits
if (string.IsNullOrEmpty(machineId) || machineId.Length != 32)
{
Trace.Warning("Can not get valid machine id from '/etc/machine-id'.");
machineId = "5f767374735f6167656e745f63726564"; //_vsts_agent_cred
}
}
else
{
// /etc/machine-id not exist
Trace.Warning("/etc/machine-id doesn't exist.");
machineId = "5f767374735f6167656e745f63726564"; //_vsts_agent_cred
}
List<byte> keyBuilder = new List<byte>();
foreach (var c in machineId)
{
keyBuilder.Add(Convert.ToByte(c));
}
_symmetricKey = keyBuilder.ToArray();
}
public NetworkCredential Write(string target, string username, string password)
{
Trace.Entering();
ArgUtil.NotNullOrEmpty(target, nameof(target));
ArgUtil.NotNullOrEmpty(username, nameof(username));
ArgUtil.NotNullOrEmpty(password, nameof(password));
Trace.Info($"Store credential for '{target}' to cred store.");
Credential cred = new Credential(username, Encrypt(password));
_credStore[target] = cred;
SyncCredentialStoreFile();
return new NetworkCredential(username, password);
}
public NetworkCredential Read(string target)
{
Trace.Entering();
ArgUtil.NotNullOrEmpty(target, nameof(target));
Trace.Info($"Read credential for '{target}' from cred store.");
if (_credStore.ContainsKey(target))
{
Credential cred = _credStore[target];
if (!string.IsNullOrEmpty(cred.UserName) && !string.IsNullOrEmpty(cred.Password))
{
Trace.Info($"Return credential for '{target}' from cred store.");
return new NetworkCredential(cred.UserName, Decrypt(cred.Password));
}
}
throw new KeyNotFoundException(target);
}
public void Delete(string target)
{
Trace.Entering();
ArgUtil.NotNullOrEmpty(target, nameof(target));
if (_credStore.ContainsKey(target))
{
Trace.Info($"Delete credential for '{target}' from cred store.");
_credStore.Remove(target);
SyncCredentialStoreFile();
}
else
{
throw new KeyNotFoundException(target);
}
}
private void SyncCredentialStoreFile()
{
Trace.Entering();
Trace.Info("Sync in-memory credential store with credential store file.");
// delete cred store file when all creds gone
if (_credStore.Count == 0)
{
IOUtil.DeleteFile(_credStoreFile);
return;
}
if (!File.Exists(_credStoreFile))
{
CreateCredentialStoreFile();
}
IOUtil.SaveObject(_credStore, _credStoreFile);
}
private string Encrypt(string secret)
{
using (Aes aes = Aes.Create())
{
aes.Key = _symmetricKey;
aes.IV = iv;
// Create a decrytor to perform the stream transform.
ICryptoTransform encryptor = aes.CreateEncryptor();
// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(secret);
}
return Convert.ToBase64String(msEncrypt.ToArray());
}
}
}
}
private string Decrypt(string encryptedText)
{
using (Aes aes = Aes.Create())
{
aes.Key = _symmetricKey;
aes.IV = iv;
// Create a decrytor to perform the stream transform.
ICryptoTransform decryptor = aes.CreateDecryptor();
// Create the streams used for decryption.
using (MemoryStream msDecrypt = new MemoryStream(Convert.FromBase64String(encryptedText)))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
// Read the decrypted bytes from the decrypting stream and place them in a string.
return srDecrypt.ReadToEnd();
}
}
}
}
}
private void CreateCredentialStoreFile()
{
File.WriteAllText(_credStoreFile, "");
File.SetAttributes(_credStoreFile, File.GetAttributes(_credStoreFile) | FileAttributes.Hidden);
// Try to lock down the .credentials_store file to the owner/group
var chmodPath = WhichUtil.Which("chmod", trace: Trace);
if (!String.IsNullOrEmpty(chmodPath))
{
var arguments = $"600 {new FileInfo(_credStoreFile).FullName}";
using (var invoker = HostContext.CreateService<IProcessInvoker>())
{
var exitCode = invoker.ExecuteAsync(HostContext.GetDirectory(WellKnownDirectory.Root), chmodPath, arguments, null, default(CancellationToken)).GetAwaiter().GetResult();
if (exitCode == 0)
{
Trace.Info("Successfully set permissions for credentials store file {0}", _credStoreFile);
}
else
{
Trace.Warning("Unable to successfully set permissions for credentials store file {0}. Received exit code {1} from {2}", _credStoreFile, exitCode, chmodPath);
}
}
}
else
{
Trace.Warning("Unable to locate chmod to set permissions for credentials store file {0}.", _credStoreFile);
}
}
}
[DataContract]
internal class Credential
{
public Credential()
{ }
public Credential(string userName, string password)
{
UserName = userName;
Password = password;
}
[DataMember(IsRequired = true)]
public string UserName { get; set; }
[DataMember(IsRequired = true)]
public string Password { get; set; }
}
}
| |
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Input.Handlers;
using OpenTK;
using OpenTK.Input;
using osu.Framework.Platform;
namespace osu.Framework.Input
{
public class InputManager : Container, IRequireHighFrequencyMousePosition
{
/// <summary>
/// The initial delay before key repeat begins.
/// </summary>
private const int repeat_initial_delay = 250;
/// <summary>
/// The delay between key repeats after the initial repeat.
/// </summary>
private const int repeat_tick_rate = 70;
/// <summary>
/// The maximum time between two clicks for a double-click to be considered.
/// </summary>
private const int double_click_time = 250;
/// <summary>
/// The distance that must be moved before a drag begins.
/// </summary>
private const float drag_start_distance = 0;
/// <summary>
/// The distance that must be moved until a dragged click becomes invalid.
/// </summary>
private const float click_drag_distance = 40;
/// <summary>
/// The time of the last input action.
/// </summary>
public double LastActionTime;
protected GameHost Host;
internal Drawable FocusedDrawable;
private readonly List<InputHandler> inputHandlers = new List<InputHandler>();
private double lastClickTime;
private double keyboardRepeatTime;
private bool isDragging;
private bool isValidClick;
/// <summary>
/// The last processed state.
/// </summary>
public InputState CurrentState = new InputState();
/// <summary>
/// The sequential list in which to handle mouse input.
/// </summary>
private readonly List<Drawable> mouseInputQueue = new List<Drawable>();
/// <summary>
/// The sequential list in which to handle keyboard input.
/// </summary>
private readonly List<Drawable> keyboardInputQueue = new List<Drawable>();
private Drawable draggingDrawable;
private readonly List<Drawable> hoveredDrawables = new List<Drawable>();
private Drawable hoverHandledDrawable;
public IEnumerable<Drawable> HoveredDrawables => hoveredDrawables;
public InputManager()
{
RelativeSizeAxes = Axes.Both;
}
[BackgroundDependencyLoader(permitNulls: true)]
private void load(GameHost host)
{
Host = host;
}
/// <summary>
/// Handles the internal passing on focus. Note that this doesn't perform a check on the new focus drawable.
/// Usually you'd want to call TriggerFocus on the drawable directly instead.
/// </summary>
/// <param name="focus">The drawable to become focused.</param>
internal void ChangeFocus(Drawable focus)
{
if (focus == FocusedDrawable) return;
FocusedDrawable?.TriggerFocusLost(null, true);
FocusedDrawable = focus;
FocusedDrawable?.TriggerFocus(CurrentState, true);
}
internal override bool BuildKeyboardInputQueue(List<Drawable> queue) => false;
internal override bool BuildMouseInputQueue(Vector2 screenSpaceMousePos, List<Drawable> queue) => false;
protected override void Update()
{
var pendingStates = createDistinctInputStates(GetPendingStates()).ToArray();
unfocusIfNoLongerValid(CurrentState);
//we need to make sure the code in the foreach below is run at least once even if we have no new pending states.
if (pendingStates.Length == 0)
pendingStates = new[] { new InputState() };
foreach (InputState s in pendingStates)
{
bool hasNewKeyboard = s.Keyboard != null;
bool hasNewMouse = s.Mouse != null;
var last = CurrentState;
//avoid lingering references that would stay forever.
last.Last = null;
CurrentState = s;
CurrentState.Last = last;
if (CurrentState.Keyboard == null) CurrentState.Keyboard = last.Keyboard ?? new KeyboardState();
if (CurrentState.Mouse == null) CurrentState.Mouse = last.Mouse ?? new MouseState();
TransformState(CurrentState);
//move above?
updateInputQueues(CurrentState);
if (hasNewMouse)
{
(s.Mouse as MouseState)?.SetLast(last.Mouse); //necessary for now as last state is used internally for stuff
updateHoverEvents(CurrentState);
updateMouseEvents(CurrentState);
}
if (hasNewKeyboard || CurrentState.Keyboard.Keys.Any())
updateKeyboardEvents(CurrentState);
}
if (CurrentState.Mouse != null)
{
foreach (var d in mouseInputQueue)
if (d is IRequireHighFrequencyMousePosition)
if (d.TriggerMouseMove(CurrentState)) break;
}
keyboardRepeatTime -= Time.Elapsed;
if (FocusedDrawable == null)
focusTopMostRequestingDrawable(CurrentState);
base.Update();
}
/// <summary>
/// In order to provide a reliable event system to drawables, we want to ensure that we reprocess input queues (via the
/// main loop in<see cref="updateInputQueues(InputState)"/> after each and every button or key change. This allows
/// correct behaviour in a case where the input queues change based on triggered by a button or key.
/// </summary>
/// <param name="states">A list of <see cref="InputState"/>s</param>
/// <returns>Processed states such that at most one button change occurs between any two consecutive states.</returns>
private IEnumerable<InputState> createDistinctInputStates(List<InputState> states)
{
InputState last = CurrentState;
foreach (var i in states)
{
//first we want to create a copy of ourselves without any button changes
//we do this by updating our buttons to the state of the last frame.
var iWithoutButtons = i.Clone();
var iHasMouse = iWithoutButtons.Mouse != null;
var iHasKeyboard = iWithoutButtons.Keyboard != null;
if (iHasMouse)
for (MouseButton b = 0; b < MouseButton.LastButton; b++)
iWithoutButtons.Mouse.SetPressed(b, last.Mouse?.IsPressed(b) ?? false);
if (iHasKeyboard)
iWithoutButtons.Keyboard.Keys = last.Keyboard?.Keys ?? new Key[] { };
//we start by adding this state to the processed list...
yield return iWithoutButtons;
last = iWithoutButtons;
//and then iterate over each button/key change, adding intermediate states along the way.
if (iHasMouse)
{
for (MouseButton b = 0; b < MouseButton.LastButton; b++)
{
if (i.Mouse.IsPressed(b) != (last.Mouse?.IsPressed(b) ?? false))
{
var intermediateState = last.Clone();
if (intermediateState.Mouse == null) intermediateState.Mouse = new MouseState();
//add our single local change
intermediateState.Mouse.SetPressed(b, i.Mouse.IsPressed(b));
last = intermediateState;
yield return intermediateState;
}
}
}
if (iHasKeyboard)
{
foreach (var releasedKey in last.Keyboard?.Keys.Except(i.Keyboard.Keys) ?? new Key[] { })
{
var intermediateState = last.Clone();
if (intermediateState.Keyboard == null) intermediateState.Keyboard = new KeyboardState();
intermediateState.Keyboard.Keys = intermediateState.Keyboard.Keys.Where(d => d != releasedKey);
last = intermediateState;
yield return intermediateState;
}
foreach (var pressedKey in i.Keyboard.Keys.Except(last.Keyboard?.Keys ?? new Key[] { }))
{
var intermediateState = last.Clone();
if (intermediateState.Keyboard == null) intermediateState.Keyboard = new KeyboardState();
intermediateState.Keyboard.Keys = intermediateState.Keyboard.Keys.Union(new[] { pressedKey });
last = intermediateState;
yield return intermediateState;
}
}
}
}
protected virtual List<InputState> GetPendingStates()
{
var pendingStates = new List<InputState>();
foreach (var h in inputHandlers)
{
if (h.IsActive)
pendingStates.AddRange(h.GetPendingStates());
else
h.GetPendingStates();
}
return pendingStates;
}
protected virtual void TransformState(InputState inputState)
{
}
private void updateInputQueues(InputState state)
{
keyboardInputQueue.Clear();
mouseInputQueue.Clear();
if (state.Keyboard != null)
foreach (Drawable d in AliveInternalChildren)
d.BuildKeyboardInputQueue(keyboardInputQueue);
if (state.Mouse != null)
foreach (Drawable d in AliveInternalChildren)
d.BuildMouseInputQueue(state.Mouse.Position, mouseInputQueue);
keyboardInputQueue.Reverse();
mouseInputQueue.Reverse();
}
private void updateHoverEvents(InputState state)
{
Drawable lastHoverHandledDrawable = hoverHandledDrawable;
hoverHandledDrawable = null;
List<Drawable> lastHoveredDrawables = new List<Drawable>(hoveredDrawables);
hoveredDrawables.Clear();
// Unconditionally unhover all that aren't directly hovered anymore
List<Drawable> newlyUnhoveredDrawables = lastHoveredDrawables.Except(mouseInputQueue).ToList();
foreach (Drawable d in newlyUnhoveredDrawables)
{
d.Hovering = false;
d.TriggerHoverLost(state);
}
// Don't care about what's now explicitly unhovered
lastHoveredDrawables = lastHoveredDrawables.Except(newlyUnhoveredDrawables).ToList();
// lastHoveredDrawables now contain only drawables that were hovered in the previous frame
// that may continue being hovered. We need to construct hoveredDrawables for the current frame
foreach (Drawable d in mouseInputQueue)
{
hoveredDrawables.Add(d);
lastHoveredDrawables.Remove(d);
// Don't need to re-hover those that are already hovered
if (d.Hovering)
{
// Check if this drawable previously handled hover, and assume it would once more
if (d == lastHoverHandledDrawable)
{
hoverHandledDrawable = lastHoverHandledDrawable;
break;
}
continue;
}
d.Hovering = true;
if (d.TriggerHover(state))
{
hoverHandledDrawable = d;
break;
}
}
// lastHoveredDrawables now contains only drawables that were hovered in the previous frame
// but should no longer be hovered as a result of a drawable handling hover this frame
foreach (Drawable d in lastHoveredDrawables)
{
d.Hovering = false;
d.TriggerHoverLost(state);
}
}
private void updateKeyboardEvents(InputState state)
{
KeyboardState keyboard = (KeyboardState)state.Keyboard;
if (!keyboard.Keys.Any())
keyboardRepeatTime = 0;
var last = state.Last?.Keyboard;
if (last == null) return;
foreach (var k in last.Keys)
{
if (!keyboard.Keys.Contains(k))
handleKeyUp(state, k);
}
foreach (Key k in keyboard.Keys.Distinct())
{
bool isModifier = k == Key.LControl || k == Key.RControl
|| k == Key.LAlt || k == Key.RAlt
|| k == Key.LShift || k == Key.RShift
|| k == Key.LWin || k == Key.RWin;
LastActionTime = Time.Current;
bool isRepetition = last.Keys.Contains(k);
if (isModifier)
{
//modifiers shouldn't affect or report key repeat
if (!isRepetition)
handleKeyDown(state, k, false);
continue;
}
if (isRepetition)
{
if (keyboardRepeatTime <= 0)
{
keyboardRepeatTime += repeat_tick_rate;
handleKeyDown(state, k, true);
}
}
else
{
keyboardRepeatTime = repeat_initial_delay;
handleKeyDown(state, k, false);
}
}
}
private List<Drawable> mouseDownInputQueue;
private void updateMouseEvents(InputState state)
{
MouseState mouse = (MouseState)state.Mouse;
var last = state.Last?.Mouse as MouseState;
if (last == null) return;
if (mouse.Position != last.Position)
{
handleMouseMove(state);
if (isDragging)
handleMouseDrag(state);
}
for (MouseButton b = 0; b < MouseButton.LastButton; b++)
{
var lastPressed = last.IsPressed(b);
if (lastPressed != mouse.IsPressed(b))
{
if (lastPressed)
handleMouseUp(state, b);
else
handleMouseDown(state, b);
}
}
if (mouse.WheelDelta != 0)
handleWheel(state);
if (mouse.HasAnyButtonPressed)
{
if (!last.HasAnyButtonPressed)
{
//stuff which only happens once after the mousedown state
mouse.PositionMouseDown = state.Mouse.Position;
LastActionTime = Time.Current;
if (mouse.IsPressed(MouseButton.Left))
{
isValidClick = true;
if (Time.Current - lastClickTime < double_click_time)
{
if (handleMouseDoubleClick(state))
//when we handle a double-click we want to block a normal click from firing.
isValidClick = false;
lastClickTime = 0;
}
lastClickTime = Time.Current;
}
}
if (!isDragging && Vector2.Distance(mouse.PositionMouseDown ?? mouse.Position, mouse.Position) > drag_start_distance)
{
isDragging = true;
handleMouseDragStart(state);
}
}
else if (last.HasAnyButtonPressed)
{
if (isValidClick && (draggingDrawable == null || Vector2.Distance(mouse.PositionMouseDown ?? mouse.Position, mouse.Position) < click_drag_distance))
handleMouseClick(state);
mouseDownInputQueue = null;
mouse.PositionMouseDown = null;
isValidClick = false;
if (isDragging)
{
isDragging = false;
handleMouseDragEnd(state);
}
}
}
private bool handleMouseDown(InputState state, MouseButton button)
{
MouseDownEventArgs args = new MouseDownEventArgs
{
Button = button
};
mouseDownInputQueue = new List<Drawable>(mouseInputQueue);
return mouseInputQueue.Find(target => target.TriggerMouseDown(state, args)) != null;
}
private bool handleMouseUp(InputState state, MouseButton button)
{
if (mouseDownInputQueue == null) return false;
MouseUpEventArgs args = new MouseUpEventArgs
{
Button = button
};
//extra check for IsAlive because we are using an outdated queue.
return mouseDownInputQueue.Any(target => target.IsAlive && target.IsPresent && target.TriggerMouseUp(state, args));
}
private bool handleMouseMove(InputState state)
{
return mouseInputQueue.Any(target => target.TriggerMouseMove(state));
}
private bool handleMouseClick(InputState state)
{
//extra check for IsAlive because we are using an outdated queue.
if (mouseInputQueue.Intersect(mouseDownInputQueue).Any(t => t.IsHovered(state.Mouse.Position) && t.TriggerClick(state) | t.TriggerFocus(state, true)))
return true;
FocusedDrawable?.TriggerFocusLost();
return false;
}
private bool handleMouseDoubleClick(InputState state)
{
return mouseInputQueue.Any(target => target.TriggerDoubleClick(state));
}
private bool handleMouseDrag(InputState state)
{
//Once a drawable is dragged, it remains in a dragged state until the drag is finished.
return draggingDrawable?.TriggerDrag(state) ?? false;
}
private bool handleMouseDragStart(InputState state)
{
draggingDrawable = mouseDownInputQueue?.FirstOrDefault(target => target.IsAlive && target.TriggerDragStart(state));
return draggingDrawable != null;
}
private bool handleMouseDragEnd(InputState state)
{
if (draggingDrawable == null)
return false;
bool result = draggingDrawable.TriggerDragEnd(state);
draggingDrawable = null;
return result;
}
private bool handleWheel(InputState state)
{
return mouseInputQueue.Any(target => target.TriggerWheel(state));
}
private bool handleKeyDown(InputState state, Key key, bool repeat)
{
KeyDownEventArgs args = new KeyDownEventArgs
{
Key = key,
Repeat = repeat
};
if (!unfocusIfNoLongerValid(state))
{
if (args.Key == Key.Escape)
{
FocusedDrawable.TriggerFocusLost(state);
return true;
}
if (FocusedDrawable.TriggerKeyDown(state, args))
return true;
}
return keyboardInputQueue.Any(target => target.TriggerKeyDown(state, args));
}
private bool handleKeyUp(InputState state, Key key)
{
KeyUpEventArgs args = new KeyUpEventArgs
{
Key = key
};
if (!unfocusIfNoLongerValid(state) && (FocusedDrawable?.TriggerKeyUp(state, args) ?? false))
return true;
return keyboardInputQueue.Any(target => target.TriggerKeyUp(state, args));
}
/// <summary>
/// Unfocus the current focused drawable if it is no longer in a valid state.
/// </summary>
/// <returns>true if there is no longer a focus.</returns>
private bool unfocusIfNoLongerValid(InputState state)
{
if (FocusedDrawable == null) return true;
bool stillValid = FocusedDrawable.IsPresent && FocusedDrawable.Parent != null;
if (stillValid)
{
//ensure we are visible
IContainer d = FocusedDrawable.Parent;
while (d != null)
{
if (!d.IsPresent)
{
stillValid = false;
break;
}
d = d.Parent;
}
}
if (stillValid)
return false;
FocusedDrawable.TriggerFocusLost(state);
FocusedDrawable = null;
return true;
}
private void focusTopMostRequestingDrawable(InputState state) => keyboardInputQueue.FirstOrDefault(target => target.RequestingFocus)?.TriggerFocus(state, true);
public InputHandler GetHandler(Type handlerType)
{
return inputHandlers.Find(h => h.GetType() == handlerType);
}
protected bool AddHandler(InputHandler handler)
{
try
{
if (handler.Initialize(Host))
{
int index = inputHandlers.BinarySearch(handler, new InputHandlerComparer());
if (index < 0)
{
index = ~index;
}
inputHandlers.Insert(index, handler);
return true;
}
}
catch
{
}
return false;
}
protected bool RemoveHandler(InputHandler handler) => inputHandlers.Remove(handler);
protected override void Dispose(bool isDisposing)
{
foreach (var h in inputHandlers)
h.Dispose();
base.Dispose(isDisposing);
}
}
public enum ConfineMouseMode
{
Never,
Fullscreen,
Always
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="WebPartMenu.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.UI.WebControls.WebParts {
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Globalization;
using System.Web;
using System.Web.Handlers;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Util;
internal sealed class WebPartMenu {
private static string _defaultCheckImageUrl;
private int _cssStyleIndex;
private IWebPartMenuUser _menuUser;
public WebPartMenu(IWebPartMenuUser menuUser) {
_menuUser = menuUser;
}
private static string DefaultCheckImageUrl {
get {
if (_defaultCheckImageUrl == null) {
_defaultCheckImageUrl = AssemblyResourceLoader.GetWebResourceUrl(typeof(WebPartMenu), "WebPartMenu_Check.gif");
}
return _defaultCheckImageUrl;
}
}
private void RegisterStartupScript(string clientID) {
string menuItemStyleCss = String.Empty;
string menuItemHoverStyleCss = String.Empty;
Style itemStyle = _menuUser.ItemStyle;
if (itemStyle != null) {
menuItemStyleCss = itemStyle.GetStyleAttributes(_menuUser.UrlResolver).Value;
}
Style itemHoverStyle = _menuUser.ItemHoverStyle;
if (itemHoverStyle != null) {
menuItemHoverStyleCss = itemHoverStyle.GetStyleAttributes(_menuUser.UrlResolver).Value;
}
string labelHoverColor = String.Empty;
string labelHoverClass = String.Empty;
Style labelHoverStyle = _menuUser.LabelHoverStyle;
if (labelHoverStyle != null) {
Color foreColor = labelHoverStyle.ForeColor;
if (foreColor.IsEmpty == false) {
labelHoverColor = ColorTranslator.ToHtml(foreColor);
}
labelHoverClass = labelHoverStyle.RegisteredCssClass;
}
// Using concatenation instead of String.Format for perf
// (here, the compiler will build an object[] and call String.Concat only once).
string script = @"
<script type=""text/javascript"">
var menu" + clientID + " = new WebPartMenu(document.getElementById('" + clientID + "'), document.getElementById('" + clientID + "Popup'), document.getElementById('" + clientID + @"Menu'));
menu" + clientID + ".itemStyle = '" + Util.QuoteJScriptString(menuItemStyleCss) + @"';
menu" + clientID + ".itemHoverStyle = '" + Util.QuoteJScriptString(menuItemHoverStyleCss) + @"';
menu" + clientID + ".labelHoverColor = '" + labelHoverColor + @"';
menu" + clientID + ".labelHoverClassName = '" + labelHoverClass + @"';
</script>
";
if (_menuUser.Page != null) {
_menuUser.Page.ClientScript.RegisterStartupScript((Control)_menuUser, typeof(WebPartMenu), clientID, script, false);
IScriptManager scriptManager = _menuUser.Page.ScriptManager;
if ((scriptManager != null) && scriptManager.SupportsPartialRendering) {
scriptManager.RegisterDispose((Control)_menuUser,
"document.getElementById('" + clientID + "').__menu.Dispose();");
}
}
}
private void RegisterStyle(Style style) {
Debug.Assert(_menuUser.Page != null && _menuUser.Page.SupportsStyleSheets);
if (style != null && !style.IsEmpty) {
// The style should not have already been registered
Debug.Assert(style.RegisteredCssClass.Length == 0);
string name = _menuUser.ClientID + "__Menu_" + _cssStyleIndex++.ToString(NumberFormatInfo.InvariantInfo);
_menuUser.Page.Header.StyleSheet.CreateStyleRule(style, _menuUser.UrlResolver, "." + name);
style.SetRegisteredCssClass(name);
}
}
public void RegisterStyles() {
// Assert is fine here as the class is internal
Debug.Assert(_menuUser.Page != null && _menuUser.Page.SupportsStyleSheets);
// Registering the static label style before hover so hover takes precedence
RegisterStyle(_menuUser.LabelStyle);
RegisterStyle(_menuUser.LabelHoverStyle);
}
public void Render(HtmlTextWriter writer, string clientID) {
RenderLabel(writer, clientID, null);
}
public void Render(HtmlTextWriter writer, ICollection verbs, string clientID, WebPart associatedWebPart,
WebPartManager webPartManager) {
// This method should only be called when Zone.RenderClientScript is true, which means
// WebPartManager is not null.
Debug.Assert(webPartManager != null);
RegisterStartupScript(clientID);
RenderLabel(writer, clientID, associatedWebPart);
RenderMenuPopup(writer, verbs, clientID, associatedWebPart, webPartManager);
}
private void RenderLabel(HtmlTextWriter writer, string clientID, WebPart associatedWebPart) {
_menuUser.OnBeginRender(writer);
if (associatedWebPart != null) {
writer.AddAttribute(HtmlTextWriterAttribute.Id, clientID);
Style labelStyle = _menuUser.LabelStyle;
if (labelStyle != null) {
labelStyle.AddAttributesToRender(writer, _menuUser as WebControl);
}
}
writer.AddStyleAttribute(HtmlTextWriterStyle.Cursor, "hand");
writer.AddStyleAttribute(HtmlTextWriterStyle.Display, "inline-block");
writer.AddStyleAttribute(HtmlTextWriterStyle.Padding, "1px");
writer.AddStyleAttribute(HtmlTextWriterStyle.TextDecoration, "none");
writer.RenderBeginTag(HtmlTextWriterTag.Span);
string labelImageUrl = _menuUser.LabelImageUrl;
string text = _menuUser.LabelText;
if (!String.IsNullOrEmpty(labelImageUrl)) {
writer.AddAttribute(HtmlTextWriterAttribute.Src, labelImageUrl);
writer.AddAttribute(HtmlTextWriterAttribute.Alt,
(!String.IsNullOrEmpty(text) ?
text :
SR.GetString(SR.WebPartMenu_DefaultDropDownAlternateText)),
true);
writer.AddStyleAttribute("vertical-align", "middle");
writer.AddStyleAttribute(HtmlTextWriterStyle.BorderStyle, "none");
writer.RenderBeginTag(HtmlTextWriterTag.Img);
writer.RenderEndTag();
writer.Write(" ");
}
if (!String.IsNullOrEmpty(text)) {
writer.Write(text);
writer.Write(" ");
}
writer.AddAttribute(HtmlTextWriterAttribute.Id, clientID + "Popup");
string popupImageUrl = _menuUser.PopupImageUrl;
if (!String.IsNullOrEmpty(popupImageUrl)) {
writer.AddAttribute(HtmlTextWriterAttribute.Src, popupImageUrl);
writer.AddAttribute(HtmlTextWriterAttribute.Alt,
(!String.IsNullOrEmpty(text) ?
text :
SR.GetString(SR.WebPartMenu_DefaultDropDownAlternateText)),
true);
writer.AddStyleAttribute("vertical-align", "middle");
writer.AddStyleAttribute(HtmlTextWriterStyle.BorderStyle, "none");
writer.RenderBeginTag(HtmlTextWriterTag.Img);
writer.RenderEndTag();
}
else {
// Render down arrow using windows font
writer.AddStyleAttribute(HtmlTextWriterStyle.FontFamily, "Marlett");
writer.AddStyleAttribute(HtmlTextWriterStyle.FontSize, "8pt");
writer.RenderBeginTag(HtmlTextWriterTag.Span);
writer.Write("u");
writer.RenderEndTag();
}
writer.RenderEndTag(); // Span
_menuUser.OnEndRender(writer);
}
private void RenderMenuPopup(HtmlTextWriter writer, ICollection verbs, string clientID, WebPart associatedWebPart,
WebPartManager webPartManager) {
writer.AddAttribute(HtmlTextWriterAttribute.Id, clientID + "Menu");
writer.AddStyleAttribute(HtmlTextWriterStyle.Display, "none");
writer.RenderBeginTag(HtmlTextWriterTag.Div);
bool popupSpansFullExtent = true;
WebPartMenuStyle menuStyle = _menuUser.MenuPopupStyle;
if (menuStyle != null) {
menuStyle.AddAttributesToRender(writer, _menuUser as WebControl);
popupSpansFullExtent = menuStyle.Width.IsEmpty;
}
else {
// generate attributes corresponding to defaults on WebPartMenuStyle
writer.AddAttribute(HtmlTextWriterAttribute.Cellspacing, "0");
writer.AddAttribute(HtmlTextWriterAttribute.Cellpadding, "1");
writer.AddStyleAttribute(HtmlTextWriterStyle.BorderCollapse, "collapse");
}
if (popupSpansFullExtent) {
writer.AddStyleAttribute(HtmlTextWriterStyle.Width, "100%");
}
writer.RenderBeginTag(HtmlTextWriterTag.Table);
writer.RenderBeginTag(HtmlTextWriterTag.Tr);
writer.AddStyleAttribute(HtmlTextWriterStyle.WhiteSpace, "nowrap");
writer.RenderBeginTag(HtmlTextWriterTag.Td);
bool isParentEnabled = associatedWebPart.Zone.IsEnabled;
foreach (WebPartVerb verb in verbs) {
Debug.Assert(verb != null);
writer.RenderBeginTag(HtmlTextWriterTag.Div);
string alt;
if (associatedWebPart != null) {
alt = String.Format(CultureInfo.CurrentCulture, verb.Description, associatedWebPart.DisplayTitle);
}
else {
alt = verb.Description;
}
if (alt.Length != 0) {
writer.AddAttribute(HtmlTextWriterAttribute.Title, alt);
}
bool isEnabled = isParentEnabled && verb.Enabled;
// Special case help, export, etc.
if (verb is WebPartHelpVerb) {
Debug.Assert(associatedWebPart != null);
string resolvedHelpUrl =
((IUrlResolutionService)associatedWebPart).ResolveClientUrl(associatedWebPart.HelpUrl);
writer.AddAttribute(HtmlTextWriterAttribute.Href, "javascript:void(0)");
if (isEnabled) {
writer.AddAttribute(HtmlTextWriterAttribute.Onclick,
"document.body.__wpm.ShowHelp('" +
Util.QuoteJScriptString(resolvedHelpUrl) +
"', " +
((int)associatedWebPart.HelpMode).ToString(CultureInfo.InvariantCulture) + ")");
}
}
else if (verb is WebPartExportVerb) {
Debug.Assert(associatedWebPart != null);
string exportUrl = webPartManager.GetExportUrl(associatedWebPart);
writer.AddAttribute(HtmlTextWriterAttribute.Href, "javascript:void(0)");
if (isEnabled) {
writer.AddAttribute(HtmlTextWriterAttribute.Onclick,
"document.body.__wpm.ExportWebPart('" +
Util.QuoteJScriptString(exportUrl) +
((associatedWebPart.ExportMode == WebPartExportMode.All) ?
"', true, false)" :
"', false, false)"));
}
}
else {
string target = _menuUser.PostBackTarget;
writer.AddAttribute(HtmlTextWriterAttribute.Href, "javascript:void(0)");
if (isEnabled) {
string eventArgument = verb.EventArgument;
if (associatedWebPart != null) {
eventArgument = verb.GetEventArgument(associatedWebPart.ID);
}
string submitScript = null;
if (!String.IsNullOrEmpty(eventArgument)) {
submitScript = "document.body.__wpm.SubmitPage('" +
Util.QuoteJScriptString(target) +
"', '" +
Util.QuoteJScriptString(eventArgument) +
"');";
_menuUser.Page.ClientScript.RegisterForEventValidation(target, eventArgument);
}
string clientClickScript = null;
if (!String.IsNullOrEmpty(verb.ClientClickHandler)) {
clientClickScript = "document.body.__wpm.Execute('" +
Util.QuoteJScriptString(Util.EnsureEndWithSemiColon(verb.ClientClickHandler)) +
"')";
}
// There must be either an EventArgument or a ClientClickHandler
Debug.Assert(submitScript != null || clientClickScript != null);
string onclick = String.Empty;
if (submitScript != null && clientClickScript != null) {
onclick = "if(" + clientClickScript + "){" + submitScript + "}";
}
else if (submitScript != null) {
onclick = submitScript;
}
else if (clientClickScript != null) {
onclick = clientClickScript;
}
if (verb is WebPartCloseVerb) {
Debug.Assert(associatedWebPart != null);
// PERF: First check if this WebPart even has provider connection points
ProviderConnectionPointCollection connectionPoints =
webPartManager.GetProviderConnectionPoints(associatedWebPart);
if (connectionPoints != null && connectionPoints.Count > 0 &&
webPartManager.Connections.ContainsProvider(associatedWebPart)) {
onclick = "if(document.body.__wpmCloseProviderWarning.length == 0 || " +
"confirm(document.body.__wpmCloseProviderWarning)){" + onclick + "}";
}
}
else if (verb is WebPartDeleteVerb) {
onclick = "if(document.body.__wpmDeleteWarning.length == 0 || " +
"confirm(document.body.__wpmDeleteWarning)){" + onclick + "}";
}
writer.AddAttribute(HtmlTextWriterAttribute.Onclick, onclick);
}
}
string disabledClass = "menuItem";
if (!verb.Enabled) {
if (associatedWebPart.Zone.RenderingCompatibility < VersionUtil.Framework40) {
writer.AddAttribute(HtmlTextWriterAttribute.Disabled, "disabled");
}
else if (!String.IsNullOrEmpty(WebControl.DisabledCssClass)) {
disabledClass = WebControl.DisabledCssClass + " " + disabledClass;
}
}
writer.AddAttribute(HtmlTextWriterAttribute.Class, disabledClass);
writer.RenderBeginTag(HtmlTextWriterTag.A);
string img = verb.ImageUrl;
if (img.Length != 0) {
img = _menuUser.UrlResolver.ResolveClientUrl(img);
}
else {
if (verb.Checked) {
img = _menuUser.CheckImageUrl;
if (img.Length == 0) {
img = DefaultCheckImageUrl;
}
}
else {
img = webPartManager.SpacerImageUrl;
}
}
writer.AddAttribute(HtmlTextWriterAttribute.Src, img);
writer.AddAttribute(HtmlTextWriterAttribute.Alt, alt, true);
writer.AddAttribute(HtmlTextWriterAttribute.Width, "16");
writer.AddAttribute(HtmlTextWriterAttribute.Height, "16");
writer.AddStyleAttribute(HtmlTextWriterStyle.BorderStyle, "none");
writer.AddStyleAttribute("vertical-align", "middle");
if (verb.Checked) {
Style checkImageStyle = _menuUser.CheckImageStyle;
if (checkImageStyle != null) {
checkImageStyle.AddAttributesToRender(writer, _menuUser as WebControl);
}
}
writer.RenderBeginTag(HtmlTextWriterTag.Img);
writer.RenderEndTag(); // Img
writer.Write(" ");
writer.Write(verb.Text);
writer.Write(" ");
writer.RenderEndTag(); // A
writer.RenderEndTag(); // Div
}
writer.RenderEndTag(); // Td
writer.RenderEndTag(); // Tr
writer.RenderEndTag(); // Table
writer.RenderEndTag(); // Div
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using Xunit;
namespace System.Linq.Tests
{
public class AppendPrependTests : EnumerableTests
{
[Fact]
public void SameResultsRepeatCallsIntQueryAppend()
{
var q1 = from x1 in new int?[] { 2, 3, null, 2, null, 4, 5 }
select x1;
Assert.Equal(q1.Append(42), q1.Append(42));
Assert.Equal(q1.Append(42), q1.Concat(new int?[] { 42 }));
}
[Fact]
public void SameResultsRepeatCallsIntQueryPrepend()
{
var q1 = from x1 in new int?[] { 2, 3, null, 2, null, 4, 5 }
select x1;
Assert.Equal(q1.Prepend(42), q1.Prepend(42));
Assert.Equal(q1.Prepend(42), (new int?[] { 42 }).Concat(q1));
}
[Fact]
public void SameResultsRepeatCallsStringQueryAppend()
{
var q1 = from x1 in new[] { "AAA", string.Empty, "q", "C", "#", "!@#$%^", "0987654321", "Calling Twice" }
select x1;
Assert.Equal(q1.Append("hi"), q1.Append("hi"));
Assert.Equal(q1.Append("hi"), q1.Concat(new string[] { "hi" }));
}
[Fact]
public void SameResultsRepeatCallsStringQueryPrepend()
{
var q1 = from x1 in new[] { "AAA", string.Empty, "q", "C", "#", "!@#$%^", "0987654321", "Calling Twice" }
select x1;
Assert.Equal(q1.Prepend("hi"), q1.Prepend("hi"));
Assert.Equal(q1.Prepend("hi"), (new string[] { "hi" }).Concat(q1));
}
[Fact]
public void RepeatIteration()
{
var q = Enumerable.Range(3, 4).Append(12);
Assert.Equal(q, q);
q = q.Append(14);
Assert.Equal(q, q);
}
[Fact]
public void EmptyAppend()
{
int[] first = { };
Assert.Single(first.Append(42), 42);
}
[Fact]
public void EmptyPrepend()
{
string[] first = { };
Assert.Single(first.Prepend("aa"), "aa");
}
[Fact]
public void PrependNoIteratingSourceBeforeFirstItem()
{
var ie = new List<int>();
var prepended = (from i in ie select i).Prepend(4);
ie.Add(42);
Assert.Equal(prepended, ie.Prepend(4));
}
[Fact]
public void ForcedToEnumeratorDoesntEnumeratePrepend()
{
var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).Prepend(4);
// Don't insist on this behaviour, but check it's correct if it happens
var en = iterator as IEnumerator<int>;
Assert.False(en != null && en.MoveNext());
}
[Fact]
public void ForcedToEnumeratorDoesntEnumerateAppend()
{
var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).Append(4);
// Don't insist on this behaviour, but check it's correct if it happens
var en = iterator as IEnumerator<int>;
Assert.False(en != null && en.MoveNext());
}
[Fact]
public void ForcedToEnumeratorDoesntEnumerateMultipleAppendsAndPrepends()
{
var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).Append(4).Append(5).Prepend(-1).Prepend(-2);
// Don't insist on this behaviour, but check it's correct if it happens
var en = iterator as IEnumerator<int>;
Assert.False(en != null && en.MoveNext());
}
[Fact]
public void SourceNull()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<int>)null).Append(1));
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<int>)null).Prepend(1));
}
[Fact]
public void Combined()
{
var v = "foo".Append('1').Append('2').Prepend('3').Concat("qq".Append('Q').Prepend('W'));
Assert.Equal(v.ToArray(), "3foo12WqqQ".ToArray());
var v1 = "a".Append('b').Append('c').Append('d');
Assert.Equal(v1.ToArray(), "abcd".ToArray());
var v2 = "a".Prepend('b').Prepend('c').Prepend('d');
Assert.Equal(v2.ToArray(), "dcba".ToArray());
}
[Fact]
public void AppendCombinations()
{
var source = Enumerable.Range(0, 3).Append(3).Append(4);
var app0a = source.Append(5);
var app0b = source.Append(6);
var app1aa = app0a.Append(7);
var app1ab = app0a.Append(8);
var app1ba = app0b.Append(9);
var app1bb = app0b.Append(10);
Assert.Equal(new[] { 0, 1, 2, 3, 4, 5 }, app0a);
Assert.Equal(new[] { 0, 1, 2, 3, 4, 6 }, app0b);
Assert.Equal(new[] { 0, 1, 2, 3, 4, 5, 7 }, app1aa);
Assert.Equal(new[] { 0, 1, 2, 3, 4, 5, 8 }, app1ab);
Assert.Equal(new[] { 0, 1, 2, 3, 4, 6, 9 }, app1ba);
Assert.Equal(new[] { 0, 1, 2, 3, 4, 6, 10 }, app1bb);
}
[Fact]
public void PrependCombinations()
{
var source = Enumerable.Range(2, 2).Prepend(1).Prepend(0);
var pre0a = source.Prepend(5);
var pre0b = source.Prepend(6);
var pre1aa = pre0a.Prepend(7);
var pre1ab = pre0a.Prepend(8);
var pre1ba = pre0b.Prepend(9);
var pre1bb = pre0b.Prepend(10);
Assert.Equal(new[] { 5, 0, 1, 2, 3 }, pre0a);
Assert.Equal(new[] { 6, 0, 1, 2, 3 }, pre0b);
Assert.Equal(new[] { 7, 5, 0, 1, 2, 3 }, pre1aa);
Assert.Equal(new[] { 8, 5, 0, 1, 2, 3 }, pre1ab);
Assert.Equal(new[] { 9, 6, 0, 1, 2, 3 }, pre1ba);
Assert.Equal(new[] { 10, 6, 0, 1, 2, 3 }, pre1bb);
}
[Fact]
public void Append1ToArrayToList()
{
var source = Enumerable.Range(0, 2).Append(2);
Assert.Equal(Enumerable.Range(0, 3), source.ToList());
Assert.Equal(Enumerable.Range(0, 3), source.ToArray());
source = Enumerable.Range(0, 2).ToList().Append(2);
Assert.Equal(Enumerable.Range(0, 3), source.ToList());
Assert.Equal(Enumerable.Range(0, 3), source.ToArray());
source = NumberRangeGuaranteedNotCollectionType(0, 2).Append(2);
Assert.Equal(Enumerable.Range(0, 3), source.ToList());
Assert.Equal(Enumerable.Range(0, 3), source.ToArray());
}
[Fact]
public void Prepend1ToArrayToList()
{
var source = Enumerable.Range(1, 2).Prepend(0);
Assert.Equal(Enumerable.Range(0, 3), source.ToList());
Assert.Equal(Enumerable.Range(0, 3), source.ToArray());
source = Enumerable.Range(1, 2).ToList().Prepend(0);
Assert.Equal(Enumerable.Range(0, 3), source.ToList());
Assert.Equal(Enumerable.Range(0, 3), source.ToArray());
source = NumberRangeGuaranteedNotCollectionType(1, 2).Prepend(0);
Assert.Equal(Enumerable.Range(0, 3), source.ToList());
Assert.Equal(Enumerable.Range(0, 3), source.ToArray());
}
[Fact]
public void AppendNToArrayToList()
{
var source = Enumerable.Range(0, 2).Append(2).Append(3);
Assert.Equal(Enumerable.Range(0, 4), source.ToList());
Assert.Equal(Enumerable.Range(0, 4), source.ToArray());
source = Enumerable.Range(0, 2).ToList().Append(2).Append(3);
Assert.Equal(Enumerable.Range(0, 4), source.ToList());
Assert.Equal(Enumerable.Range(0, 4), source.ToArray());
source = NumberRangeGuaranteedNotCollectionType(0, 2).Append(2).Append(3);
Assert.Equal(Enumerable.Range(0, 4), source.ToList());
Assert.Equal(Enumerable.Range(0, 4), source.ToArray());
}
[Fact]
public void PrependNToArrayToList()
{
var source = Enumerable.Range(2, 2).Prepend(1).Prepend(0);
Assert.Equal(Enumerable.Range(0, 4), source.ToList());
Assert.Equal(Enumerable.Range(0, 4), source.ToArray());
source = Enumerable.Range(2, 2).ToList().Prepend(1).Prepend(0);
Assert.Equal(Enumerable.Range(0, 4), source.ToList());
Assert.Equal(Enumerable.Range(0, 4), source.ToArray());
source = NumberRangeGuaranteedNotCollectionType(2, 2).Prepend(1).Prepend(0);
Assert.Equal(Enumerable.Range(0, 4), source.ToList());
Assert.Equal(Enumerable.Range(0, 4), source.ToArray());
}
[Fact]
public void AppendPrependToArrayToList()
{
var source = Enumerable.Range(2, 2).Prepend(1).Append(4).Prepend(0).Append(5);
Assert.Equal(Enumerable.Range(0, 6), source.ToList());
Assert.Equal(Enumerable.Range(0, 6), source.ToArray());
source = Enumerable.Range(2, 2).ToList().Prepend(1).Append(4).Prepend(0).Append(5);
Assert.Equal(Enumerable.Range(0, 6), source.ToList());
Assert.Equal(Enumerable.Range(0, 6), source.ToArray());
source = NumberRangeGuaranteedNotCollectionType(2, 2).Append(4).Prepend(1).Append(5).Prepend(0);
Assert.Equal(Enumerable.Range(0, 6), source.ToList());
Assert.Equal(Enumerable.Range(0, 6), source.ToArray());
source = NumberRangeGuaranteedNotCollectionType(2, 2).Prepend(1).Prepend(0).Append(4).Append(5);
Assert.Equal(Enumerable.Range(0, 6), source.ToList());
Assert.Equal(Enumerable.Range(0, 6), source.ToArray());
}
[Fact]
public void AppendPrependRunOnce()
{
var source = NumberRangeGuaranteedNotCollectionType(2, 2).RunOnce().Prepend(1).RunOnce().Prepend(0).RunOnce().Append(4).RunOnce().Append(5).RunOnce();
Assert.Equal(Enumerable.Range(0, 6), source.ToList());
source = NumberRangeGuaranteedNotCollectionType(2, 2).Prepend(1).Prepend(0).Append(4).Append(5).RunOnce();
Assert.Equal(Enumerable.Range(0, 6), source.ToList());
}
}
}
| |
namespace Fonet.DataTypes
{
using System;
using System.Globalization;
using Fonet.Util;
internal class ColorType : ICloneable
{
private float red;
private float green;
private float blue;
private float alpha = 0;
public ColorType(float red, float green, float blue)
{
this.red = red;
this.green = green;
this.blue = blue;
}
public ColorType(string value)
{
string colorValue = value.ToLower();
if (colorValue.StartsWith("#"))
{
try
{
if (colorValue.Length == 4)
{
// note: divide by 15 so F = FF = 1 and so on
red = Int32.Parse(
colorValue.Substring(1, 1), NumberStyles.HexNumber) / 15f;
green = Int32.Parse(
colorValue.Substring(2, 1), NumberStyles.HexNumber) / 15f;
blue = Int32.Parse(
colorValue.Substring(3, 1), NumberStyles.HexNumber) / 15f;
}
else if (colorValue.Length == 7)
{
// note: divide by 255 so FF = 1
red = Int32.Parse(
colorValue.Substring(1, 2), NumberStyles.HexNumber) / 255f;
green = Int32.Parse(
colorValue.Substring(3, 2), NumberStyles.HexNumber) / 255f;
blue = Int32.Parse(
colorValue.Substring(5, 2), NumberStyles.HexNumber) / 255f;
}
else
{
red = 0;
green = 0;
blue = 0;
FonetDriver.ActiveDriver.FireFonetError(
"Unknown colour format. Must be #RGB or #RRGGBB");
}
}
catch (Exception)
{
red = 0;
green = 0;
blue = 0;
FonetDriver.ActiveDriver.FireFonetError(
"Unknown colour format. Must be #RGB or #RRGGBB");
}
}
else if (colorValue.StartsWith("rgb("))
{
int poss = colorValue.IndexOf("(");
int pose = colorValue.IndexOf(")");
if (poss != -1 && pose != -1)
{
colorValue = colorValue.Substring(poss + 1, pose);
StringTokenizer st = new StringTokenizer(colorValue, ",");
try
{
if (st.HasMoreTokens())
{
String str = st.NextToken().Trim();
if (str.EndsWith("%"))
{
this.Red =
Int32.Parse(str.Substring(0, str.Length - 1))
* 2.55f;
}
else
{
this.Red = Int32.Parse(str) / 255f;
}
}
if (st.HasMoreTokens())
{
String str = st.NextToken().Trim();
if (str.EndsWith("%"))
{
this.Green =
Int32.Parse(str.Substring(0, str.Length - 1))
* 2.55f;
}
else
{
this.Green = Int32.Parse(str) / 255f;
}
}
if (st.HasMoreTokens())
{
String str = st.NextToken().Trim();
if (str.EndsWith("%"))
{
this.Blue =
Int32.Parse(str.Substring(0, str.Length - 1))
* 2.55f;
}
else
{
this.Blue = Int32.Parse(str) / 255f;
}
}
}
catch
{
this.Red = 0;
this.Green = 0;
this.Blue = 0;
FonetDriver.ActiveDriver.FireFonetError(
"Unknown colour format. Must be #RGB or #RRGGBB");
}
}
}
else if (colorValue.StartsWith("url("))
{
// refers to a gradient
FonetDriver.ActiveDriver.FireFonetError(
"unsupported color format");
}
else
{
if (colorValue.Equals("transparent"))
{
Red = 0;
Green = 0;
Blue = 0;
Alpha = 1;
}
else
{
bool found = false;
for (int count = 0; count < names.Length; count++)
{
if (colorValue.Equals(names[count]))
{
Red = vals[count, 0] / 255f;
Green = vals[count, 1] / 255f;
Blue = vals[count, 2] / 255f;
found = true;
break;
}
}
if (!found)
{
Red = 0;
Green = 0;
Blue = 0;
FonetDriver.ActiveDriver.FireFonetWarning(
"Unknown colour name: " + colorValue + ". Defaulting to black.");
}
}
}
}
public float Blue
{
get
{
return blue;
}
set
{
blue = value;
}
}
public float Green
{
get
{
return green;
}
set
{
green = value;
}
}
public float Red
{
get
{
return red;
}
set
{
red = value;
}
}
public float Alpha
{
get
{
return alpha;
}
set
{
alpha = value;
}
}
public object Clone()
{
return new ColorType(Red, Green, Blue);
}
private static readonly string[] names = {
"aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige",
"bisque", "black", "blanchedalmond", "blue", "blueviolet", "brown",
"burlywood", "cadetblue", "chartreuse", "chocolate", "coral",
"cornflowerblue", "cornsilk", "crimson", "cyan", "darkblue",
"darkcyan", "darkgoldenrod", "darkgray", "darkgreen", "darkgrey",
"darkkhaki", "darkmagenta", "darkolivegreen", "darkorange",
"darkorchid", "darkred", "darksalmon", "darkseagreen",
"darkslateblue", "darkslategray", "darkslategrey", "darkturquoise",
"darkviolet", "deeppink", "deepskyblue", "dimgray", "dimgrey",
"dodgerblue", "firebrick", "floralwhite", "forestgreen", "fuchsia",
"gainsboro", "lightpink", "lightsalmon", "lightseagreen",
"lightskyblue", "lightslategray", "lightslategrey", "lightsteelblue",
"lightyellow", "lime", "limegreen", "linen", "magenta", "maroon",
"mediumaquamarine", "mediumblue", "mediumorchid", "mediumpurple",
"mediumseagreen", "mediumslateblue", "mediumspringgreen",
"mediumturquoise", "mediumvioletred", "midnightblue", "mintcream",
"mistyrose", "moccasin", "navajowhite", "navy", "oldlace", "olive",
"olivedrab", "orange", "orangered", "orchid", "palegoldenrod",
"palegreen", "paleturquoise", "palevioletred", "papayawhip",
"peachpuff", "peru", "pink", "plum", "powderblue", "purple", "red",
"rosybrown", "royalblue", "saddlebrown", "salmon", "ghostwhite",
"gold", "goldenrod", "gray", "grey", "green", "greenyellow",
"honeydew", "hotpink", "indianred", "indigo", "ivory", "khaki",
"lavender", "lavenderblush", "lawngreen", "lemonchiffon",
"lightblue", "lightcoral", "lightcyan", "lightgoldenrodyellow",
"lightgray", "lightgreen", "lightgrey", "sandybrown", "seagreen",
"seashell", "sienna", "silver", "skyblue", "slateblue", "slategray",
"slategrey", "snow", "springgreen", "steelblue", "tan", "teal",
"thistle", "tomato", "turquoise", "violet", "wheat", "white",
"whitesmoke", "yellow", "yellowgreen"
};
private static readonly int[,] vals = {
{240, 248, 255},
{250, 235, 215},
{0, 255, 255},
{127, 255, 212},
{240, 255, 255},
{245, 245, 220},
{255, 228, 196},
{0, 0, 0},
{255, 235, 205},
{0, 0, 255},
{138, 43, 226},
{165, 42, 42},
{222, 184, 135},
{95, 158, 160},
{127, 255, 0},
{210, 105, 30},
{255, 127, 80},
{100, 149, 237},
{255, 248, 220},
{220, 20, 60},
{0, 255, 255},
{0, 0, 139},
{0, 139, 139},
{184, 134, 11},
{169, 169, 169},
{0, 100, 0},
{169, 169, 169},
{189, 183, 107},
{139, 0, 139},
{85, 107, 47},
{255, 140, 0},
{153, 50, 204},
{139, 0, 0},
{233, 150, 122},
{143, 188, 143},
{72, 61, 139},
{47, 79, 79},
{47, 79, 79},
{0, 206, 209},
{148, 0, 211},
{255, 20, 147},
{0, 191, 255},
{105, 105, 105},
{105, 105, 105},
{30, 144, 255},
{178, 34, 34},
{255, 250, 240},
{34, 139, 34},
{255, 0, 255},
{220, 220, 220},
{255, 182, 193},
{255, 160, 122},
{32, 178, 170},
{135, 206, 250},
{119, 136, 153},
{119, 136, 153},
{176, 196, 222},
{255, 255, 224},
{0, 255, 0},
{50, 205, 50},
{250, 240, 230},
{255, 0, 255},
{128, 0, 0},
{102, 205, 170},
{0, 0, 205},
{186, 85, 211},
{147, 112, 219},
{60, 179, 113},
{123, 104, 238},
{0, 250, 154},
{72, 209, 204},
{199, 21, 133},
{25, 25, 112},
{245, 255, 250},
{255, 228, 225},
{255, 228, 181},
{255, 222, 173},
{0, 0, 128},
{253, 245, 230},
{128, 128, 0},
{107, 142, 35},
{255, 165, 0},
{255, 69, 0},
{218, 112, 214},
{238, 232, 170},
{152, 251, 152},
{175, 238, 238},
{219, 112, 147},
{255, 239, 213},
{255, 218, 185},
{205, 133, 63},
{255, 192, 203},
{221, 160, 221},
{176, 224, 230},
{128, 0, 128},
{255, 0, 0},
{188, 143, 143},
{65, 105, 225},
{139, 69, 19},
{250, 128, 114},
{248, 248, 255},
{255, 215, 0},
{218, 165, 32},
{128, 128, 128},
{128, 128, 128},
{0, 128, 0},
{173, 255, 47},
{240, 255, 240},
{255, 105, 180},
{205, 92, 92},
{75, 0, 130},
{255, 255, 240},
{240, 230, 140},
{230, 230, 250},
{255, 240, 245},
{124, 252, 0},
{255, 250, 205},
{173, 216, 230},
{240, 128, 128},
{224, 255, 255},
{250, 250, 210},
{211, 211, 211},
{144, 238, 144},
{211, 211, 211},
{244, 164, 96},
{46, 139, 87},
{255, 245, 238},
{160, 82, 45},
{192, 192, 192},
{135, 206, 235},
{106, 90, 205},
{112, 128, 144},
{112, 128, 144},
{255, 250, 250},
{0, 255, 127},
{70, 130, 180},
{210, 180, 140},
{0, 128, 128},
{216, 191, 216},
{255, 99, 71},
{64, 224, 208},
{238, 130, 238},
{245, 222, 179},
{255, 255, 255},
{245, 245, 245},
{255, 255, 0},
{154, 205, 50}
};
}
}
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Build.Construction;
namespace Microsoft.DotNet.ProjectJsonMigration
{
public static class MSBuildExtensions
{
public static IEnumerable<string> GetEncompassedIncludes(this ProjectItemElement item,
ProjectItemElement otherItem, TextWriter trace = null)
{
if (otherItem.IsEquivalentToExceptIncludeAndExclude(item, trace) &&
new HashSet<string>(otherItem.Excludes()).IsSubsetOf(new HashSet<string>(item.Excludes())))
{
return otherItem.IntersectIncludes(item);
}
return Enumerable.Empty<string>();
}
public static bool IsEquivalentTo(this ProjectItemElement item, ProjectItemElement otherItem, TextWriter trace = null)
{
// Different includes
if (item.IntersectIncludes(otherItem).Count() != item.Includes().Count())
{
trace?.WriteLine(String.Format(LocalizableStrings.IncludesNotEquivalent, nameof(MSBuildExtensions), nameof(IsEquivalentTo)));
return false;
}
// Different Excludes
if (item.IntersectExcludes(otherItem).Count() != item.Excludes().Count())
{
trace?.WriteLine(String.Format(LocalizableStrings.ExcludesNotEquivalent, nameof(MSBuildExtensions), nameof(IsEquivalentTo)));
return false;
}
return item.IsEquivalentToExceptIncludeAndExclude(otherItem, trace);
}
public static bool IsEquivalentToExceptIncludeAndExclude(this ProjectItemElement item, ProjectItemElement otherItem, TextWriter trace = null)
{
// Different remove
if (item.Remove != otherItem.Remove)
{
trace?.WriteLine(String.Format(LocalizableStrings.RemovesNotEquivalent, nameof(MSBuildExtensions), nameof(IsEquivalentTo)));
return false;
}
// Different Metadata
var metadataTuples = otherItem.Metadata.Select(m => Tuple.Create(m, item)).Concat(
item.Metadata.Select(m => Tuple.Create(m, otherItem)));
foreach (var metadataTuple in metadataTuples)
{
var metadata = metadataTuple.Item1;
var itemToCompare = metadataTuple.Item2;
var otherMetadata = itemToCompare.GetMetadataWithName(metadata.Name);
if (otherMetadata == null)
{
trace?.WriteLine(String.Format(LocalizableStrings.MetadataDoesntExist, nameof(MSBuildExtensions), nameof(IsEquivalentTo), metadata.Name, metadata.Value));
return false;
}
if (!metadata.ValueEquals(otherMetadata))
{
trace?.WriteLine(String.Format(LocalizableStrings.MetadataHasAnotherValue, nameof(MSBuildExtensions), nameof(IsEquivalentTo), metadata.Name, metadata.Value, otherMetadata.Value));
return false;
}
}
return true;
}
public static ISet<string> ConditionChain(this ProjectElement projectElement)
{
var conditionChainSet = new HashSet<string>();
if (!string.IsNullOrEmpty(projectElement.Condition))
{
conditionChainSet.Add(projectElement.Condition);
}
foreach (var parent in projectElement.AllParents)
{
if (!string.IsNullOrEmpty(parent.Condition))
{
conditionChainSet.Add(parent.Condition);
}
}
return conditionChainSet;
}
public static bool ConditionChainsAreEquivalent(this ProjectElement projectElement, ProjectElement otherProjectElement)
{
return projectElement.ConditionChain().SetEquals(otherProjectElement.ConditionChain());
}
public static IEnumerable<ProjectPropertyElement> PropertiesWithoutConditions(
this ProjectRootElement projectRoot)
{
return ElementsWithoutConditions(projectRoot.Properties);
}
public static IEnumerable<ProjectItemElement> ItemsWithoutConditions(
this ProjectRootElement projectRoot)
{
return ElementsWithoutConditions(projectRoot.Items);
}
public static IEnumerable<string> Includes(
this ProjectItemElement item)
{
return SplitSemicolonDelimitedValues(item.Include);
}
public static IEnumerable<string> Excludes(
this ProjectItemElement item)
{
return SplitSemicolonDelimitedValues(item.Exclude);
}
public static IEnumerable<string> Removes(
this ProjectItemElement item)
{
return SplitSemicolonDelimitedValues(item.Remove);
}
public static IEnumerable<string> AllConditions(this ProjectElement projectElement)
{
return new string[] { projectElement.Condition }.Concat(projectElement.AllParents.Select(p=> p.Condition));
}
public static IEnumerable<string> IntersectIncludes(this ProjectItemElement item, ProjectItemElement otherItem)
{
return item.Includes().Intersect(otherItem.Includes());
}
public static IEnumerable<string> IntersectExcludes(this ProjectItemElement item, ProjectItemElement otherItem)
{
return item.Excludes().Intersect(otherItem.Excludes());
}
public static void RemoveIncludes(this ProjectItemElement item, IEnumerable<string> includesToRemove)
{
item.Include = string.Join(";", item.Includes().Except(includesToRemove));
}
public static void UnionIncludes(this ProjectItemElement item, IEnumerable<string> includesToAdd)
{
item.Include = string.Join(";", item.Includes().Union(includesToAdd));
}
public static void UnionExcludes(this ProjectItemElement item, IEnumerable<string> excludesToAdd)
{
item.Exclude = string.Join(";", item.Excludes().Union(excludesToAdd));
}
public static bool ValueEquals(this ProjectMetadataElement metadata, ProjectMetadataElement otherMetadata)
{
return metadata.Value.Equals(otherMetadata.Value, StringComparison.Ordinal);
}
public static void AddMetadata(this ProjectItemElement item, ICollection<ProjectMetadataElement> metadataElements, TextWriter trace = null)
{
foreach (var metadata in metadataElements)
{
item.AddMetadata(metadata, trace);
}
}
public static void RemoveIfEmpty(this ProjectElementContainer container)
{
if (!container.Children.Any())
{
container.Parent.RemoveChild(container);
}
}
public static ProjectMetadataElement GetMetadataWithName(this ProjectItemElement item, string name)
{
return item.Metadata.FirstOrDefault(m => m.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
}
public static void AddMetadata(this ProjectItemElement item, ProjectMetadataElement metadata, TextWriter trace = null)
{
var existingMetadata = item.GetMetadataWithName(metadata.Name);
if (existingMetadata != default(ProjectMetadataElement) && !existingMetadata.ValueEquals(metadata))
{
throw new Exception(LocalizableStrings.CannotMergeMetadataError);
}
if (existingMetadata == default(ProjectMetadataElement))
{
trace?.WriteLine(String.Format(LocalizableStrings.AddingMetadataToItem, nameof(AddMetadata), item.ItemType, metadata.Name, metadata.Value, metadata.Condition));
var metametadata = item.AddMetadata(metadata.Name, metadata.Value);
metametadata.Condition = metadata.Condition;
metametadata.ExpressedAsAttribute = metadata.ExpressedAsAttribute;
}
}
public static void SetExcludeOnlyIfIncludeIsSet(this ProjectItemElement item, string exclude)
{
item.Exclude = string.IsNullOrEmpty(item.Include) ? string.Empty : exclude;
}
private static IEnumerable<string> SplitSemicolonDelimitedValues(string combinedValue)
{
return string.IsNullOrEmpty(combinedValue) ? Enumerable.Empty<string>() : combinedValue.Split(';');
}
private static IEnumerable<T> ElementsWithoutConditions<T>(IEnumerable<T> elements) where T : ProjectElement
{
return elements
.Where(e => string.IsNullOrEmpty(e.Condition)
&& e.AllParents.All(parent => string.IsNullOrEmpty(parent.Condition)));
}
}
}
| |
//
// CommentsFrame.cs:
//
// Author:
// Brian Nickel (brian.nickel@gmail.com)
//
// Original Source:
// id3v2commentsframe.cpp from TagLib
//
// Copyright (C) 2005-2007 Brian Nickel
// Copyright (C) 2002,2003 Scott Wheeler (Original Implementation)
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License version
// 2.1 as published by the Free Software Foundation.
//
// 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.Collections;
using System;
namespace TagLib.Id3v2 {
/// <summary>
/// This class extends <see cref="Frame" />, implementing support for
/// ID3v2 Comments (COMM) Frames.
/// </summary>
/// <remarks>
/// <para>A <see cref="CommentsFrame" /> should be used for storing
/// user readable comments on the media file.</para>
/// <para>When reading comments from a file, <see cref="GetPreferred"
/// /> should be used as it gracefully falls back to comments that
/// you, as a developer, may not be expecting. When writing comments,
/// however, it is best to use <see cref="Get" /> as it forces it to
/// be written in the exact version you are expecting.</para>
/// </remarks>
public class CommentsFrame : Frame
{
#region Private Fields
/// <summary>
/// Contains the text encoding to use when rendering the
/// current instance.
/// </summary>
private StringType encoding = Tag.DefaultEncoding;
/// <summary>
/// Contains the ISO-639-2 language code of the current
/// instance.
/// </summary>
private string language = null;
/// <summary>
/// Contains the description of the current instance.
/// </summary>
private string description = null;
/// <summary>
/// Contains the comment text of the current instance.
/// </summary>
private string text = null;
#endregion
#region Constructors
/// <summary>
/// Constructs and initializes a new instance of <see
/// cref="CommentsFrame" /> with a specified description,
/// ISO-639-2 language code, and text encoding.
/// </summary>
/// <param name="description">
/// A <see cref="string" /> containing the description of the
/// new frame.
/// </param>
/// <param name="language">
/// A <see cref="string" /> containing the ISO-639-2 language
/// code of the new frame.
/// </param>
/// <param name="encoding">
/// A <see cref="StringType" /> containing the text encoding
/// to use when rendering the new frame.
/// </param>
/// <remarks>
/// When a frame is created, it is not automatically added to
/// the tag. Consider using <see cref="Get" /> for more
/// integrated frame creation.
/// </remarks>
public CommentsFrame (string description, string language,
StringType encoding)
: base (FrameType.COMM, 4)
{
this.encoding = encoding;
this.language = language;
this.description = description;
}
/// <summary>
/// Constructs and initializes a new instance of <see
/// cref="CommentsFrame" /> with a specified description and
/// ISO-639-2 language code.
/// </summary>
/// <param name="description">
/// A <see cref="string" /> containing the description of the
/// new frame.
/// </param>
/// <param name="language">
/// A <see cref="string" /> containing the ISO-639-2 language
/// code of the new frame.
/// </param>
/// <remarks>
/// When a frame is created, it is not automatically added to
/// the tag. Consider using <see cref="Get" /> for more
/// integrated frame creation.
/// </remarks>
public CommentsFrame (string description, string language)
: this (description, language,
TagLib.Id3v2.Tag.DefaultEncoding)
{
}
/// <summary>
/// Constructs and initializes a new instance of <see
/// cref="CommentsFrame" /> with a specified description.
/// </summary>
/// <param name="description">
/// A <see cref="string" /> containing the description of the
/// new frame.
/// </param>
/// <remarks>
/// When a frame is created, it is not automatically added to
/// the tag. Consider using <see cref="Get" /> for more
/// integrated frame creation.
/// </remarks>
public CommentsFrame (string description)
: this (description, null)
{
}
/// <summary>
/// Constructs and initializes a new instance of <see
/// cref="CommentsFrame" /> by reading its raw data in a
/// specified ID3v2 version.
/// </summary>
/// <param name="data">
/// A <see cref="ByteVector" /> object starting with the raw
/// representation of the new frame.
/// </param>
/// <param name="version">
/// A <see cref="byte" /> indicating the ID3v2 version the
/// raw frame is encoded in.
/// </param>
public CommentsFrame (ByteVector data, byte version)
: base (data, version)
{
SetData (data, 0, version, true);
}
/// <summary>
/// Constructs and initializes a new instance of <see
/// cref="CommentsFrame" /> by reading its raw data in a
/// specified ID3v2 version.
/// </summary>
/// <param name="data">
/// A <see cref="ByteVector" /> object containing the raw
/// representation of the new frame.
/// </param>
/// <param name="offset">
/// A <see cref="int" /> indicating at what offset in
/// <paramref name="data" /> the frame actually begins.
/// </param>
/// <param name="header">
/// A <see cref="FrameHeader" /> containing the header of the
/// frame found at <paramref name="offset" /> in the data.
/// </param>
/// <param name="version">
/// A <see cref="byte" /> indicating the ID3v2 version the
/// raw frame is encoded in.
/// </param>
protected internal CommentsFrame (ByteVector data, int offset,
FrameHeader header,
byte version) : base(header)
{
SetData (data, offset, version, false);
}
#endregion
#region Public Properties
/// <summary>
/// Gets and sets the text encoding to use when storing the
/// current instance.
/// </summary>
/// <value>
/// A <see cref="string" /> containing the text encoding to
/// use when storing the current instance.
/// </value>
/// <remarks>
/// This encoding is overridden when rendering if <see
/// cref="Tag.ForceDefaultEncoding" /> is <see
/// langword="true" /> or the render version does not support
/// it.
/// </remarks>
public StringType TextEncoding {
get {return encoding;}
set {encoding = value;}
}
/// <summary>
/// Gets and sets the ISO-639-2 language code stored in the
/// current instance.
/// </summary>
/// <value>
/// A <see cref="string" /> containing the ISO-639-2 language
/// code stored in the current instance.
/// </value>
/// <remarks>
/// There should only be one file with a matching description
/// and ISO-639-2 language code per tag.
/// </remarks>
public string Language {
get {
if (language != null && language.Length > 2)
return language.Substring (0, 3);
return "XXX";
}
set {language = value;}
}
/// <summary>
/// Gets and sets the description stored in the current
/// instance.
/// </summary>
/// <value>
/// A <see cref="string" /> containing the description
/// stored in the current instance.
/// </value>
/// <remarks>
/// There should only be one frame with a matching
/// description and ISO-639-2 language code per tag.
/// </remarks>
public string Description {
get {
if (description != null)
return description;
return string.Empty;
}
set {description = value;}
}
/// <summary>
/// Gets and sets the comment text stored in the current
/// instance.
/// </summary>
/// <value>
/// A <see cref="string" /> containing the comment text
/// stored in the current instance.
/// </value>
public string Text {
get {
if (text != null)
return text;
return string.Empty;
}
set {text = value;}
}
#endregion
#region Public Methods
/// <summary>
/// Gets a string representation of the current instance.
/// </summary>
/// <returns>
/// A <see cref="string" /> containing the comment text.
/// </returns>
public override string ToString ()
{
return Text;
}
#endregion
#region Public Static Methods
/// <summary>
/// Gets a specified comments frame from the specified tag,
/// optionally creating it if it does not exist.
/// </summary>
/// <param name="tag">
/// A <see cref="Tag" /> object to search in.
/// </param>
/// <param name="description">
/// A <see cref="string" /> specifying the description to
/// match.
/// </param>
/// <param name="language">
/// A <see cref="string" /> specifying the ISO-639-2 language
/// code to match.
/// </param>
/// <param name="create">
/// A <see cref="bool" /> specifying whether or not to create
/// and add a new frame to the tag if a match is not found.
/// </param>
/// <returns>
/// A <see cref="CommentsFrame" /> object containing the
/// matching frame, or <see langword="null" /> if a match
/// wasn't found and <paramref name="create" /> is <see
/// langword="false" />.
/// </returns>
public static CommentsFrame Get (Tag tag, string description,
string language, bool create)
{
CommentsFrame comm;
foreach (Frame frame in tag.GetFrames (FrameType.COMM)) {
comm = frame as CommentsFrame;
if (comm == null)
continue;
if (comm.Description != description)
continue;
if (language != null && language != comm.Language)
continue;
return comm;
}
if (!create)
return null;
comm = new CommentsFrame (description, language);
tag.AddFrame (comm);
return comm;
}
/// <summary>
/// Gets a specified comments frame from the specified tag,
/// trying to to match the description and language but
/// accepting an incomplete match.
/// </summary>
/// <param name="tag">
/// A <see cref="Tag" /> object to search in.
/// </param>
/// <param name="description">
/// A <see cref="string" /> specifying the description to
/// match.
/// </param>
/// <param name="language">
/// A <see cref="string" /> specifying the ISO-639-2 language
/// code to match.
/// </param>
/// <returns>
/// A <see cref="CommentsFrame" /> object containing the
/// matching frame, or <see langword="null" /> if a match
/// wasn't found.
/// </returns>
/// <remarks>
/// <para>The method tries matching with the following order
/// of precidence:</para>
/// <list type="number">
/// <item><term>The first frame with a matching
/// description and language.</term></item>
/// <item><term>The first frame with a matching
/// language.</term></item>
/// <item><term>The first frame with a matching
/// description.</term></item>
/// <item><term>The first frame.</term></item>
/// </list>
/// </remarks>
public static CommentsFrame GetPreferred (Tag tag,
string description,
string language)
{
// This is weird, so bear with me. The best thing we can
// have is something straightforward and in our own
// language. If it has a description, then it is
// probably used for something other than an actual
// comment. If that doesn't work, we'd still rather have
// something in our language than something in another.
// After that all we have left are things in other
// languages, so we'd rather have one with actual
// content, so we try to get one with no description
// first.
bool skip_itunes = description == null ||
!description.StartsWith ("iTun");
int best_value = -1;
CommentsFrame best_frame = null;
foreach (Frame frame in tag.GetFrames (FrameType.COMM)) {
CommentsFrame comm = frame as CommentsFrame;
if (comm == null)
continue;
if (skip_itunes &&
comm.Description.StartsWith ("iTun"))
continue;
bool same_name = comm.Description == description;
bool same_lang = comm.Language == language;
if (same_name && same_lang)
return comm;
int value = same_lang ? 2 : same_name ? 1 : 0;
if (value <= best_value)
continue;
best_value = value;
best_frame = comm;
}
return best_frame;
}
#endregion
#region Protected Methods
/// <summary>
/// Populates the values in the current instance by parsing
/// its field data in a specified version.
/// </summary>
/// <param name="data">
/// A <see cref="ByteVector" /> object containing the
/// extracted field data.
/// </param>
/// <param name="version">
/// A <see cref="byte" /> indicating the ID3v2 version the
/// field data is encoded in.
/// </param>
protected override void ParseFields (ByteVector data,
byte version)
{
if (data.Count < 4)
throw new CorruptFileException (
"Not enough bytes in field.");
encoding = (StringType) data [0];
language = data.ToString (StringType.Latin1, 1, 3);
// Instead of splitting into two string, in the format
// [{desc}\0{value}], try splitting into three strings
// in case of a misformatted [{desc}\0{value}\0].
string [] split = data.ToStrings (encoding, 4, 3);
if (split.Length == 0) {
// No data in the frame.
description = String.Empty;
text = String.Empty;
} else if (split.Length == 1) {
// Bad comment frame. Assume that it lacks a
// description.
description = String.Empty;
text = split [0];
} else {
description = split [0];
text = split [1];
}
}
/// <summary>
/// Renders the values in the current instance into field
/// data for a specified version.
/// </summary>
/// <param name="version">
/// A <see cref="byte" /> indicating the ID3v2 version the
/// field data is to be encoded in.
/// </param>
/// <returns>
/// A <see cref="ByteVector" /> object containing the
/// rendered field data.
/// </returns>
protected override ByteVector RenderFields (byte version)
{
StringType encoding = CorrectEncoding (TextEncoding,
version);
ByteVector v = new ByteVector ();
v.Add ((byte) encoding);
v.Add (ByteVector.FromString (Language, StringType.Latin1));
v.Add (ByteVector.FromString (description, encoding));
v.Add (ByteVector.TextDelimiter (encoding));
v.Add (ByteVector.FromString (text, encoding));
return v;
}
#endregion
#region ICloneable
/// <summary>
/// Creates a deep copy of the current instance.
/// </summary>
/// <returns>
/// A new <see cref="Frame" /> object identical to the
/// current instance.
/// </returns>
public override Frame Clone ()
{
CommentsFrame frame = new CommentsFrame (description,
language, encoding);
frame.text = text;
return frame;
}
#endregion
}
}
| |
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 PnFactura class.
/// </summary>
[Serializable]
public partial class PnFacturaCollection : ActiveList<PnFactura, PnFacturaCollection>
{
public PnFacturaCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>PnFacturaCollection</returns>
public PnFacturaCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
PnFactura 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 PN_factura table.
/// </summary>
[Serializable]
public partial class PnFactura : ActiveRecord<PnFactura>, IActiveRecord
{
#region .ctors and Default Settings
public PnFactura()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public PnFactura(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public PnFactura(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public PnFactura(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("PN_factura", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdFactura = new TableSchema.TableColumn(schema);
colvarIdFactura.ColumnName = "id_factura";
colvarIdFactura.DataType = DbType.Int32;
colvarIdFactura.MaxLength = 0;
colvarIdFactura.AutoIncrement = true;
colvarIdFactura.IsNullable = false;
colvarIdFactura.IsPrimaryKey = true;
colvarIdFactura.IsForeignKey = false;
colvarIdFactura.IsReadOnly = false;
colvarIdFactura.DefaultSetting = @"";
colvarIdFactura.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdFactura);
TableSchema.TableColumn colvarCuie = new TableSchema.TableColumn(schema);
colvarCuie.ColumnName = "cuie";
colvarCuie.DataType = DbType.AnsiString;
colvarCuie.MaxLength = 10;
colvarCuie.AutoIncrement = false;
colvarCuie.IsNullable = true;
colvarCuie.IsPrimaryKey = false;
colvarCuie.IsForeignKey = false;
colvarCuie.IsReadOnly = false;
colvarCuie.DefaultSetting = @"";
colvarCuie.ForeignKeyTableName = "";
schema.Columns.Add(colvarCuie);
TableSchema.TableColumn colvarPeriodo = new TableSchema.TableColumn(schema);
colvarPeriodo.ColumnName = "periodo";
colvarPeriodo.DataType = DbType.AnsiString;
colvarPeriodo.MaxLength = -1;
colvarPeriodo.AutoIncrement = false;
colvarPeriodo.IsNullable = true;
colvarPeriodo.IsPrimaryKey = false;
colvarPeriodo.IsForeignKey = false;
colvarPeriodo.IsReadOnly = false;
colvarPeriodo.DefaultSetting = @"";
colvarPeriodo.ForeignKeyTableName = "";
schema.Columns.Add(colvarPeriodo);
TableSchema.TableColumn colvarEstado = new TableSchema.TableColumn(schema);
colvarEstado.ColumnName = "estado";
colvarEstado.DataType = DbType.AnsiString;
colvarEstado.MaxLength = 10;
colvarEstado.AutoIncrement = false;
colvarEstado.IsNullable = true;
colvarEstado.IsPrimaryKey = false;
colvarEstado.IsForeignKey = false;
colvarEstado.IsReadOnly = false;
colvarEstado.DefaultSetting = @"";
colvarEstado.ForeignKeyTableName = "";
schema.Columns.Add(colvarEstado);
TableSchema.TableColumn colvarObservaciones = new TableSchema.TableColumn(schema);
colvarObservaciones.ColumnName = "observaciones";
colvarObservaciones.DataType = DbType.AnsiString;
colvarObservaciones.MaxLength = -1;
colvarObservaciones.AutoIncrement = false;
colvarObservaciones.IsNullable = true;
colvarObservaciones.IsPrimaryKey = false;
colvarObservaciones.IsForeignKey = false;
colvarObservaciones.IsReadOnly = false;
colvarObservaciones.DefaultSetting = @"";
colvarObservaciones.ForeignKeyTableName = "";
schema.Columns.Add(colvarObservaciones);
TableSchema.TableColumn colvarFechaCarga = new TableSchema.TableColumn(schema);
colvarFechaCarga.ColumnName = "fecha_carga";
colvarFechaCarga.DataType = DbType.DateTime;
colvarFechaCarga.MaxLength = 0;
colvarFechaCarga.AutoIncrement = false;
colvarFechaCarga.IsNullable = true;
colvarFechaCarga.IsPrimaryKey = false;
colvarFechaCarga.IsForeignKey = false;
colvarFechaCarga.IsReadOnly = false;
colvarFechaCarga.DefaultSetting = @"";
colvarFechaCarga.ForeignKeyTableName = "";
schema.Columns.Add(colvarFechaCarga);
TableSchema.TableColumn colvarFechaFactura = new TableSchema.TableColumn(schema);
colvarFechaFactura.ColumnName = "fecha_factura";
colvarFechaFactura.DataType = DbType.DateTime;
colvarFechaFactura.MaxLength = 0;
colvarFechaFactura.AutoIncrement = false;
colvarFechaFactura.IsNullable = true;
colvarFechaFactura.IsPrimaryKey = false;
colvarFechaFactura.IsForeignKey = false;
colvarFechaFactura.IsReadOnly = false;
colvarFechaFactura.DefaultSetting = @"";
colvarFechaFactura.ForeignKeyTableName = "";
schema.Columns.Add(colvarFechaFactura);
TableSchema.TableColumn colvarMesFactDC = new TableSchema.TableColumn(schema);
colvarMesFactDC.ColumnName = "mes_fact_d_c";
colvarMesFactDC.DataType = DbType.AnsiString;
colvarMesFactDC.MaxLength = -1;
colvarMesFactDC.AutoIncrement = false;
colvarMesFactDC.IsNullable = true;
colvarMesFactDC.IsPrimaryKey = false;
colvarMesFactDC.IsForeignKey = false;
colvarMesFactDC.IsReadOnly = false;
colvarMesFactDC.DefaultSetting = @"";
colvarMesFactDC.ForeignKeyTableName = "";
schema.Columns.Add(colvarMesFactDC);
TableSchema.TableColumn colvarMontoPrefactura = new TableSchema.TableColumn(schema);
colvarMontoPrefactura.ColumnName = "monto_prefactura";
colvarMontoPrefactura.DataType = DbType.Decimal;
colvarMontoPrefactura.MaxLength = 0;
colvarMontoPrefactura.AutoIncrement = false;
colvarMontoPrefactura.IsNullable = true;
colvarMontoPrefactura.IsPrimaryKey = false;
colvarMontoPrefactura.IsForeignKey = false;
colvarMontoPrefactura.IsReadOnly = false;
colvarMontoPrefactura.DefaultSetting = @"";
colvarMontoPrefactura.ForeignKeyTableName = "";
schema.Columns.Add(colvarMontoPrefactura);
TableSchema.TableColumn colvarFechaControl = new TableSchema.TableColumn(schema);
colvarFechaControl.ColumnName = "fecha_control";
colvarFechaControl.DataType = DbType.DateTime;
colvarFechaControl.MaxLength = 0;
colvarFechaControl.AutoIncrement = false;
colvarFechaControl.IsNullable = true;
colvarFechaControl.IsPrimaryKey = false;
colvarFechaControl.IsForeignKey = false;
colvarFechaControl.IsReadOnly = false;
colvarFechaControl.DefaultSetting = @"";
colvarFechaControl.ForeignKeyTableName = "";
schema.Columns.Add(colvarFechaControl);
TableSchema.TableColumn colvarNroExp = new TableSchema.TableColumn(schema);
colvarNroExp.ColumnName = "nro_exp";
colvarNroExp.DataType = DbType.AnsiString;
colvarNroExp.MaxLength = -1;
colvarNroExp.AutoIncrement = false;
colvarNroExp.IsNullable = true;
colvarNroExp.IsPrimaryKey = false;
colvarNroExp.IsForeignKey = false;
colvarNroExp.IsReadOnly = false;
colvarNroExp.DefaultSetting = @"";
colvarNroExp.ForeignKeyTableName = "";
schema.Columns.Add(colvarNroExp);
TableSchema.TableColumn colvarTraba = new TableSchema.TableColumn(schema);
colvarTraba.ColumnName = "traba";
colvarTraba.DataType = DbType.AnsiString;
colvarTraba.MaxLength = -1;
colvarTraba.AutoIncrement = false;
colvarTraba.IsNullable = true;
colvarTraba.IsPrimaryKey = false;
colvarTraba.IsForeignKey = false;
colvarTraba.IsReadOnly = false;
colvarTraba.DefaultSetting = @"";
colvarTraba.ForeignKeyTableName = "";
schema.Columns.Add(colvarTraba);
TableSchema.TableColumn colvarOnline = new TableSchema.TableColumn(schema);
colvarOnline.ColumnName = "online";
colvarOnline.DataType = DbType.AnsiStringFixedLength;
colvarOnline.MaxLength = 2;
colvarOnline.AutoIncrement = false;
colvarOnline.IsNullable = true;
colvarOnline.IsPrimaryKey = false;
colvarOnline.IsForeignKey = false;
colvarOnline.IsReadOnly = false;
colvarOnline.DefaultSetting = @"";
colvarOnline.ForeignKeyTableName = "";
schema.Columns.Add(colvarOnline);
TableSchema.TableColumn colvarNroExpExt = new TableSchema.TableColumn(schema);
colvarNroExpExt.ColumnName = "nro_exp_ext";
colvarNroExpExt.DataType = DbType.AnsiString;
colvarNroExpExt.MaxLength = -1;
colvarNroExpExt.AutoIncrement = false;
colvarNroExpExt.IsNullable = true;
colvarNroExpExt.IsPrimaryKey = false;
colvarNroExpExt.IsForeignKey = false;
colvarNroExpExt.IsReadOnly = false;
colvarNroExpExt.DefaultSetting = @"";
colvarNroExpExt.ForeignKeyTableName = "";
schema.Columns.Add(colvarNroExpExt);
TableSchema.TableColumn colvarFechaExpExt = new TableSchema.TableColumn(schema);
colvarFechaExpExt.ColumnName = "fecha_exp_ext";
colvarFechaExpExt.DataType = DbType.DateTime;
colvarFechaExpExt.MaxLength = 0;
colvarFechaExpExt.AutoIncrement = false;
colvarFechaExpExt.IsNullable = true;
colvarFechaExpExt.IsPrimaryKey = false;
colvarFechaExpExt.IsForeignKey = false;
colvarFechaExpExt.IsReadOnly = false;
colvarFechaExpExt.DefaultSetting = @"";
colvarFechaExpExt.ForeignKeyTableName = "";
schema.Columns.Add(colvarFechaExpExt);
TableSchema.TableColumn colvarPeriodoContable = new TableSchema.TableColumn(schema);
colvarPeriodoContable.ColumnName = "periodo_contable";
colvarPeriodoContable.DataType = DbType.AnsiString;
colvarPeriodoContable.MaxLength = -1;
colvarPeriodoContable.AutoIncrement = false;
colvarPeriodoContable.IsNullable = true;
colvarPeriodoContable.IsPrimaryKey = false;
colvarPeriodoContable.IsForeignKey = false;
colvarPeriodoContable.IsReadOnly = false;
colvarPeriodoContable.DefaultSetting = @"";
colvarPeriodoContable.ForeignKeyTableName = "";
schema.Columns.Add(colvarPeriodoContable);
TableSchema.TableColumn colvarPeriodoActual = new TableSchema.TableColumn(schema);
colvarPeriodoActual.ColumnName = "periodo_actual";
colvarPeriodoActual.DataType = DbType.AnsiString;
colvarPeriodoActual.MaxLength = -1;
colvarPeriodoActual.AutoIncrement = false;
colvarPeriodoActual.IsNullable = true;
colvarPeriodoActual.IsPrimaryKey = false;
colvarPeriodoActual.IsForeignKey = false;
colvarPeriodoActual.IsReadOnly = false;
colvarPeriodoActual.DefaultSetting = @"";
colvarPeriodoActual.ForeignKeyTableName = "";
schema.Columns.Add(colvarPeriodoActual);
TableSchema.TableColumn colvarEstadoExp = new TableSchema.TableColumn(schema);
colvarEstadoExp.ColumnName = "estado_exp";
colvarEstadoExp.DataType = DbType.Int32;
colvarEstadoExp.MaxLength = 0;
colvarEstadoExp.AutoIncrement = false;
colvarEstadoExp.IsNullable = false;
colvarEstadoExp.IsPrimaryKey = false;
colvarEstadoExp.IsForeignKey = false;
colvarEstadoExp.IsReadOnly = false;
colvarEstadoExp.DefaultSetting = @"((0))";
colvarEstadoExp.ForeignKeyTableName = "";
schema.Columns.Add(colvarEstadoExp);
TableSchema.TableColumn colvarAltaComp = new TableSchema.TableColumn(schema);
colvarAltaComp.ColumnName = "alta_comp";
colvarAltaComp.DataType = DbType.AnsiString;
colvarAltaComp.MaxLength = 2;
colvarAltaComp.AutoIncrement = false;
colvarAltaComp.IsNullable = true;
colvarAltaComp.IsPrimaryKey = false;
colvarAltaComp.IsForeignKey = false;
colvarAltaComp.IsReadOnly = false;
colvarAltaComp.DefaultSetting = @"";
colvarAltaComp.ForeignKeyTableName = "";
schema.Columns.Add(colvarAltaComp);
TableSchema.TableColumn colvarIdTipoDePrestacion = new TableSchema.TableColumn(schema);
colvarIdTipoDePrestacion.ColumnName = "idTipoDePrestacion";
colvarIdTipoDePrestacion.DataType = DbType.Int32;
colvarIdTipoDePrestacion.MaxLength = 0;
colvarIdTipoDePrestacion.AutoIncrement = false;
colvarIdTipoDePrestacion.IsNullable = true;
colvarIdTipoDePrestacion.IsPrimaryKey = false;
colvarIdTipoDePrestacion.IsForeignKey = true;
colvarIdTipoDePrestacion.IsReadOnly = false;
colvarIdTipoDePrestacion.DefaultSetting = @"";
colvarIdTipoDePrestacion.ForeignKeyTableName = "PN_TipoDePrestacion";
schema.Columns.Add(colvarIdTipoDePrestacion);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("PN_factura",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdFactura")]
[Bindable(true)]
public int IdFactura
{
get { return GetColumnValue<int>(Columns.IdFactura); }
set { SetColumnValue(Columns.IdFactura, value); }
}
[XmlAttribute("Cuie")]
[Bindable(true)]
public string Cuie
{
get { return GetColumnValue<string>(Columns.Cuie); }
set { SetColumnValue(Columns.Cuie, value); }
}
[XmlAttribute("Periodo")]
[Bindable(true)]
public string Periodo
{
get { return GetColumnValue<string>(Columns.Periodo); }
set { SetColumnValue(Columns.Periodo, value); }
}
[XmlAttribute("Estado")]
[Bindable(true)]
public string Estado
{
get { return GetColumnValue<string>(Columns.Estado); }
set { SetColumnValue(Columns.Estado, value); }
}
[XmlAttribute("Observaciones")]
[Bindable(true)]
public string Observaciones
{
get { return GetColumnValue<string>(Columns.Observaciones); }
set { SetColumnValue(Columns.Observaciones, value); }
}
[XmlAttribute("FechaCarga")]
[Bindable(true)]
public DateTime? FechaCarga
{
get { return GetColumnValue<DateTime?>(Columns.FechaCarga); }
set { SetColumnValue(Columns.FechaCarga, value); }
}
[XmlAttribute("FechaFactura")]
[Bindable(true)]
public DateTime? FechaFactura
{
get { return GetColumnValue<DateTime?>(Columns.FechaFactura); }
set { SetColumnValue(Columns.FechaFactura, value); }
}
[XmlAttribute("MesFactDC")]
[Bindable(true)]
public string MesFactDC
{
get { return GetColumnValue<string>(Columns.MesFactDC); }
set { SetColumnValue(Columns.MesFactDC, value); }
}
[XmlAttribute("MontoPrefactura")]
[Bindable(true)]
public decimal? MontoPrefactura
{
get { return GetColumnValue<decimal?>(Columns.MontoPrefactura); }
set { SetColumnValue(Columns.MontoPrefactura, value); }
}
[XmlAttribute("FechaControl")]
[Bindable(true)]
public DateTime? FechaControl
{
get { return GetColumnValue<DateTime?>(Columns.FechaControl); }
set { SetColumnValue(Columns.FechaControl, value); }
}
[XmlAttribute("NroExp")]
[Bindable(true)]
public string NroExp
{
get { return GetColumnValue<string>(Columns.NroExp); }
set { SetColumnValue(Columns.NroExp, value); }
}
[XmlAttribute("Traba")]
[Bindable(true)]
public string Traba
{
get { return GetColumnValue<string>(Columns.Traba); }
set { SetColumnValue(Columns.Traba, value); }
}
[XmlAttribute("Online")]
[Bindable(true)]
public string Online
{
get { return GetColumnValue<string>(Columns.Online); }
set { SetColumnValue(Columns.Online, value); }
}
[XmlAttribute("NroExpExt")]
[Bindable(true)]
public string NroExpExt
{
get { return GetColumnValue<string>(Columns.NroExpExt); }
set { SetColumnValue(Columns.NroExpExt, value); }
}
[XmlAttribute("FechaExpExt")]
[Bindable(true)]
public DateTime? FechaExpExt
{
get { return GetColumnValue<DateTime?>(Columns.FechaExpExt); }
set { SetColumnValue(Columns.FechaExpExt, value); }
}
[XmlAttribute("PeriodoContable")]
[Bindable(true)]
public string PeriodoContable
{
get { return GetColumnValue<string>(Columns.PeriodoContable); }
set { SetColumnValue(Columns.PeriodoContable, value); }
}
[XmlAttribute("PeriodoActual")]
[Bindable(true)]
public string PeriodoActual
{
get { return GetColumnValue<string>(Columns.PeriodoActual); }
set { SetColumnValue(Columns.PeriodoActual, value); }
}
[XmlAttribute("EstadoExp")]
[Bindable(true)]
public int EstadoExp
{
get { return GetColumnValue<int>(Columns.EstadoExp); }
set { SetColumnValue(Columns.EstadoExp, value); }
}
[XmlAttribute("AltaComp")]
[Bindable(true)]
public string AltaComp
{
get { return GetColumnValue<string>(Columns.AltaComp); }
set { SetColumnValue(Columns.AltaComp, value); }
}
[XmlAttribute("IdTipoDePrestacion")]
[Bindable(true)]
public int? IdTipoDePrestacion
{
get { return GetColumnValue<int?>(Columns.IdTipoDePrestacion); }
set { SetColumnValue(Columns.IdTipoDePrestacion, value); }
}
#endregion
#region PrimaryKey Methods
protected override void SetPrimaryKey(object oValue)
{
base.SetPrimaryKey(oValue);
SetPKValues();
}
private DalSic.PnComprobanteCollection colPnComprobanteRecords;
public DalSic.PnComprobanteCollection PnComprobanteRecords
{
get
{
if(colPnComprobanteRecords == null)
{
colPnComprobanteRecords = new DalSic.PnComprobanteCollection().Where(PnComprobante.Columns.IdFactura, IdFactura).Load();
colPnComprobanteRecords.ListChanged += new ListChangedEventHandler(colPnComprobanteRecords_ListChanged);
}
return colPnComprobanteRecords;
}
set
{
colPnComprobanteRecords = value;
colPnComprobanteRecords.ListChanged += new ListChangedEventHandler(colPnComprobanteRecords_ListChanged);
}
}
void colPnComprobanteRecords_ListChanged(object sender, ListChangedEventArgs e)
{
if (e.ListChangedType == ListChangedType.ItemAdded)
{
// Set foreign key value
colPnComprobanteRecords[e.NewIndex].IdFactura = IdFactura;
}
}
#endregion
#region ForeignKey Properties
/// <summary>
/// Returns a PnTipoDePrestacion ActiveRecord object related to this PnFactura
///
/// </summary>
public DalSic.PnTipoDePrestacion PnTipoDePrestacion
{
get { return DalSic.PnTipoDePrestacion.FetchByID(this.IdTipoDePrestacion); }
set { SetColumnValue("idTipoDePrestacion", value.IdTipoDePrestacion); }
}
#endregion
//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 varCuie,string varPeriodo,string varEstado,string varObservaciones,DateTime? varFechaCarga,DateTime? varFechaFactura,string varMesFactDC,decimal? varMontoPrefactura,DateTime? varFechaControl,string varNroExp,string varTraba,string varOnline,string varNroExpExt,DateTime? varFechaExpExt,string varPeriodoContable,string varPeriodoActual,int varEstadoExp,string varAltaComp,int? varIdTipoDePrestacion)
{
PnFactura item = new PnFactura();
item.Cuie = varCuie;
item.Periodo = varPeriodo;
item.Estado = varEstado;
item.Observaciones = varObservaciones;
item.FechaCarga = varFechaCarga;
item.FechaFactura = varFechaFactura;
item.MesFactDC = varMesFactDC;
item.MontoPrefactura = varMontoPrefactura;
item.FechaControl = varFechaControl;
item.NroExp = varNroExp;
item.Traba = varTraba;
item.Online = varOnline;
item.NroExpExt = varNroExpExt;
item.FechaExpExt = varFechaExpExt;
item.PeriodoContable = varPeriodoContable;
item.PeriodoActual = varPeriodoActual;
item.EstadoExp = varEstadoExp;
item.AltaComp = varAltaComp;
item.IdTipoDePrestacion = varIdTipoDePrestacion;
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 varIdFactura,string varCuie,string varPeriodo,string varEstado,string varObservaciones,DateTime? varFechaCarga,DateTime? varFechaFactura,string varMesFactDC,decimal? varMontoPrefactura,DateTime? varFechaControl,string varNroExp,string varTraba,string varOnline,string varNroExpExt,DateTime? varFechaExpExt,string varPeriodoContable,string varPeriodoActual,int varEstadoExp,string varAltaComp,int? varIdTipoDePrestacion)
{
PnFactura item = new PnFactura();
item.IdFactura = varIdFactura;
item.Cuie = varCuie;
item.Periodo = varPeriodo;
item.Estado = varEstado;
item.Observaciones = varObservaciones;
item.FechaCarga = varFechaCarga;
item.FechaFactura = varFechaFactura;
item.MesFactDC = varMesFactDC;
item.MontoPrefactura = varMontoPrefactura;
item.FechaControl = varFechaControl;
item.NroExp = varNroExp;
item.Traba = varTraba;
item.Online = varOnline;
item.NroExpExt = varNroExpExt;
item.FechaExpExt = varFechaExpExt;
item.PeriodoContable = varPeriodoContable;
item.PeriodoActual = varPeriodoActual;
item.EstadoExp = varEstadoExp;
item.AltaComp = varAltaComp;
item.IdTipoDePrestacion = varIdTipoDePrestacion;
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 IdFacturaColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn CuieColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn PeriodoColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn EstadoColumn
{
get { return Schema.Columns[3]; }
}
public static TableSchema.TableColumn ObservacionesColumn
{
get { return Schema.Columns[4]; }
}
public static TableSchema.TableColumn FechaCargaColumn
{
get { return Schema.Columns[5]; }
}
public static TableSchema.TableColumn FechaFacturaColumn
{
get { return Schema.Columns[6]; }
}
public static TableSchema.TableColumn MesFactDCColumn
{
get { return Schema.Columns[7]; }
}
public static TableSchema.TableColumn MontoPrefacturaColumn
{
get { return Schema.Columns[8]; }
}
public static TableSchema.TableColumn FechaControlColumn
{
get { return Schema.Columns[9]; }
}
public static TableSchema.TableColumn NroExpColumn
{
get { return Schema.Columns[10]; }
}
public static TableSchema.TableColumn TrabaColumn
{
get { return Schema.Columns[11]; }
}
public static TableSchema.TableColumn OnlineColumn
{
get { return Schema.Columns[12]; }
}
public static TableSchema.TableColumn NroExpExtColumn
{
get { return Schema.Columns[13]; }
}
public static TableSchema.TableColumn FechaExpExtColumn
{
get { return Schema.Columns[14]; }
}
public static TableSchema.TableColumn PeriodoContableColumn
{
get { return Schema.Columns[15]; }
}
public static TableSchema.TableColumn PeriodoActualColumn
{
get { return Schema.Columns[16]; }
}
public static TableSchema.TableColumn EstadoExpColumn
{
get { return Schema.Columns[17]; }
}
public static TableSchema.TableColumn AltaCompColumn
{
get { return Schema.Columns[18]; }
}
public static TableSchema.TableColumn IdTipoDePrestacionColumn
{
get { return Schema.Columns[19]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdFactura = @"id_factura";
public static string Cuie = @"cuie";
public static string Periodo = @"periodo";
public static string Estado = @"estado";
public static string Observaciones = @"observaciones";
public static string FechaCarga = @"fecha_carga";
public static string FechaFactura = @"fecha_factura";
public static string MesFactDC = @"mes_fact_d_c";
public static string MontoPrefactura = @"monto_prefactura";
public static string FechaControl = @"fecha_control";
public static string NroExp = @"nro_exp";
public static string Traba = @"traba";
public static string Online = @"online";
public static string NroExpExt = @"nro_exp_ext";
public static string FechaExpExt = @"fecha_exp_ext";
public static string PeriodoContable = @"periodo_contable";
public static string PeriodoActual = @"periodo_actual";
public static string EstadoExp = @"estado_exp";
public static string AltaComp = @"alta_comp";
public static string IdTipoDePrestacion = @"idTipoDePrestacion";
}
#endregion
#region Update PK Collections
public void SetPKValues()
{
if (colPnComprobanteRecords != null)
{
foreach (DalSic.PnComprobante item in colPnComprobanteRecords)
{
if (item.IdFactura != IdFactura)
{
item.IdFactura = IdFactura;
}
}
}
}
#endregion
#region Deep Save
public void DeepSave()
{
Save();
if (colPnComprobanteRecords != null)
{
colPnComprobanteRecords.SaveAll();
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
namespace System.Data.Entity.Interception
{
using System.Data.Common;
using System.Data.Entity.Core;
using System.Data.Entity.Core.Common;
using System.Data.Entity.Core.EntityClient;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Infrastructure.DependencyResolution;
using System.Data.Entity.Infrastructure.Interception;
using System.Data.Entity.SqlServer;
using System.Data.Entity.TestHelpers;
using System.Data.SqlClient;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Moq;
using Xunit;
public class CommitFailureTests : FunctionalTestBase
{
private void Execute_commit_failure_test(
Action<Action> verifyInitialization, Action<Action> verifySaveChanges, int expectedBlogs, bool useTransactionHandler,
bool useExecutionStrategy, bool rollbackOnFail)
{
using (var context = new BlogContextCommit())
{
Assert.Equal(expectedBlogs, context.Blogs.Count());
using (var transactionContext = new TransactionContext(context.Database.Connection))
{
using (var infoContext = GetInfoContext(transactionContext))
{
Assert.True(
!infoContext.TableExists("__Transactions")
|| !transactionContext.Transactions.Any());
}
}
}
}
finally
{
DbInterception.Remove(failingTransactionInterceptor);
MutableResolver.ClearResolvers();
}
DbDispatchersHelpers.AssertNoInterceptors();
}
[Fact]
public void No_TransactionHandler_and_no_ExecutionStrategy_throws_CommitFailedException_on_commit_fail()
{
Execute_commit_failure_test(
c => Assert.Throws<DataException>(() => c()).InnerException.ValidateMessage("CommitFailed"),
c => Assert.Throws<CommitFailedException>(() => c()).ValidateMessage("CommitFailed"),
expectedBlogs: 1,
useTransactionHandler: false,
useExecutionStrategy: false,
rollbackOnFail: true);
}
[Fact]
public void No_TransactionHandler_and_no_ExecutionStrategy_throws_CommitFailedException_on_false_commit_fail()
{
Execute_commit_failure_test(
c => Assert.Throws<DataException>(() => c()).InnerException.ValidateMessage("CommitFailed"),
c => Assert.Throws<CommitFailedException>(() => c()).ValidateMessage("CommitFailed"),
expectedBlogs: 2,
useTransactionHandler: false,
useExecutionStrategy: false,
rollbackOnFail: false);
}
[Fact]
[UseDefaultExecutionStrategy]
public void TransactionHandler_and_no_ExecutionStrategy_rethrows_original_exception_on_commit_fail()
{
Execute_commit_failure_test(
c => Assert.Throws<TimeoutException>(() => c()),
c =>
{
var exception = Assert.Throws<EntityException>(() => c());
Assert.IsType<TimeoutException>(exception.InnerException);
},
expectedBlogs: 1,
useTransactionHandler: true,
useExecutionStrategy: false,
rollbackOnFail: true);
}
[Fact]
public void TransactionHandler_and_no_ExecutionStrategy_does_not_throw_on_false_commit_fail()
{
Execute_commit_failure_test(
c => c(),
c => c(),
expectedBlogs: 2,
useTransactionHandler: true,
useExecutionStrategy: false,
rollbackOnFail: false);
}
[Fact]
public void No_TransactionHandler_and_ExecutionStrategy_throws_CommitFailedException_on_commit_fail()
{
Execute_commit_failure_test(
c => Assert.Throws<DataException>(() => c()).InnerException.ValidateMessage("CommitFailed"),
c => Assert.Throws<CommitFailedException>(() => c()).ValidateMessage("CommitFailed"),
expectedBlogs: 1,
useTransactionHandler: false,
useExecutionStrategy: true,
rollbackOnFail: true);
}
[Fact]
public void No_TransactionHandler_and_ExecutionStrategy_throws_CommitFailedException_on_false_commit_fail()
{
Execute_commit_failure_test(
c => Assert.Throws<DataException>(() => c()).InnerException.ValidateMessage("CommitFailed"),
c => Assert.Throws<CommitFailedException>(() => c()).ValidateMessage("CommitFailed"),
expectedBlogs: 2,
useTransactionHandler: false,
useExecutionStrategy: true,
rollbackOnFail: false);
}
[Fact]
public void TransactionHandler_and_ExecutionStrategy_retries_on_commit_fail()
{
Execute_commit_failure_test(
c => c(),
c => c(),
expectedBlogs: 2,
useTransactionHandler: true,
useExecutionStrategy: true,
rollbackOnFail: true);
}
[Fact]
public void TransactionHandler_and_ExecutionStrategy_does_not_retry_on_false_commit_fail()
{
MutableResolver.AddResolver<Func<TransactionHandler>>(
new TransactionHandlerResolver(() => new CommitFailureHandler(), null, null));
TransactionHandler_and_ExecutionStrategy_does_not_retry_on_false_commit_fail_implementation(
context => context.SaveChanges());
}
#if !NET40
[Fact]
public void TransactionHandler_and_ExecutionStrategy_does_not_retry_on_false_commit_fail_async()
{
MutableResolver.AddResolver<Func<TransactionHandler>>(
new TransactionHandlerResolver(() => new CommitFailureHandler(), null, null));
TransactionHandler_and_ExecutionStrategy_does_not_retry_on_false_commit_fail_implementation(
context => context.SaveChangesAsync().Wait());
}
#endif
[Fact]
public void TransactionHandler_and_ExecutionStrategy_does_not_retry_on_false_commit_fail_with_custom_TransactionContext()
{
MutableResolver.AddResolver<Func<TransactionHandler>>(
new TransactionHandlerResolver(() => new CommitFailureHandler(c => new MyTransactionContext(c)), null, null));
TransactionHandler_and_ExecutionStrategy_does_not_retry_on_false_commit_fail_implementation(
context =>
{
context.SaveChanges();
using (var infoContext = GetInfoContext(context))
{
Assert.True(infoContext.TableExists("MyTransactions"));
var column = infoContext.Columns.Single(c => c.Name == "Time");
Assert.Equal("datetime2", column.Type);
}
});
}
public class MyTransactionContext : TransactionContext
{
public MyTransactionContext(DbConnection connection)
: base(connection)
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<TransactionRow>()
.ToTable("MyTransactions")
.HasKey(e => e.Id)
.Property(e => e.CreationTime).HasColumnName("Time").HasColumnType("datetime2");
}
}
private void TransactionHandler_and_ExecutionStrategy_does_not_retry_on_false_commit_fail_implementation(
Action<BlogContextCommit> runAndVerify)
{
var failingTransactionInterceptorMock = new Mock<FailingTransactionInterceptor> { CallBase = true };
var failingTransactionInterceptor = failingTransactionInterceptorMock.Object;
DbInterception.Add(failingTransactionInterceptor);
var isSqlAzure = DatabaseTestHelpers.IsSqlAzure(ModelHelpers.BaseConnectionString);
MutableResolver.AddResolver<Func<IDbExecutionStrategy>>(
key =>
(Func<IDbExecutionStrategy>)
(() => isSqlAzure
? new TestSqlAzureExecutionStrategy()
: (IDbExecutionStrategy)new SqlAzureExecutionStrategy(maxRetryCount: 2, maxDelay: TimeSpan.FromMilliseconds(1))));
try
{
using (var context = new BlogContextCommit())
{
failingTransactionInterceptor.ShouldFailTimes = 0;
context.Database.Delete();
Assert.Equal(1, context.Blogs.Count());
failingTransactionInterceptor.ShouldFailTimes = 2;
failingTransactionInterceptor.ShouldRollBack = false;
context.Blogs.Add(new BlogContext.Blog());
runAndVerify(context);
failingTransactionInterceptorMock.Verify(
m => m.Committing(It.IsAny<DbTransaction>(), It.IsAny<DbTransactionInterceptionContext>()),
isSqlAzure
? Times.AtLeast(3)
: Times.Exactly(3));
}
using (var context = new BlogContextCommit())
{
Assert.Equal(2, context.Blogs.Count());
using (var transactionContext = new TransactionContext(context.Database.Connection))
{
using (var infoContext = GetInfoContext(transactionContext))
{
Assert.True(
!infoContext.TableExists("__Transactions")
|| !transactionContext.Transactions.Any());
}
}
}
}
finally
{
DbInterception.Remove(failingTransactionInterceptorMock.Object);
MutableResolver.ClearResolvers();
}
DbDispatchersHelpers.AssertNoInterceptors();
}
[Fact]
public void CommitFailureHandler_Dispose_does_not_use_ExecutionStrategy()
{
CommitFailureHandler_with_ExecutionStrategy_test(
(c, executionStrategyMock) =>
{
c.TransactionHandler.Dispose();
executionStrategyMock.Verify(e => e.Execute(It.IsAny<Func<int>>()), Times.Exactly(3));
});
}
[Fact]
public void CommitFailureHandler_Dispose_catches_exceptions()
{
CommitFailureHandler_with_ExecutionStrategy_test(
(c, executionStrategyMock) =>
{
using (var transactionContext = new TransactionContext(((EntityConnection)c.Connection).StoreConnection))
{
foreach (var tran in transactionContext.Set<TransactionRow>().ToList())
{
transactionContext.Transactions.Remove(tran);
}
transactionContext.SaveChanges();
}
c.TransactionHandler.Dispose();
});
}
[Fact]
public void CommitFailureHandler_prunes_transactions_after_set_amount()
{
CommitFailureHandler_prunes_transactions_after_set_amount_implementation(false);
}
[Fact]
public void CommitFailureHandler_prunes_transactions_after_set_amount_and_handles_false_failure()
{
CommitFailureHandler_prunes_transactions_after_set_amount_implementation(true);
}
private void CommitFailureHandler_prunes_transactions_after_set_amount_implementation(bool shouldThrow)
{
var failingTransactionInterceptor = new FailingTransactionInterceptor();
DbInterception.Add(failingTransactionInterceptor);
MutableResolver.AddResolver<Func<TransactionHandler>>(
new TransactionHandlerResolver(() => new MyCommitFailureHandler(c => new TransactionContext(c)), null, null));
try
{
using (var context = new BlogContextCommit())
{
context.Database.Delete();
Assert.Equal(1, context.Blogs.Count());
var objectContext = ((IObjectContextAdapter)context).ObjectContext;
var transactionHandler = (MyCommitFailureHandler)objectContext.TransactionHandler;
for (var i = 0; i < transactionHandler.PruningLimit; i++)
{
context.Blogs.Add(new BlogContext.Blog());
context.SaveChanges();
}
AssertTransactionHistoryCount(context, transactionHandler.PruningLimit);
if (shouldThrow)
{
failingTransactionInterceptor.ShouldFailTimes = 1;
failingTransactionInterceptor.ShouldRollBack = false;
}
context.Blogs.Add(new BlogContext.Blog());
context.SaveChanges();
context.Blogs.Add(new BlogContext.Blog());
context.SaveChanges();
AssertTransactionHistoryCount(context, 1);
Assert.Equal(1, transactionHandler.TransactionContext.ChangeTracker.Entries<TransactionRow>().Count());
}
}
finally
{
DbInterception.Remove(failingTransactionInterceptor);
MutableResolver.ClearResolvers();
}
DbDispatchersHelpers.AssertNoInterceptors();
}
[Fact]
public void CommitFailureHandler_ClearTransactionHistory_uses_ExecutionStrategy()
{
CommitFailureHandler_with_ExecutionStrategy_test(
(c, executionStrategyMock) =>
{
((MyCommitFailureHandler)c.TransactionHandler).ClearTransactionHistory();
executionStrategyMock.Verify(e => e.Execute(It.IsAny<Func<int>>()), Times.Exactly(4));
Assert.Empty(((MyCommitFailureHandler)c.TransactionHandler).TransactionContext.ChangeTracker.Entries<TransactionRow>());
});
}
[Fact]
public void CommitFailureHandler_ClearTransactionHistory_does_not_catch_exceptions()
{
var failingTransactionInterceptor = new FailingTransactionInterceptor();
DbInterception.Add(failingTransactionInterceptor);
try
{
CommitFailureHandler_with_ExecutionStrategy_test(
(c, executionStrategyMock) =>
{
MutableResolver.AddResolver<Func<IDbExecutionStrategy>>(
key => (Func<IDbExecutionStrategy>)(() => new SimpleExecutionStrategy()));
failingTransactionInterceptor.ShouldFailTimes = 1;
failingTransactionInterceptor.ShouldRollBack = true;
Assert.Throws<EntityException>(
() => ((MyCommitFailureHandler)c.TransactionHandler).ClearTransactionHistory());
MutableResolver.ClearResolvers();
AssertTransactionHistoryCount(c, 1);
((MyCommitFailureHandler)c.TransactionHandler).ClearTransactionHistory();
AssertTransactionHistoryCount(c, 0);
});
}
finally
{
DbInterception.Remove(failingTransactionInterceptor);
}
}
[Fact]
public void CommitFailureHandler_PruneTransactionHistory_uses_ExecutionStrategy()
{
CommitFailureHandler_with_ExecutionStrategy_test(
(c, executionStrategyMock) =>
{
((MyCommitFailureHandler)c.TransactionHandler).PruneTransactionHistory();
executionStrategyMock.Verify(e => e.Execute(It.IsAny<Func<int>>()), Times.Exactly(4));
Assert.Empty(((MyCommitFailureHandler)c.TransactionHandler).TransactionContext.ChangeTracker.Entries<TransactionRow>());
});
}
[Fact]
public void CommitFailureHandler_PruneTransactionHistory_does_not_catch_exceptions()
{
var failingTransactionInterceptor = new FailingTransactionInterceptor();
DbInterception.Add(failingTransactionInterceptor);
try
{
CommitFailureHandler_with_ExecutionStrategy_test(
(c, executionStrategyMock) =>
{
MutableResolver.AddResolver<Func<IDbExecutionStrategy>>(
key => (Func<IDbExecutionStrategy>)(() => new SimpleExecutionStrategy()));
failingTransactionInterceptor.ShouldFailTimes = 1;
failingTransactionInterceptor.ShouldRollBack = true;
Assert.Throws<EntityException>(
() => ((MyCommitFailureHandler)c.TransactionHandler).PruneTransactionHistory());
MutableResolver.ClearResolvers();
AssertTransactionHistoryCount(c, 1);
((MyCommitFailureHandler)c.TransactionHandler).PruneTransactionHistory();
AssertTransactionHistoryCount(c, 0);
});
}
finally
{
DbInterception.Remove(failingTransactionInterceptor);
}
}
#if !NET40
[Fact]
public void CommitFailureHandler_ClearTransactionHistoryAsync_uses_ExecutionStrategy()
{
CommitFailureHandler_with_ExecutionStrategy_test(
(c, executionStrategyMock) =>
{
((MyCommitFailureHandler)c.TransactionHandler).ClearTransactionHistoryAsync().Wait();
executionStrategyMock.Verify(
e => e.ExecuteAsync(It.IsAny<Func<Task<int>>>(), It.IsAny<CancellationToken>()), Times.Once());
Assert.Empty(((MyCommitFailureHandler)c.TransactionHandler).TransactionContext.ChangeTracker.Entries<TransactionRow>());
});
}
[Fact]
public void CommitFailureHandler_ClearTransactionHistoryAsync_does_not_catch_exceptions()
{
var failingTransactionInterceptor = new FailingTransactionInterceptor();
DbInterception.Add(failingTransactionInterceptor);
try
{
CommitFailureHandler_with_ExecutionStrategy_test(
(c, executionStrategyMock) =>
{
MutableResolver.AddResolver<Func<IDbExecutionStrategy>>(
key => (Func<IDbExecutionStrategy>)(() => new SimpleExecutionStrategy()));
failingTransactionInterceptor.ShouldFailTimes = 1;
failingTransactionInterceptor.ShouldRollBack = true;
Assert.Throws<EntityException>(
() => ExceptionHelpers.UnwrapAggregateExceptions(
() => ((MyCommitFailureHandler)c.TransactionHandler).ClearTransactionHistoryAsync().Wait()));
MutableResolver.ClearResolvers();
AssertTransactionHistoryCount(c, 1);
((MyCommitFailureHandler)c.TransactionHandler).ClearTransactionHistoryAsync().Wait();
AssertTransactionHistoryCount(c, 0);
});
}
finally
{
DbInterception.Remove(failingTransactionInterceptor);
}
}
[Fact]
public void CommitFailureHandler_PruneTransactionHistoryAsync_uses_ExecutionStrategy()
{
CommitFailureHandler_with_ExecutionStrategy_test(
(c, executionStrategyMock) =>
{
((MyCommitFailureHandler)c.TransactionHandler).PruneTransactionHistoryAsync().Wait();
executionStrategyMock.Verify(
e => e.ExecuteAsync(It.IsAny<Func<Task<int>>>(), It.IsAny<CancellationToken>()), Times.Once());
Assert.Empty(((MyCommitFailureHandler)c.TransactionHandler).TransactionContext.ChangeTracker.Entries<TransactionRow>());
});
}
[Fact]
public void CommitFailureHandler_PruneTransactionHistoryAsync_does_not_catch_exceptions()
{
var failingTransactionInterceptor = new FailingTransactionInterceptor();
DbInterception.Add(failingTransactionInterceptor);
try
{
CommitFailureHandler_with_ExecutionStrategy_test(
(c, executionStrategyMock) =>
{
MutableResolver.AddResolver<Func<IDbExecutionStrategy>>(
key => (Func<IDbExecutionStrategy>)(() => new SimpleExecutionStrategy()));
failingTransactionInterceptor.ShouldFailTimes = 1;
failingTransactionInterceptor.ShouldRollBack = true;
Assert.Throws<EntityException>(
() => ExceptionHelpers.UnwrapAggregateExceptions(
() => ((MyCommitFailureHandler)c.TransactionHandler).PruneTransactionHistoryAsync().Wait()));
MutableResolver.ClearResolvers();
AssertTransactionHistoryCount(c, 1);
((MyCommitFailureHandler)c.TransactionHandler).PruneTransactionHistoryAsync().Wait();
AssertTransactionHistoryCount(c, 0);
});
}
finally
{
DbInterception.Remove(failingTransactionInterceptor);
}
}
#endif
private void CommitFailureHandler_with_ExecutionStrategy_test(
Action<ObjectContext, Mock<TestSqlAzureExecutionStrategy>> pruneAndVerify)
{
MutableResolver.AddResolver<Func<TransactionHandler>>(
new TransactionHandlerResolver(() => new MyCommitFailureHandler(c => new TransactionContext(c)), null, null));
var executionStrategyMock = new Mock<TestSqlAzureExecutionStrategy> { CallBase = true };
MutableResolver.AddResolver<Func<IDbExecutionStrategy>>(
key => (Func<IDbExecutionStrategy>)(() => executionStrategyMock.Object));
try
{
using (var context = new BlogContextCommit())
{
context.Database.Delete();
Assert.Equal(1, context.Blogs.Count());
context.Blogs.Add(new BlogContext.Blog());
context.SaveChanges();
AssertTransactionHistoryCount(context, 1);
executionStrategyMock.Verify(e => e.Execute(It.IsAny<Func<int>>()), Times.Exactly(3));
#if !NET40
executionStrategyMock.Verify(
e => e.ExecuteAsync(It.IsAny<Func<Task<int>>>(), It.IsAny<CancellationToken>()), Times.Never());
#endif
var objectContext = ((IObjectContextAdapter)context).ObjectContext;
pruneAndVerify(objectContext, executionStrategyMock);
using (var transactionContext = new TransactionContext(context.Database.Connection))
{
Assert.Equal(0, transactionContext.Transactions.Count());
}
}
}
finally
{
MutableResolver.ClearResolvers();
}
}
private void AssertTransactionHistoryCount(DbContext context, int count)
{
AssertTransactionHistoryCount(((IObjectContextAdapter)context).ObjectContext, count);
}
private void AssertTransactionHistoryCount(ObjectContext context, int count)
{
using (var transactionContext = new TransactionContext(((EntityConnection)context.Connection).StoreConnection))
{
Assert.Equal(count, transactionContext.Transactions.Count());
}
}
public class SimpleExecutionStrategy : IDbExecutionStrategy
{
public bool RetriesOnFailure
{
get { return false; }
}
public virtual void Execute(Action operation)
{
operation();
}
public virtual TResult Execute<TResult>(Func<TResult> operation)
{
return operation();
}
#if !NET40
public virtual Task ExecuteAsync(Func<Task> operation, CancellationToken cancellationToken)
{
return operation();
}
public virtual Task<TResult> ExecuteAsync<TResult>(Func<Task<TResult>> operation, CancellationToken cancellationToken)
{
return operation();
}
#endif
}
public class MyCommitFailureHandler : CommitFailureHandler
{
public MyCommitFailureHandler(Func<DbConnection, TransactionContext> transactionContextFactory)
: base(transactionContextFactory)
{
}
public new void MarkTransactionForPruning(TransactionRow transaction)
{
base.MarkTransactionForPruning(transaction);
}
public new TransactionContext TransactionContext
{
get { return base.TransactionContext; }
}
public new virtual int PruningLimit
{
get { return base.PruningLimit; }
}
}
[Fact]
[UseDefaultExecutionStrategy]
public void CommitFailureHandler_supports_nested_transactions()
{
MutableResolver.AddResolver<Func<TransactionHandler>>(
new TransactionHandlerResolver(() => new CommitFailureHandler(), null, null));
try
{
using (var context = new BlogContextCommit())
{
context.Database.Delete();
Assert.Equal(1, context.Blogs.Count());
context.Blogs.Add(new BlogContext.Blog());
using (var transaction = context.Database.BeginTransaction())
{
using (var innerContext = new BlogContextCommit())
{
using (var innerTransaction = innerContext.Database.BeginTransaction())
{
Assert.Equal(1, innerContext.Blogs.Count());
innerContext.Blogs.Add(new BlogContext.Blog());
innerContext.SaveChanges();
innerTransaction.Commit();
}
}
context.SaveChanges();
transaction.Commit();
}
}
using (var context = new BlogContextCommit())
{
Assert.Equal(3, context.Blogs.Count());
}
}
finally
{
MutableResolver.ClearResolvers();
}
DbDispatchersHelpers.AssertNoInterceptors();
}
[Fact]
public void BuildDatabaseInitializationScript_can_be_used_to_initialize_the_database()
{
MutableResolver.AddResolver<Func<TransactionHandler>>(
new TransactionHandlerResolver(() => new CommitFailureHandler(), null, null));
MutableResolver.AddResolver<Func<IDbExecutionStrategy>>(
key => (Func<IDbExecutionStrategy>)(() => new TestSqlAzureExecutionStrategy()));
try
{
using (var context = new BlogContextCommit())
{
context.Database.Delete();
Assert.Equal(1, context.Blogs.Count());
}
MutableResolver.AddResolver<Func<TransactionHandler>>(
new TransactionHandlerResolver(() => new CommitFailureHandler(c => new TransactionContextNoInit(c)), null, null));
using (var context = new BlogContextCommit())
{
context.Blogs.Add(new BlogContext.Blog());
Assert.Throws<EntityException>(() => context.SaveChanges());
context.Database.ExecuteSqlCommand(
TransactionalBehavior.DoNotEnsureTransaction,
((IObjectContextAdapter)context).ObjectContext.TransactionHandler.BuildDatabaseInitializationScript());
context.SaveChanges();
}
using (var context = new BlogContextCommit())
{
Assert.Equal(2, context.Blogs.Count());
}
}
finally
{
MutableResolver.ClearResolvers();
}
DbDispatchersHelpers.AssertNoInterceptors();
}
[Fact]
public void BuildDatabaseInitializationScript_can_be_used_to_initialize_the_database_if_no_migration_generator()
{
var mockDbProviderServiceResolver = new Mock<IDbDependencyResolver>();
mockDbProviderServiceResolver
.Setup(r => r.GetService(It.IsAny<Type>(), It.IsAny<string>()))
.Returns(SqlProviderServices.Instance);
MutableResolver.AddResolver<DbProviderServices>(mockDbProviderServiceResolver.Object);
var mockDbProviderFactoryResolver = new Mock<IDbDependencyResolver>();
mockDbProviderFactoryResolver
.Setup(r => r.GetService(It.IsAny<Type>(), It.IsAny<string>()))
.Returns(SqlClientFactory.Instance);
MutableResolver.AddResolver<DbProviderFactory>(mockDbProviderFactoryResolver.Object);
BuildDatabaseInitializationScript_can_be_used_to_initialize_the_database();
}
[Fact]
public void FromContext_returns_the_current_handler()
{
MutableResolver.AddResolver<Func<TransactionHandler>>(
new TransactionHandlerResolver(() => new CommitFailureHandler(), null, null));
try
{
using (var context = new BlogContextCommit())
{
context.Database.Delete();
var commitFailureHandler = CommitFailureHandler.FromContext(((IObjectContextAdapter)context).ObjectContext);
Assert.IsType<CommitFailureHandler>(commitFailureHandler);
Assert.Same(commitFailureHandler, CommitFailureHandler.FromContext(context));
}
}
finally
{
MutableResolver.ClearResolvers();
}
}
[Fact]
public void TransactionHandler_is_disposed_even_if_the_context_is_not()
{
var context = new BlogContextCommit();
context.Database.Delete();
Assert.Equal(1, context.Blogs.Count());
var weakDbContext = new WeakReference(context);
var weakObjectContext = new WeakReference(((IObjectContextAdapter)context).ObjectContext);
var weakTransactionHandler = new WeakReference(((IObjectContextAdapter)context).ObjectContext.TransactionHandler);
context = null;
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.False(weakDbContext.IsAlive);
Assert.False(weakObjectContext.IsAlive);
DbDispatchersHelpers.AssertNoInterceptors();
// Need a second pass as the TransactionHandler is removed from the interceptors in the ObjectContext finalizer
GC.Collect();
Assert.False(weakTransactionHandler.IsAlive);
}
public class TransactionContextNoInit : TransactionContext
{
static TransactionContextNoInit()
{
Database.SetInitializer<TransactionContextNoInit>(null);
}
public TransactionContextNoInit(DbConnection connection)
: base(connection)
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<TransactionRow>()
.ToTable("TransactionContextNoInit");
}
}
public class FailingTransactionInterceptor : IDbTransactionInterceptor
{
private int _timesToFail;
private int _shouldFailTimes;
public int ShouldFailTimes
{
get { return _shouldFailTimes; }
set
{
_shouldFailTimes = value;
_timesToFail = value;
}
}
public bool ShouldRollBack;
public FailingTransactionInterceptor()
{
_timesToFail = ShouldFailTimes;
}
public void ConnectionGetting(DbTransaction transaction, DbTransactionInterceptionContext<DbConnection> interceptionContext)
{
}
public void ConnectionGot(DbTransaction transaction, DbTransactionInterceptionContext<DbConnection> interceptionContext)
{
}
public void IsolationLevelGetting(
DbTransaction transaction, DbTransactionInterceptionContext<IsolationLevel> interceptionContext)
{
}
public void IsolationLevelGot(DbTransaction transaction, DbTransactionInterceptionContext<IsolationLevel> interceptionContext)
{
}
public virtual void Committing(DbTransaction transaction, DbTransactionInterceptionContext interceptionContext)
{
if (_timesToFail-- > 0)
{
if (ShouldRollBack)
{
transaction.Rollback();
}
else
{
transaction.Commit();
}
interceptionContext.Exception = new TimeoutException();
}
else
{
_timesToFail = ShouldFailTimes;
}
}
public void Committed(DbTransaction transaction, DbTransactionInterceptionContext interceptionContext)
{
if (interceptionContext.Exception != null)
{
_timesToFail--;
}
}
public void Disposing(DbTransaction transaction, DbTransactionInterceptionContext interceptionContext)
{
}
public void Disposed(DbTransaction transaction, DbTransactionInterceptionContext interceptionContext)
{
}
public void RollingBack(DbTransaction transaction, DbTransactionInterceptionContext interceptionContext)
{
}
public void RolledBack(DbTransaction transaction, DbTransactionInterceptionContext interceptionContext)
{
}
}
public class BlogContextCommit : BlogContext
{
static BlogContextCommit()
{
Database.SetInitializer<BlogContextCommit>(new BlogInitializer());
}
}
}
}
| |
// 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.Threading;
using Xunit;
namespace System.Linq.Parallel.Tests
{
public static class ExceptTests
{
private const int DuplicateFactor = 4;
public static IEnumerable<int> RightCounts(int leftCount)
{
int upperBound = Math.Max(DuplicateFactor, leftCount);
return new[] { 0, 1, upperBound, upperBound * 2 }.Distinct();
}
public static IEnumerable<object[]> ExceptUnorderedData(int[] leftCounts)
{
foreach (int leftCount in leftCounts.DefaultIfEmpty(Sources.OuterLoopCount / 4))
{
foreach (int rightCount in RightCounts(leftCount))
{
int rightStart = 0 - rightCount / 2;
yield return new object[] { leftCount, rightStart, rightCount, rightStart + rightCount, Math.Max(0, leftCount - (rightCount + 1) / 2) };
}
}
}
public static IEnumerable<object[]> ExceptData(int[] leftCounts)
{
foreach (int leftCount in leftCounts.DefaultIfEmpty(Sources.OuterLoopCount / 4))
{
foreach (int rightCount in RightCounts(leftCount))
{
int rightStart = 0 - rightCount / 2;
foreach (object[] left in Sources.Ranges(new[] { leftCount }))
{
yield return left.Concat(new object[] { UnorderedSources.Default(rightStart, rightCount), rightCount, rightStart + rightCount, Math.Max(0, leftCount - (rightCount + 1) / 2) }).ToArray();
}
}
}
}
public static IEnumerable<object[]> ExceptSourceMultipleData(int[] counts)
{
foreach (int leftCount in counts.DefaultIfEmpty(Sources.OuterLoopCount / DuplicateFactor / 2))
{
ParallelQuery<int> left = Enumerable.Range(0, leftCount * DuplicateFactor).Select(x => x % leftCount).ToArray().AsParallel().AsOrdered();
foreach (int rightCount in RightCounts(leftCount))
{
int rightStart = 0 - rightCount / 2;
yield return new object[] { left, leftCount, UnorderedSources.Default(rightStart, rightCount), rightCount, rightStart + rightCount, Math.Max(0, leftCount - (rightCount + 1) / 2) };
}
}
}
//
// Except
//
[Theory]
[MemberData(nameof(ExceptUnorderedData), new[] { 0, 1, 2, 16 })]
public static void Except_Unordered(int leftCount, int rightStart, int rightCount, int start, int count)
{
ParallelQuery<int> leftQuery = UnorderedSources.Default(leftCount);
ParallelQuery<int> rightQuery = UnorderedSources.Default(rightStart, rightCount);
IntegerRangeSet seen = new IntegerRangeSet(start, count);
foreach (int i in leftQuery.Except(rightQuery))
{
seen.Add(i);
}
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData(nameof(ExceptUnorderedData), new int[] { /* Sources.OuterLoopCount */ })]
public static void Except_Unordered_Longrunning(int leftCount, int rightStart, int rightCount, int start, int count)
{
Except_Unordered(leftCount, rightStart, rightCount, start, count);
}
[Theory]
[MemberData(nameof(ExceptData), new[] { 0, 1, 2, 16 })]
public static void Except(
Labeled<ParallelQuery<int>> left, int leftCount,
ParallelQuery<int> rightQuery, int rightCount,
int start, int count)
{
_ = leftCount;
_ = rightCount;
ParallelQuery<int> leftQuery = left.Item;
int seen = start;
foreach (int i in leftQuery.Except(rightQuery))
{
Assert.Equal(seen++, i);
}
Assert.Equal(count + start, seen);
}
[Theory]
[OuterLoop]
[MemberData(nameof(ExceptData), new int[] { /* Sources.OuterLoopCount */ })]
public static void Except_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int start, int count)
{
Except(left, leftCount, rightQuery, rightCount, start, count);
}
[Theory]
[MemberData(nameof(ExceptUnorderedData), new[] { 0, 1, 2, 16 })]
public static void Except_Unordered_NotPipelined(int leftCount, int rightStart, int rightCount, int start, int count)
{
ParallelQuery<int> leftQuery = UnorderedSources.Default(leftCount);
ParallelQuery<int> rightQuery = UnorderedSources.Default(rightStart, rightCount);
IntegerRangeSet seen = new IntegerRangeSet(start, count);
Assert.All(leftQuery.Except(rightQuery).ToList(), x => seen.Add(x));
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData(nameof(ExceptUnorderedData), new int[] { /* Sources.OuterLoopCount */ })]
public static void Except_Unordered_NotPipelined_Longrunning(int leftCount, int rightStart, int rightCount, int start, int count)
{
Except_Unordered_NotPipelined(leftCount, rightStart, rightCount, start, count);
}
[Theory]
[MemberData(nameof(ExceptData), new[] { 0, 1, 2, 16 })]
public static void Except_NotPipelined(
Labeled<ParallelQuery<int>> left, int leftCount,
ParallelQuery<int> rightQuery, int rightCount,
int start, int count)
{
_ = leftCount;
_ = rightCount;
ParallelQuery<int> leftQuery = left.Item;
int seen = start;
Assert.All(leftQuery.Except(rightQuery).ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(count + start, seen);
}
[Theory]
[OuterLoop]
[MemberData(nameof(ExceptData), new int[] { /* Sources.OuterLoopCount */ })]
public static void Except_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int start, int count)
{
Except_NotPipelined(left, leftCount, rightQuery, rightCount, start, count);
}
[Theory]
[MemberData(nameof(ExceptUnorderedData), new[] { 0, 1, 2, 16 })]
public static void Except_Unordered_Distinct(int leftCount, int rightStart, int rightCount, int start, int count)
{
_ = start;
_ = count;
ParallelQuery<int> leftQuery = UnorderedSources.Default(leftCount);
ParallelQuery<int> rightQuery = UnorderedSources.Default(rightStart, rightCount);
leftCount = Math.Min(DuplicateFactor * 2, leftCount);
rightCount = Math.Min(DuplicateFactor, (rightCount + 1) / 2);
int expectedCount = Math.Max(0, leftCount - rightCount);
IntegerRangeSet seen = new IntegerRangeSet(leftCount - expectedCount, expectedCount);
foreach (int i in leftQuery.Except(rightQuery.Select(x => Math.Abs(x) % DuplicateFactor), new ModularCongruenceComparer(DuplicateFactor * 2)))
{
seen.Add(i % (DuplicateFactor * 2));
}
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData(nameof(ExceptUnorderedData), new int[] { /* Sources.OuterLoopCount */ })]
public static void Except_Unordered_Distinct_Longrunning(int leftCount, int rightStart, int rightCount, int start, int count)
{
Except_Unordered_Distinct(leftCount, rightStart, rightCount, start, count);
}
[Theory]
[MemberData(nameof(ExceptData), new[] { 0, 1, 2, 16 })]
public static void Except_Distinct(Labeled<ParallelQuery<int>> left, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int start, int count)
{
_ = start;
_ = count;
ParallelQuery<int> leftQuery = left.Item;
leftCount = Math.Min(DuplicateFactor * 2, leftCount);
rightCount = Math.Min(DuplicateFactor, (rightCount + 1) / 2);
int expectedCount = Math.Max(0, leftCount - rightCount);
int seen = expectedCount == 0 ? 0 : leftCount - expectedCount;
foreach (int i in leftQuery.Except(rightQuery.Select(x => Math.Abs(x) % DuplicateFactor), new ModularCongruenceComparer(DuplicateFactor * 2)))
{
Assert.Equal(seen++, i);
}
Assert.Equal(expectedCount == 0 ? 0 : leftCount, seen);
}
[Theory]
[OuterLoop]
[MemberData(nameof(ExceptData), new int[] { /* Sources.OuterLoopCount */ })]
public static void Except_Distinct_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int start, int count)
{
Except_Distinct(left, leftCount, rightQuery, rightCount, start, count);
}
[Theory]
[MemberData(nameof(ExceptUnorderedData), new[] { 0, 1, 2, 16 })]
public static void Except_Unordered_Distinct_NotPipelined(int leftCount, int rightStart, int rightCount, int start, int count)
{
_ = start;
_ = count;
ParallelQuery<int> leftQuery = UnorderedSources.Default(leftCount);
ParallelQuery<int> rightQuery = UnorderedSources.Default(rightStart, rightCount);
leftCount = Math.Min(DuplicateFactor * 2, leftCount);
rightCount = Math.Min(DuplicateFactor, (rightCount + 1) / 2);
int expectedCount = Math.Max(0, leftCount - rightCount);
IntegerRangeSet seen = new IntegerRangeSet(leftCount - expectedCount, expectedCount);
Assert.All(leftQuery.Except(rightQuery.Select(x => Math.Abs(x) % DuplicateFactor),
new ModularCongruenceComparer(DuplicateFactor * 2)).ToList(), x => seen.Add(x % (DuplicateFactor * 2)));
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData(nameof(ExceptUnorderedData), new int[] { /* Sources.OuterLoopCount */ })]
public static void Except_Unordered_Distinct_NotPipelined_Longrunning(int leftCount, int rightStart, int rightCount, int start, int count)
{
Except_Unordered_Distinct_NotPipelined(leftCount, rightStart, rightCount, start, count);
}
[Theory]
[MemberData(nameof(ExceptData), new[] { 0, 1, 2, 16 })]
public static void Except_Distinct_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int start, int count)
{
_ = start;
_ = count;
ParallelQuery<int> leftQuery = left.Item;
leftCount = Math.Min(DuplicateFactor * 2, leftCount);
rightCount = Math.Min(DuplicateFactor, (rightCount + 1) / 2);
int expectedCount = Math.Max(0, leftCount - rightCount);
int seen = expectedCount == 0 ? 0 : leftCount - expectedCount;
Assert.All(leftQuery.Except(rightQuery.Select(x => Math.Abs(x) % DuplicateFactor),
new ModularCongruenceComparer(DuplicateFactor * 2)).ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(expectedCount == 0 ? 0 : leftCount, seen);
}
[Theory]
[OuterLoop]
[MemberData(nameof(ExceptData), new int[] { /* Sources.OuterLoopCount */ })]
public static void Except_Distinct_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int start, int count)
{
Except_Distinct_NotPipelined(left, leftCount, rightQuery, rightCount, start, count);
}
[Theory]
[MemberData(nameof(ExceptSourceMultipleData), new[] { 0, 1, 2, 16 })]
public static void Except_Unordered_SourceMultiple(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int start, int count)
{
// The difference between this test and the previous, is that it's not possible to
// get non-unique results from ParallelEnumerable.Range()...
// Those tests either need modification of source (via .Select(x => x / DuplicateFactor) or similar,
// or via a comparator that considers some elements equal.
_ = leftCount;
_ = rightCount;
IntegerRangeSet seen = new IntegerRangeSet(start, count);
Assert.All(leftQuery.AsUnordered().Except(rightQuery), x => seen.Add(x));
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData(nameof(ExceptSourceMultipleData), new int[] { /* Sources.OuterLoopCount */ })]
public static void Except_Unordered_SourceMultiple_Longrunning(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int start, int count)
{
Except_Unordered_SourceMultiple(leftQuery, leftCount, rightQuery, rightCount, start, count);
}
[Theory]
[MemberData(nameof(ExceptSourceMultipleData), new[] { 0, 1, 2, 16 })]
public static void Except_SourceMultiple(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int start, int count)
{
_ = leftCount;
_ = rightCount;
int seen = start;
Assert.All(leftQuery.Except(rightQuery), x => Assert.Equal(seen++, x));
Assert.Equal(start + count, seen);
}
[Theory]
[OuterLoop]
[MemberData(nameof(ExceptSourceMultipleData), new int[] { /* Sources.OuterLoopCount */ })]
public static void Except_SourceMultiple_Longrunning(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int start, int count)
{
Except_SourceMultiple(leftQuery, leftCount, rightQuery, rightCount, start, count);
}
[Fact]
public static void Except_NotSupportedException()
{
#pragma warning disable 618
Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).Except(Enumerable.Range(0, 1)));
Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).Except(Enumerable.Range(0, 1), null));
#pragma warning restore 618
}
[Fact]
// Should not get the same setting from both operands.
public static void Except_NoDuplicateSettings()
{
CancellationToken t = new CancellationTokenSource().Token;
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithCancellation(t).Except(ParallelEnumerable.Range(0, 1).WithCancellation(t)));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithDegreeOfParallelism(1).Except(ParallelEnumerable.Range(0, 1).WithDegreeOfParallelism(1)));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithExecutionMode(ParallelExecutionMode.Default).Except(ParallelEnumerable.Range(0, 1).WithExecutionMode(ParallelExecutionMode.Default)));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithMergeOptions(ParallelMergeOptions.Default).Except(ParallelEnumerable.Range(0, 1).WithMergeOptions(ParallelMergeOptions.Default)));
}
[Fact]
public static void Except_ArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("first", () => ((ParallelQuery<int>)null).Except(ParallelEnumerable.Range(0, 1)));
AssertExtensions.Throws<ArgumentNullException>("second", () => ParallelEnumerable.Range(0, 1).Except(null));
AssertExtensions.Throws<ArgumentNullException>("first", () => ((ParallelQuery<int>)null).Except(ParallelEnumerable.Range(0, 1), EqualityComparer<int>.Default));
AssertExtensions.Throws<ArgumentNullException>("second", () => ParallelEnumerable.Range(0, 1).Except(null, EqualityComparer<int>.Default));
}
}
}
| |
using J2N;
using J2N.Text;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using JCG = J2N.Collections.Generic;
/*
* dk.brics.automaton
*
* Copyright (c) 2001-2009 Anders Moeller
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* this SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* this SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
namespace YAF.Lucene.Net.Util.Automaton
{
// LUCENENET specific - converted constants from RegExp
// into a flags enum.
[Flags]
public enum RegExpSyntax
{
/// <summary>
/// Syntax flag, enables intersection (<c>&</c>).
/// </summary>
INTERSECTION = 0x0001,
/// <summary>
/// Syntax flag, enables complement (<c>~</c>).
/// </summary>
COMPLEMENT = 0x0002,
/// <summary>
/// Syntax flag, enables empty language (<c>#</c>).
/// </summary>
EMPTY = 0x0004,
/// <summary>
/// Syntax flag, enables anystring (<c>@</c>).
/// </summary>
ANYSTRING = 0x0008,
/// <summary>
/// Syntax flag, enables named automata (<c><</c>identifier<c>></c>).
/// </summary>
AUTOMATON = 0x0010,
/// <summary>
/// Syntax flag, enables numerical intervals (
/// <c><<i>n</i>-<i>m</i>></c>).
/// </summary>
INTERVAL = 0x0020,
/// <summary>
/// Syntax flag, enables all optional regexp syntax.
/// </summary>
ALL = 0xffff,
/// <summary>
/// Syntax flag, enables no optional regexp syntax.
/// </summary>
NONE = 0x0000
}
/// <summary>
/// Regular Expression extension to <see cref="Util.Automaton.Automaton"/>.
/// <para/>
/// Regular expressions are built from the following abstract syntax:
/// <para/>
/// <list type="table">
/// <item>
/// <term><i>regexp</i></term>
/// <term>::=</term>
/// <term><i>unionexp</i></term>
/// <term></term>
/// <term></term>
/// </item>
/// <item>
/// <term></term>
/// <term>|</term>
/// <term></term>
/// <term></term>
/// <term></term>
/// </item>
///
/// <item>
/// <term><i>unionexp</i></term>
/// <term>::=</term>
/// <term><i>interexp</i> <tt><b>|</b></tt> <i>unionexp</i></term>
/// <term>(union)</term>
/// <term></term>
/// </item>
/// <item>
/// <term></term>
/// <term>|</term>
/// <term><i>interexp</i></term>
/// <term></term>
/// <term></term>
/// </item>
///
/// <item>
/// <term><i>interexp</i></term>
/// <term>::=</term>
/// <term><i>concatexp</i> <tt><b>&</b></tt> <i>interexp</i></term>
/// <term>(intersection)</term>
/// <term><small>[OPTIONAL]</small></term>
/// </item>
/// <item>
/// <term></term>
/// <term>|</term>
/// <term><i>concatexp</i></term>
/// <term></term>
/// <term></term>
/// </item>
///
/// <item>
/// <term><i>concatexp</i></term>
/// <term>::=</term>
/// <term><i>repeatexp</i> <i>concatexp</i></term>
/// <term>(concatenation)</term>
/// <term></term>
/// </item>
/// <item>
/// <term></term>
/// <term>|</term>
/// <term><i>repeatexp</i></term>
/// <term></term>
/// <term></term>
/// </item>
///
/// <item>
/// <term><i>repeatexp</i></term>
/// <term>::=</term>
/// <term><i>repeatexp</i> <tt><b>?</b></tt></term>
/// <term>(zero or one occurrence)</term>
/// <term></term>
/// </item>
/// <item>
/// <term></term>
/// <term>|</term>
/// <term><i>repeatexp</i> <tt><b>*</b></tt></term>
/// <term>(zero or more occurrences)</term>
/// <term></term>
/// </item>
/// <item>
/// <term></term>
/// <term>|</term>
/// <term><i>repeatexp</i> <tt><b>+</b></tt></term>
/// <term>(one or more occurrences)</term>
/// <term></term>
/// </item>
/// <item>
/// <term></term>
/// <term>|</term>
/// <term><i>repeatexp</i> <tt><b>{</b><i>n</i><b>}</b></tt></term>
/// <term>(<tt><i>n</i></tt> occurrences)</term>
/// <term></term>
/// </item>
/// <item>
/// <term></term>
/// <term>|</term>
/// <term><i>repeatexp</i> <tt><b>{</b><i>n</i><b>,}</b></tt></term>
/// <term>(<tt><i>n</i></tt> or more occurrences)</term>
/// <term></term>
/// </item>
/// <item>
/// <term></term>
/// <term>|</term>
/// <term><i>repeatexp</i> <tt><b>{</b><i>n</i><b>,</b><i>m</i><b>}</b></tt></term>
/// <term>(<tt><i>n</i></tt> to <tt><i>m</i></tt> occurrences, including both)</term>
/// <term></term>
/// </item>
/// <item>
/// <term></term>
/// <term>|</term>
/// <term><i>complexp</i></term>
/// <term></term>
/// <term></term>
/// </item>
///
/// <item>
/// <term><i>complexp</i></term>
/// <term>::=</term>
/// <term><tt><b>~</b></tt> <i>complexp</i></term>
/// <term>(complement)</term>
/// <term><small>[OPTIONAL]</small></term>
/// </item>
/// <item>
/// <term></term>
/// <term>|</term>
/// <term><i>charclassexp</i></term>
/// <term></term>
/// <term></term>
/// </item>
///
/// <item>
/// <term><i>charclassexp</i></term>
/// <term>::=</term>
/// <term><tt><b>[</b></tt> <i>charclasses</i> <tt><b>]</b></tt></term>
/// <term>(character class)</term>
/// <term></term>
/// </item>
/// <item>
/// <term></term>
/// <term>|</term>
/// <term><tt><b>[^</b></tt> <i>charclasses</i> <tt><b>]</b></tt></term>
/// <term>(negated character class)</term>
/// <term></term>
/// </item>
/// <item>
/// <term></term>
/// <term>|</term>
/// <term><i>simpleexp</i></term>
/// <term></term>
/// <term></term>
/// </item>
///
/// <item>
/// <term><i>charclasses</i></term>
/// <term>::=</term>
/// <term><i>charclass</i> <i>charclasses</i></term>
/// <term></term>
/// <term></term>
/// </item>
/// <item>
/// <term></term>
/// <term>|</term>
/// <term><i>charclass</i></term>
/// <term></term>
/// <term></term>
/// </item>
///
/// <item>
/// <term><i>charclass</i></term>
/// <term>::=</term>
/// <term><i>charexp</i> <tt><b>-</b></tt> <i>charexp</i></term>
/// <term>(character range, including end-points)</term>
/// <term></term>
/// </item>
/// <item>
/// <term></term>
/// <term>|</term>
/// <term><i>charexp</i></term>
/// <term></term>
/// <term></term>
/// </item>
///
/// <item>
/// <term><i>simpleexp</i></term>
/// <term>::=</term>
/// <term><i>charexp</i></term>
/// <term></term>
/// <term></term>
/// </item>
/// <item>
/// <term></term>
/// <term>|</term>
/// <term><tt><b>.</b></tt></term>
/// <term>(any single character)</term>
/// <term></term>
/// </item>
/// <item>
/// <term></term>
/// <term>|</term>
/// <term><tt><b>#</b></tt></term>
/// <term>(the empty language)</term>
/// <term><small>[OPTIONAL]</small></term>
/// </item>
/// <item>
/// <term></term>
/// <term>|</term>
/// <term><tt><b>@</b></tt></term>
/// <term>(any string)</term>
/// <term><small>[OPTIONAL]</small></term>
/// </item>
/// <item>
/// <term></term>
/// <term>|</term>
/// <term><tt><b>"</b></tt> <Unicode string without double-quotes>  <tt><b>"</b></tt></term>
/// <term>(a string)</term>
/// <term></term>
/// </item>
/// <item>
/// <term></term>
/// <term>|</term>
/// <term><tt><b>(</b></tt> <tt><b>)</b></tt></term>
/// <term>(the empty string)</term>
/// <term></term>
/// </item>
/// <item>
/// <term></term>
/// <term>|</term>
/// <term><tt><b>(</b></tt> <i>unionexp</i> <tt><b>)</b></tt></term>
/// <term>(precedence override)</term>
/// <term></term>
/// </item>
/// <item>
/// <term></term>
/// <term>|</term>
/// <term><tt><b><</b></tt> <identifier> <tt><b>></b></tt></term>
/// <term>(named automaton)</term>
/// <term><small>[OPTIONAL]</small></term>
/// </item>
/// <item>
/// <term></term>
/// <term>|</term>
/// <term><tt><b><</b><i>n</i>-<i>m</i><b>></b></tt></term>
/// <term>(numerical interval)</term>
/// <term><small>[OPTIONAL]</small></term>
/// </item>
///
/// <item>
/// <term><i>charexp</i></term>
/// <term>::=</term>
/// <term><Unicode character></term>
/// <term>(a single non-reserved character)</term>
/// <term></term>
/// </item>
/// <item>
/// <term></term>
/// <term>|</term>
/// <term><tt><b>\</b></tt> <Unicode character> </term>
/// <term>(a single character)</term>
/// <term></term>
/// </item>
///
/// </list>
///
/// <para/>
/// The productions marked <small>[OPTIONAL]</small> are only allowed if
/// specified by the syntax flags passed to the <see cref="RegExp"/> constructor.
/// The reserved characters used in the (enabled) syntax must be escaped with
/// backslash (<c>\</c>) or double-quotes (<c>"..."</c>). (In
/// contrast to other regexp syntaxes, this is required also in character
/// classes.) Be aware that dash (<c>-</c>) has a special meaning in
/// <i>charclass</i> expressions. An identifier is a string not containing right
/// angle bracket (<c>></c>) or dash (<c>-</c>). Numerical
/// intervals are specified by non-negative decimal integers and include both end
/// points, and if <c>n</c> and <c>m</c> have the same number
/// of digits, then the conforming strings must have that length (i.e. prefixed
/// by 0's).
/// <para/>
/// @lucene.experimental
/// </summary>
public class RegExp
{
internal enum Kind
{
REGEXP_UNION,
REGEXP_CONCATENATION,
REGEXP_INTERSECTION,
REGEXP_OPTIONAL,
REGEXP_REPEAT,
REGEXP_REPEAT_MIN,
REGEXP_REPEAT_MINMAX,
REGEXP_COMPLEMENT,
REGEXP_CHAR,
REGEXP_CHAR_RANGE,
REGEXP_ANYCHAR,
REGEXP_EMPTY,
REGEXP_STRING,
REGEXP_ANYSTRING,
REGEXP_AUTOMATON,
REGEXP_INTERVAL
}
// LUCENENET specific - made flags into their own [Flags] enum named RegExpSyntax and de-nested from this type
private static bool allow_mutation = false;
internal Kind kind;
internal RegExp exp1, exp2;
internal string s;
internal int c;
internal int min, max, digits;
internal int from, to;
internal string b;
internal RegExpSyntax flags;
internal int pos;
internal RegExp()
{
}
/// <summary>
/// Constructs new <see cref="RegExp"/> from a string. Same as
/// <c>RegExp(s, RegExpSyntax.ALL)</c>.
/// </summary>
/// <param name="s"> Regexp string. </param>
/// <exception cref="ArgumentException"> If an error occured while parsing the
/// regular expression. </exception>
public RegExp(string s)
: this(s, RegExpSyntax.ALL)
{
}
/// <summary>
/// Constructs new <see cref="RegExp"/> from a string.
/// </summary>
/// <param name="s"> Regexp string. </param>
/// <param name="syntax_flags"> Boolean 'or' of optional <see cref="RegExpSyntax"/> constructs to be
/// enabled. </param>
/// <exception cref="ArgumentException"> If an error occured while parsing the
/// regular expression </exception>
public RegExp(string s, RegExpSyntax syntax_flags)
{
b = s;
flags = syntax_flags;
RegExp e;
if (s.Length == 0)
{
e = MakeString("");
}
else
{
e = ParseUnionExp();
if (pos < b.Length)
{
throw new ArgumentException("end-of-string expected at position " + pos);
}
}
kind = e.kind;
exp1 = e.exp1;
exp2 = e.exp2;
this.s = e.s;
c = e.c;
min = e.min;
max = e.max;
digits = e.digits;
from = e.from;
to = e.to;
b = null;
}
/// <summary>
/// Constructs new <see cref="Automaton"/> from this <see cref="RegExp"/>. Same
/// as <c>ToAutomaton(null)</c> (empty automaton map).
/// </summary>
public virtual Automaton ToAutomaton()
{
return ToAutomatonAllowMutate(null, null);
}
/// <summary>
/// Constructs new <see cref="Automaton"/> from this <see cref="RegExp"/>. The
/// constructed automaton is minimal and deterministic and has no transitions
/// to dead states.
/// </summary>
/// <param name="automaton_provider"> Provider of automata for named identifiers. </param>
/// <exception cref="ArgumentException"> If this regular expression uses a named
/// identifier that is not available from the automaton provider. </exception>
public virtual Automaton ToAutomaton(IAutomatonProvider automaton_provider)
{
return ToAutomatonAllowMutate(null, automaton_provider);
}
/// <summary>
/// Constructs new <see cref="Automaton"/> from this <see cref="RegExp"/>. The
/// constructed automaton is minimal and deterministic and has no transitions
/// to dead states.
/// </summary>
/// <param name="automata"> A map from automaton identifiers to automata (of type
/// <see cref="Automaton"/>). </param>
/// <exception cref="ArgumentException"> If this regular expression uses a named
/// identifier that does not occur in the automaton map. </exception>
public virtual Automaton ToAutomaton(IDictionary<string, Automaton> automata)
{
return ToAutomatonAllowMutate(automata, null);
}
/// <summary>
/// Sets or resets allow mutate flag. If this flag is set, then automata
/// construction uses mutable automata, which is slightly faster but not thread
/// safe. By default, the flag is not set.
/// </summary>
/// <param name="flag"> If <c>true</c>, the flag is set </param>
/// <returns> Previous value of the flag. </returns>
public virtual bool SetAllowMutate(bool flag)
{
bool b = allow_mutation;
allow_mutation = flag;
return b;
}
private Automaton ToAutomatonAllowMutate(IDictionary<string, Automaton> automata, IAutomatonProvider automaton_provider)
{
bool b = false;
if (allow_mutation) // thread unsafe
{
b = Automaton.SetAllowMutate(true);
}
Automaton a = ToAutomaton(automata, automaton_provider);
if (allow_mutation)
{
Automaton.SetAllowMutate(b);
}
return a;
}
private Automaton ToAutomaton(IDictionary<string, Automaton> automata, IAutomatonProvider automaton_provider)
{
IList<Automaton> list;
Automaton a = null;
switch (kind)
{
case Kind.REGEXP_UNION:
list = new List<Automaton>();
FindLeaves(exp1, Kind.REGEXP_UNION, list, automata, automaton_provider);
FindLeaves(exp2, Kind.REGEXP_UNION, list, automata, automaton_provider);
a = BasicOperations.Union(list);
MinimizationOperations.Minimize(a);
break;
case Kind.REGEXP_CONCATENATION:
list = new List<Automaton>();
FindLeaves(exp1, Kind.REGEXP_CONCATENATION, list, automata, automaton_provider);
FindLeaves(exp2, Kind.REGEXP_CONCATENATION, list, automata, automaton_provider);
a = BasicOperations.Concatenate(list);
MinimizationOperations.Minimize(a);
break;
case Kind.REGEXP_INTERSECTION:
a = exp1.ToAutomaton(automata, automaton_provider).Intersection(exp2.ToAutomaton(automata, automaton_provider));
MinimizationOperations.Minimize(a);
break;
case Kind.REGEXP_OPTIONAL:
a = exp1.ToAutomaton(automata, automaton_provider).Optional();
MinimizationOperations.Minimize(a);
break;
case Kind.REGEXP_REPEAT:
a = exp1.ToAutomaton(automata, automaton_provider).Repeat();
MinimizationOperations.Minimize(a);
break;
case Kind.REGEXP_REPEAT_MIN:
a = exp1.ToAutomaton(automata, automaton_provider).Repeat(min);
MinimizationOperations.Minimize(a);
break;
case Kind.REGEXP_REPEAT_MINMAX:
a = exp1.ToAutomaton(automata, automaton_provider).Repeat(min, max);
MinimizationOperations.Minimize(a);
break;
case Kind.REGEXP_COMPLEMENT:
a = exp1.ToAutomaton(automata, automaton_provider).Complement();
MinimizationOperations.Minimize(a);
break;
case Kind.REGEXP_CHAR:
a = BasicAutomata.MakeChar(c);
break;
case Kind.REGEXP_CHAR_RANGE:
a = BasicAutomata.MakeCharRange(from, to);
break;
case Kind.REGEXP_ANYCHAR:
a = BasicAutomata.MakeAnyChar();
break;
case Kind.REGEXP_EMPTY:
a = BasicAutomata.MakeEmpty();
break;
case Kind.REGEXP_STRING:
a = BasicAutomata.MakeString(s);
break;
case Kind.REGEXP_ANYSTRING:
a = BasicAutomata.MakeAnyString();
break;
case Kind.REGEXP_AUTOMATON:
Automaton aa = null;
if (automata != null)
{
aa = automata[s];
}
if (aa == null && automaton_provider != null)
{
try
{
aa = automaton_provider.GetAutomaton(s);
}
catch (System.IO.IOException e)
{
throw new ArgumentException(e.ToString(), e);
}
}
if (aa == null)
{
throw new ArgumentException("'" + s + "' not found");
}
a = (Automaton)aa.Clone(); // always clone here (ignore allow_mutate)
break;
case Kind.REGEXP_INTERVAL:
a = BasicAutomata.MakeInterval(min, max, digits);
break;
}
return a;
}
private void FindLeaves(RegExp exp, Kind kind, IList<Automaton> list, IDictionary<string, Automaton> automata, IAutomatonProvider automaton_provider)
{
if (exp.kind == kind)
{
FindLeaves(exp.exp1, kind, list, automata, automaton_provider);
FindLeaves(exp.exp2, kind, list, automata, automaton_provider);
}
else
{
list.Add(exp.ToAutomaton(automata, automaton_provider));
}
}
/// <summary>
/// Constructs string from parsed regular expression.
/// </summary>
public override string ToString()
{
return ToStringBuilder(new StringBuilder()).ToString();
}
internal virtual StringBuilder ToStringBuilder(StringBuilder b)
{
switch (kind)
{
case Kind.REGEXP_UNION:
b.Append("(");
exp1.ToStringBuilder(b);
b.Append("|");
exp2.ToStringBuilder(b);
b.Append(")");
break;
case Kind.REGEXP_CONCATENATION:
exp1.ToStringBuilder(b);
exp2.ToStringBuilder(b);
break;
case Kind.REGEXP_INTERSECTION:
b.Append("(");
exp1.ToStringBuilder(b);
b.Append("&");
exp2.ToStringBuilder(b);
b.Append(")");
break;
case Kind.REGEXP_OPTIONAL:
b.Append("(");
exp1.ToStringBuilder(b);
b.Append(")?");
break;
case Kind.REGEXP_REPEAT:
b.Append("(");
exp1.ToStringBuilder(b);
b.Append(")*");
break;
case Kind.REGEXP_REPEAT_MIN:
b.Append("(");
exp1.ToStringBuilder(b);
b.Append("){").Append(min).Append(",}");
break;
case Kind.REGEXP_REPEAT_MINMAX:
b.Append("(");
exp1.ToStringBuilder(b);
b.Append("){").Append(min).Append(",").Append(max).Append("}");
break;
case Kind.REGEXP_COMPLEMENT:
b.Append("~(");
exp1.ToStringBuilder(b);
b.Append(")");
break;
case Kind.REGEXP_CHAR:
b.Append("\\").AppendCodePoint(c);
break;
case Kind.REGEXP_CHAR_RANGE:
b.Append("[\\").AppendCodePoint(from).Append("-\\").AppendCodePoint(to).Append("]");
break;
case Kind.REGEXP_ANYCHAR:
b.Append(".");
break;
case Kind.REGEXP_EMPTY:
b.Append("#");
break;
case Kind.REGEXP_STRING:
b.Append("\"").Append(s).Append("\"");
break;
case Kind.REGEXP_ANYSTRING:
b.Append("@");
break;
case Kind.REGEXP_AUTOMATON:
b.Append("<").Append(s).Append(">");
break;
case Kind.REGEXP_INTERVAL:
string s1 = Convert.ToString(min, CultureInfo.InvariantCulture);
string s2 = Convert.ToString(max, CultureInfo.InvariantCulture);
b.Append("<");
if (digits > 0)
{
for (int i = s1.Length; i < digits; i++)
{
b.Append('0');
}
}
b.Append(s1).Append("-");
if (digits > 0)
{
for (int i = s2.Length; i < digits; i++)
{
b.Append('0');
}
}
b.Append(s2).Append(">");
break;
}
return b;
}
/// <summary>
/// Returns set of automaton identifiers that occur in this regular expression.
/// </summary>
public virtual ISet<string> GetIdentifiers()
{
ISet<string> set = new JCG.HashSet<string>();
GetIdentifiers(set);
return set;
}
internal virtual void GetIdentifiers(ISet<string> set)
{
switch (kind)
{
case Kind.REGEXP_UNION:
case Kind.REGEXP_CONCATENATION:
case Kind.REGEXP_INTERSECTION:
exp1.GetIdentifiers(set);
exp2.GetIdentifiers(set);
break;
case Kind.REGEXP_OPTIONAL:
case Kind.REGEXP_REPEAT:
case Kind.REGEXP_REPEAT_MIN:
case Kind.REGEXP_REPEAT_MINMAX:
case Kind.REGEXP_COMPLEMENT:
exp1.GetIdentifiers(set);
break;
case Kind.REGEXP_AUTOMATON:
set.Add(s);
break;
default:
break;
}
}
internal static RegExp MakeUnion(RegExp exp1, RegExp exp2)
{
RegExp r = new RegExp();
r.kind = Kind.REGEXP_UNION;
r.exp1 = exp1;
r.exp2 = exp2;
return r;
}
internal static RegExp MakeConcatenation(RegExp exp1, RegExp exp2)
{
if ((exp1.kind == Kind.REGEXP_CHAR || exp1.kind == Kind.REGEXP_STRING) && (exp2.kind == Kind.REGEXP_CHAR || exp2.kind == Kind.REGEXP_STRING))
{
return MakeString(exp1, exp2);
}
RegExp r = new RegExp();
r.kind = Kind.REGEXP_CONCATENATION;
if (exp1.kind == Kind.REGEXP_CONCATENATION && (exp1.exp2.kind == Kind.REGEXP_CHAR || exp1.exp2.kind == Kind.REGEXP_STRING) && (exp2.kind == Kind.REGEXP_CHAR || exp2.kind == Kind.REGEXP_STRING))
{
r.exp1 = exp1.exp1;
r.exp2 = MakeString(exp1.exp2, exp2);
}
else if ((exp1.kind == Kind.REGEXP_CHAR || exp1.kind == Kind.REGEXP_STRING) && exp2.kind == Kind.REGEXP_CONCATENATION && (exp2.exp1.kind == Kind.REGEXP_CHAR || exp2.exp1.kind == Kind.REGEXP_STRING))
{
r.exp1 = MakeString(exp1, exp2.exp1);
r.exp2 = exp2.exp2;
}
else
{
r.exp1 = exp1;
r.exp2 = exp2;
}
return r;
}
private static RegExp MakeString(RegExp exp1, RegExp exp2)
{
StringBuilder b = new StringBuilder();
if (exp1.kind == Kind.REGEXP_STRING)
{
b.Append(exp1.s);
}
else
{
b.AppendCodePoint(exp1.c);
}
if (exp2.kind == Kind.REGEXP_STRING)
{
b.Append(exp2.s);
}
else
{
b.AppendCodePoint(exp2.c);
}
return MakeString(b.ToString());
}
internal static RegExp MakeIntersection(RegExp exp1, RegExp exp2)
{
RegExp r = new RegExp();
r.kind = Kind.REGEXP_INTERSECTION;
r.exp1 = exp1;
r.exp2 = exp2;
return r;
}
internal static RegExp MakeOptional(RegExp exp)
{
RegExp r = new RegExp();
r.kind = Kind.REGEXP_OPTIONAL;
r.exp1 = exp;
return r;
}
internal static RegExp MakeRepeat(RegExp exp)
{
RegExp r = new RegExp();
r.kind = Kind.REGEXP_REPEAT;
r.exp1 = exp;
return r;
}
internal static RegExp MakeRepeat(RegExp exp, int min)
{
RegExp r = new RegExp();
r.kind = Kind.REGEXP_REPEAT_MIN;
r.exp1 = exp;
r.min = min;
return r;
}
internal static RegExp MakeRepeat(RegExp exp, int min, int max)
{
RegExp r = new RegExp();
r.kind = Kind.REGEXP_REPEAT_MINMAX;
r.exp1 = exp;
r.min = min;
r.max = max;
return r;
}
internal static RegExp MakeComplement(RegExp exp)
{
RegExp r = new RegExp();
r.kind = Kind.REGEXP_COMPLEMENT;
r.exp1 = exp;
return r;
}
internal static RegExp MakeChar(int c)
{
RegExp r = new RegExp();
r.kind = Kind.REGEXP_CHAR;
r.c = c;
return r;
}
internal static RegExp MakeCharRange(int from, int to)
{
if (from > to)
{
throw new System.ArgumentException("invalid range: from (" + from + ") cannot be > to (" + to + ")");
}
RegExp r = new RegExp();
r.kind = Kind.REGEXP_CHAR_RANGE;
r.from = from;
r.to = to;
return r;
}
internal static RegExp MakeAnyChar()
{
RegExp r = new RegExp();
r.kind = Kind.REGEXP_ANYCHAR;
return r;
}
internal static RegExp MakeEmpty()
{
RegExp r = new RegExp();
r.kind = Kind.REGEXP_EMPTY;
return r;
}
internal static RegExp MakeString(string s)
{
RegExp r = new RegExp();
r.kind = Kind.REGEXP_STRING;
r.s = s;
return r;
}
internal static RegExp MakeAnyString()
{
RegExp r = new RegExp();
r.kind = Kind.REGEXP_ANYSTRING;
return r;
}
internal static RegExp MakeAutomaton(string s)
{
RegExp r = new RegExp();
r.kind = Kind.REGEXP_AUTOMATON;
r.s = s;
return r;
}
internal static RegExp MakeInterval(int min, int max, int digits)
{
RegExp r = new RegExp();
r.kind = Kind.REGEXP_INTERVAL;
r.min = min;
r.max = max;
r.digits = digits;
return r;
}
private bool Peek(string s)
{
return More() && s.IndexOf(b.CodePointAt(pos)) != -1;
}
private bool Match(int c)
{
if (pos >= b.Length)
{
return false;
}
if (b.CodePointAt(pos) == c)
{
pos += Character.CharCount(c);
return true;
}
return false;
}
private bool More()
{
return pos < b.Length;
}
private int Next()
{
if (!More())
{
throw new ArgumentException("unexpected end-of-string");
}
int ch = b.CodePointAt(pos);
pos += Character.CharCount(ch);
return ch;
}
private bool Check(RegExpSyntax flag)
{
return (flags & flag) != 0;
}
internal RegExp ParseUnionExp()
{
RegExp e = ParseInterExp();
if (Match('|'))
{
e = MakeUnion(e, ParseUnionExp());
}
return e;
}
internal RegExp ParseInterExp()
{
RegExp e = ParseConcatExp();
if (Check(RegExpSyntax.INTERSECTION) && Match('&'))
{
e = MakeIntersection(e, ParseInterExp());
}
return e;
}
internal RegExp ParseConcatExp()
{
RegExp e = ParseRepeatExp();
if (More() && !Peek(")|") && (!Check(RegExpSyntax.INTERSECTION) || !Peek("&")))
{
e = MakeConcatenation(e, ParseConcatExp());
}
return e;
}
internal RegExp ParseRepeatExp()
{
RegExp e = ParseComplExp();
while (Peek("?*+{"))
{
if (Match('?'))
{
e = MakeOptional(e);
}
else if (Match('*'))
{
e = MakeRepeat(e);
}
else if (Match('+'))
{
e = MakeRepeat(e, 1);
}
else if (Match('{'))
{
int start = pos;
while (Peek("0123456789"))
{
Next();
}
if (start == pos)
{
throw new ArgumentException("integer expected at position " + pos);
}
int n = Convert.ToInt32(b.Substring(start, pos - start), CultureInfo.InvariantCulture);
int m = -1;
if (Match(','))
{
start = pos;
while (Peek("0123456789"))
{
Next();
}
if (start != pos)
{
m = Convert.ToInt32(b.Substring(start, pos - start), CultureInfo.InvariantCulture);
}
}
else
{
m = n;
}
if (!Match('}'))
{
throw new ArgumentException("expected '}' at position " + pos);
}
if (m == -1)
{
e = MakeRepeat(e, n);
}
else
{
e = MakeRepeat(e, n, m);
}
}
}
return e;
}
internal RegExp ParseComplExp()
{
if (Check(RegExpSyntax.COMPLEMENT) && Match('~'))
{
return MakeComplement(ParseComplExp());
}
else
{
return ParseCharClassExp();
}
}
internal RegExp ParseCharClassExp()
{
if (Match('['))
{
bool negate = false;
if (Match('^'))
{
negate = true;
}
RegExp e = ParseCharClasses();
if (negate)
{
e = MakeIntersection(MakeAnyChar(), MakeComplement(e));
}
if (!Match(']'))
{
throw new ArgumentException("expected ']' at position " + pos);
}
return e;
}
else
{
return ParseSimpleExp();
}
}
internal RegExp ParseCharClasses()
{
RegExp e = ParseCharClass();
while (More() && !Peek("]"))
{
e = MakeUnion(e, ParseCharClass());
}
return e;
}
internal RegExp ParseCharClass()
{
int c = ParseCharExp();
if (Match('-'))
{
return MakeCharRange(c, ParseCharExp());
}
else
{
return MakeChar(c);
}
}
internal RegExp ParseSimpleExp()
{
if (Match('.'))
{
return MakeAnyChar();
}
else if (Check(RegExpSyntax.EMPTY) && Match('#'))
{
return MakeEmpty();
}
else if (Check(RegExpSyntax.ANYSTRING) && Match('@'))
{
return MakeAnyString();
}
else if (Match('"'))
{
int start = pos;
while (More() && !Peek("\""))
{
Next();
}
if (!Match('"'))
{
throw new ArgumentException("expected '\"' at position " + pos);
}
return MakeString(b.Substring(start, pos - 1 - start));
}
else if (Match('('))
{
if (Match(')'))
{
return MakeString("");
}
RegExp e = ParseUnionExp();
if (!Match(')'))
{
throw new ArgumentException("expected ')' at position " + pos);
}
return e;
}
else if ((Check(RegExpSyntax.AUTOMATON) || Check(RegExpSyntax.INTERVAL)) && Match('<'))
{
int start = pos;
while (More() && !Peek(">"))
{
Next();
}
if (!Match('>'))
{
throw new ArgumentException("expected '>' at position " + pos);
}
string s = b.Substring(start, pos - 1 - start);
int i = s.IndexOf('-');
if (i == -1)
{
if (!Check(RegExpSyntax.AUTOMATON))
{
throw new ArgumentException("interval syntax error at position " + (pos - 1));
}
return MakeAutomaton(s);
}
else
{
if (!Check(RegExpSyntax.INTERVAL))
{
throw new ArgumentException("illegal identifier at position " + (pos - 1));
}
try
{
if (i == 0 || i == s.Length - 1 || i != s.LastIndexOf('-'))
{
throw new FormatException();
}
string smin = s.Substring(0, i);
string smax = s.Substring(i + 1, s.Length - (i + 1));
int imin = Convert.ToInt32(smin, CultureInfo.InvariantCulture);
int imax = Convert.ToInt32(smax, CultureInfo.InvariantCulture);
int digits;
if (smin.Length == smax.Length)
{
digits = smin.Length;
}
else
{
digits = 0;
}
if (imin > imax)
{
int t = imin;
imin = imax;
imax = t;
}
return MakeInterval(imin, imax, digits);
}
#pragma warning disable 168
catch (System.FormatException e)
#pragma warning restore 168
{
throw new ArgumentException("interval syntax error at position " + (pos - 1), e);
}
}
}
else
{
return MakeChar(ParseCharExp());
}
}
internal int ParseCharExp()
{
Match('\\');
return Next();
}
}
}
| |
#region Copyright (c) 2004 Ian Davis and James Carlyle
/*------------------------------------------------------------------------------
COPYRIGHT AND PERMISSION NOTICE
Copyright (c) 2004 Ian Davis and James Carlyle
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------*/
#endregion
namespace SemPlan.Spiral.Tests.Core {
using NUnit.Framework;
using System;
/// <summary>
/// Compares a list of NTriples against an Expected list to see if the two lists are equivilent
/// </summary>
/// <remarks>
/// $Id: NTripleListVerifierTest.cs,v 1.2 2005/05/26 14:24:30 ian Exp $
///</remarks>
[TestFixture]
public class NTripleListVerifierTest {
[Test]
public void VerifySingleUUUMatch() {
NTripleListVerifier verifier = new NTripleListVerifier();
verifier.Expect("<http://example/subj> <http://example/pred> <http://example/obj> .");
verifier.Receive("<http://example/subj> <http://example/pred> <http://example/obj> .");
Assert.IsTrue( verifier.Verify() );
}
[Test]
public void VerifySingleUUUMismatch() {
NTripleListVerifier verifier = new NTripleListVerifier();
verifier.Expect("<http://example/subj> <http://example/pred> <http://example/obj> .");
verifier.Receive("<http://example/subj> <http://example/pred> <http://example/obj2> .");
Assert.IsFalse( verifier.Verify() );
}
[Test]
public void VerifySingleUUPMatch() {
NTripleListVerifier verifier = new NTripleListVerifier();
verifier.Expect("<http://example/subj> <http://example/pred> \"fizz\" .");
verifier.Receive("<http://example/subj> <http://example/pred> \"fizz\" .");
Assert.IsTrue( verifier.Verify() );
}
[Test]
public void VerifySingleUUPMatchWithLanguage() {
NTripleListVerifier verifier = new NTripleListVerifier();
verifier.Expect("<http://example/subj> <http://example/pred> \"fizz\"@en .");
verifier.Receive("<http://example/subj> <http://example/pred> \"fizz\"@en .");
Assert.IsTrue( verifier.Verify() );
}
[Test]
public void VerifySingleUUPMismatchByLexicalValue() {
NTripleListVerifier verifier = new NTripleListVerifier();
verifier.Expect("<http://example/subj> <http://example/pred> \"fizz\" .");
verifier.Receive("<http://example/subj> <http://example/pred> \"bang\" .");
Assert.IsFalse( verifier.Verify() );
}
[Test]
public void VerifySingleUUPMismatchWithLanguageByLexicalValue() {
NTripleListVerifier verifier = new NTripleListVerifier();
verifier.Expect("<http://example/subj> <http://example/pred> \"fizz\"@en .");
verifier.Receive("<http://example/subj> <http://example/pred> \"bang\"@en .");
Assert.IsFalse( verifier.Verify() );
}
[Test]
public void VerifySingleUUPMismatchByLanguage() {
NTripleListVerifier verifier = new NTripleListVerifier();
verifier.Expect("<http://example/subj> <http://example/pred> \"fizz\"@en .");
verifier.Receive("<http://example/subj> <http://example/pred> \"fizz\"@fr .");
Assert.IsFalse( verifier.Verify() );
}
[Test]
public void VerifySingleUUTMatch() {
NTripleListVerifier verifier = new NTripleListVerifier();
verifier.Expect("<http://example/subj> <http://example/pred> \"fizz\"^^<http://example.com/type> .");
verifier.Receive("<http://example/subj> <http://example/pred> \"fizz\"^^<http://example.com/type> .");
Assert.IsTrue( verifier.Verify() );
}
[Test]
public void VerifySingleUUTMismatchByLexicalValue() {
NTripleListVerifier verifier = new NTripleListVerifier();
verifier.Expect("<http://example/subj> <http://example/pred> \"fizz\"^^<http://example.com/type> .");
verifier.Receive("<http://example/subj> <http://example/pred> \"bang\"^^<http://example.com/type> .");
Assert.IsFalse( verifier.Verify() );
}
[Test]
public void VerifySingleUUTMismatchByDatatype() {
NTripleListVerifier verifier = new NTripleListVerifier();
verifier.Expect("<http://example/subj> <http://example/pred> \"fizz\"^^<http://example.com/type> .");
verifier.Receive("<http://example/subj> <http://example/pred> \"fizz\"^^<http://example.com/foo> .");
Assert.IsFalse( verifier.Verify() );
}
[Test]
public void VerifyNonBlankNodeTriplesComparedInAnyOrder() {
NTripleListVerifier verifier = new NTripleListVerifier();
verifier.Expect("<http://example/subj> <http://example/pred> \"fizz\"@en .");
verifier.Expect("<http://example/subj> <http://example/pred> \"fizz\"^^<http://example.com/type> .");
verifier.Expect("<http://example/subj> <http://example/pred> <http://example/obj> .");
verifier.Receive("<http://example/subj> <http://example/pred> <http://example/obj> .");
verifier.Receive("<http://example/subj> <http://example/pred> \"fizz\"^^<http://example.com/type> .");
verifier.Receive("<http://example/subj> <http://example/pred> \"fizz\"@en .");
Assert.IsTrue( verifier.Verify() );
}
[Test]
public void VerifyRecievedCountMustNotBeLessThanExpected() {
NTripleListVerifier verifier = new NTripleListVerifier();
verifier.Expect("<http://example/subj> <http://example/pred> \"fizz\"@en .");
verifier.Expect("<http://example/subj> <http://example/pred> \"fizz\"@fr .");
verifier.Expect("<http://example/subj> <http://example/pred> \"fizz\"^^<http://example.com/type> .");
verifier.Receive("<http://example/subj> <http://example/pred> \"fizz\"^^<http://example.com/type> .");
verifier.Receive("<http://example/subj> <http://example/pred> \"fizz\"@en .");
Assert.IsFalse( verifier.Verify() );
}
[Test]
public void VerifyRecievedCountMustNotBeGreaterThanExpected() {
NTripleListVerifier verifier = new NTripleListVerifier();
verifier.Expect("<http://example/subj> <http://example/pred> \"fizz\"^^<http://example.com/type> .");
verifier.Receive("<http://example/subj> <http://example/pred> \"fizz\"^^<http://example.com/type> .");
verifier.Receive("<http://example/subj> <http://example/pred> \"fizz\"@en .");
Assert.IsFalse( verifier.Verify() );
}
[Test]
public void VerifyConsidersDuplicateReceivedTriples() {
NTripleListVerifier verifier = new NTripleListVerifier();
verifier.Expect("<http://example/subj> <http://example/pred> \"fizz\"^^<http://example.com/type> .");
verifier.Receive("<http://example/subj> <http://example/pred> \"fizz\"^^<http://example.com/type> .");
verifier.Receive("<http://example/subj> <http://example/pred> \"fizz\"^^<http://example.com/type> .");
Assert.IsFalse( verifier.Verify() );
}
[Test]
public void VerifySingleUUBMatchWithSameNodeId() {
NTripleListVerifier verifier = new NTripleListVerifier();
verifier.Expect("<http://example/subj> <http://example/pred> _:genid1 .");
verifier.Receive("<http://example/subj> <http://example/pred> _:genid1 .");
Assert.IsTrue( verifier.Verify() );
}
[Test]
public void VerifySingleUUBMatchWithDifferentNodeId() {
NTripleListVerifier verifier = new NTripleListVerifier();
verifier.Expect("<http://example/subj> <http://example/pred> _:genid1 .");
verifier.Receive("<http://example/subj> <http://example/pred> _:gook .");
Assert.IsTrue( verifier.Verify() );
}
[Test]
public void VerifyMultipleUUBMatchWithSameNodeId() {
NTripleListVerifier verifier = new NTripleListVerifier();
verifier.Expect("<http://example/subj> <http://example/pred> _:genid1 .");
verifier.Expect("<http://example/subj> <http://example/pred2> _:genid1 .");
verifier.Receive("<http://example/subj> <http://example/pred> _:genid1 .");
verifier.Receive("<http://example/subj> <http://example/pred2> _:genid1 .");
Assert.IsTrue( verifier.Verify() );
}
[Test]
public void VerifyMultipleUUBMatchWithDifferentNodeId() {
NTripleListVerifier verifier = new NTripleListVerifier();
verifier.Expect("<http://example/subj> <http://example/pred> _:genid1 .");
verifier.Expect("<http://example/subj> <http://example/pred2> _:genid1 .");
verifier.Receive("<http://example/subj> <http://example/pred> _:jim .");
verifier.Receive("<http://example/subj> <http://example/pred2> _:jim .");
Assert.IsTrue( verifier.Verify() );
}
[Test]
public void VerifySingleBUUMatchWithSameNodeId() {
NTripleListVerifier verifier = new NTripleListVerifier();
verifier.Expect("_:genid1 <http://example/pred> <http://example/obj> .");
verifier.Receive("_:genid1 <http://example/pred> <http://example/obj> .");
Assert.IsTrue( verifier.Verify() );
}
[Test]
public void VerifySingleBUUMatchWithDifferentNodeId() {
NTripleListVerifier verifier = new NTripleListVerifier();
verifier.Expect("_:genid1 <http://example/pred> <http://example/obj> .");
verifier.Receive("_:jimbob <http://example/pred> <http://example/obj> .");
Assert.IsTrue( verifier.Verify() );
}
[Test]
public void VerifyMultipleBUUMatchWithSameNodeId() {
NTripleListVerifier verifier = new NTripleListVerifier();
verifier.Expect("_:genid1 <http://example/pred> <http://example/obj> .");
verifier.Expect("_:genid1 <http://example/pred2> <http://example/obj> .");
verifier.Receive("_:genid1 <http://example/pred> <http://example/obj> .");
verifier.Receive("_:genid1 <http://example/pred2> <http://example/obj> .");
Assert.IsTrue( verifier.Verify() );
}
[Test]
public void VerifyMultipleBUUMatchWithDifferentNodeId() {
NTripleListVerifier verifier = new NTripleListVerifier();
verifier.Expect("_:genid1 <http://example/pred> <http://example/obj> .");
verifier.Expect("_:genid1 <http://example/pred2> <http://example/obj> .");
verifier.Receive("_:buffy <http://example/pred> <http://example/obj> .");
verifier.Receive("_:buffy <http://example/pred2> <http://example/obj> .");
Assert.IsTrue( verifier.Verify() );
}
[Test]
public void VerifySingleBUBMatchWithSameNodeId() {
NTripleListVerifier verifier = new NTripleListVerifier();
verifier.Expect("_:genid1 <http://example/pred> _:genid1 .");
verifier.Receive("_:genid1 <http://example/pred> _:genid1 .");
Assert.IsTrue( verifier.Verify() );
}
[Test]
public void VerifySingleBUBMatchWithDifferentNodeId() {
NTripleListVerifier verifier = new NTripleListVerifier();
verifier.Expect("_:genid1 <http://example/pred> _:genid1 .");
verifier.Receive("_:buffy <http://example/pred> _:buffy .");
Assert.IsTrue( verifier.Verify() );
}
[Test]
public void VerifyMultipleBUBMatchWithSameNodeId() {
NTripleListVerifier verifier = new NTripleListVerifier();
verifier.Expect("_:genid1 <http://example/pred> _:genid1 .");
verifier.Expect("_:genid1 <http://example/pred2> _:genid1 .");
verifier.Receive("_:genid1 <http://example/pred> _:genid1 .");
verifier.Receive("_:genid1 <http://example/pred2> _:genid1 .");
Assert.IsTrue( verifier.Verify() );
}
[Test]
public void VerifyMultipleBUBMatchWithDifferentNodeId() {
NTripleListVerifier verifier = new NTripleListVerifier();
verifier.Expect("_:genid1 <http://example/pred> _:genid1 .");
verifier.Expect("_:genid1 <http://example/pred2> _:genid1 .");
verifier.Receive("_:buffy <http://example/pred> _:buffy .");
verifier.Receive("_:buffy <http://example/pred2> _:buffy .");
Assert.IsTrue( verifier.Verify() );
}
[Test]
public void VerifyMultipleUUBMatchWithTwoNodeIdsReceiveUsesSameIds() {
NTripleListVerifier verifier = new NTripleListVerifier();
verifier.Expect("<http://example/subj> <http://example/pred> _:genid1 .");
verifier.Expect("<http://example/subj> <http://example/pred2> _:genid2 .");
verifier.Receive("<http://example/subj> <http://example/pred> _:genid1 .");
verifier.Receive("<http://example/subj> <http://example/pred2> _:genid2 .");
Assert.IsTrue( verifier.Verify() );
}
[Test]
public void VerifyMultipleUUBMatchWithTwoNodeIdsReceiveUsesDifferentIds() {
NTripleListVerifier verifier = new NTripleListVerifier();
verifier.Expect("<http://example/subj> <http://example/pred> _:genid1 .");
verifier.Expect("<http://example/subj> <http://example/pred2> _:genid2 .");
verifier.Receive("<http://example/subj> <http://example/pred> _:buffy1 .");
verifier.Receive("<http://example/subj> <http://example/pred2> _:buffy2 .");
Assert.IsTrue( verifier.Verify() );
}
[Test]
public void VerifyMultipleUUBMatchWithTwoNodeIdsReceiveUsesDifferentIdsOutOfOrder() {
NTripleListVerifier verifier = new NTripleListVerifier();
verifier.Expect("<http://example/subj> <http://example/pred> _:genid1 .");
verifier.Expect("<http://example/subj> <http://example/pred2> _:genid2 .");
verifier.Receive("<http://example/subj> <http://example/pred2> _:buffy2 .");
verifier.Receive("<http://example/subj> <http://example/pred> _:buffy1 .");
Assert.IsTrue( verifier.Verify() );
}
[Test]
public void VerifyMultipleUUBMatchWithThreeNodeIdsReceiveUsesDifferentIdsOutOfOrder() {
NTripleListVerifier verifier = new NTripleListVerifier();
verifier.Expect("<http://example/subj> <http://example/pred> _:genid1 .");
verifier.Expect("<http://example/subj> <http://example/pred2> _:genid2 .");
verifier.Expect("<http://example/subj> <http://example/pred2> _:genid3 .");
verifier.Receive("<http://example/subj> <http://example/pred2> _:buffy2 .");
verifier.Receive("<http://example/subj> <http://example/pred2> _:buffy3 .");
verifier.Receive("<http://example/subj> <http://example/pred> _:buffy1 .");
Assert.IsTrue( verifier.Verify() );
}
[Test]
public void VerifyMultipleBUUMatchWithTwoNodeIdsReceiveUsesSameIds() {
NTripleListVerifier verifier = new NTripleListVerifier();
verifier.Expect("_:genid2 <http://example/pred> <http://example.com/obj> .");
verifier.Expect("_:genid1 <http://example/pred2> <http://example.com/obj> .");
verifier.Receive("_:genid2 <http://example/pred> <http://example.com/obj> .");
verifier.Receive("_:genid1 <http://example/pred2> <http://example.com/obj> .");
Assert.IsTrue( verifier.Verify() );
}
[Test]
public void VerifyMultipleBUUMatchWithTwoNodeIdsReceiveUsesDifferentIds() {
NTripleListVerifier verifier = new NTripleListVerifier();
verifier.Expect("_:genid2 <http://example/pred> <http://example.com/obj> .");
verifier.Expect("_:genid1 <http://example/pred2> <http://example.com/obj> .");
verifier.Receive("_:buffy2 <http://example/pred> <http://example.com/obj> .");
verifier.Receive("_:buffy1 <http://example/pred2> <http://example.com/obj> .");
Assert.IsTrue( verifier.Verify() );
}
[Test]
public void VerifyMultipleBUUMatchWithTwoNodeIdsReceiveUsesDifferentIdsOutOfOrder() {
NTripleListVerifier verifier = new NTripleListVerifier();
verifier.Expect("_:genid2 <http://example/pred> <http://example.com/obj> .");
verifier.Expect("_:genid1 <http://example/pred2> <http://example.com/obj> .");
verifier.Receive("_:buffy1 <http://example/pred2> <http://example.com/obj> .");
verifier.Receive("_:buffy2 <http://example/pred> <http://example.com/obj> .");
Assert.IsTrue( verifier.Verify() );
}
[Test]
public void VerifyMultipleBUUMatchWithThreeNodeIdsReceiveUsesDifferentIdsOutOfOrder() {
NTripleListVerifier verifier = new NTripleListVerifier();
verifier.Expect("_:genid2 <http://example/pred> <http://example.com/obj> .");
verifier.Expect("_:genid1 <http://example/pred2> <http://example.com/obj> .");
verifier.Expect("_:genid3 <http://example/pred2> <http://example.com/obj> .");
verifier.Receive("_:buffy1 <http://example/pred2> <http://example.com/obj> .");
verifier.Receive("_:buffy2 <http://example/pred> <http://example.com/obj> .");
verifier.Receive("_:buffy3 <http://example/pred2> <http://example.com/obj> .");
Assert.IsTrue( verifier.Verify() );
}
[Test]
public void VerifyMultipleBUBMatchWithThreeNodeIdsReceiveUsesDifferentIdsOutOfOrder() {
NTripleListVerifier verifier = new NTripleListVerifier();
verifier.Expect("_:genid2 <http://example/pred> _:genid1 .");
verifier.Expect("_:genid1 <http://example/pred2> _:genid2 .");
verifier.Expect("_:genid3 <http://example/pred2> <http://example.com/obj> .");
verifier.Receive("_:buffy3 <http://example/pred2> _:buffy2 .");
verifier.Receive("_:buffy2 <http://example/pred> _:buffy3 .");
verifier.Receive("_:buffy1 <http://example/pred2> <http://example.com/obj> .");
Assert.IsTrue( verifier.Verify() );
}
[Test]
public void VerifierNormalisesWhitespaceBetweenExpectedTripleComponents() {
NTripleListVerifier verifier = new NTripleListVerifier();
verifier.Expect("<http://example/subj> <http://example/pred> <http://example/obj> .");
verifier.Receive("<http://example/subj> <http://example/pred> <http://example/obj> .");
Assert.IsTrue( verifier.Verify() );
}
}
}
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.UnitTests.Config
{
using NLog.Conditions;
using NLog.Config;
using NLog.LayoutRenderers;
using NLog.Layouts;
using NLog.Targets;
using NLog.Targets.Wrappers;
using System;
using System.Globalization;
using System.IO;
using System.Text;
using Xunit;
public class TargetConfigurationTests : NLogTestBase
{
[Fact]
public void SimpleTest()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='d' type='Debug' layout='${message}' />
</targets>
</nlog>");
DebugTarget t = c.FindTargetByName("d") as DebugTarget;
Assert.NotNull(t);
Assert.Equal("d", t.Name);
SimpleLayout l = t.Layout as SimpleLayout;
Assert.Equal("${message}", l.Text);
Assert.NotNull(t.Layout);
Assert.Single(l.Renderers);
Assert.IsType<MessageLayoutRenderer>(l.Renderers[0]);
}
[Fact]
public void SimpleElementSyntaxTest()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target type='Debug'>
<name>d</name>
<layout>${message}</layout>
</target>
</targets>
</nlog>");
DebugTarget t = c.FindTargetByName("d") as DebugTarget;
Assert.NotNull(t);
Assert.Equal("d", t.Name);
SimpleLayout l = t.Layout as SimpleLayout;
Assert.Equal("${message}", l.Text);
Assert.NotNull(t.Layout);
Assert.Single(l.Renderers);
Assert.IsType<MessageLayoutRenderer>(l.Renderers[0]);
}
[Fact]
public void TargetWithLayoutHasUniqueLayout()
{
var target1 = new StructuredDebugTarget();
var target2 = new StructuredDebugTarget();
var simpleLayout1 = target1.Layout as SimpleLayout;
var simpleLayout2 = target2.Layout as SimpleLayout;
// Ensure the default Layout for two Targets are not reusing objects
// As it would cause havoc with initializing / closing lifetime-events
Assert.NotSame(simpleLayout1, simpleLayout2);
Assert.Equal(simpleLayout1.Renderers.Count, simpleLayout1.Renderers.Count);
for (int i = 0; i < simpleLayout1.Renderers.Count; ++i)
{
Assert.NotSame(simpleLayout1.Renderers[i], simpleLayout2.Renderers[i]);
}
}
[Fact]
public void NestedXmlConfigElementTest()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<extensions>
<add type='" + typeof(StructuredDebugTarget).AssemblyQualifiedName + @"' />
</extensions>
<targets>
<target type='StructuredDebugTarget'>
<name>structuredTgt</name>
<layout>${message}</layout>
<config platform='any'>
<parameter name='param1' />
</config>
</target>
</targets>
</nlog>");
var t = c.FindTargetByName("structuredTgt") as StructuredDebugTarget;
Assert.NotNull(t);
Assert.Equal("any", t.Config.Platform);
Assert.Equal("param1", t.Config.Parameter.Name);
}
[Fact]
public void ArrayParameterTest()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target type='MethodCall' name='mct'>
<parameter name='p1' layout='${message}' />
<parameter name='p2' layout='${level}' />
<parameter name='p3' layout='${logger}' />
</target>
</targets>
</nlog>");
var t = c.FindTargetByName("mct") as MethodCallTarget;
Assert.NotNull(t);
Assert.Equal(3, t.Parameters.Count);
Assert.Equal("p1", t.Parameters[0].Name);
Assert.Equal("${message}", t.Parameters[0].Layout.ToString());
Assert.Equal("p2", t.Parameters[1].Name);
Assert.Equal("${level}", t.Parameters[1].Layout.ToString());
Assert.Equal("p3", t.Parameters[2].Name);
Assert.Equal("${logger}", t.Parameters[2].Layout.ToString());
}
[Fact]
public void ArrayElementParameterTest()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target type='MethodCall' name='mct'>
<parameter>
<name>p1</name>
<layout>${message}</layout>
</parameter>
<parameter>
<name>p2</name>
<layout type='CsvLayout'>
<column name='x' layout='${message}' />
<column name='y' layout='${level}' />
</layout>
</parameter>
<parameter>
<name>p3</name>
<layout>${logger}</layout>
</parameter>
</target>
</targets>
</nlog>");
var t = c.FindTargetByName("mct") as MethodCallTarget;
Assert.NotNull(t);
Assert.Equal(3, t.Parameters.Count);
Assert.Equal("p1", t.Parameters[0].Name);
Assert.Equal("${message}", t.Parameters[0].Layout.ToString());
Assert.Equal("p2", t.Parameters[1].Name);
CsvLayout csvLayout = t.Parameters[1].Layout as CsvLayout;
Assert.NotNull(csvLayout);
Assert.Equal(2, csvLayout.Columns.Count);
Assert.Equal("x", csvLayout.Columns[0].Name);
Assert.Equal("y", csvLayout.Columns[1].Name);
Assert.Equal("p3", t.Parameters[2].Name);
Assert.Equal("${logger}", t.Parameters[2].Layout.ToString());
}
[Fact]
public void SimpleTest2()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='d' type='Debug' layout='${message} ${level}' />
</targets>
</nlog>");
DebugTarget t = c.FindTargetByName("d") as DebugTarget;
Assert.NotNull(t);
Assert.Equal("d", t.Name);
SimpleLayout l = t.Layout as SimpleLayout;
Assert.Equal("${message} ${level}", l.Text);
Assert.NotNull(l);
Assert.Equal(3, l.Renderers.Count);
Assert.IsType<MessageLayoutRenderer>(l.Renderers[0]);
Assert.IsType<LiteralLayoutRenderer>(l.Renderers[1]);
Assert.IsType<LevelLayoutRenderer>(l.Renderers[2]);
Assert.Equal(" ", ((LiteralLayoutRenderer)l.Renderers[1]).Text);
}
[Fact]
public void WrapperTest()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<wrapper-target name='b' type='BufferingWrapper' bufferSize='19'>
<wrapper name='a' type='AsyncWrapper'>
<target name='c' type='Debug' layout='${message}' />
</wrapper>
</wrapper-target>
</targets>
</nlog>");
Assert.NotNull(c.FindTargetByName("a"));
Assert.NotNull(c.FindTargetByName("b"));
Assert.NotNull(c.FindTargetByName("c"));
Assert.IsType<BufferingTargetWrapper>(c.FindTargetByName("b"));
Assert.IsType<AsyncTargetWrapper>(c.FindTargetByName("a"));
Assert.IsType<DebugTarget>(c.FindTargetByName("c"));
BufferingTargetWrapper btw = c.FindTargetByName("b") as BufferingTargetWrapper;
AsyncTargetWrapper atw = c.FindTargetByName("a") as AsyncTargetWrapper;
DebugTarget dt = c.FindTargetByName("c") as DebugTarget;
Assert.Same(atw, btw.WrappedTarget);
Assert.Same(dt, atw.WrappedTarget);
Assert.Equal(19, btw.BufferSize);
}
[Fact]
public void WrapperRefTest()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='c' type='Debug' layout='${message}' />
<wrapper name='a' type='AsyncWrapper'>
<target-ref name='c' />
</wrapper>
<wrapper-target name='b' type='BufferingWrapper' bufferSize='19'>
<wrapper-target-ref name='a' />
</wrapper-target>
</targets>
</nlog>");
Assert.NotNull(c.FindTargetByName("a"));
Assert.NotNull(c.FindTargetByName("b"));
Assert.NotNull(c.FindTargetByName("c"));
Assert.IsType<BufferingTargetWrapper>(c.FindTargetByName("b"));
Assert.IsType<AsyncTargetWrapper>(c.FindTargetByName("a"));
Assert.IsType<DebugTarget>(c.FindTargetByName("c"));
BufferingTargetWrapper btw = c.FindTargetByName("b") as BufferingTargetWrapper;
AsyncTargetWrapper atw = c.FindTargetByName("a") as AsyncTargetWrapper;
DebugTarget dt = c.FindTargetByName("c") as DebugTarget;
Assert.Same(atw, btw.WrappedTarget);
Assert.Same(dt, atw.WrappedTarget);
Assert.Equal(19, btw.BufferSize);
}
[Fact]
public void CompoundTest()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<compound-target name='rr' type='RoundRobinGroup'>
<target name='d1' type='Debug' layout='${message}1' />
<target name='d2' type='Debug' layout='${message}2' />
<target name='d3' type='Debug' layout='${message}3' />
<target name='d4' type='Debug' layout='${message}4' />
</compound-target>
</targets>
</nlog>");
Assert.NotNull(c.FindTargetByName("rr"));
Assert.NotNull(c.FindTargetByName("d1"));
Assert.NotNull(c.FindTargetByName("d2"));
Assert.NotNull(c.FindTargetByName("d3"));
Assert.NotNull(c.FindTargetByName("d4"));
Assert.IsType<RoundRobinGroupTarget>(c.FindTargetByName("rr"));
Assert.IsType<DebugTarget>(c.FindTargetByName("d1"));
Assert.IsType<DebugTarget>(c.FindTargetByName("d2"));
Assert.IsType<DebugTarget>(c.FindTargetByName("d3"));
Assert.IsType<DebugTarget>(c.FindTargetByName("d4"));
RoundRobinGroupTarget rr = c.FindTargetByName("rr") as RoundRobinGroupTarget;
DebugTarget d1 = c.FindTargetByName("d1") as DebugTarget;
DebugTarget d2 = c.FindTargetByName("d2") as DebugTarget;
DebugTarget d3 = c.FindTargetByName("d3") as DebugTarget;
DebugTarget d4 = c.FindTargetByName("d4") as DebugTarget;
Assert.Equal(4, rr.Targets.Count);
Assert.Same(d1, rr.Targets[0]);
Assert.Same(d2, rr.Targets[1]);
Assert.Same(d3, rr.Targets[2]);
Assert.Same(d4, rr.Targets[3]);
Assert.Equal("${message}1", ((SimpleLayout)d1.Layout).Text);
Assert.Equal("${message}2", ((SimpleLayout)d2.Layout).Text);
Assert.Equal("${message}3", ((SimpleLayout)d3.Layout).Text);
Assert.Equal("${message}4", ((SimpleLayout)d4.Layout).Text);
}
[Fact]
public void CompoundRefTest()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='d1' type='Debug' layout='${message}1' />
<target name='d2' type='Debug' layout='${message}2' />
<target name='d3' type='Debug' layout='${message}3' />
<target name='d4' type='Debug' layout='${message}4' />
<compound-target name='rr' type='RoundRobinGroup'>
<target-ref name='d1' />
<target-ref name='d2' />
<target-ref name='d3' />
<target-ref name='d4' />
</compound-target>
</targets>
</nlog>");
Assert.NotNull(c.FindTargetByName("rr"));
Assert.NotNull(c.FindTargetByName("d1"));
Assert.NotNull(c.FindTargetByName("d2"));
Assert.NotNull(c.FindTargetByName("d3"));
Assert.NotNull(c.FindTargetByName("d4"));
Assert.IsType<RoundRobinGroupTarget>(c.FindTargetByName("rr"));
Assert.IsType<DebugTarget>(c.FindTargetByName("d1"));
Assert.IsType<DebugTarget>(c.FindTargetByName("d2"));
Assert.IsType<DebugTarget>(c.FindTargetByName("d3"));
Assert.IsType<DebugTarget>(c.FindTargetByName("d4"));
RoundRobinGroupTarget rr = c.FindTargetByName("rr") as RoundRobinGroupTarget;
DebugTarget d1 = c.FindTargetByName("d1") as DebugTarget;
DebugTarget d2 = c.FindTargetByName("d2") as DebugTarget;
DebugTarget d3 = c.FindTargetByName("d3") as DebugTarget;
DebugTarget d4 = c.FindTargetByName("d4") as DebugTarget;
Assert.Equal(4, rr.Targets.Count);
Assert.Same(d1, rr.Targets[0]);
Assert.Same(d2, rr.Targets[1]);
Assert.Same(d3, rr.Targets[2]);
Assert.Same(d4, rr.Targets[3]);
Assert.Equal("${message}1", ((SimpleLayout)d1.Layout).Text);
Assert.Equal("${message}2", ((SimpleLayout)d2.Layout).Text);
Assert.Equal("${message}3", ((SimpleLayout)d3.Layout).Text);
Assert.Equal("${message}4", ((SimpleLayout)d4.Layout).Text);
}
[Fact]
public void AsyncWrappersTest()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets async='true'>
<target type='Debug' name='d' />
<target type='Debug' name='d2' />
</targets>
</nlog>");
var t = c.FindTargetByName("d") as AsyncTargetWrapper;
Assert.NotNull(t);
Assert.Equal("d", t.Name);
var wrappedTarget = t.WrappedTarget as DebugTarget;
Assert.NotNull(wrappedTarget);
Assert.Equal("d_wrapped", wrappedTarget.Name);
t = c.FindTargetByName("d2") as AsyncTargetWrapper;
Assert.NotNull(t);
Assert.Equal("d2", t.Name);
wrappedTarget = t.WrappedTarget as DebugTarget;
Assert.NotNull(wrappedTarget);
Assert.Equal("d2_wrapped", wrappedTarget.Name);
}
[Fact]
public void UnnamedWrappedTargetTest()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets async='true'>
<target type='AsyncWrapper' name='d'>
<target type='Debug' />
</target>
</targets>
</nlog>");
var t = c.FindTargetByName("d") as AsyncTargetWrapper;
Assert.NotNull(t);
Assert.Equal("d", t.Name);
var wrappedTarget = t.WrappedTarget as DebugTarget;
Assert.NotNull(wrappedTarget);
Assert.Equal("d_wrapped", wrappedTarget.Name);
}
[Fact]
public void DefaultTargetParametersTest()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<default-target-parameters type='Debug' layout='x${message}x' />
<target type='Debug' name='d' />
<target type='Debug' name='d2' />
</targets>
</nlog>");
var t = c.FindTargetByName("d") as DebugTarget;
Assert.NotNull(t);
Assert.Equal("x${message}x", t.Layout.ToString());
t = c.FindTargetByName("d2") as DebugTarget;
Assert.NotNull(t);
Assert.Equal("x${message}x", t.Layout.ToString());
}
[Fact]
public void DefaultTargetParametersOnWrappedTargetTest()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<default-target-parameters type='Debug' layout='x${message}x' />
<target type='BufferingWrapper' name='buf1'>
<target type='Debug' name='d1' />
</target>
</targets>
</nlog>");
var wrap = c.FindTargetByName("buf1") as BufferingTargetWrapper;
Assert.NotNull(wrap);
Assert.NotNull(wrap.WrappedTarget);
var t = wrap.WrappedTarget as DebugTarget;
Assert.NotNull(t);
Assert.Equal("x${message}x", t.Layout.ToString());
}
[Fact]
public void DefaultWrapperTest()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<default-wrapper type='BufferingWrapper'>
<wrapper type='RetryingWrapper' />
</default-wrapper>
<target type='Debug' name='d' layout='${level}' />
<target type='Debug' name='d2' layout='${level}' />
</targets>
</nlog>");
var bufferingTargetWrapper = c.FindTargetByName("d") as BufferingTargetWrapper;
Assert.NotNull(bufferingTargetWrapper);
var retryingTargetWrapper = bufferingTargetWrapper.WrappedTarget as RetryingTargetWrapper;
Assert.NotNull(retryingTargetWrapper);
Assert.Null(retryingTargetWrapper.Name);
var debugTarget = retryingTargetWrapper.WrappedTarget as DebugTarget;
Assert.NotNull(debugTarget);
Assert.Equal("d_wrapped", debugTarget.Name);
Assert.Equal("${level}", debugTarget.Layout.ToString());
var debugTarget2 = c.FindTargetByName<DebugTarget>("d");
Assert.Same(debugTarget, debugTarget2);
}
[Fact]
public void DontThrowExceptionWhenArchiveEverySetByDefaultParameters()
{
var fileName = Path.GetFileNameWithoutExtension(Path.GetTempFileName()) + ".log";
try
{
var logFactory = new LogFactory().Setup().LoadConfigurationFromXml($@"
<nlog throwExceptions='true'>
<targets>
<default-target-parameters
type='File'
concurrentWrites='true'
keepFileOpen='true'
maxArchiveFiles='5'
archiveNumbering='Rolling'
archiveEvery='Day' />
<target fileName='{fileName}'
name = 'file'
type = 'File' />
</targets>
<rules>
<logger name='*' writeTo='file'/>
</rules>
</nlog> ").LogFactory;
logFactory.GetLogger("TestLogger").Info("DefaultFileTargetParametersTests.DontThrowExceptionWhenArchiveEverySetByDefaultParameters is true");
}
finally
{
if (File.Exists(fileName))
File.Delete(fileName);
}
}
[Fact]
public void DontThrowExceptionsWhenMissingRequiredParameters()
{
using (new NoThrowNLogExceptions())
{
var logFactory = new LogFactory().Setup().LoadConfigurationFromXml($@"
<nlog>
<targets>
<target type='bufferingwrapper' name='mytarget'>
<target type='unknowntargettype' name='badtarget' />
</target>
</targets>
<rules>
<logger name='*' writeTo='mytarget'/>
</rules>
</nlog>").LogFactory;
logFactory.GetLogger(nameof(DontThrowExceptionsWhenMissingRequiredParameters)).Info("Test");
}
}
[Fact]
public void DataTypesTest()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<extensions>
<add type='" + typeof(MyTarget).AssemblyQualifiedName + @"' />
</extensions>
<targets>
<target type='MyTarget' name='myTarget'
byteProperty='42'
int16Property='42'
int32Property='42'
int64Property='42000000000'
stringProperty='foobar'
boolProperty='true'
doubleProperty='3.14159'
floatProperty='3.14159'
enumProperty='Value3'
flagsEnumProperty='Value1,Value3'
encodingProperty='utf-8'
cultureProperty='en-US'
typeProperty='System.Int32'
layoutProperty='${level}'
conditionProperty=""starts-with(message, 'x')""
uriProperty='http://nlog-project.org'
lineEndingModeProperty='default'
/>
</targets>
</nlog>");
var myTarget = c.FindTargetByName("myTarget") as MyTarget;
Assert.NotNull(myTarget);
Assert.Equal((byte)42, myTarget.ByteProperty);
Assert.Equal((short)42, myTarget.Int16Property);
Assert.Equal(42, myTarget.Int32Property);
Assert.Equal(42000000000L, myTarget.Int64Property);
Assert.Equal("foobar", myTarget.StringProperty);
Assert.True(myTarget.BoolProperty);
Assert.Equal(3.14159, myTarget.DoubleProperty);
Assert.Equal(3.14159f, myTarget.FloatProperty);
Assert.Equal(MyEnum.Value3, myTarget.EnumProperty);
Assert.Equal(MyFlagsEnum.Value1 | MyFlagsEnum.Value3, myTarget.FlagsEnumProperty);
Assert.Equal(Encoding.UTF8, myTarget.EncodingProperty);
Assert.Equal("en-US", myTarget.CultureProperty.Name);
Assert.Equal(typeof(int), myTarget.TypeProperty);
Assert.Equal("${level}", myTarget.LayoutProperty.ToString());
Assert.Equal("starts-with(message, 'x')", myTarget.ConditionProperty.ToString());
Assert.Equal(new Uri("http://nlog-project.org"), myTarget.UriProperty);
Assert.Equal(LineEndingMode.Default, myTarget.LineEndingModeProperty);
}
[Fact]
public void NullableDataTypesTest()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<extensions>
<add type='" + typeof(MyNullableTarget).AssemblyQualifiedName + @"' />
</extensions>
<targets>
<target type='MyNullableTarget' name='myTarget'
byteProperty='42'
int16Property='42'
int32Property='42'
int64Property='42000000000'
stringProperty='foobar'
boolProperty='true'
doubleProperty='3.14159'
floatProperty='3.14159'
enumProperty='Value3'
flagsEnumProperty='Value1,Value3'
encodingProperty='utf-8'
cultureProperty='en-US'
typeProperty='System.Int32'
layoutProperty='${level}'
conditionProperty=""starts-with(message, 'x')""
/>
</targets>
</nlog>");
var myTarget = c.FindTargetByName("myTarget") as MyNullableTarget;
Assert.NotNull(myTarget);
Assert.Equal((byte)42, myTarget.ByteProperty);
Assert.Equal((short)42, myTarget.Int16Property);
Assert.Equal(42, myTarget.Int32Property);
Assert.Equal(42000000000L, myTarget.Int64Property);
Assert.Equal("foobar", myTarget.StringProperty);
Assert.True(myTarget.BoolProperty);
Assert.Equal(3.14159, myTarget.DoubleProperty);
Assert.Equal(3.14159f, myTarget.FloatProperty);
Assert.Equal(MyEnum.Value3, myTarget.EnumProperty);
Assert.Equal(MyFlagsEnum.Value1 | MyFlagsEnum.Value3, myTarget.FlagsEnumProperty);
Assert.Equal(Encoding.UTF8, myTarget.EncodingProperty);
Assert.Equal("en-US", myTarget.CultureProperty.Name);
Assert.Equal(typeof(int), myTarget.TypeProperty);
Assert.Equal("${level}", myTarget.LayoutProperty.ToString());
Assert.Equal("starts-with(message, 'x')", myTarget.ConditionProperty.ToString());
}
[Target("MyTarget")]
public class MyTarget : Target
{
public byte ByteProperty { get; set; }
public short Int16Property { get; set; }
public int Int32Property { get; set; }
public long Int64Property { get; set; }
public string StringProperty { get; set; }
public bool BoolProperty { get; set; }
public double DoubleProperty { get; set; }
public float FloatProperty { get; set; }
public MyEnum EnumProperty { get; set; }
public MyFlagsEnum FlagsEnumProperty { get; set; }
public Encoding EncodingProperty { get; set; }
public CultureInfo CultureProperty { get; set; }
public Type TypeProperty { get; set; }
public Layout LayoutProperty { get; set; }
public ConditionExpression ConditionProperty { get; set; }
public Uri UriProperty { get; set; }
public LineEndingMode LineEndingModeProperty { get; set; }
public MyTarget() : base()
{
}
public MyTarget(string name) : this()
{
Name = name;
}
}
[Target("MyNullableTarget")]
public class MyNullableTarget : Target
{
public byte? ByteProperty { get; set; }
public short? Int16Property { get; set; }
public int? Int32Property { get; set; }
public long? Int64Property { get; set; }
public string StringProperty { get; set; }
public bool? BoolProperty { get; set; }
public double? DoubleProperty { get; set; }
public float? FloatProperty { get; set; }
public MyEnum? EnumProperty { get; set; }
public MyFlagsEnum? FlagsEnumProperty { get; set; }
public Encoding EncodingProperty { get; set; }
public CultureInfo CultureProperty { get; set; }
public Type TypeProperty { get; set; }
public Layout LayoutProperty { get; set; }
public ConditionExpression ConditionProperty { get; set; }
public MyNullableTarget() : base()
{
}
public MyNullableTarget(string name) : this()
{
Name = name;
}
}
public enum MyEnum
{
Value1,
Value2,
Value3,
}
[Flags]
public enum MyFlagsEnum
{
Value1 = 1,
Value2 = 2,
Value3 = 4,
}
[Target("StructuredDebugTarget")]
public class StructuredDebugTarget : TargetWithLayout
{
public StructuredDebugTargetConfig Config { get; set; }
public StructuredDebugTarget()
{
Config = new StructuredDebugTargetConfig();
}
}
public class StructuredDebugTargetConfig
{
public string Platform { get; set; }
public StructuredDebugTargetParameter Parameter { get; set; }
public StructuredDebugTargetConfig()
{
Parameter = new StructuredDebugTargetParameter();
}
}
public class StructuredDebugTargetParameter
{
public string Name { get; set; }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using hw.Helper;
namespace hw.DebugFormatter
{
public sealed class Profiler
{
sealed class Dumper
{
readonly int? _count;
readonly ProfileItem[] _data;
readonly TimeSpan _sumMax;
readonly TimeSpan _sumAll;
int _index;
TimeSpan _sum;
public Dumper(Profiler profiler, int? count, double hidden)
{
_count = count;
_data = profiler._profileItems.Values.OrderByDescending(x => x.Duration).ToArray();
_sumAll = _data.Sum(x => x.Duration);
_sumMax = new TimeSpan((long) (_sumAll.Ticks * (1.0 - hidden)));
_index = 0;
_sum = new TimeSpan();
}
public string Format()
{
if(_data.Length == 0)
return "\n=========== Profile empty ============\n";
var result = "";
for(; _index < _data.Length && _index != _count && _sum <= _sumMax; _index++)
{
var item = _data[_index];
result += item.Format(_index.ToString());
_sum += item.Duration;
}
var stringAligner = new StringAligner();
stringAligner.AddFloatingColumn("#");
stringAligner.AddFloatingColumn(" ");
stringAligner.AddFloatingColumn(" ");
stringAligner.AddFloatingColumn(" ");
result = "\n=========== Profile ==================\n" + stringAligner.Format(result);
result += "Total:\t" + _sumAll.Format3Digits();
if(_index < _data.Length)
result +=
" ("
+ (_data.Length - _index)
+ " not-shown-items "
+ (_sumAll - _sum).Format3Digits()
+ ")";
result += "\n======================================\n";
return result;
}
}
/// <summary>
/// Provides a standard frame for accumulating and reporting result of measurements, that are contained in the given
/// action
/// </summary>
/// <param name="action"></param>
/// <param name="count"> The number of measured expressions in result, default is "null" for "no restricton. </param>
/// <param name="hidden"> The relative amount of time that will be hidden in result, default is 0.1. </param>
public static void Frame(Action action, int? count = null, double hidden = 0.1)
{
Reset();
_instance.InternalMeasure(action, "", 1);
Tracer.FlaggedLine(Format(count, hidden));
}
/// <summary>
/// Provides a standard frame for accumulating and reporting result of measurements, that are contained in the given
/// function
/// </summary>
/// <param name="function"></param>
/// <param name="count"> The number of measured expressions in result, default is "null" for "no restricton. </param>
/// <param name="hidden"> The relative amount of time that will be hidden in result, default is 0.1. </param>
public static TResult Frame<TResult>(Func<TResult> function, int? count = null, double hidden = 0.1)
{
Reset();
var result = _instance.InternalMeasure(function, "", 1);
Tracer.FlaggedLine(Format(count, hidden));
return result;
}
/// <summary>
/// Start measurement of the following code parts until next item.End() statement.
/// </summary>
/// <param name="flag"> </param>
/// <returns> an item, that represents the measurement.</returns>
public static Item Start(string flag = "") { return new Item(_instance, flag, 1); }
/// <summary>
/// Measures the specified expression.
/// </summary>
/// <typeparam name="T"> The type the specitied expression returns </typeparam>
/// <param name="expression"> a function without parameters returning something. </param>
/// <param name="flag"> A flag that is used in dump. </param>
/// <returns> the result of the invokation of the specified expression </returns>
public static T Measure<T>(Func<T> expression, string flag = "") { return _instance.InternalMeasure(expression, flag, 1); }
/// <summary>
/// Measures the specified action.
/// </summary>
/// <param name="action"> The action. </param>
/// <param name="flag"> A flag that is used in dump. </param>
public static void Measure(Action action, string flag = "") { _instance.InternalMeasure(action, flag, 1); }
/// <summary>
/// Resets the profiler data.
/// </summary>
public static void Reset()
{
lock(_instance)
_instance.InternalReset();
_instance = new Profiler();
}
/// <summary>
/// Formats the data accumulated so far.
/// </summary>
/// <param name="count"> The number of measured expressions in result, default is "null" for "no restricton. </param>
/// <param name="hidden"> The relative amount of time that will be hidden in result, default is 0.1. </param>
/// <returns> The formatted data. </returns>
/// <remarks>
/// The result contains one line for each measured expression, that is not ignored.
/// Each line contains
/// <para>
/// - the file path, the line and the start column of the measuered expression in the source file, (The
/// information is formatted in a way, that within VisualStudio doubleclicking on such a line will open it.)
/// </para>
/// <para> - the flag, if provided, </para>
/// <para> - the ranking, </para>
/// <para> - the execution count, </para>
/// <para> - the average duration of one execution, </para>
/// <para> - the duration, </para>
/// of the expression.
/// The the lines are sorted by descending duration.
/// by use of <paramref name="count" /> and <paramref name="hidden" /> the number of lines can be restricted.
/// </remarks>
public static string Format(int? count = null, double hidden = 0.1)
{
lock(_instance)
return new Dumper(_instance, count, hidden).Format();
}
static Profiler _instance = new Profiler();
readonly Dictionary<string, ProfileItem> _profileItems = new Dictionary<string, ProfileItem>();
readonly Stopwatch _stopwatch;
readonly Stack<ProfileItem> _stack = new Stack<ProfileItem>();
ProfileItem _current;
Profiler()
{
_current = new ProfileItem("");
_stopwatch = new Stopwatch();
_current.Start(_stopwatch.Elapsed);
_stopwatch.Start();
}
void InternalMeasure(Action action, string flag, int stackFrameDepth)
{
BeforeAction(flag, stackFrameDepth + 1);
action();
AfterAction();
}
T InternalMeasure<T>(Func<T> expression, string flag, int stackFrameDepth)
{
BeforeAction(flag, stackFrameDepth + 1);
var result = expression();
AfterAction();
return result;
}
void BeforeAction(string flag, int stackFrameDepth)
{
lock(this)
{
_stopwatch.Stop();
var start = _stopwatch.Elapsed;
_current.Suspend(start);
_stack.Push(_current);
var position = Tracer.MethodHeader(stackFrameDepth:stackFrameDepth + 1) + flag;
if(!_profileItems.TryGetValue(position, out _current))
{
_current = new ProfileItem(position);
_profileItems.Add(position, _current);
}
_current.Start(start);
_stopwatch.Start();
}
}
void AfterAction()
{
lock(this)
{
_stopwatch.Stop();
var end = _stopwatch.Elapsed;
_current.End(end);
_current = _stack.Pop();
_current.Resume(end);
_stopwatch.Start();
}
}
void InternalReset() { Tracer.Assert(_stack.Count == 0); }
/// <summary>
/// Measuement Item
/// </summary>
public sealed class Item
{
readonly Profiler _profiler;
ProfileItem _item;
internal Item(Profiler profiler, string flag, int stackFrameDepth)
{
_profiler = profiler;
Start(flag, stackFrameDepth + 1);
}
void Start(string flag, int stackFrameDepth)
{
_instance.BeforeAction(flag, stackFrameDepth + 1);
_item = _profiler._current;
}
/// <summary>
/// End of measurement for this item
/// </summary>
public void End()
{
Tracer.Assert(_profiler._current == _item);
_profiler.AfterAction();
}
/// <summary>
/// End of measurement for this item and start of new measurement
/// </summary>
public void Next(string flag = "")
{
End();
Start(flag, 1);
}
}
}
sealed class ProfileItem
{
readonly string _position;
TimeSpan _duration;
long _countStart;
long _countEnd;
long _suspendCount;
public ProfileItem(string position) { _position = position; }
public TimeSpan Duration { get { return _duration; } }
TimeSpan AverageDuration { get { return new TimeSpan(_duration.Ticks / _countEnd); } }
bool IsValid { get { return _countStart == _countEnd && _suspendCount == 0; } }
public void Start(TimeSpan duration)
{
_countStart++;
_duration -= duration;
if(IsValid)
Tracer.Assert(_duration.Ticks >= 0);
}
public void End(TimeSpan duration)
{
_countEnd++;
_duration += duration;
if(IsValid)
Tracer.Assert(_duration.Ticks >= 0);
}
public string Format(string tag)
{
Tracer.Assert(IsValid);
return _position
+ " #"
+ tag
+ ": "
+ _countEnd.Format3Digits()
+ "x "
+ AverageDuration.Format3Digits()
+ " "
+ _duration.Format3Digits()
+ "\n";
}
public void Suspend(TimeSpan start)
{
_suspendCount++;
_duration += start;
if(IsValid)
Tracer.Assert(_duration.Ticks >= 0);
}
public void Resume(TimeSpan end)
{
_suspendCount--;
_duration -= end;
if(IsValid)
Tracer.Assert(_duration.Ticks >= 0);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
using Crestron.SimplSharp;
using Crestron.SimplSharpPro;
using VTPro;
using VTPro.Objects;
using VTPro.SmartObjects;
using VTPro.Panels;
using le.Methods;
using $$addnamespace$$.Drivers;
using $$addnamespace$$.SmartObjects;
using Crestron.ThirdPartyCommon.Interfaces;
using $$addnamespace$$.Constants;
namespace $$addnamespace$$
{
public class Panel : BasePanel
{
public Panel(ControlSystem ControlSystem, uint ID, PanelType Type)
: base(ControlSystem, ID, Type)
{
this.ControlSystem = ControlSystem;
ButtonCollection = new VTBCollection();
FormattedTextCollection = new VTBCollection();
SliderCollection = new VTBCollection();
TextEntryCollection = new VTBCollection();
SmartObjectCollection = new VTSCollection();
}
public override void Initialize()
{
base.Initialize();
DisplayButtons = new DisplayVTButtons(this);
DisplaySliders = new DisplayVTSliders(this);
DisplayTextEntryBoxes = new DisplayVTTextEntryBoxes(this);
CableBoxButtons = new CableBoxVTButtons(this);
CableBoxSliders = new CableBoxVTSliders(this);
CableBoxTextEntryBoxes = new CableBoxVTTextEntryBoxes(this);
VideoServerButtons = new VideoServerVTButtons(this);
VideoServerTextEntryBoxes = new VideoServerVTTextEntryBoxes(this);
BlurayPlayerButtons = new BlurayPlayerVTButtons(this);
BlurayPlayerTextBoxes = new BlurayPlayerVTTextEntryBoxes(this);
VTSDisplayMethods = new VTSDisplayMethods(ControlSystem, this);
VTSCableBoxMethods = new VTSCableBoxMethods(ControlSystem, this);
VTSVideoServerMethods = new VTSVideoServerMethods(ControlSystem, this);
VTSBlurayPlayerMethods = new VTSBlurayPlayerMethods(ControlSystem, this);
AddObjects();
SetDefaultStates();
}
public override void HandleEvent(SigEventArgs Args)
{
switch (Args.Sig.Type)
{
case eSigType.Bool:
if (Args.Sig.BoolValue)
{
if (Pages.GetElement(Args.Sig.Number) != null)
{
Pages.FlipTo(Args.Sig.Number);
}
if (Subpages.GetElement(Args.Sig.Number) != null)
{
Subpages.FlipTo(Args.Sig.Number);
}
}
if (ButtonCollection.GetElement(VTBJoin.Digital, Args.Sig.Number) != null)
{
ButtonCollection.GetElement(VTBJoin.Digital, Args.Sig.Number).TriggerAction(VTBAction.PressButton, Args.Sig.BoolValue);
}
break;
case eSigType.UShort:
if (SliderCollection.GetElement(VTBJoin.Analog, Args.Sig.Number) != null)
{
SliderCollection.GetElement(VTBJoin.Analog, Args.Sig.Number).TriggerAction(VTBAction.SetValue, Args.Sig.UShortValue);
}
break;
case eSigType.String:
if (TextEntryCollection.GetElement(VTBJoin.Serial, Args.Sig.Number) != null)
{
TextEntryCollection.GetElement(VTBJoin.Serial, Args.Sig.Number).TriggerAction(VTBAction.GatherTextInput, Args.Sig.StringValue);
}
break;
}
}
private void AddObjects()
{
//Page/SubPages
AddPages();
AddSubpages();
//Objects
AddFormattedText();
AddSliders();
AddButtons();
AddTextEntry();
}
private void AddPages()
{
//addpagesPages.AddElement(3,"Device Control"
Pages.AddElement(0,"DeviceControl_CABLE"
Pages.AddElement(0,"DeviceControl_CODEC"
Pages.AddElement(0,"event_parameters"
Pages.AddElement(200,"Event-ADD"
Pages.AddElement(0,"Event-EDIT"
Pages.AddElement(0,"Home"
Pages.AddElement(0,"Lighting Loads"
Pages.AddElement(0,"Lighting Preset Name_SAVE"
Pages.AddElement(0,"Lighting_Load_Object"
Pages.AddElement(0,"Lighting-Loads"
Pages.AddElement(0,"Lights"
Pages.AddElement(100,"Preset Add"
Pages.AddElement(0,"Preset Edit"
Pages.AddElement(4,"Scheduling"
Pages.AddElement(0,"VC_Call_Incoming"
Pages.AddElement(2,"Video Switching"
//end page
}
private void AddSubpages()
{
#region Device Control
#endregion
#region DeviceControl_CABLE
#endregion
#region DeviceControl_CODEC
#endregion
#region event_parameters
#endregion
#region Event-ADD
#endregion
#region Event-EDIT
#endregion
#region Home
#endregion
#region Lighting Loads
#endregion
#region Lighting Preset Name_SAVE
#endregion
#region Lighting_Load_Object
#endregion
#region Lighting-Loads
#endregion
#region Lights
#endregion
#region Preset Add
#endregion
#region Preset Edit
#endregion
#region Scheduling
#endregion
#region VC_Call_Incoming
#endregion
#region Video Switching
#endregion
}
private void AddTextEntry()
{
}
private void AddFormattedText()
{
}
private void AddSliders()
{
}
private void AddButtons()
{
#region Device Control
#endregion
#region DeviceControl_CABLE
ButtonCollection.AddElement(new VTButton(this, new Dictionary<VTBJoin, uint> { { VTBJoin.Press, 302}, { VTBJoin.Enable, 302 } },InterlockList, "CableBox - FScan", DeviceControl_CABLE_Buttons.CableBox_-_FScan));
ButtonCollection.AddElement(new VTButton(this, new Dictionary<VTBJoin, uint> { { VTBJoin.Press, 305}, { VTBJoin.Enable, 305 } },InterlockList, "CableBox - FSkip", DeviceControl_CABLE_Buttons.CableBox_-_FSkip));
ButtonCollection.AddElement(new VTButton(this, new Dictionary<VTBJoin, uint> { { VTBJoin.Press, 300}, { VTBJoin.Enable, 300 } },InterlockList, "CableBox - Pause", DeviceControl_CABLE_Buttons.CableBox_-_Pause));
ButtonCollection.AddElement(new VTButton(this, new Dictionary<VTBJoin, uint> { { VTBJoin.Press, 303}, { VTBJoin.Enable, 303 } },InterlockList, "CableBox - Play", DeviceControl_CABLE_Buttons.CableBox_-_Play));
ButtonCollection.AddElement(new VTButton(this, new Dictionary<VTBJoin, uint> { { VTBJoin.Press, 301}, { VTBJoin.Enable, 301 } },InterlockList, "CableBox - RScan", DeviceControl_CABLE_Buttons.CableBox_-_RScan));
ButtonCollection.AddElement(new VTButton(this, new Dictionary<VTBJoin, uint> { { VTBJoin.Press, 304}, { VTBJoin.Enable, 304 } },InterlockList, "CableBox - RSkip", DeviceControl_CABLE_Buttons.CableBox_-_RSkip));
#endregion
#region DeviceControl_CODEC
ButtonCollection.AddElement(new VTButton(this, new Dictionary<VTBJoin, uint> { { VTBJoin.Press, 302}, { VTBJoin.Enable, 302 } },InterlockList, "CableBox - FScan_2", DeviceControl_CODEC_Buttons.CableBox_-_FScan_2));
ButtonCollection.AddElement(new VTButton(this, new Dictionary<VTBJoin, uint> { { VTBJoin.Press, 305}, { VTBJoin.Enable, 305 } },InterlockList, "CableBox - FSkip_2", DeviceControl_CODEC_Buttons.CableBox_-_FSkip_2));
ButtonCollection.AddElement(new VTButton(this, new Dictionary<VTBJoin, uint> { { VTBJoin.Press, 301}, { VTBJoin.Enable, 301 } },InterlockList, "CableBox - RScan_2", DeviceControl_CODEC_Buttons.CableBox_-_RScan_2));
ButtonCollection.AddElement(new VTButton(this, new Dictionary<VTBJoin, uint> { { VTBJoin.Press, 304}, { VTBJoin.Enable, 304 } },InterlockList, "CableBox - RSkip_2", DeviceControl_CODEC_Buttons.CableBox_-_RSkip_2));
#endregion
#region event_parameters
#endregion
#region Event-ADD
ButtonCollection.AddElement(new VTButton(this, new Dictionary<VTBJoin, uint> { { VTBJoin.Press, 63}, { VTBJoin.Enable, } },InterlockList, "Button_1_7", Event-ADD_Buttons.Button_1_7));
#endregion
#region Event-EDIT
#endregion
#region Home
ButtonCollection.AddElement(new VTButton(this, new Dictionary<VTBJoin, uint> { { VTBJoin.Press, 2}, { VTBJoin.Enable, } },InterlockList, "Button_1", Home_Buttons.Button_1));
ButtonCollection.AddElement(new VTButton(this, new Dictionary<VTBJoin, uint> { { VTBJoin.Press, 3}, { VTBJoin.Enable, } },InterlockList, "Button_1_1", Home_Buttons.Button_1_1));
ButtonCollection.AddElement(new VTButton(this, new Dictionary<VTBJoin, uint> { { VTBJoin.Press, 4}, { VTBJoin.Enable, } },InterlockList, "Button_1_1_1", Home_Buttons.Button_1_1_1));
#endregion
#region Lighting Loads
#endregion
#region Lighting Preset Name_SAVE
#endregion
#region Lighting_Load_Object
ButtonCollection.AddElement(new VTButton(this, new Dictionary<VTBJoin, uint> { { VTBJoin.Press, 1}, { VTBJoin.Enable, } },InterlockList, "Button_1_11", Lighting_Load_Object_Buttons.Button_1_11));
ButtonCollection.AddElement(new VTButton(this, new Dictionary<VTBJoin, uint> { { VTBJoin.Press, 4}, { VTBJoin.Enable, } },InterlockList, "Button_1_1_2", Lighting_Load_Object_Buttons.Button_1_1_2));
ButtonCollection.AddElement(new VTButton(this, new Dictionary<VTBJoin, uint> { { VTBJoin.Press, 2}, { VTBJoin.Enable, } },InterlockList, "Button_42", Lighting_Load_Object_Buttons.Button_42));
ButtonCollection.AddElement(new VTButton(this, new Dictionary<VTBJoin, uint> { { VTBJoin.Press, 3}, { VTBJoin.Enable, } },InterlockList, "Button_43", Lighting_Load_Object_Buttons.Button_43));
#endregion
#region Lighting-Loads
#endregion
#region Lights
ButtonCollection.AddElement(new VTButton(this, new Dictionary<VTBJoin, uint> { { VTBJoin.Press, 52}, { VTBJoin.Enable, } },InterlockList, "Button_1_17", Lights_Buttons.Button_1_17));
ButtonCollection.AddElement(new VTButton(this, new Dictionary<VTBJoin, uint> { { VTBJoin.Press, 51}, { VTBJoin.Enable, } },InterlockList, "Button_1_2", Lights_Buttons.Button_1_2));
ButtonCollection.AddElement(new VTButton(this, new Dictionary<VTBJoin, uint> { { VTBJoin.Press, 53}, { VTBJoin.Enable, } },InterlockList, "Button_39", Lights_Buttons.Button_39));
ButtonCollection.AddElement(new VTButton(this, new Dictionary<VTBJoin, uint> { { VTBJoin.Press, 50}, { VTBJoin.Enable, } },InterlockList, "Button_40", Lights_Buttons.Button_40));
#endregion
#region Preset Add
#endregion
#region Preset Edit
#endregion
#region Scheduling
ButtonCollection.AddElement(new VTButton(this, new Dictionary<VTBJoin, uint> { { VTBJoin.Press, 60}, { VTBJoin.Enable, } },InterlockList, "Button_10", Scheduling_Buttons.Button_10));
ButtonCollection.AddElement(new VTButton(this, new Dictionary<VTBJoin, uint> { { VTBJoin.Press, 62}, { VTBJoin.Enable, } },InterlockList, "Button_11", Scheduling_Buttons.Button_11));
ButtonCollection.AddElement(new VTButton(this, new Dictionary<VTBJoin, uint> { { VTBJoin.Press, 4}, { VTBJoin.Enable, } },InterlockList, "Button_1_1_3", Scheduling_Buttons.Button_1_1_3));
ButtonCollection.AddElement(new VTButton(this, new Dictionary<VTBJoin, uint> { { VTBJoin.Press, 3}, { VTBJoin.Enable, } },InterlockList, "Button_1_3", Scheduling_Buttons.Button_1_3));
ButtonCollection.AddElement(new VTButton(this, new Dictionary<VTBJoin, uint> { { VTBJoin.Press, 61}, { VTBJoin.Enable, } },InterlockList, "Button_1_6", Scheduling_Buttons.Button_1_6));
ButtonCollection.AddElement(new VTButton(this, new Dictionary<VTBJoin, uint> { { VTBJoin.Press, 2}, { VTBJoin.Enable, } },InterlockList, "Button_5", Scheduling_Buttons.Button_5));
#endregion
#region VC_Call_Incoming
#endregion
#region Video Switching
ButtonCollection.AddElement(new VTButton(this, new Dictionary<VTBJoin, uint> { { VTBJoin.Press, 6}, { VTBJoin.Enable, } },InterlockList, "Button_45", Video Switching_Buttons.Button_45));
ButtonCollection.AddElement(new VTButton(this, new Dictionary<VTBJoin, uint> { { VTBJoin.Press, 5}, { VTBJoin.Enable, } },InterlockList, "Button_46", Video Switching_Buttons.Button_46));
#endregion
}
public override void InitializeSmartObjects()
{
List<string> IRPorts = new List<string>();
List<string> COMPorts = new List<string>();
foreach (IROutputPort port in ControlSystem.IROutputPorts)
{
IRPorts.Add(port.ID.ToString());
}
foreach (var port in ControlSystem.ComPorts)
{
COMPorts.Add(port.ID.ToString());
}
#region VideoServer
SmartObjectCollection.AddElement(new VTButtonList(this, null, ExtendedInterface.SmartObjects[VTSObjects.VideoServer_Footer_SubpageSelection],
"VideoServer Subpage Selection", 5, VTSVideoServerMethods.SubpageSelection, true));
SmartObjectCollection.AddElement(new VTButtonList(this, null, ExtendedInterface.SmartObjects[VTSObjects.VideoServer_DriverSelection_DriverTypes],
"VideoServer Driver Types", 3, VTSVideoServerMethods.DriverTypeSelection, false));
SmartObjectCollection.AddElement(new VTDynamicButtonList(this, null, ExtendedInterface.SmartObjects[VTSObjects.VideoServer_IRDriverPorts],
"VideoServer IR Driver Ports", IRPorts, VTSVideoServerMethods.IRDriverPorts, true));
SmartObjectCollection.AddElement(new VTDynamicButtonList(this, null, ExtendedInterface.SmartObjects[VTSObjects.VideoServer_IRDrivers],
"VideoServer IR Drivers", DriverHelper.IRVideoServers.Keys.ToList(), VTSVideoServerMethods.IRDrivers, true));
SmartObjectCollection.AddElement(new VTDynamicButtonList(this, null, ExtendedInterface.SmartObjects[VTSObjects.VideoServer_SerialDriverPorts],
"VideoServer Serial Driver Ports", COMPorts, VTSVideoServerMethods.SerialDriverPorts, true));
SmartObjectCollection.AddElement(new VTDynamicButtonList(this, null, ExtendedInterface.SmartObjects[VTSObjects.VideoServer_SerialDrivers],
"VideoServer Serial Drivers", DriverHelper.SerialVideoServers.Keys.ToList(), VTSVideoServerMethods.SerialDrivers, true));
SmartObjectCollection.AddElement(new VTDynamicButtonList(this, null, ExtendedInterface.SmartObjects[VTSObjects.VideoServer_TCPIPDrivers],
"VideoServer TCPIP Drivers", DriverHelper.TcpVideoServers.Keys.ToList(), VTSVideoServerMethods.TCPIPDrivers, true));
SmartObjectCollection.AddElement(new VTKeypad(this, new Dictionary<VTBJoin, uint> { { VTBJoin.Enable, 1040 } }, ExtendedInterface.SmartObjects[VTSObjects.VideoServer_Keypad],
"VideoServer Control Keypad", VTSVideoServerMethods.TransportKeypad));
SmartObjectCollection.AddElement(new VTDPad(this, new Dictionary<VTBJoin, uint> { { VTBJoin.Enable, 1041 } }, ExtendedInterface.SmartObjects[VTSObjects.VideoServer_DPad],
"VideoServer Control DPad", VTSVideoServerMethods.TransportDPad));
#endregion
#region CableBox
SmartObjectCollection.AddElement(new VTButtonList(this, null, ExtendedInterface.SmartObjects[VTSObjects.Source_Footer_SubpageSelection],
"CableBox Subpage Selection", 5, VTSCableBoxMethods.SubpageSelection, true));
SmartObjectCollection.AddElement(new VTButtonList(this, null, ExtendedInterface.SmartObjects[VTSObjects.Source_DriverSelection_DriverTypes],
"CableBox Driver Types", 3, VTSCableBoxMethods.DriverTypeSelection, false));
SmartObjectCollection.AddElement(new VTDynamicButtonList(this, null, ExtendedInterface.SmartObjects[VTSObjects.Source_IRDriverPorts],
"CableBox IR Driver Ports", IRPorts, VTSCableBoxMethods.IRDriverPorts, true));
SmartObjectCollection.AddElement(new VTDynamicButtonList(this, null, ExtendedInterface.SmartObjects[VTSObjects.Source_IRDrivers],
"CableBox IR Drivers", DriverHelper.IRCableBoxes.Keys.ToList(), VTSCableBoxMethods.IRDrivers, true));
SmartObjectCollection.AddElement(new VTDynamicButtonList(this, null, ExtendedInterface.SmartObjects[VTSObjects.Source_SerialDriverPorts],
"CableBox Serial Driver Ports", COMPorts, VTSCableBoxMethods.SerialDriverPorts, true));
SmartObjectCollection.AddElement(new VTDynamicButtonList(this, null, ExtendedInterface.SmartObjects[VTSObjects.Source_SerialDrivers],
"CableBox Serial Drivers", DriverHelper.SerialCableBoxes.Keys.ToList(), VTSCableBoxMethods.SerialDrivers, true));
SmartObjectCollection.AddElement(new VTDynamicButtonList(this, null, ExtendedInterface.SmartObjects[VTSObjects.Source_TCPIPDrivers],
"CableBox TCPIP Drivers", DriverHelper.TcpCableBoxes.Keys.ToList(), VTSCableBoxMethods.TCPIPDrivers, true));
SmartObjectCollection.AddElement(new VTKeypad(this, new Dictionary<VTBJoin, uint> { { VTBJoin.Enable, 111 } } , ExtendedInterface.SmartObjects[VTSObjects.Source_Keypad],
"CableBox Control Keypad", VTSCableBoxMethods.TransportKeypad));
SmartObjectCollection.AddElement(new VTDPad(this, new Dictionary<VTBJoin, uint> { { VTBJoin.Enable, 110 } }, ExtendedInterface.SmartObjects[VTSObjects.Source_DPad],
"CableBox Control DPad", VTSCableBoxMethods.TransportDPad));
#endregion
#region Display
SmartObjectCollection.AddElement(new VTButtonList(this, null, ExtendedInterface.SmartObjects[VTSObjects.Display_Footer_SubpageSelection],
"Display Subpage Selection", 5, VTSDisplayMethods.SubpageSelection, true));
SmartObjectCollection.AddElement(new VTButtonList(this, null, ExtendedInterface.SmartObjects[VTSObjects.Display_DriverSelection_DriverTypes],
"Display Driver Type List", 3, VTSDisplayMethods.DriverTypes, false));
SmartObjectCollection.AddElement(new VTDynamicButtonList(this, null, ExtendedInterface.SmartObjects[VTSObjects.Display_SerialDrivers],
"Display Serial Driver List", DriverHelper.SerialDisplays.Keys.ToList(), VTSDisplayMethods.SerialDrivers, true));
SmartObjectCollection.AddElement(new VTDynamicButtonList(this, null, ExtendedInterface.SmartObjects[VTSObjects.Display_SerialDriverPorts],
"Display Serial Driver COM Port List", COMPorts, VTSDisplayMethods.SerialDriverCOMPorts, true));
SmartObjectCollection.AddElement(new VTDynamicButtonList(this, null, ExtendedInterface.SmartObjects[VTSObjects.Display_TCPIPDrivers],
"Display TCP/IP Driver List", DriverHelper.TcpDisplays.Keys.ToList(), VTSDisplayMethods.TcpIpDrivers, true));
SmartObjectCollection.AddElement(new VTDynamicButtonList(this, null, ExtendedInterface.SmartObjects[VTSObjects.Display_IRDriverPorts],
"Display IR Driver Port List", IRPorts, VTSDisplayMethods.IRPorts, true));
SmartObjectCollection.AddElement(new VTDynamicButtonList(this, null, ExtendedInterface.SmartObjects[VTSObjects.Display_IRDrivers],
"Display IR Driver List", DriverHelper.IRDisplays.Keys.ToList(), VTSDisplayMethods.IRDrivers, true));
#endregion
#region BlurayPlayer
SmartObjectCollection.AddElement(new VTDPad(this, new Dictionary<VTBJoin, uint> { { VTBJoin.Enable, 1541 } }, ExtendedInterface.SmartObjects[VTSObjects.BlurayPlayer_DPad],
"BlurayPlayer Control DPad", VTSBlurayPlayerMethods.TransportDPad));
SmartObjectCollection.AddElement(new VTKeypad(this, new Dictionary<VTBJoin, uint> { { VTBJoin.Enable, 1540 } }, ExtendedInterface.SmartObjects[VTSObjects.BlurayPlayer_Keypad],
"BlurayPlayer Keypad", VTSBlurayPlayerMethods.TransportKeypad));
SmartObjectCollection.AddElement(new VTButtonList(this, null, ExtendedInterface.SmartObjects[VTSObjects.BlurayPlayer_Footer_SubpageSelection],
"BlurayPlayer Subpage Selection", 5, VTSBlurayPlayerMethods.SubpageSelection, true));
SmartObjectCollection.AddElement(new VTButtonList(this, null, ExtendedInterface.SmartObjects[VTSObjects.BlurayPlayer_DriverSelection_DriverTypes],
"BlurayPlayer Driver Types", 3, VTSBlurayPlayerMethods.DriverTypeSelection, false));
SmartObjectCollection.AddElement(new VTDynamicButtonList(this, null, ExtendedInterface.SmartObjects[VTSObjects.BlurayPlayer_IRDriverPorts],
"BlurayPlayer IR Driver Ports", IRPorts, VTSBlurayPlayerMethods.IRDriverPorts, true));
SmartObjectCollection.AddElement(new VTDynamicButtonList(this, null, ExtendedInterface.SmartObjects[VTSObjects.BlurayPlayer_IRDrivers],
"BlurayPlayer IR Drivers", DriverHelper.IRBlurayPlayers.Keys.ToList(), VTSBlurayPlayerMethods.IRDrivers, true));
SmartObjectCollection.AddElement(new VTDynamicButtonList(this, null, ExtendedInterface.SmartObjects[VTSObjects.BlurayPlayer_SerialDriverPorts],
"BlurayPlayer Serial Driver Ports", COMPorts, VTSBlurayPlayerMethods.SerialDriverPorts, true));
SmartObjectCollection.AddElement(new VTDynamicButtonList(this, null, ExtendedInterface.SmartObjects[VTSObjects.BlurayPlayer_SerialDrivers],
"BlurayPlayer Serial Drivers", DriverHelper.SerialBlurayPlayers.Keys.ToList(), VTSBlurayPlayerMethods.SerialDrivers, true));
SmartObjectCollection.AddElement(new VTDynamicButtonList(this, null, ExtendedInterface.SmartObjects[VTSObjects.BlurayPlayer_TCPIPDrivers],
"BlurayPlayer TCPIP Drivers", DriverHelper.TcpBlurayPlayers.Keys.ToList(), VTSBlurayPlayerMethods.TCPIPDrivers, true));
#endregion
}
private bool CheckSmartObject(uint ID)
{
return ExtendedInterface.SmartObjects.Contains(ID);
}
public void SetDefaultStates()
{
//Display Settings
TextEntryCollection.GetElement("TCP/IP Display IP Address").TriggerAction(VTBAction.SetIndirectText, "0.0.0.0");
TextEntryCollection.GetElement("TCP/IP CableBox IP Address").TriggerAction(VTBAction.SetIndirectText, "0.0.0.0");
TextEntryCollection.GetElement("TCP/IP VideoServer IP Address").TriggerAction(VTBAction.SetIndirectText, "0.0.0.0");
TextEntryCollection.GetElement("TCP/IP BlurayPlayer IP Address").TriggerAction(VTBAction.SetIndirectText, "0.0.0.0");
FormattedTextCollection.GetElement("DisplayHeader").TriggerAction(VTBAction.SetIndirectText, "Unknown");
FormattedTextCollection.GetElement("CableBox ConnectionStatus").TriggerAction(VTBAction.SetIndirectText, "Unknown");
FormattedTextCollection.GetElement("VideoServer ConnectionStatus").TriggerAction(VTBAction.SetIndirectText, "Unknown");
FormattedTextCollection.GetElement("BlurayPlayer ConnectionStatus").TriggerAction(VTBAction.SetIndirectText, "Unknown");
}
public void SetVideoServerSupports()
{
if (ControlSystem._videoServer == null)
{
return;
}
IBasicVideoServer videoServer = ControlSystem._videoServer;
videoServer.CustomLogger = VideoServerLogOut;
videoServer.RxOut += VideoServerRxOut;
#region Header
if (videoServer.Description.Contains("Generic IR"))
{
FormattedTextCollection.GetElement("VideoServer ConnectionStatus").TriggerAction(VTBAction.SetIndirectText, "IR Port Ready");
}
else
{
FormattedTextCollection.GetElement("VideoServer ConnectionStatus").TriggerAction(VTBAction.SetIndirectText, videoServer.Connected ? "Connected" : "Disconnected");
}
#endregion
#region Transport
ButtonCollection.GetElement("VideoServer Pause").TriggerAction(VTBAction.SetEnableState, videoServer.SupportsPause);
ButtonCollection.GetElement("VideoServer Rewind").TriggerAction(VTBAction.SetEnableState, videoServer.SupportsReverseScan);
ButtonCollection.GetElement("VideoServer Forward").TriggerAction(VTBAction.SetEnableState, videoServer.SupportsForwardScan);
ButtonCollection.GetElement("VideoServer Play").TriggerAction(VTBAction.SetEnableState, videoServer.SupportsPlay);
ButtonCollection.GetElement("VideoServer Repeat").TriggerAction(VTBAction.SetEnableState, videoServer.SupportsRepeat);
ButtonCollection.GetElement("VideoServer Next").TriggerAction(VTBAction.SetEnableState, videoServer.SupportsForwardSkip);
ButtonCollection.GetElement("VideoServer Previous").TriggerAction(VTBAction.SetEnableState, videoServer.SupportsReverseSkip);
ButtonCollection.GetElement("VideoServer Stop").TriggerAction(VTBAction.SetEnableState, videoServer.SupportsStop);
SmartObjectCollection.GetElement("VideoServer Control DPad").TriggerAction(VTSAction.SetEnabledState, videoServer.SupportsArrowKeys);
ButtonCollection.GetElement("VideoServer Home").TriggerAction(VTBAction.SetEnableState, videoServer.SupportsHome);
ButtonCollection.GetElement("VideoServer Back").TriggerAction(VTBAction.SetEnableState, videoServer.SupportsBack);
ButtonCollection.GetElement("VideoServer Clear").TriggerAction(VTBAction.SetEnableState, videoServer.SupportsClear);
ButtonCollection.GetElement("VideoServer Return").TriggerAction(VTBAction.SetEnableState, videoServer.SupportsReturn);
ButtonCollection.GetElement("VideoServer Menu").TriggerAction(VTBAction.SetEnableState, videoServer.SupportsMenu);
ButtonCollection.GetElement("VideoServer Exit").TriggerAction(VTBAction.SetEnableState, videoServer.SupportsExit);
ButtonCollection.GetElement("VideoServer Backspace").TriggerAction(VTBAction.SetEnableState, videoServer.SupportsKeypadBackSpace);
SmartObjectCollection.GetElement("VideoServer Control Keypad").TriggerAction(VTSAction.SetEnabledState, videoServer.SupportsKeypadNumber);
#endregion
#region Info
FormattedTextCollection.GetElement("VideoServer Description").TriggerAction(VTBAction.SetIndirectText, videoServer.Description);
FormattedTextCollection.GetElement("VideoServer GUID").TriggerAction(VTBAction.SetIndirectText, videoServer.Guid.ToString());
FormattedTextCollection.GetElement("VideoServer Manufacturer").TriggerAction(VTBAction.SetIndirectText, videoServer.Manufacturer);
FormattedTextCollection.GetElement("VideoServer Version").TriggerAction(VTBAction.SetIndirectText, videoServer.Version);
FormattedTextCollection.GetElement("VideoServer VersionDate").TriggerAction(VTBAction.SetIndirectText, videoServer.VersionDate.ToString());
FormattedTextCollection.GetElement("VideoServer SupportsFeedback").TriggerAction(VTBAction.SetIndirectText, videoServer.SupportsFeedback.ToString());
if (ControlSystem._videoServer.Description.Contains("Generic IR"))
{
ButtonCollection.GetElement("VideoServer EnableLogging").TriggerAction(VTBAction.SetEnableState, false);
ButtonCollection.GetElement("VideoServer DisableLogging").TriggerAction(VTBAction.SetEnableState, false);
}
else
{
ButtonCollection.GetElement("VideoServer EnableLogging").TriggerAction(VTBAction.SetEnableState, true);
ButtonCollection.GetElement("VideoServer DisableLogging").TriggerAction(VTBAction.SetEnableState, true);
}
ButtonCollection.GetElement("VideoServer DisableLogging").TriggerAction(VTBAction.PressButton, true);
#endregion
#region Advanced
if (videoServer.Description.Contains("Generic IR"))
{
ButtonCollection.GetElement("VideoServer EnableRxOut").TriggerAction(VTBAction.SetEnableState, false);
ButtonCollection.GetElement("VideoServer DisableRxOut").TriggerAction(VTBAction.SetEnableState, false);
}
else
{
ButtonCollection.GetElement("VideoServer EnableRxOut").TriggerAction(VTBAction.SetEnableState, true);
ButtonCollection.GetElement("VideoServer DisableRxOut").TriggerAction(VTBAction.SetEnableState, true);
}
ButtonCollection.GetElement("VideoServer DisableRxOut").TriggerAction(VTBAction.PressButton, true);
#endregion
}
public void SetCableBoxSupports()
{
if (ControlSystem._cableBox == null)
{
return;
}
IBasicCableBox cableBox = ControlSystem._cableBox;
ControlSystem._cableBox.CustomLogger = CableBoxLogOut;
ControlSystem._cableBox.RxOut += CableBoxRxOut;
#region Header
if (ControlSystem._cableBox.Description.Contains("Generic IR"))
{
FormattedTextCollection.GetElement("CableBox ConnectionStatus").TriggerAction(VTBAction.SetIndirectText, "IR Port Ready");
}
else
{
FormattedTextCollection.GetElement("CableBox ConnectionStatus").TriggerAction(VTBAction.SetIndirectText, cableBox.Connected ? "Connected" : "Disconnected");
}
#endregion
#region Transport/left
ButtonCollection.GetElement("CableBox Pause").TriggerAction(VTBAction.SetEnableState, cableBox.SupportsPause);
ButtonCollection.GetElement("CableBox Rewind").TriggerAction(VTBAction.SetEnableState, cableBox.SupportsReverseScan);
ButtonCollection.GetElement("CableBox Forward").TriggerAction(VTBAction.SetEnableState, cableBox.SupportsForwardScan);
ButtonCollection.GetElement("CableBox Play").TriggerAction(VTBAction.SetEnableState, cableBox.SupportsPlay);
ButtonCollection.GetElement("CableBox Repeat").TriggerAction(VTBAction.SetEnableState, cableBox.SupportsRepeat);
ButtonCollection.GetElement("CableBox Next").TriggerAction(VTBAction.SetEnableState, cableBox.SupportsForwardSkip);
ButtonCollection.GetElement("CableBox Record").TriggerAction(VTBAction.SetEnableState, cableBox.SupportsRecord);
ButtonCollection.GetElement("CableBox Live").TriggerAction(VTBAction.SetEnableState, cableBox.SupportsLive);
FormattedTextCollection.GetElement("CableBox Volume").TriggerAction(VTBAction.SetVisibilityState, cableBox.SupportsVolumePercentFeedback);
FormattedTextCollection.GetElement("CableBox Channel").TriggerAction(VTBAction.SetVisibilityState, cableBox.SupportsChannelFeedback);
FormattedTextCollection.GetElement("CableBox Volume").TriggerAction(VTBAction.SetIndirectText, "Unknown");
FormattedTextCollection.GetElement("CableBox Channel").TriggerAction(VTBAction.SetIndirectText, "Unknown");
ButtonCollection.GetElement("CableBox VolumeUp").TriggerAction(VTBAction.SetEnableState, cableBox.SupportsChangeVolume);
ButtonCollection.GetElement("CableBox VolumeDown").TriggerAction(VTBAction.SetEnableState, cableBox.SupportsChangeVolume);
ButtonCollection.GetElement("CableBox ChannelUp").TriggerAction(VTBAction.SetEnableState, cableBox.SupportsChangeChannel);
ButtonCollection.GetElement("CableBox ChannelDown").TriggerAction(VTBAction.SetEnableState, cableBox.SupportsChangeChannel);
SmartObjectCollection.GetElement("CableBox Control DPad").TriggerAction(VTSAction.SetEnabledState, cableBox.SupportsArrowKeys);
#endregion
#region Transport/right
ButtonCollection.GetElement("CableBox Yellow").TriggerAction(VTBAction.SetEnableState, cableBox.SupportsColorButtons);
ButtonCollection.GetElement("CableBox Blue").TriggerAction(VTBAction.SetEnableState, cableBox.SupportsColorButtons);
ButtonCollection.GetElement("CableBox Red").TriggerAction(VTBAction.SetEnableState, cableBox.SupportsColorButtons);
ButtonCollection.GetElement("CableBox Green").TriggerAction(VTBAction.SetEnableState, cableBox.SupportsColorButtons);
ButtonCollection.GetElement("CableBox Power On").TriggerAction(VTBAction.SetEnableState, cableBox.SupportsDiscretePower);
ButtonCollection.GetElement("CableBox Power Off").TriggerAction(VTBAction.SetEnableState, cableBox.SupportsDiscretePower);
ButtonCollection.GetElement("CableBox Power Toggle").TriggerAction(VTBAction.SetEnableState, cableBox.SupportsTogglePower);
ButtonCollection.GetElement("CableBox Home").TriggerAction(VTBAction.SetEnableState, cableBox.SupportsHome);
ButtonCollection.GetElement("CableBox Back").TriggerAction(VTBAction.SetEnableState, cableBox.SupportsBack);
ButtonCollection.GetElement("CableBox Clear").TriggerAction(VTBAction.SetEnableState, cableBox.SupportsClear);
ButtonCollection.GetElement("CableBox Info").TriggerAction(VTBAction.SetEnableState, cableBox.SupportsInfo);
ButtonCollection.GetElement("CableBox Return").TriggerAction(VTBAction.SetEnableState, cableBox.SupportsReturn);
ButtonCollection.GetElement("CableBox Guide").TriggerAction(VTBAction.SetEnableState, cableBox.SupportsGuide);
ButtonCollection.GetElement("CableBox Menu").TriggerAction(VTBAction.SetEnableState, cableBox.SupportsMenu);
ButtonCollection.GetElement("CableBox Favorite").TriggerAction(VTBAction.SetEnableState, cableBox.SupportsFavorite);
ButtonCollection.GetElement("CableBox Exit").TriggerAction(VTBAction.SetEnableState, cableBox.SupportsExit);
SmartObjectCollection.GetElement("CableBox Control Keypad").TriggerAction(VTSAction.SetEnabledState, cableBox.SupportsKeypadNumber);
#endregion
#region Info
FormattedTextCollection.GetElement("CableBox Description").TriggerAction(VTBAction.SetIndirectText, cableBox.Description);
FormattedTextCollection.GetElement("CableBox GUID").TriggerAction(VTBAction.SetIndirectText, cableBox.Guid.ToString());
FormattedTextCollection.GetElement("CableBox Manufacturer").TriggerAction(VTBAction.SetIndirectText, cableBox.Manufacturer);
FormattedTextCollection.GetElement("CableBox Version").TriggerAction(VTBAction.SetIndirectText, cableBox.Version);
FormattedTextCollection.GetElement("CableBox VersionDate").TriggerAction(VTBAction.SetIndirectText, cableBox.VersionDate.ToString());
FormattedTextCollection.GetElement("CableBox SupportsFeedback").TriggerAction(VTBAction.SetIndirectText, cableBox.SupportsFeedback.ToString());
if (ControlSystem._cableBox.Description.Contains("Generic IR"))
{
ButtonCollection.GetElement("CableBox EnableLogging").TriggerAction(VTBAction.SetEnableState, false);
ButtonCollection.GetElement("CableBox DisableLogging").TriggerAction(VTBAction.SetEnableState, false);
}
else
{
ButtonCollection.GetElement("CableBox EnableLogging").TriggerAction(VTBAction.SetEnableState, true);
ButtonCollection.GetElement("CableBox DisableLogging").TriggerAction(VTBAction.SetEnableState, true);
}
ButtonCollection.GetElement("CableBox DisableLogging").TriggerAction(VTBAction.PressButton, true);
#endregion
#region Advanced
SliderCollection.GetElement("CableBox WarmUpTime").TriggerAction(VTBAction.SetEnableState, cableBox.SupportsWarmUpTime);
SliderCollection.GetElement("CableBox CoolDownTime").TriggerAction(VTBAction.SetEnableState, cableBox.SupportsCoolDownTime);
SliderCollection.GetElement("CableBox WarmUpTime").TriggerAction(VTBAction.UpdateValue, cableBox.WarmUpTime);
SliderCollection.GetElement("CableBox CoolDownTime").TriggerAction(VTBAction.UpdateValue, cableBox.CoolDownTime);
if (ControlSystem._cableBox.Description.Contains("Generic IR"))
{
ButtonCollection.GetElement("CableBox EnableRxOut").TriggerAction(VTBAction.SetEnableState, false);
ButtonCollection.GetElement("CableBox DisableRxOut").TriggerAction(VTBAction.SetEnableState, false);
}
else
{
ButtonCollection.GetElement("CableBox EnableRxOut").TriggerAction(VTBAction.SetEnableState, true);
ButtonCollection.GetElement("CableBox DisableRxOut").TriggerAction(VTBAction.SetEnableState, true);
}
ButtonCollection.GetElement("CableBox DisableRxOut").TriggerAction(VTBAction.PressButton, true);
#endregion
#region Feedback
FormattedTextCollection.GetElement("CableBox PowerFb").TriggerAction(VTBAction.SetIndirectText, "Unknown");
FormattedTextCollection.GetElement("CableBox MuteFb").TriggerAction(VTBAction.SetIndirectText, "Unknown");
FormattedTextCollection.GetElement("CableBox ChannelFb").TriggerAction(VTBAction.SetIndirectText, "Unknown");
#endregion
}
public void SetDisplaySupports()
{
if (ControlSystem._display == null)
{
return;
}
IBasicVideoDisplay display = ControlSystem._display;
display.CustomLogger = DisplayLogOut;
display.RxOut += DisplayRxOut;
#region Header
if (ControlSystem._display.Description.Contains("Generic IR"))
{
FormattedTextCollection.GetElement("DisplayHeader").TriggerAction(VTBAction.SetIndirectText, "IR Port Ready");
}
else
{
FormattedTextCollection.GetElement("DisplayHeader").TriggerAction(VTBAction.SetIndirectText, display.Connected ? "Connected" : "Disconnected");
}
#endregion
#region Info
FormattedTextCollection.GetElement("DisplayDescription").TriggerAction(VTBAction.SetIndirectText, display.Description);
FormattedTextCollection.GetElement("DisplayGUID").TriggerAction(VTBAction.SetIndirectText, display.Guid.ToString());
FormattedTextCollection.GetElement("DisplayManufacturer").TriggerAction(VTBAction.SetIndirectText, display.Manufacturer);
FormattedTextCollection.GetElement("DisplayVersion").TriggerAction(VTBAction.SetIndirectText, display.Version);
FormattedTextCollection.GetElement("DisplayVersionDate").TriggerAction(VTBAction.SetIndirectText, display.VersionDate.ToString(CultureInfo.InvariantCulture));
FormattedTextCollection.GetElement("DisplaySupportsFeedback").TriggerAction(VTBAction.SetIndirectText, display.SupportsFeedback.ToString());
#endregion
#region Control
//Valid input sources
for (uint i = 0; i < display.GetUsableInputs().Length; i++)
{
VTButton button = ButtonCollection.GetElement("DisplaySourceSelect" + i) as VTButton;
if (button != null)
{
button.TriggerAction(VTBAction.SetFeedback, false);
button.TriggerAction(VTBAction.SetEnableState, true);
button.TriggerAction(VTBAction.SetIndirectText, display.GetUsableInputs()[i].InputType.ToString());
}
}
//Non-valid input sources
for (var i = (uint)display.GetUsableInputs().Length; i < 16; i++)
{
VTButton button = ButtonCollection.GetElement("DisplaySourceSelect" + i) as VTButton;
if (button != null)
{
button.TriggerAction(VTBAction.SetEnableState, false);
button.TriggerAction(VTBAction.SetIndirectText, String.Empty);
}
}
ButtonCollection.GetElement("DisplayPowerOff").TriggerAction(VTBAction.SetEnableState, display.SupportsDiscretePower);
ButtonCollection.GetElement("DisplayPowerOn").TriggerAction(VTBAction.SetEnableState, display.SupportsDiscretePower);
ButtonCollection.GetElement("DisplayPowerToggle").TriggerAction(VTBAction.SetEnableState, display.SupportsTogglePower);
ButtonCollection.GetElement("DisplayPowerOff").TriggerAction(VTBAction.SetFeedback, false);
ButtonCollection.GetElement("DisplayPowerOn").TriggerAction(VTBAction.SetFeedback, false);
ButtonCollection.GetElement("DisplayPowerToggle").TriggerAction(VTBAction.SetFeedback, false);
ButtonCollection.GetElement("DisplayMuteOff").TriggerAction(VTBAction.SetEnableState, display.SupportsDiscreteMute);
ButtonCollection.GetElement("DisplayMuteOn").TriggerAction(VTBAction.SetEnableState, display.SupportsDiscreteMute);
ButtonCollection.GetElement("DisplayMuteToggle").TriggerAction(VTBAction.SetEnableState, display.SupportsMute);
ButtonCollection.GetElement("DisplayMuteOff").TriggerAction(VTBAction.SetFeedback, false);
ButtonCollection.GetElement("DisplayMuteOn").TriggerAction(VTBAction.SetFeedback, false);
ButtonCollection.GetElement("DisplayMuteToggle").TriggerAction(VTBAction.SetFeedback, false);
SliderCollection.GetElement("DisplayVolume").TriggerAction(VTBAction.SetVisibilityState, display.SupportsVolumePercentFeedback);
SliderCollection.GetElement("DisplayVolume").TriggerAction(VTBAction.UpdateValue, (ushort)0);
ButtonCollection.GetElement("DisplayVolumeUp").TriggerAction(VTBAction.SetVisibilityState, display.SupportsChangeVolume);
ButtonCollection.GetElement("DisplayVolumeDown").TriggerAction(VTBAction.SetVisibilityState, display.SupportsChangeVolume);
#endregion
#region Settings
ButtonCollection.GetElement("DisplayDisconnect").TriggerAction(VTBAction.SetEnableState, display.SupportsDisconnect);
ButtonCollection.GetElement("DisplayReconnect").TriggerAction(VTBAction.SetEnableState, display.SupportsReconnect);
#endregion
#region Feedback
if (display.SupportsFeedback)
{//Feedback is supported
FormattedTextCollection.GetElement("DisplayPowerFeedback").TriggerAction(VTBAction.SetIndirectText, "Unknown");
FormattedTextCollection.GetElement("DisplayMuteFeedback").TriggerAction(VTBAction.SetIndirectText, "Unknown");
FormattedTextCollection.GetElement("DisplayInputFeedback").TriggerAction(VTBAction.SetIndirectText, "Unknown");
}
else
{//Feedback is not supported
FormattedTextCollection.GetElement("DisplayPowerFeedback").TriggerAction(VTBAction.SetIndirectText, "Not supported");
FormattedTextCollection.GetElement("DisplayMuteFeedback").TriggerAction(VTBAction.SetIndirectText, "Not supported");
FormattedTextCollection.GetElement("DisplayInputFeedback").TriggerAction(VTBAction.SetIndirectText, "Not supported");
}
#endregion
#region Advanced
FormattedTextCollection.GetElement("DisplayCoolDownTime").TriggerAction(VTBAction.SetIndirectText, display.CoolDownTime.ToString());
FormattedTextCollection.GetElement("DisplayWarmUpTime").TriggerAction(VTBAction.SetIndirectText, display.CoolDownTime.ToString());
SliderCollection.GetElement("DisplaySetWarmUpTime").TriggerAction(VTBAction.SetEnableState, display.SupportsWarmUpTime);
SliderCollection.GetElement("DisplaySetCoolDownTime").TriggerAction(VTBAction.SetEnableState, display.SupportsCoolDownTime);
SliderCollection.GetElement("DisplaySetWarmUpTime").TriggerAction(VTBAction.UpdateValue, display.WarmUpTime);
SliderCollection.GetElement("DisplaySetCoolDownTime").TriggerAction(VTBAction.UpdateValue, display.CoolDownTime);
if (!ControlSystem._display.Description.Contains("Crestron Generic IR Display Driver"))
{//RX Out and logging enabled since this is not an IR driver
ButtonCollection.GetElement("DisplayDisableRxOut").TriggerAction(VTBAction.SetEnableState, true);
ButtonCollection.GetElement("DisplayDisableLogging").TriggerAction(VTBAction.SetEnableState, true);
ButtonCollection.GetElement("DisplayEnableRxOut").TriggerAction(VTBAction.SetEnableState, true);
ButtonCollection.GetElement("DisplayEnableLogging").TriggerAction(VTBAction.SetEnableState, true);
ButtonCollection.GetElement("DisplayDisableRxOut").TriggerAction(VTBAction.PressButton, true);
ButtonCollection.GetElement("DisplayDisableLogging").TriggerAction(VTBAction.PressButton, true);
}
else
{//IR drivers do not support RX Out or Logging
ButtonCollection.GetElement("DisplayDisableRxOut").TriggerAction(VTBAction.SetEnableState, false);
ButtonCollection.GetElement("DisplayDisableLogging").TriggerAction(VTBAction.SetEnableState, false);
ButtonCollection.GetElement("DisplayEnableRxOut").TriggerAction(VTBAction.SetEnableState, false);
ButtonCollection.GetElement("DisplayEnableLogging").TriggerAction(VTBAction.SetEnableState, false);
FormattedTextCollection.GetElement("DisplayLog").TriggerAction(VTBAction.SetIndirectText, "Not supported");
FormattedTextCollection.GetElement("DisplayRxOut").TriggerAction(VTBAction.SetIndirectText, "Not supported");
}
#endregion
}
public void SetBlurayPlayerSupports()
{
if (ControlSystem._blurayPlayer == null)
{
return;
}
IBasicBlurayPlayer blurayPlayer = ControlSystem._blurayPlayer;
ControlSystem._blurayPlayer.CustomLogger = BlurayPlayerLogOut;
ControlSystem._blurayPlayer.RxOut += BlurayPlayerRxOut;
#region Header
if (ControlSystem._blurayPlayer.Description.Contains("Generic IR"))
{
FormattedTextCollection.GetElement("BlurayPlayer ConnectionStatus").TriggerAction(VTBAction.SetIndirectText, "IR Port Ready");
}
else
{
FormattedTextCollection.GetElement("BlurayPlayer ConnectionStatus").TriggerAction(VTBAction.SetIndirectText, blurayPlayer.Connected ? "Connected" : "Disconnected");
}
#endregion
#region Info
FormattedTextCollection.GetElement("BlurayPlayer Description").TriggerAction(VTBAction.SetIndirectText, blurayPlayer.Description);
FormattedTextCollection.GetElement("BlurayPlayer GUID").TriggerAction(VTBAction.SetIndirectText, blurayPlayer.Guid.ToString());
FormattedTextCollection.GetElement("BlurayPlayer Manufacturer").TriggerAction(VTBAction.SetIndirectText, blurayPlayer.Manufacturer);
FormattedTextCollection.GetElement("BlurayPlayer Version").TriggerAction(VTBAction.SetIndirectText, blurayPlayer.Version);
FormattedTextCollection.GetElement("BlurayPlayer VersionDate").TriggerAction(VTBAction.SetIndirectText, blurayPlayer.VersionDate.ToString());
FormattedTextCollection.GetElement("BlurayPlayer SupportsFeedback").TriggerAction(VTBAction.SetIndirectText, blurayPlayer.SupportsFeedback.ToString());
if (ControlSystem._blurayPlayer.Description.Contains("Generic IR"))
{
ButtonCollection.GetElement("BlurayPlayer EnableLogging").TriggerAction(VTBAction.SetEnableState, false);
ButtonCollection.GetElement("BlurayPlayer DisableLogging").TriggerAction(VTBAction.SetEnableState, false);
}
else
{
ButtonCollection.GetElement("BlurayPlayer EnableLogging").TriggerAction(VTBAction.SetEnableState, true);
ButtonCollection.GetElement("BlurayPlayer DisableLogging").TriggerAction(VTBAction.SetEnableState, true);
}
#endregion
#region Advanced
if (ControlSystem._blurayPlayer.Description.Contains("Generic IR"))
{
ButtonCollection.GetElement("BlurayPlayer EnableRxOut").TriggerAction(VTBAction.SetEnableState, false);
ButtonCollection.GetElement("BlurayPlayer DisableRxOut").TriggerAction(VTBAction.SetEnableState, false);
}
else
{
ButtonCollection.GetElement("BlurayPlayer EnableRxOut").TriggerAction(VTBAction.SetEnableState, true);
ButtonCollection.GetElement("BlurayPlayer DisableRxOut").TriggerAction(VTBAction.SetEnableState, true);
}
ButtonCollection.GetElement("BlurayPlayer DisableRxOut").TriggerAction(VTBAction.PressButton, true);
FormattedTextCollection.GetElement("BlurayPlayer PlaybackStatus").TriggerAction(VTBAction.SetEnableState, blurayPlayer.SupportsPlayBackStatusFeedback);
FormattedTextCollection.GetElement("BlurayPlayer TrackFeedback").TriggerAction(VTBAction.SetEnableState, blurayPlayer.SupportsTrackFeedback);
FormattedTextCollection.GetElement("BlurayPlayer ChapterFeedback").TriggerAction(VTBAction.SetEnableState, blurayPlayer.SupportsChapterFeedback);
FormattedTextCollection.GetElement("BlurayPlayer TrackElapsedTime").TriggerAction(VTBAction.SetEnableState, blurayPlayer.SupportsTrackElapsedTimeFeedback);
FormattedTextCollection.GetElement("BlurayPlayer TrackRemainingTime").TriggerAction(VTBAction.SetEnableState, blurayPlayer.SupportsTotalRemainingTimeFeedback);
FormattedTextCollection.GetElement("BlurayPlayer ChapterElapsedTime").TriggerAction(VTBAction.SetEnableState, blurayPlayer.SupportsChapterElapsedTimeFeedback);
FormattedTextCollection.GetElement("BlurayPlayer ChapterRemainingTime").TriggerAction(VTBAction.SetEnableState, blurayPlayer.SupportsChapterRemainingTimeFeedback);
FormattedTextCollection.GetElement("BlurayPlayer TotalElapsedTime").TriggerAction(VTBAction.SetEnableState, blurayPlayer.SupportsTotalElapsedTimeFeedback);
FormattedTextCollection.GetElement("BlurayPlayer TotalRemainingTime").TriggerAction(VTBAction.SetEnableState, blurayPlayer.SupportsTotalRemainingTimeFeedback);
#endregion
#region Transport Controls
ButtonCollection.GetElement("BlurayPlayer ReverseScan").TriggerAction(VTBAction.SetEnableState, blurayPlayer.SupportsReverseScan);
ButtonCollection.GetElement("BlurayPlayer ReverseSkip").TriggerAction(VTBAction.SetEnableState, blurayPlayer.SupportsReverseSkip);
ButtonCollection.GetElement("BlurayPlayer ForwardSkip").TriggerAction(VTBAction.SetEnableState, blurayPlayer.SupportsForwardScan);
ButtonCollection.GetElement("BlurayPlayer ForwardScan").TriggerAction(VTBAction.SetEnableState, blurayPlayer.SupportsForwardSkip);
ButtonCollection.GetElement("BlurayPlayer Play").TriggerAction(VTBAction.SetEnableState, blurayPlayer.SupportsPlay);
ButtonCollection.GetElement("BlurayPlayer Pause").TriggerAction(VTBAction.SetEnableState, blurayPlayer.SupportsPause);
ButtonCollection.GetElement("BlurayPlayer Stop").TriggerAction(VTBAction.SetEnableState, blurayPlayer.SupportsStop);
ButtonCollection.GetElement("BlurayPlayer Audio").TriggerAction(VTBAction.SetEnableState, blurayPlayer.SupportsAudio);
ButtonCollection.GetElement("BlurayPlayer Display").TriggerAction(VTBAction.SetEnableState, blurayPlayer.SupportsDisplay);
ButtonCollection.GetElement("BlurayPlayer Menu").TriggerAction(VTBAction.SetEnableState, blurayPlayer.SupportsMenu);
ButtonCollection.GetElement("BlurayPlayer Repeat").TriggerAction(VTBAction.SetEnableState, blurayPlayer.SupportsRepeat);
ButtonCollection.GetElement("BlurayPlayer Return").TriggerAction(VTBAction.SetEnableState, blurayPlayer.SupportsReturn);
ButtonCollection.GetElement("BlurayPlayer Exit").TriggerAction(VTBAction.SetEnableState, blurayPlayer.SupportsExit);
ButtonCollection.GetElement("BlurayPlayer Back").TriggerAction(VTBAction.SetEnableState, blurayPlayer.SupportsBack);
ButtonCollection.GetElement("BlurayPlayer Eject").TriggerAction(VTBAction.SetEnableState, blurayPlayer.SupportsEject);
ButtonCollection.GetElement("BlurayPlayer Subtitle").TriggerAction(VTBAction.SetEnableState, blurayPlayer.SupportsSubtitle);
ButtonCollection.GetElement("BlurayPlayer Options").TriggerAction(VTBAction.SetEnableState, blurayPlayer.SupportsOptions);
SmartObjectCollection.GetElement("BlurayPlayer Control DPad").TriggerAction(VTSAction.SetEnabledState, blurayPlayer.SupportsArrowKeys);
SmartObjectCollection.GetElement("BlurayPlayer Keypad").TriggerAction(VTSAction.SetEnabledState, blurayPlayer.SupportsKeypadNumber);
#endregion
}
private void DisplayLogOut(string message)
{
FormattedTextCollection.GetElement("DisplayLog").TriggerAction(VTBAction.SetIndirectText, message);
CrestronConsole.PrintLine("Message={0}", message);
}
private void DisplayRxOut(string message)
{
FormattedTextCollection.GetElement("DisplayRxOut").TriggerAction(VTBAction.SetIndirectText, message);
CrestronConsole.PrintLine("RxOutMessage={0}", message);
}
private void CableBoxLogOut(string message)
{
FormattedTextCollection.GetElement("CableBox Log").TriggerAction(VTBAction.SetIndirectText, message);
CrestronConsole.PrintLine("Message={0}", message);
}
private void CableBoxRxOut(string message)
{
FormattedTextCollection.GetElement("CableBox RxOut").TriggerAction(VTBAction.SetIndirectText, message);
CrestronConsole.PrintLine("RxOutMessage={0}", message);
}
private void VideoServerLogOut(string message)
{
FormattedTextCollection.GetElement("VideoServer Log").TriggerAction(VTBAction.SetIndirectText, message);
CrestronConsole.PrintLine("Message={0}", message);
}
private void VideoServerRxOut(string message)
{
FormattedTextCollection.GetElement("VideoServer RxOut").TriggerAction(VTBAction.SetIndirectText, message);
CrestronConsole.PrintLine("RxOutMessage={0}", message);
}
private void BlurayPlayerLogOut(string message)
{
FormattedTextCollection.GetElement("BlurayPlayer Log").TriggerAction(VTBAction.SetIndirectText, message);
CrestronConsole.PrintLine("Message={0}", message);
}
private void BlurayPlayerRxOut(string message)
{
FormattedTextCollection.GetElement("BlurayPlayer RxOut").TriggerAction(VTBAction.SetIndirectText, message);
CrestronConsole.PrintLine("RxOutMessage={0}", message);
}
public ControlSystem ControlSystem { get; private set; }
//Smart Object callbacks
public VTSDisplayMethods VTSDisplayMethods { get; private set; }
public VTSCableBoxMethods VTSCableBoxMethods { get; private set; }
public VTSVideoServerMethods VTSVideoServerMethods { get; private set; }
public VTSBlurayPlayerMethods VTSBlurayPlayerMethods { get; private set; }
//Element callbacks
public DisplayVTButtons DisplayButtons { get; private set; }
public DisplayVTSliders DisplaySliders { get; private set; }
public DisplayVTTextEntryBoxes DisplayTextEntryBoxes { get; private set; }
public CableBoxVTButtons CableBoxButtons { get; private set; }
public CableBoxVTSliders CableBoxSliders { get; private set; }
public CableBoxVTTextEntryBoxes CableBoxTextEntryBoxes { get; private set; }
public VideoServerVTButtons VideoServerButtons { get; private set; }
public VideoServerVTTextEntryBoxes VideoServerTextEntryBoxes { get; private set; }
public BlurayPlayerVTButtons BlurayPlayerButtons { get; private set; }
public BlurayPlayerVTTextEntryBoxes BlurayPlayerTextBoxes { get; private set; }
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.Management.Automation.Language;
using System.Management.Automation.Host;
using System.Management.Automation.Runspaces;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Security;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation.Internal.Host
{
internal partial
class InternalHostUserInterface : PSHostUserInterface, IHostUISupportsMultipleChoiceSelection
{
internal
InternalHostUserInterface(PSHostUserInterface externalUI, InternalHost parentHost)
{
// externalUI may be null
_externalUI = externalUI;
// parent may not be null, however
Dbg.Assert(parentHost != null, "parent may not be null");
if (parentHost == null)
{
throw PSTraceSource.NewArgumentNullException("parentHost");
}
_parent = parentHost;
PSHostRawUserInterface rawui = null;
if (externalUI != null)
{
rawui = externalUI.RawUI;
}
_internalRawUI = new InternalHostRawUserInterface(rawui, _parent);
}
private
void
ThrowNotInteractive()
{
_internalRawUI.ThrowNotInteractive();
}
private
void
ThrowPromptNotInteractive(string promptMessage)
{
string message = StringUtil.Format(HostInterfaceExceptionsStrings.HostFunctionPromptNotImplemented, promptMessage);
HostException e = new HostException(
message,
null,
"HostFunctionNotImplemented",
ErrorCategory.NotImplemented);
throw e;
}
/// <summary>
///
/// See base class
///
/// </summary>
/// <value></value>
/// <exception/>
public override
System.Management.Automation.Host.PSHostRawUserInterface
RawUI
{
get
{
return _internalRawUI;
}
}
public override bool SupportsVirtualTerminal
{
get { return _externalUI.SupportsVirtualTerminal; }
}
/// <summary>
///
/// See base class
///
/// </summary>
/// <exception cref="HostException">
///
/// if the UI property of the external host is null, possibly because the PSHostUserInterface is not
/// implemented by the external host
///
/// </exception>
public override
string
ReadLine()
{
if (_externalUI == null)
{
ThrowNotInteractive();
}
string result = null;
try
{
result = _externalUI.ReadLine();
}
catch (PipelineStoppedException)
{
//PipelineStoppedException is thrown by host when it wants
//to stop the pipeline.
LocalPipeline lpl = (LocalPipeline)((RunspaceBase)_parent.Context.CurrentRunspace).GetCurrentlyRunningPipeline();
if (lpl == null)
{
throw;
}
lpl.Stopper.Stop();
}
return result;
}
/// <summary>
///
/// See base class
///
/// </summary>
/// <exception cref="HostException">
///
/// if the UI property of the external host is null, possibly because the PSHostUserInterface is not
/// implemented by the external host
///
/// </exception>
public override
SecureString
ReadLineAsSecureString()
{
if (_externalUI == null)
{
ThrowNotInteractive();
}
SecureString result = null;
try
{
result = _externalUI.ReadLineAsSecureString();
}
catch (PipelineStoppedException)
{
//PipelineStoppedException is thrown by host when it wants
//to stop the pipeline.
LocalPipeline lpl = (LocalPipeline)((RunspaceBase)_parent.Context.CurrentRunspace).GetCurrentlyRunningPipeline();
if (lpl == null)
{
throw;
}
lpl.Stopper.Stop();
}
return result;
}
/// <summary>
///
/// See base class
///
/// </summary>
/// <param name="value">
/// </param>
/// <exception cref="HostException">
///
/// if <paramref name="value"/> is not null and the UI property of the external host is null,
/// possibly because the PSHostUserInterface is not implemented by the external host
///
/// </exception>
public override
void
Write(string value)
{
if (value == null)
{
return;
}
if (_externalUI == null)
{
return;
}
_externalUI.Write(value);
}
/// <summary>
///
/// See base class
///
/// </summary>
/// <param name="foregroundColor">
/// </param>
/// <param name="backgroundColor">
/// </param>
/// <param name="value">
/// </param>
/// <exception cref="HostException">
///
/// if <paramref name="value"/> is not null and the UI property of the external host is null,
/// possibly because the PSHostUserInterface is not implemented by the external host
///
/// </exception>
public override
void
Write(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string value)
{
if (value == null)
{
return;
}
if (_externalUI == null)
{
return;
}
_externalUI.Write(foregroundColor, backgroundColor, value);
}
/// <summary>
///
/// See base class
///
/// <seealso cref="Write(string)"/>
/// <seealso cref="WriteLine(string)"/>
/// </summary>
/// <exception cref="HostException">
///
/// if the UI property of the external host is null, possibly because the PSHostUserInterface is not
/// implemented by the external host
///
/// </exception>
public override
void
WriteLine()
{
if (_externalUI == null)
{
return;
}
_externalUI.WriteLine();
}
/// <summary>
///
/// See base class
///
/// </summary>
/// <param name="value">
/// </param>
/// <exception cref="HostException">
///
/// if <paramref name="value"/> is not null and the UI property of the external host is null,
/// possibly because the PSHostUserInterface is not implemented by the external host
///
/// </exception>
public override
void
WriteLine(string value)
{
if (value == null)
{
return;
}
if (_externalUI == null)
{
return;
}
_externalUI.WriteLine(value);
}
public override
void
WriteErrorLine(string value)
{
if (value == null)
{
return;
}
if (_externalUI == null)
{
return;
}
_externalUI.WriteErrorLine(value);
}
/// <summary>
///
/// See base class
///
/// </summary>
/// <param name="foregroundColor">
/// </param>
/// <param name="backgroundColor">
/// </param>
/// <param name="value">
/// </param>
/// <exception cref="HostException">
///
/// if <paramref name="value"/> is not null and the UI property of the external host is null,
/// possibly because the PSHostUserInterface is not implemented by the external host
///
/// </exception>
public override
void
WriteLine(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string value)
{
if (value == null)
{
return;
}
if (_externalUI == null)
{
return;
}
_externalUI.WriteLine(foregroundColor, backgroundColor, value);
}
/// <summary>
///
/// See base class
///
/// </summary>
/// <exception cref="HostException">
///
/// if <paramref name="message"/> is not null and the UI property of the external host is null,
/// possibly because the PSHostUserInterface is not implemented by the external host
///
/// </exception>
public override
void
WriteDebugLine(string message)
{
WriteDebugLineHelper(message);
}
/// <summary>
///
/// </summary>
internal void WriteDebugRecord(DebugRecord record)
{
WriteDebugInfoBuffers(record);
if (_externalUI == null)
{
return;
}
_externalUI.WriteDebugLine(record.Message);
}
/// <summary>
/// Writes the DebugRecord to informational buffers.
/// </summary>
/// <param name="record">DebugRecord</param>
internal void WriteDebugInfoBuffers(DebugRecord record)
{
if (_informationalBuffers != null)
{
_informationalBuffers.AddDebug(record);
}
}
/// <summary>
/// Helper function for WriteDebugLine
/// </summary>
/// <param name="message"></param>
/// <param name="preference"></param>
/// <exception cref="ActionPreferenceStopException">
///
/// If the debug preference is set to ActionPreference.Stop
///
/// </exception>
/// <exception cref="ActionPreferenceStopException">
///
/// If the debug preference is set to ActionPreference.Inquire and user requests to stop execution.
///
/// </exception>
/// <exception cref="ArgumentException">
///
/// If the debug preference is not a valid ActionPrefernce value.
///
/// </exception>
internal
void
WriteDebugLine(string message, ref ActionPreference preference)
{
string errorMsg = null;
ErrorRecord errorRecord = null;
switch (preference)
{
case ActionPreference.Continue:
WriteDebugLineHelper(message);
break;
case ActionPreference.SilentlyContinue:
case ActionPreference.Ignore:
break;
case ActionPreference.Inquire:
if (!DebugShouldContinue(message, ref preference))
{
// user asked to exit with an error
errorMsg = InternalHostUserInterfaceStrings.WriteDebugLineStoppedError;
errorRecord = new ErrorRecord(new ParentContainsErrorRecordException(errorMsg),
"UserStopRequest", ErrorCategory.OperationStopped, null);
ActionPreferenceStopException e = new ActionPreferenceStopException(errorRecord);
// We cannot call ThrowTerminatingError since this is not a cmdlet or provider
throw e;
}
else
{
WriteDebugLineHelper(message);
}
break;
case ActionPreference.Stop:
WriteDebugLineHelper(message);
errorMsg = InternalHostUserInterfaceStrings.WriteDebugLineStoppedError;
errorRecord = new ErrorRecord(new ParentContainsErrorRecordException(errorMsg),
"ActionPreferenceStop", ErrorCategory.OperationStopped, null);
ActionPreferenceStopException ense = new ActionPreferenceStopException(errorRecord);
// We cannot call ThrowTerminatingError since this is not a cmdlet or provider
throw ense;
default:
Dbg.Assert(false, "all preferences should be checked");
throw PSTraceSource.NewArgumentException("preference",
InternalHostUserInterfaceStrings.UnsupportedPreferenceError, preference);
// break;
}
}
/// <summary>
/// If informationBuffers is not null, the respective messages will also
/// be written to the buffers along with external host.
/// </summary>
/// <param name="informationalBuffers">
/// Buffers to which Debug, Verbose, Warning, Progress, Information messages
/// will be writtern to.
/// </param>
/// <remarks>
/// This method is not thread safe. Caller should make sure of the
/// assosciated risks.
/// </remarks>
internal void SetInformationalMessageBuffers(PSInformationalBuffers informationalBuffers)
{
_informationalBuffers = informationalBuffers;
}
/// <summary>
/// Gets the informational message buffers of the host
/// </summary>
/// <returns>informational message buffers</returns>
internal PSInformationalBuffers GetInformationalMessageBuffers()
{
return _informationalBuffers;
}
private
void
WriteDebugLineHelper(string message)
{
if (message == null)
{
return;
}
WriteDebugRecord(new DebugRecord(message));
}
/// <summary>
///
/// Ask the user whether to continue/stop or break to a nested prompt.
///
/// </summary>
/// <param name="message">
///
/// Message to display to the user. This routine will append the text "Continue" to ensure that people know what question
/// they are answering.
///
/// </param>
/// <param name="actionPreference">
///
/// Preference setting which determines the behaviour. This is by-ref and will be modified based upon what the user
/// types. (e.g. YesToAll will change Inquire => NotifyContinue)
///
/// </param>
private
bool
DebugShouldContinue(string message, ref ActionPreference actionPreference)
{
Dbg.Assert(actionPreference == ActionPreference.Inquire, "Why are you inquiring if your preference is not to?");
bool shouldContinue = false;
Collection<ChoiceDescription> choices = new Collection<ChoiceDescription>();
choices.Add(new ChoiceDescription(InternalHostUserInterfaceStrings.ShouldContinueYesLabel, InternalHostUserInterfaceStrings.ShouldContinueYesHelp));
choices.Add(new ChoiceDescription(InternalHostUserInterfaceStrings.ShouldContinueYesToAllLabel, InternalHostUserInterfaceStrings.ShouldContinueYesToAllHelp));
choices.Add(new ChoiceDescription(InternalHostUserInterfaceStrings.ShouldContinueNoLabel, InternalHostUserInterfaceStrings.ShouldContinueNoHelp));
choices.Add(new ChoiceDescription(InternalHostUserInterfaceStrings.ShouldContinueNoToAllLabel, InternalHostUserInterfaceStrings.ShouldContinueNoToAllHelp));
choices.Add(new ChoiceDescription(InternalHostUserInterfaceStrings.ShouldContinueSuspendLabel, InternalHostUserInterfaceStrings.ShouldContinueSuspendHelp));
bool endLoop = true;
do
{
endLoop = true;
switch (
PromptForChoice(
InternalHostUserInterfaceStrings.ShouldContinuePromptMessage,
message,
choices,
0))
{
case 0:
shouldContinue = true;
break;
case 1:
actionPreference = ActionPreference.Continue;
shouldContinue = true;
break;
case 2:
shouldContinue = false;
break;
case 3:
// No to All means that we want to stop everytime WriteDebug is called. Since No throws an error, I
// think that ordinarily, the caller will terminate. So I don't think the caller will ever get back
// calling WriteDebug again, and thus "No to All" might not be a useful option to have.
actionPreference = ActionPreference.Stop;
shouldContinue = false;
break;
case 4:
// This call returns when the user exits the nested prompt.
_parent.EnterNestedPrompt();
endLoop = false;
break;
}//switch
} while (endLoop != true);
return shouldContinue;
}
/// <summary>
///
/// See base class
///
/// </summary>
/// <exception cref="HostException">
///
/// if <paramref name="record"/> is not null and the UI property of the external host is null,
/// possibly because the PSHostUserInterface is not implemented by the external host
///
/// </exception>
public override
void
WriteProgress(Int64 sourceId, ProgressRecord record)
{
if (record == null)
{
throw PSTraceSource.NewArgumentNullException("record");
}
// Write to Information Buffers
if (null != _informationalBuffers)
{
_informationalBuffers.AddProgress(record);
}
if (_externalUI == null)
{
return;
}
_externalUI.WriteProgress(sourceId, record);
}
/// <summary>
///
/// See base class
///
/// </summary>
/// <exception cref="HostException">
///
/// if <paramref name="message"/> is not null and the UI property of the external host is null,
/// possibly because the PSHostUserInterface is not implemented by the external host
///
/// </exception>
public override
void
WriteVerboseLine(string message)
{
if (message == null)
{
return;
}
WriteVerboseRecord(new VerboseRecord(message));
}
/// <summary>
///
/// </summary>
internal void WriteVerboseRecord(VerboseRecord record)
{
WriteVerboseInfoBuffers(record);
if (_externalUI == null)
{
return;
}
_externalUI.WriteVerboseLine(record.Message);
}
/// <summary>
/// Writes the VerboseRecord to informational buffers.
/// </summary>
/// <param name="record">VerboseRecord</param>
internal void WriteVerboseInfoBuffers(VerboseRecord record)
{
if (_informationalBuffers != null)
{
_informationalBuffers.AddVerbose(record);
}
}
/// <summary>
///
/// See base class
///
/// </summary>
/// <exception cref="HostException">
///
/// if <paramref name="message"/> is not null and the UI property of the external host is null,
/// possibly because the PSHostUserInterface is not implemented by the external host
///
/// </exception>
public override void WriteWarningLine(string message)
{
if (message == null)
{
return;
}
WriteWarningRecord(new WarningRecord(message));
}
/// <summary>
///
/// </summary>
internal void WriteWarningRecord(WarningRecord record)
{
WriteWarningInfoBuffers(record);
if (_externalUI == null)
{
return;
}
_externalUI.WriteWarningLine(record.Message);
}
/// <summary>
/// Writes the WarningRecord to informational buffers.
/// </summary>
/// <param name="record">WarningRecord</param>
internal void WriteWarningInfoBuffers(WarningRecord record)
{
if (_informationalBuffers != null)
{
_informationalBuffers.AddWarning(record);
}
}
/// <summary>
///
/// </summary>
internal void WriteInformationRecord(InformationRecord record)
{
WriteInformationInfoBuffers(record);
if (_externalUI == null)
{
return;
}
_externalUI.WriteInformation(record);
}
/// <summary>
/// Writes the InformationRecord to informational buffers.
/// </summary>
/// <param name="record">WarningRecord</param>
internal void WriteInformationInfoBuffers(InformationRecord record)
{
if (_informationalBuffers != null)
{
_informationalBuffers.AddInformation(record);
}
}
internal static Type GetFieldType(FieldDescription field)
{
Type result;
if (TypeResolver.TryResolveType(field.ParameterAssemblyFullName, out result) ||
TypeResolver.TryResolveType(field.ParameterTypeFullName, out result))
{
return result;
}
return null;
}
internal static bool IsSecuritySensitiveType(string typeName)
{
if (typeName.Equals(typeof(PSCredential).Name, StringComparison.OrdinalIgnoreCase))
{
return true;
}
if (typeName.Equals(typeof(SecureString).Name, StringComparison.OrdinalIgnoreCase))
{
return true;
}
return false;
}
/// <summary>
///
/// See base class
///
/// </summary>
/// <param name="caption">
/// </param>
/// <param name="message">
/// </param>
/// <param name="descriptions">
/// </param>
/// <exception cref="ArgumentNullException">
///
/// If <paramref name="descriptions"/> is null.
///
/// </exception>
/// <exception cref="ArgumentException">
///
/// If <paramref name="descriptions"/>.Count is less than 1.
///
/// </exception>
/// <exception cref="HostException">
///
/// if the UI property of the external host is null,
/// possibly because the PSHostUserInterface is not implemented by the external host
///
/// </exception>
public override
Dictionary<String, PSObject>
Prompt(string caption, string message, Collection<FieldDescription> descriptions)
{
if (descriptions == null)
{
throw PSTraceSource.NewArgumentNullException("descriptions");
}
if (descriptions.Count < 1)
{
throw PSTraceSource.NewArgumentException("descriptions", InternalHostUserInterfaceStrings.PromptEmptyDescriptionsError, "descriptions");
}
if (_externalUI == null)
{
ThrowPromptNotInteractive(message);
}
Dictionary<String, PSObject> result = null;
try
{
result = _externalUI.Prompt(caption, message, descriptions);
}
catch (PipelineStoppedException)
{
//PipelineStoppedException is thrown by host when it wants
//to stop the pipeline.
LocalPipeline lpl = (LocalPipeline)((RunspaceBase)_parent.Context.CurrentRunspace).GetCurrentlyRunningPipeline();
if (lpl == null)
{
throw;
}
lpl.Stopper.Stop();
}
return result;
}
/// <summary>
///
/// See base class
///
/// </summary>
/// <param name="caption"></param>
/// <param name="message"></param>
/// <param name="choices"></param>
/// <param name="defaultChoice">
/// </param>
/// <exception cref="HostException">
///
/// if the UI property of the external host is null,
/// possibly because the PSHostUserInterface is not implemented by the external host
///
/// </exception>
public override
int
PromptForChoice(string caption, string message, Collection<ChoiceDescription> choices, int defaultChoice)
{
if (_externalUI == null)
{
ThrowPromptNotInteractive(message);
}
int result = -1;
try
{
result = _externalUI.PromptForChoice(caption, message, choices, defaultChoice);
}
catch (PipelineStoppedException)
{
//PipelineStoppedException is thrown by host when it wants
//to stop the pipeline.
LocalPipeline lpl = (LocalPipeline)((RunspaceBase)_parent.Context.CurrentRunspace).GetCurrentlyRunningPipeline();
if (lpl == null)
{
throw;
}
lpl.Stopper.Stop();
}
return result;
}
/// <summary>
/// Presents a dialog allowing the user to choose options from a set of options.
/// </summary>
/// <param name="caption">
/// Caption to preceed or title the prompt. E.g. "Parameters for get-foo (instance 1 of 2)"
/// </param>
/// <param name="message">
/// A message that describes what the choice is for.
/// </param>
/// <param name="choices">
/// An Collection of ChoiceDescription objects that describe each choice.
/// </param>
/// <param name="defaultChoices">
/// The index of the labels in the choices collection element to be presented to the user as
/// the default choice(s).
/// </param>
/// <returns>
/// The indices of the choice elements that corresponds to the options selected.
/// </returns>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.PromptForChoice"/>
public Collection<int> PromptForChoice(string caption,
string message,
Collection<ChoiceDescription> choices,
IEnumerable<int> defaultChoices)
{
if (_externalUI == null)
{
ThrowPromptNotInteractive(message);
}
IHostUISupportsMultipleChoiceSelection hostForMultipleChoices =
_externalUI as IHostUISupportsMultipleChoiceSelection;
Collection<int> result = null;
try
{
if (null == hostForMultipleChoices)
{
// host did not implement this new interface..
// so work with V1 host API to get the behavior..
// this will allow Hosts that were developed with
// V1 API to interact with PowerShell V2.
result = EmulatePromptForMultipleChoice(caption, message, choices, defaultChoices);
}
else
{
result = hostForMultipleChoices.PromptForChoice(caption, message, choices, defaultChoices);
}
}
catch (PipelineStoppedException)
{
//PipelineStoppedException is thrown by host when it wants
//to stop the pipeline.
LocalPipeline lpl = (LocalPipeline)((RunspaceBase)_parent.Context.CurrentRunspace).GetCurrentlyRunningPipeline();
if (lpl == null)
{
throw;
}
lpl.Stopper.Stop();
}
return result;
}
/// <summary>
/// This method is added to be backward compatible with V1 hosts w.r.t
/// new PromptForChoice method added in PowerShell V2.
/// </summary>
/// <param name="caption"></param>
/// <param name="message"></param>
/// <param name="choices"></param>
/// <param name="defaultChoices"></param>
/// <returns></returns>
/// <exception cref="ArgumentException">
/// 1. Choices is null.
/// 2. Choices.Count = 0
/// 3. DefaultChoice is either less than 0 or greater than Choices.Count
/// </exception>
private Collection<int> EmulatePromptForMultipleChoice(string caption,
string message,
Collection<ChoiceDescription> choices,
IEnumerable<int> defaultChoices)
{
Dbg.Assert(null != _externalUI, "externalUI cannot be null.");
if (choices == null)
{
throw PSTraceSource.NewArgumentNullException("choices");
}
if (choices.Count == 0)
{
throw PSTraceSource.NewArgumentException("choices",
InternalHostUserInterfaceStrings.EmptyChoicesError, "choices");
}
Dictionary<int, bool> defaultChoiceKeys = new Dictionary<int, bool>();
if (null != defaultChoices)
{
foreach (int defaultChoice in defaultChoices)
{
if ((defaultChoice < 0) || (defaultChoice >= choices.Count))
{
throw PSTraceSource.NewArgumentOutOfRangeException("defaultChoice", defaultChoice,
InternalHostUserInterfaceStrings.InvalidDefaultChoiceForMultipleSelection,
"defaultChoice",
"choices",
defaultChoice);
}
if (!defaultChoiceKeys.ContainsKey(defaultChoice))
{
defaultChoiceKeys.Add(defaultChoice, true);
}
}
}
// Construct the caption + message + list of choices + default choices
Text.StringBuilder choicesMessage = new Text.StringBuilder();
char newLine = '\n';
if (!string.IsNullOrEmpty(caption))
{
choicesMessage.Append(caption);
choicesMessage.Append(newLine);
}
if (!string.IsNullOrEmpty(message))
{
choicesMessage.Append(message);
choicesMessage.Append(newLine);
}
string[,] hotkeysAndPlainLabels = null;
HostUIHelperMethods.BuildHotkeysAndPlainLabels(choices, out hotkeysAndPlainLabels);
string choiceTemplate = "[{0}] {1} ";
for (int i = 0; i < hotkeysAndPlainLabels.GetLength(1); ++i)
{
string choice =
String.Format(
Globalization.CultureInfo.InvariantCulture,
choiceTemplate,
hotkeysAndPlainLabels[0, i],
hotkeysAndPlainLabels[1, i]);
choicesMessage.Append(choice);
choicesMessage.Append(newLine);
}
// default choices
string defaultPrompt = "";
if (defaultChoiceKeys.Count > 0)
{
string prepend = "";
Text.StringBuilder defaultChoicesBuilder = new Text.StringBuilder();
foreach (int defaultChoice in defaultChoiceKeys.Keys)
{
string defaultStr = hotkeysAndPlainLabels[0, defaultChoice];
if (string.IsNullOrEmpty(defaultStr))
{
defaultStr = hotkeysAndPlainLabels[1, defaultChoice];
}
defaultChoicesBuilder.Append(string.Format(Globalization.CultureInfo.InvariantCulture,
"{0}{1}", prepend, defaultStr));
prepend = ",";
}
string defaultChoicesStr = defaultChoicesBuilder.ToString();
if (defaultChoiceKeys.Count == 1)
{
defaultPrompt = StringUtil.Format(InternalHostUserInterfaceStrings.DefaultChoice,
defaultChoicesStr);
}
else
{
defaultPrompt = StringUtil.Format(InternalHostUserInterfaceStrings.DefaultChoicesForMultipleChoices,
defaultChoicesStr);
}
}
string messageToBeDisplayed = choicesMessage.ToString() + defaultPrompt + newLine;
// read choices from the user
Collection<int> result = new Collection<int>();
int choicesSelected = 0;
do
{
string choiceMsg = StringUtil.Format(InternalHostUserInterfaceStrings.ChoiceMessage, choicesSelected);
messageToBeDisplayed += choiceMsg;
_externalUI.WriteLine(messageToBeDisplayed);
string response = _externalUI.ReadLine();
// they just hit enter
if (response.Length == 0)
{
// this may happen when
// 1. user wants to go with the defaults
// 2. user selected some choices and wanted those
// choices to be picked.
// user did not pick up any choices..choose the default
if ((result.Count == 0) && (defaultChoiceKeys.Keys.Count >= 0))
{
// if there's a default, pick that one.
foreach (int defaultChoice in defaultChoiceKeys.Keys)
{
result.Add(defaultChoice);
}
}
// allow for no choice selection.
break;
}
int choicePicked = HostUIHelperMethods.DetermineChoicePicked(response.Trim(), choices, hotkeysAndPlainLabels);
if (choicePicked >= 0)
{
result.Add(choicePicked);
choicesSelected++;
}
// reset messageToBeDisplayed
messageToBeDisplayed = "";
} while (true);
return result;
}
private PSHostUserInterface _externalUI = null;
private InternalHostRawUserInterface _internalRawUI = null;
private InternalHost _parent = null;
private PSInformationalBuffers _informationalBuffers = null;
}
} // namespace
| |
// Copyright (C) 2015 Google, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Reflection;
using GoogleMobileAds.Api;
using UnityEngine;
namespace GoogleMobileAds.Common
{
public class DummyClient : IBannerClient, IInterstitialClient, IRewardBasedVideoAdClient,
IAdLoaderClient, IMobileAdsClient
{
public DummyClient()
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
}
// Disable warnings for unused dummy ad events.
#pragma warning disable 67
public event EventHandler<EventArgs> OnAdLoaded;
public event EventHandler<AdFailedToLoadEventArgs> OnAdFailedToLoad;
public event EventHandler<EventArgs> OnAdOpening;
public event EventHandler<EventArgs> OnAdStarted;
public event EventHandler<EventArgs> OnAdClosed;
public event EventHandler<Reward> OnAdRewarded;
public event EventHandler<EventArgs> OnAdLeavingApplication;
public event EventHandler<EventArgs> OnAdCompleted;
public event EventHandler<CustomNativeEventArgs> OnCustomNativeTemplateAdLoaded;
#pragma warning restore 67
public string UserId
{
get
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
return "UserId";
}
set
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
}
}
public void Initialize(string appId)
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
}
public void SetApplicationMuted(bool muted)
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
}
public void SetApplicationVolume(float volume)
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
}
public void SetiOSAppPauseOnBackground(bool pause)
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
}
public void CreateBannerView(string adUnitId, AdSize adSize, AdPosition position)
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
}
public void CreateBannerView(string adUnitId, AdSize adSize, int positionX, int positionY)
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
}
public void LoadAd(AdRequest request)
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
}
public void ShowBannerView()
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
}
public void HideBannerView()
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
}
public void DestroyBannerView()
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
}
public float GetHeightInPixels()
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
return 0;
}
public float GetWidthInPixels()
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
return 0;
}
public void SetPosition(AdPosition adPosition)
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
}
public void SetPosition(int x, int y)
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
}
public void CreateInterstitialAd(string adUnitId)
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
}
public bool IsLoaded()
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
return true;
}
public void ShowInterstitial()
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
}
public void DestroyInterstitial()
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
}
public void CreateRewardBasedVideoAd()
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
}
public void SetUserId(string userId)
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
}
public void LoadAd(AdRequest request, string adUnitId)
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
}
public void DestroyRewardBasedVideoAd()
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
}
public void ShowRewardBasedVideoAd()
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
}
public void CreateAdLoader(AdLoader.Builder builder)
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
}
public void Load(AdRequest request)
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
}
public void SetAdSize(AdSize adSize)
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
}
public string MediationAdapterClassName()
{
Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);
return null;
}
}
}
| |
// 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.Testing;
using Xunit;
using VerifyCS = Test.Utilities.CSharpCodeFixVerifier<
Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.DoNotHideBaseClassMethodsAnalyzer,
Microsoft.CodeQuality.CSharp.Analyzers.ApiDesignGuidelines.CSharpDoNotHideBaseClassMethodsFixer>;
using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier<
Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.DoNotHideBaseClassMethodsAnalyzer,
Microsoft.CodeQuality.VisualBasic.Analyzers.ApiDesignGuidelines.BasicDoNotHideBaseClassMethodsFixer>;
namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.UnitTests
{
public class DoNotHideBaseClassMethodsTests
{
[Fact]
public async Task CA1061_DerivedMethodMatchesBaseMethod_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
class Base
{
public void Method(string input)
{
}
}
class Derived : Base
{
public void Method(string input)
{
}
}");
await VerifyVB.VerifyAnalyzerAsync(@"
Class Base
Public Sub Method(input As String)
End Sub
End Class
Class Derived
Inherits Base
Public Sub Method(input As String)
End Sub
End Class");
}
[Fact]
public async Task CA1061_DerivedMethodHasMoreDerivedParameter_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
class Base
{
public void Method(object input)
{
}
}
class Derived : Base
{
public void Method(string input)
{
}
}");
await VerifyVB.VerifyAnalyzerAsync(@"
Class Base
Public Sub Method(input As Object)
End Sub
End Class
Class Derived
Inherits Base
Public Sub Method(input As String)
End Sub
End Class");
}
[Fact]
public async Task CA1061_DerivedMethodHasLessDerivedParameter_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
class Base
{
public void Method(string input)
{
}
}
class Derived : Base
{
public void Method(object input)
{
}
}",
GetCA1061CSharpResultAt(11, 17, "Derived.Method(object)", "Base.Method(string)"));
await VerifyVB.VerifyAnalyzerAsync(@"
Class Base
Public Sub Method(input As String)
End Sub
End Class
Class Derived
Inherits Base
Public Sub Method(input As Object)
End Sub
End Class",
GetCA1061BasicResultAt(10, 16, "Public Sub Method(input As Object)", "Public Sub Method(input As String)"));
}
[Fact]
public async Task CA1061_ConstructorCallsBaseConstructorWithDifferentParameterType_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
class Base
{
public Base(string input)
{
}
}
class Derived : Base
{
public Derived(object input)
:base(null)
{
}
}
");
}
[Fact]
public async Task CA1061_DerivedMethodHasLessDerivedParameter_MultipleMethodsHidden_Diagnostics()
{
await VerifyCS.VerifyAnalyzerAsync(@"
class Parent
{
public void Method(string input)
{
}
}
class Child : Parent
{
public void Method(string input)
{
}
}
class Grandchild : Child
{
public void Method(object input)
{
}
}",
GetCA1061CSharpResultAt(18, 17, "Grandchild.Method(object)", "Child.Method(string)"),
GetCA1061CSharpResultAt(18, 17, "Grandchild.Method(object)", "Parent.Method(string)"));
await VerifyVB.VerifyAnalyzerAsync(@"
Class Parent
Public Sub Method(input As String)
End Sub
End Class
Class Child
Inherits Parent
Public Sub Method(input as String)
End Sub
End Class
Class Grandchild
Inherits Child
Public Sub Method(input As Object)
End Sub
End Class",
GetCA1061BasicResultAt(17, 16, "Public Sub Method(input As Object)", "Public Sub Method(input As String)"),
GetCA1061BasicResultAt(17, 16, "Public Sub Method(input As Object)", "Public Sub Method(input As String)"));
}
[Fact]
public async Task CA1061_DerivedMethodHasLessDerivedParameter_ImplementsInterface_CompileError()
{
await VerifyCS.VerifyAnalyzerAsync(@"
interface IFace
{
void Method(string input);
}
class Derived : {|CS0535:IFace|}
{
public void Method(object input)
{
}
}");
await VerifyVB.VerifyAnalyzerAsync(@"
Interface IFace
Sub Method(input As String)
End Interface
Class Derived
Implements {|BC30149:IFace|}
Public Sub Method(input As Object) Implements {|BC30401:IFace.Method|}
End Sub
End Class");
}
[Fact]
public async Task CA1061_DerivedMethodHasLessDerivedParameter_OverridesVirtualBaseMethod_CompileError()
{
await VerifyCS.VerifyAnalyzerAsync(@"
class Base
{
public virtual void {|CS0501:Method|}(string input);
}
class Derived : Base
{
public override void {|CS0115:Method|}(object input)
{
}
}");
await VerifyVB.VerifyAnalyzerAsync(@"
Class Base
Public Overridable Sub Method(input As String)
End Sub
End Class
Class Derived
Inherits Base
Public Overrides Sub {|BC30284:Method|}(input As Object)
End Sub
End Class");
}
[Fact]
public async Task CA1061_DerivedMethodHasLessDerivedParameter_OverridesAbstractBaseMethod_CompileError()
{
await VerifyCS.VerifyAnalyzerAsync(@"
abstract class Base
{
public abstract void Method(string input);
}
class {|CS0534:Derived|} : Base
{
public override void {|CS0115:Method|}(object input)
{
}
}");
await VerifyVB.VerifyAnalyzerAsync(@"
MustInherit Class Base
Public MustOverride Sub Method(input As String)
{|BC30429:End Sub|}
End Class
Class {|BC30610:Derived|}
Inherits Base
Public Overrides Sub {|BC30284:Method|}(input As Object)
End Sub
End Class");
}
[Fact]
public async Task CA1061_DerivedMethodHasLessDerivedParameter_DerivedMethodPrivate_Diagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
class Base
{
public void Method(string input)
{
}
}
class Derived : Base
{
private void Method(object input)
{
}
}",
GetCA1061CSharpResultAt(11, 18, "Derived.Method(object)", "Base.Method(string)"));
await VerifyVB.VerifyAnalyzerAsync(@"
Class Base
Public Sub Method(input As String)
End Sub
End Class
Class Derived
Inherits Base
Public Sub Method(input As Object)
End Sub
End Class
",
GetCA1061BasicResultAt(10, 16, "Public Sub Method(input As Object)", "Public Sub Method(input As String)"));
}
[Fact]
public async Task CA1061_DerivedMethodHasLessDerivedParameter_BaseMethodPrivate_NoDiagnostic()
{
// Note: This behavior differs from FxCop's CA1061
await VerifyCS.VerifyAnalyzerAsync(@"
class Base
{
private void Method(string input)
{
}
}
class Derived : Base
{
public void Method(object input)
{
}
}");
await VerifyVB.VerifyAnalyzerAsync(@"
Class Base
Private Sub Method(input As String)
End Sub
End Class
Class Derived
Inherits Base
Public Sub Method(input As Object)
End Sub
End Class
");
}
[Fact]
public async Task CA1061_DerivedMethodHasLessDerivedParameter_ArityMismatch_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
class Base
{
public void Method(string input, string input2)
{
}
}
class Derived : Base
{
public void Method(object input)
{
}
}");
await VerifyVB.VerifyAnalyzerAsync(@"
Class Base
Private Sub Method(input As String, input2 As String)
End Sub
End Class
Class Derived
Inherits Base
Public Sub Method(input As Object)
End Sub
End Class
");
}
[Fact]
public async Task CA1061_DerivedMethodHasLessDerivedParameter_ReturnTypeMismatch_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
class Base
{
public void Method(string input)
{
}
}
class Derived : Base
{
public int Method(object input)
{
return 0;
}
}");
await VerifyVB.VerifyAnalyzerAsync(@"
Class Base
Private Sub Method(input As String)
End Sub
End Class
Class Derived
Inherits Base
Public Function Method(input As Object) As Integer
Method = 0
End Function
End Class
");
}
[Fact]
public async Task CA1061_DerivedMethodHasLessDerivedParameter_ParameterTypeMismatchAtStart_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
class Base
{
public void Method(int input, string input2)
{
}
}
class Derived : Base
{
public void Method(char input, object input2)
{
}
}");
await VerifyVB.VerifyAnalyzerAsync(@"
Class Base
Private Sub Method(input As Integer, input2 As String)
End Sub
End Class
Class Derived
Inherits Base
Public Sub Method(input As Char, input2 As Object)
End Sub
End Class
");
}
[Fact]
public async Task CA1061_DerivedMethodHasLessDerivedParameter_ParameterTypeMismatchAtEnd_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
class Base
{
public void Method(string input, int input2)
{
}
}
class Derived : Base
{
public void Method(object input, char input2)
{
}
}");
await VerifyVB.VerifyAnalyzerAsync(@"
Class Base
Private Sub Method(input As String, input2 As Integer)
End Sub
End Class
Class Derived
Inherits Base
Public Sub Method(input As Object, input2 As Char)
End Sub
End Class
");
}
private static DiagnosticResult GetCA1061CSharpResultAt(int line, int column, string derivedMethod, string baseMethod)
#pragma warning disable RS0030 // Do not used banned APIs
=> VerifyCS.Diagnostic()
.WithLocation(line, column)
#pragma warning restore RS0030 // Do not used banned APIs
.WithArguments(derivedMethod, baseMethod);
private static DiagnosticResult GetCA1061BasicResultAt(int line, int column, string derivedMethod, string baseMethod)
#pragma warning disable RS0030 // Do not used banned APIs
=> VerifyVB.Diagnostic()
.WithLocation(line, column)
#pragma warning restore RS0030 // Do not used banned APIs
.WithArguments(derivedMethod, baseMethod);
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
// Copyright (c) 2004 Mainsoft Co.
//
// 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 Xunit;
using System.Collections;
namespace System.Data.Tests
{
public class DataRowCollectionTest2
{
[Fact]
public void CopyTo()
{
DataTable dt = DataProvider.CreateParentDataTable();
DataRow[] arr = new DataRow[dt.Rows.Count];
dt.Rows.CopyTo(arr, 0);
Assert.Equal(dt.Rows.Count, arr.Length);
int index = 0;
foreach (DataRow dr in dt.Rows)
{
Assert.Equal(dr, arr[index]);
index++;
}
}
[Fact]
public void Count()
{
DataTable dt = DataProvider.CreateParentDataTable();
Assert.Equal(6, dt.Rows.Count);
dt.Rows.Remove(dt.Rows[0]);
Assert.Equal(5, dt.Rows.Count);
dt.Rows.Add(new object[] { 1, "1-String1", "1-String2", new DateTime(2005, 1, 1, 0, 0, 0, 0), 1.534, true });
Assert.Equal(6, dt.Rows.Count);
}
[Fact]
public void GetEnumerator()
{
DataTable dt = DataProvider.CreateParentDataTable();
IEnumerator myEnumerator = dt.Rows.GetEnumerator();
int index = 0;
while (myEnumerator.MoveNext())
{
Assert.Equal(dt.Rows[index], (DataRow)myEnumerator.Current);
index++;
}
Assert.Equal(index, dt.Rows.Count);
}
[Fact]
public void RemoveAt_ByIndex()
{
DataTable dt = DataProvider.CreateParentDataTable();
int counter = dt.Rows.Count;
dt.PrimaryKey = new DataColumn[] { dt.Columns[0] };
dt.Rows.RemoveAt(3);
Assert.Equal(counter - 1, dt.Rows.Count);
Assert.Equal(null, dt.Rows.Find(4));
}
[Fact]
public void Remove_ByDataRow()
{
DataTable dt = DataProvider.CreateParentDataTable();
int counter = dt.Rows.Count;
dt.PrimaryKey = new DataColumn[] { dt.Columns[0] };
Assert.Equal(dt.Rows[0], dt.Rows.Find(1));
dt.Rows.Remove(dt.Rows[0]);
Assert.Equal(counter - 1, dt.Rows.Count);
Assert.Equal(null, dt.Rows.Find(1));
}
[Fact]
public void DataRowCollection_Add_D1()
{
DataTable dt = DataProvider.CreateParentDataTable();
dt.Rows.Clear();
DataRow dr = dt.NewRow();
dr["ParentId"] = 10;
dr["String1"] = "string1";
dr["String2"] = string.Empty;
dr["ParentDateTime"] = new DateTime(2004, 12, 15);
dr["ParentDouble"] = 3.14;
dr["ParentBool"] = false;
dt.Rows.Add(dr);
Assert.Equal(1, dt.Rows.Count);
Assert.Equal(dr, dt.Rows[0]);
}
[Fact]
public void DataRowCollection_Add_D2()
{
Assert.Throws<ArgumentException>(() =>
{
DataTable dt = DataProvider.CreateParentDataTable();
dt.Rows.Add(dt.Rows[0]);
});
}
[Fact]
public void DataRowCollection_Add_D3()
{
Assert.Throws<ArgumentNullException>(() =>
{
DataTable dt = DataProvider.CreateParentDataTable();
dt.Rows.Add((DataRow)null);
});
}
[Fact]
public void DataRowCollection_Add_D4()
{
Assert.Throws<ArgumentException>(() =>
{
DataTable dt = DataProvider.CreateParentDataTable();
DataTable dt1 = DataProvider.CreateParentDataTable();
dt.Rows.Add(dt1.Rows[0]);
});
}
[Fact]
public void DataRowCollection_Add_O1()
{
DataTable dt = DataProvider.CreateParentDataTable();
dt.Rows.Clear();
dt.Rows.Add(new object[] { 1, "1-String1", "1-String2", new DateTime(2005, 1, 1, 0, 0, 0, 0), 1.534, true });
Assert.Equal(1, dt.Rows.Count);
Assert.Equal(1, dt.Rows[0]["ParentId"]);
Assert.Equal("1-String1", dt.Rows[0]["String1"]);
Assert.Equal("1-String2", dt.Rows[0]["String2"]);
Assert.Equal(new DateTime(2005, 1, 1, 0, 0, 0, 0), dt.Rows[0]["ParentDateTime"]);
Assert.Equal(1.534, dt.Rows[0]["ParentDouble"]);
Assert.Equal(true, dt.Rows[0]["ParentBool"]);
}
[Fact]
public void DataRowCollection_Add_O2()
{
DataTable dt = DataProvider.CreateParentDataTable();
int count = dt.Rows.Count;
dt.Rows.Add(new object[] { 8, "1-String1", "1-String2", new DateTime(2005, 1, 1, 0, 0, 0, 0), 1.534 });
Assert.Equal(count + 1, dt.Rows.Count);
}
[Fact]
public void DataRowCollection_Add_O4()
{
Assert.Throws<NullReferenceException>(() =>
{
DataTable dt = DataProvider.CreateParentDataTable();
dt.Rows.Add((object[])null);
});
}
[Fact]
public void FindByKey()
{
DataTable table = new DataTable();
table.Columns.Add("col1", typeof(int));
table.PrimaryKey = new DataColumn[] { table.Columns[0] };
table.Rows.Add(new object[] { 1 });
table.Rows.Add(new object[] { 2 });
table.Rows.Add(new object[] { 3 });
table.AcceptChanges();
Assert.NotNull(table.Rows.Find(new object[] { 1 }));
table.Rows[0].Delete();
Assert.Null(table.Rows.Find(new object[] { 1 }));
table.RejectChanges();
Assert.NotNull(table.Rows.Find(new object[] { 1 }));
}
[Fact]
public void FindByKey_VerifyOrder()
{
DataTable table = new DataTable();
table.Columns.Add("col1", typeof(int));
table.PrimaryKey = new DataColumn[] { table.Columns[0] };
table.Rows.Add(new object[] { 1 });
table.Rows.Add(new object[] { 2 });
table.Rows.Add(new object[] { 1000 });
table.AcceptChanges();
table.Rows[1][0] = 100;
Assert.NotNull(table.Rows.Find(100));
table.Rows[2][0] = 999;
Assert.NotNull(table.Rows.Find(999));
Assert.NotNull(table.Rows.Find(100));
}
[Fact]
public void FindByKey_DuringDataLoad()
{
DataTable table = new DataTable();
table.Columns.Add("col1", typeof(int));
table.PrimaryKey = new DataColumn[] { table.Columns[0] };
table.Rows.Add(new object[] { 1 });
table.Rows.Add(new object[] { 2 });
table.AcceptChanges();
table.BeginLoadData();
table.LoadDataRow(new object[] { 1000 }, false);
Assert.NotNull(table.Rows.Find(1));
Assert.NotNull(table.Rows.Find(1000));
table.EndLoadData();
Assert.NotNull(table.Rows.Find(1000));
}
[Fact]
public void DataRowCollection_Clear1()
{
DataTable dt = DataProvider.CreateParentDataTable();
int count = dt.Rows.Count;
Assert.Equal(count != 0, true);
dt.Rows.Clear();
Assert.Equal(0, dt.Rows.Count);
}
[Fact]
public void DataRowCollection_Clear2()
{
Assert.Throws<InvalidConstraintException>(() =>
{
DataSet ds = DataProvider.CreateForigenConstraint();
ds.Tables[0].Rows.Clear(); //Try to clear the parent table
});
}
[Fact]
public void DataRowCollection_Contains_O1()
{
DataTable dt = DataProvider.CreateParentDataTable();
dt.PrimaryKey = new DataColumn[] { dt.Columns[0] };
Assert.Equal(true, dt.Rows.Contains(1));
Assert.Equal(false, dt.Rows.Contains(10));
}
[Fact]
public void DataRowCollection_Contains_O2()
{
Assert.Throws<MissingPrimaryKeyException>(() =>
{
DataTable dt = DataProvider.CreateParentDataTable();
Assert.Equal(false, dt.Rows.Contains(1));
});
}
[Fact]
public void DataRowCollection_Contains_O3()
{
DataTable dt = DataProvider.CreateParentDataTable();
dt.PrimaryKey = new DataColumn[] { dt.Columns[0], dt.Columns[1] };
//Prepare values array
object[] arr = new object[2];
arr[0] = 1;
arr[1] = "1-String1";
Assert.Equal(true, dt.Rows.Contains(arr));
arr[0] = 8;
Assert.Equal(false, dt.Rows.Contains(arr));
}
[Fact]
public void DataRowCollection_Contains_O4()
{
Assert.Throws<ArgumentException>(() =>
{
DataTable dt = DataProvider.CreateParentDataTable();
dt.PrimaryKey = new DataColumn[] { dt.Columns[0], dt.Columns[1] };
//Prepare values array
object[] arr = new object[1];
arr[0] = 1;
Assert.Equal(false, dt.Rows.Contains(arr));
});
}
[Fact]
public void DataRowCollection_Find_O1()
{
DataTable dt = DataProvider.CreateParentDataTable();
dt.PrimaryKey = new DataColumn[] { dt.Columns[0] };
Assert.Equal(dt.Rows[0], dt.Rows.Find(1));
Assert.Equal(null, dt.Rows.Find(10));
}
[Fact]
public void DataRowCollection_Find_O2()
{
Assert.Throws<MissingPrimaryKeyException>(() =>
{
DataTable dt = DataProvider.CreateParentDataTable();
Assert.Equal(null, dt.Rows.Find(1));
});
}
[Fact]
public void DataRowCollection_Find_O3()
{
DataTable dt = DataProvider.CreateParentDataTable();
dt.PrimaryKey = new DataColumn[] { dt.Columns[0], dt.Columns[1] };
//Prepare values array
object[] arr = new object[2];
arr[0] = 2;
arr[1] = "2-String1";
Assert.Equal(dt.Rows[1], dt.Rows.Find(arr));
arr[0] = 8;
Assert.Equal(null, dt.Rows.Find(arr));
}
[Fact]
public void DataRowCollection_Find_O4()
{
Assert.Throws<ArgumentException>(() =>
{
DataTable dt = DataProvider.CreateParentDataTable();
dt.PrimaryKey = new DataColumn[] { dt.Columns[0], dt.Columns[1] };
//Prepare values array
object[] arr = new object[1];
arr[0] = 1;
Assert.Equal(null, dt.Rows.Find(arr));
});
}
[Fact]
public void DataRowCollection_InsertAt_DI1()
{
DataTable dt = DataProvider.CreateParentDataTable();
DataRow dr = GetNewDataRow(dt);
dt.Rows.InsertAt(dr, 0);
Assert.Equal(dr, dt.Rows[0]);
}
[Fact]
public void DataRowCollection_InsertAt_DI2()
{
DataTable dt = DataProvider.CreateParentDataTable();
DataRow dr = GetNewDataRow(dt);
dt.Rows.InsertAt(dr, 3);
Assert.Equal(dr, dt.Rows[3]);
}
[Fact]
public void DataRowCollection_InsertAt_DI3()
{
DataTable dt = DataProvider.CreateParentDataTable();
DataRow dr = GetNewDataRow(dt);
dt.Rows.InsertAt(dr, 300);
Assert.Equal(dr, dt.Rows[dt.Rows.Count - 1]);
}
[Fact]
public void DataRowCollection_InsertAt_DI4()
{
Assert.Throws<IndexOutOfRangeException>(() =>
{
DataTable dt = DataProvider.CreateParentDataTable();
DataRow dr = GetNewDataRow(dt);
dt.Rows.InsertAt(dr, -1);
});
}
private DataRow GetNewDataRow(DataTable dt)
{
DataRow dr = dt.NewRow();
dr["ParentId"] = 10;
dr["String1"] = "string1";
dr["String2"] = string.Empty;
dr["ParentDateTime"] = new DateTime(2004, 12, 15);
dr["ParentDouble"] = 3.14;
dr["ParentBool"] = false;
return dr;
}
[Fact]
public void DataRowCollection_Item1()
{
DataTable dt = DataProvider.CreateParentDataTable();
int index = 0;
foreach (DataRow dr in dt.Rows)
{
Assert.Equal(dr, dt.Rows[index]);
index++;
}
}
[Fact]
public void DataRowCollection_Item2()
{
Assert.Throws<IndexOutOfRangeException>(() =>
{
DataTable dt = DataProvider.CreateParentDataTable();
DataRow dr = dt.Rows[-1];
});
}
}
}
| |
/*
* Copyright (C) Sony Computer Entertainment America LLC.
* All Rights Reserved.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using Sce.Atf;
using Sce.Atf.Applications;
namespace Sce.Sled.Shared
{
/// <summary>
/// Wrapper around Scea.Utilities.MessageType
/// </summary>
public enum SledMessageType
{
/// <summary>
/// Informational message
/// </summary>
Info = 1,
/// <summary>
/// Warning message
/// </summary>
Warning = 2,
/// <summary>
/// Error message
/// </summary>
Error = 3,
}
/// <summary>
/// SledOutDevice Class
/// <remarks>Queues messages until they can be shown and then redirects them to OutputService</remarks>
/// </summary>
[Export(typeof(IInitializable))]
[Export(typeof(SledOutDevice))]
[PartCreationPolicy(CreationPolicy.Shared)]
public class SledOutDevice : IInitializable
{
/// <summary>
/// Constructor with parameters</summary>
/// <param name="mainForm">MainForm object</param>
/// <param name="writer">IOutputWriter object for output messages</param>
[ImportingConstructor]
public SledOutDevice(MainForm mainForm, IOutputWriter writer)
{
mainForm.Shown += MainFormShown;
m_writer = writer;
s_instance = this;
s_dictMsgTypeLookup.Add(SledMessageType.Info, OutputMessageType.Info);
s_dictMsgTypeLookup.Add(SledMessageType.Warning, OutputMessageType.Warning);
s_dictMsgTypeLookup.Add(SledMessageType.Error, OutputMessageType.Error);
}
#region IInitializable Interface
/// <summary>
/// Finish initializing component</summary>
void IInitializable.Initialize()
{
// Keep this here
}
#endregion
#region MainForm Events
private void MainFormShown(object sender, EventArgs e)
{
s_bOutDeviceReady = true;
// Show all queued messages
foreach (var queuedMsg in s_lstMessages)
{
if (queuedMsg.OutOrOutLine)
Out(queuedMsg.MessageType, queuedMsg.Message);
else
OutLine(queuedMsg.MessageType, queuedMsg.Message);
}
s_lstMessages.Clear();
}
#endregion
/// <summary>
/// Displays message to the user in a text control
/// </summary>
/// <param name="messageType">Message type, which modifies display of message</param>
/// <param name="format">Text message to display</param>
/// <param name="args">Optional arguments</param>
public static void Out(SledMessageType messageType, string format, params object[] args)
{
try
{
var formatted = string.Format(format, args);
if (s_bOutDeviceReady)
s_instance.m_writer.Write(s_dictMsgTypeLookup[messageType], formatted);
else
s_lstMessages.Add(new QueuedMessage(true, messageType, formatted));
}
finally
{
s_bLastMessageBreak = false;
}
}
/// <summary>
/// Displays message to the user in a text control
/// </summary>
/// <param name="messageType">Message type, which modifies display of message</param>
/// <param name="format">Text message to display</param>
/// <param name="args">Optional arguments</param>
public static void OutLine(SledMessageType messageType, string format, params object[] args)
{
try
{
var formatted = args.Length <= 0 ? format : string.Format(format, args);
if (s_bOutDeviceReady)
s_instance.m_writer.Write(s_dictMsgTypeLookup[messageType], formatted + Environment.NewLine);
else
s_lstMessages.Add(new QueuedMessage(false, messageType, formatted));
}
catch (Exception ex)
{
if ((s_instance != null) && (s_instance.m_writer != null))
s_instance.m_writer.Write(OutputMessageType.Error, "SledOutDevice Exception: {0}", ex.Message);
}
finally
{
s_bLastMessageBreak = false;
}
}
/// <summary>
/// Displays a break between groups of text
/// </summary>
public static void OutBreak()
{
if (s_bLastMessageBreak)
return;
try
{
const SledMessageType messageType = SledMessageType.Info;
if (s_bOutDeviceReady)
s_instance.m_writer.Write(s_dictMsgTypeLookup[messageType], Break);
else
s_lstMessages.Add(new QueuedMessage(false, messageType, Break));
}
finally
{
s_bLastMessageBreak = true;
}
}
/// <summary>
/// Write a list of items to the Output window with each item on a new line
/// </summary>
/// <typeparam name="T">Type of item to output</typeparam>
/// <param name="messageType">Message type</param>
/// <param name="prefix">String to prepend to each line</param>
/// <param name="lstItems">List of items to write</param>
public static void OutLineList<T>(SledMessageType messageType, string prefix, IEnumerable<T> lstItems) where T : class
{
if (lstItems == null)
return;
foreach (var item in lstItems)
{
var itemString =
item == null
? string.Empty
: item.ToString();
var message =
string.IsNullOrEmpty(prefix)
? string.Format("{0}", itemString)
: string.Format("{0} {1}", prefix, itemString);
OutLine(messageType, message);
}
}
/// <summary>
/// Clear text
/// </summary>
public static void Clear()
{
if (!s_bOutDeviceReady)
return;
s_instance.m_writer.Clear();
}
/// <summary>
/// Displays message to the user in a text control but only when "DEBUG" is defined
/// </summary>
/// <param name="messageType">Message type, which modifies display of message</param>
/// <param name="format">Text message to display</param>
/// <param name="args">Optional arguments</param>
[System.Diagnostics.Conditional("DEBUG")]
public static void OutDebug(SledMessageType messageType, string format, params object[] args)
{
try
{
var formatted = string.Format(format, args);
if (s_bOutDeviceReady)
s_instance.m_writer.Write(s_dictMsgTypeLookup[messageType], formatted);
else
s_lstMessages.Add(new QueuedMessage(true, messageType, formatted));
}
finally
{
s_bLastMessageBreak = false;
}
}
/// <summary>
/// Displays message to the user in a text control but only when "DEBUG" is defined
/// </summary>
/// <param name="messageType">Message type, which modifies display of message</param>
/// <param name="format">Text message to display</param>
/// <param name="args">Optional arguments</param>
[System.Diagnostics.Conditional("DEBUG")]
public static void OutLineDebug(SledMessageType messageType, string format, params object[] args)
{
try
{
var formatted = args.Length <= 0 ? format : string.Format(format, args);
if (s_bOutDeviceReady)
s_instance.m_writer.Write(s_dictMsgTypeLookup[messageType], formatted + Environment.NewLine);
else
s_lstMessages.Add(new QueuedMessage(false, messageType, formatted));
}
catch (Exception ex)
{
if ((s_instance != null) && (s_instance.m_writer != null))
s_instance.m_writer.Write(OutputMessageType.Error, "SledOutDeviceDebug Exception: {0}", ex.Message);
}
finally
{
s_bLastMessageBreak = false;
}
}
/// <summary>
/// BreakBlock Class
/// <remarks>Convenience to wrap a chunk of output with breaks</remarks>
/// </summary>
public class BreakBlock : IDisposable
{
/// <summary>
/// Constructor
/// </summary>
public BreakBlock()
{
OutBreak();
}
/// <summary>
/// Dispose
/// </summary>
public void Dispose()
{
OutBreak();
}
}
private readonly IOutputWriter m_writer;
private const string Break = "-";
private static bool s_bOutDeviceReady;
private static bool s_bLastMessageBreak;
private static SledOutDevice s_instance;
private static readonly List<QueuedMessage> s_lstMessages =
new List<QueuedMessage>();
private static readonly Dictionary<SledMessageType, OutputMessageType> s_dictMsgTypeLookup =
new Dictionary<SledMessageType, OutputMessageType>(new SledMessageTypeEqualityComparer());
#region QueuedMessage Class
private class QueuedMessage
{
public QueuedMessage(bool bOutOrOutLine, SledMessageType messageType, string message)
{
OutOrOutLine = bOutOrOutLine;
MessageType = messageType;
Message = message;
}
public bool OutOrOutLine { get; private set; }
public SledMessageType MessageType { get; private set; }
public string Message { get; private set; }
}
#endregion
#region SledMessageTypeEqualityComparer Class
private class SledMessageTypeEqualityComparer : IEqualityComparer<SledMessageType>
{
public bool Equals(SledMessageType item1, SledMessageType item2)
{
return item1 == item2;
}
public int GetHashCode(SledMessageType item)
{
return (int)item;
}
}
#endregion
}
}
| |
using UnityEngine;
using System;
using System.Collections;
using Chartboost;
namespace Chartboost {
public class CBManager : MonoBehaviour {
#if UNITY_ANDROID || UNITY_IPHONE
//private int canShowAdd;
void Start () {
CBBinding.init();
}
/*
void Update () {
if (Input.GetKeyUp(KeyCode.Escape)) {
if (CBBinding.onBackPressed())
return;
else
Application.Quit();
}
}
*/
#if UNITY_IPHONE
[System.Runtime.InteropServices.DllImport("__Internal")]
private static extern void _chartBoostPauseUnity();
#endif
/// Fired when an interstitial fails to load
/// First parameter is the location.
public static event Action<string> didFailToLoadInterstitialEvent;
/// Fired when an interstitial is finished via any method
/// This will always be paired with either a close or click event
/// First parameter is the location.
public static event Action<string> didDismissInterstitialEvent;
/// Fired when an interstitial is closed (i.e. by tapping the X or hitting the Android back button)
/// First parameter is the location.
public static event Action<string> didCloseInterstitialEvent;
/// Fired when an interstitial is clicked
/// First parameter is the location.
public static event Action<string> didClickInterstitialEvent;
/// Fired when an interstitial is cached
/// First parameter is the location.
public static event Action<string> didCacheInterstitialEvent;
/// Fired when an interstitial is shown
/// First parameter is the location.
public static event Action<string> didShowInterstitialEvent;
/// Fired when the more apps screen fails to load
public static event Action didFailToLoadMoreAppsEvent;
/// Fired when the more apps screen is finished via any method
/// This will always be paired with either a close or click event
public static event Action didDismissMoreAppsEvent;
/// Fired when the more apps screen is closed (i.e. by tapping the X or hitting the Android back button)
public static event Action didCloseMoreAppsEvent;
/// Fired when a listing on the more apps screen is clicked
public static event Action didClickMoreAppsEvent;
/// Fired when the more apps screen is cached
public static event Action didCacheMoreAppsEvent;
/// Fired when the more app screen is shown
public static event Action didShowMoreAppsEvent;
void Awake()
{
gameObject.name = "ChartBoostManager";
DontDestroyOnLoad( gameObject );
}
public void didFailToLoadInterstitial( string location )
{
if( didFailToLoadInterstitialEvent != null )
didFailToLoadInterstitialEvent( location );
}
public void didDismissInterstitial( string location )
{
doUnityPause(false);
if( didDismissInterstitialEvent != null )
didDismissInterstitialEvent( location );
}
public void didClickInterstitial( string location )
{
if( didClickInterstitialEvent != null )
didClickInterstitialEvent( location );
}
public void didCloseInterstitial( string location )
{
if( didCloseInterstitialEvent != null )
didCloseInterstitialEvent( location );
}
public void didCacheInterstitial( string location )
{
if( didCacheInterstitialEvent != null )
didCacheInterstitialEvent( location );
}
public void didShowInterstitial( string location )
{
doUnityPause(true);
#if UNITY_IPHONE
_chartBoostPauseUnity();
#endif
if( didShowInterstitialEvent != null )
didShowInterstitialEvent( location );
}
public void didFailToLoadMoreApps( string empty )
{
if( didFailToLoadMoreAppsEvent != null )
didFailToLoadMoreAppsEvent();
}
public void didDismissMoreApps( string empty )
{
doUnityPause(false);
if( didDismissMoreAppsEvent != null )
didDismissMoreAppsEvent();
}
public void didClickMoreApps( string empty )
{
if( didClickMoreAppsEvent != null )
didClickMoreAppsEvent();
}
public void didCloseMoreApps( string empty )
{
if( didCloseMoreAppsEvent != null )
didCloseMoreAppsEvent();
}
public void didCacheMoreApps( string empty )
{
if( didCacheMoreAppsEvent != null )
didCacheMoreAppsEvent();
}
public void didShowMoreApps( string empty )
{
doUnityPause(true);
#if UNITY_IPHONE
_chartBoostPauseUnity();
#endif
if( didShowMoreAppsEvent != null )
didShowMoreAppsEvent();
}
// Utility methods
/// var used internally for managing game pause state
private static bool isPaused = false;
/// Manages pausing
private static void doUnityPause(bool pause) {
#if UNITY_ANDROID
bool useCustomPause = true;
#endif
if (pause) {
#if UNITY_ANDROID
if (isPaused) {
useCustomPause = false;
}
#endif
isPaused = true;
#if UNITY_ANDROID
if (useCustomPause && !CBBinding.getImpressionsUseActivities())
doCustomPause(pause);
#endif
} else {
#if UNITY_ANDROID
if (!isPaused) {
useCustomPause = false;
}
#endif
isPaused = false;
#if UNITY_ANDROID
if (useCustomPause && !CBBinding.getImpressionsUseActivities())
doCustomPause(pause);
#endif
}
}
public static bool isImpressionVisible() {
return isPaused;
}
#if UNITY_ANDROID
/// Var used for custom pause method
private static float lastTimeScale = 0;
/// Update this method if you would like to change how your game is paused
/// when impressions are shown. This method is only called if you call
/// CBAndroidBinding.setImpressionsUseActivities(false). Otherwise,
/// your Unity app is halted at a much higher level
private static void doCustomPause(bool pause) {
if (pause) {
lastTimeScale = Time.timeScale;
Time.timeScale = 0;
} else {
Time.timeScale = lastTimeScale;
}
}
#endif
#endif
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace ZhAsoiafWiki.Plus.Web.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
/********************************************************************
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.Xml;
using System.Collections.Generic;
using System.Diagnostics;
using Axiom.Core;
using Axiom.MathLib;
using Axiom.Graphics;
using Axiom.Media;
using Axiom.Utility;
using Multiverse.CollisionLib;
namespace Axiom.SceneManagers.Multiverse
{
/// <summary>
/// Summary description for Boundary.
/// </summary>
public class Boundary : IDisposable
{
private List<Vector2> points;
private List<int []> tris;
private bool closed = false;
private AxisAlignedBox bounds;
// private float area; (unused)
private int pageSize;
private List<PageCoord> touchedPages;
private List<IBoundarySemantic> semantics;
private String name;
private bool hilight;
private SceneNode sceneNode;
public static SceneNode parentSceneNode;
private bool visible;
private PageCoord boundsMinPage;
private PageCoord boundsMaxPage;
private bool autoClose = false;
private static int uniqueNum = 0;
public Boundary(String name)
{
points = new List<Vector2>();
semantics = new List<IBoundarySemantic>();
touchedPages = new List<PageCoord>();
this.name = name;
sceneNode = parentSceneNode.CreateChildSceneNode(name);
pageSize = TerrainManager.Instance.PageSize;
}
public Boundary(XmlTextReader r)
{
points = new List<Vector2>();
semantics = new List<IBoundarySemantic>();
touchedPages = new List<PageCoord>();
pageSize = TerrainManager.Instance.PageSize;
FromXML(r);
sceneNode = parentSceneNode.CreateChildSceneNode(name);
}
public void AddToScene(SceneManager scene)
{
}
protected void ParsePoint(XmlTextReader r)
{
float x = 0, y = 0;
for (int i = 0; i < r.AttributeCount; i++)
{
r.MoveToAttribute(i);
// set the field in this object based on the element we just read
switch (r.Name)
{
case "x":
x = float.Parse(r.Value);
break;
case "y":
y = float.Parse(r.Value);
break;
}
}
r.MoveToElement(); //Moves the reader back to the element node.
AddPoint(new Vector3(x, 0, y));
}
protected void ParsePoints(XmlTextReader r)
{
while (r.Read())
{
// look for the start of an element
if ( (r.NodeType == XmlNodeType.Element) && ( r.Name == "point" ) )
{
// parse that element
ParsePoint(r);
}
else if (r.NodeType == XmlNodeType.EndElement)
{
// if we found an end element, it means we are at the end of the points
Close();
return;
}
}
}
protected void ParseElement(XmlTextReader r)
{
bool readEnd = true;
// set the field in this object based on the element we just read
switch (r.Name)
{
case "name":
// read the value
r.Read();
if (r.NodeType != XmlNodeType.Text)
{
return;
}
name = string.Format("{0} - unique boundary - {1}", r.Value, uniqueNum);
uniqueNum++;
break;
case "points":
ParsePoints(r);
readEnd = false;
break;
case "boundarySemantic":
BoundarySemanticType type = BoundarySemanticType.None;
for (int i = 0; i < r.AttributeCount; i++)
{
r.MoveToAttribute(i);
// set the field in this object based on the element we just read
switch (r.Name)
{
case "type":
switch (r.Value)
{
case "SpeedTreeForest":
type = BoundarySemanticType.SpeedTreeForest;
break;
case "WaterPlane":
type = BoundarySemanticType.WaterPlane;
break;
case "Vegetation":
type = BoundarySemanticType.Vegetation;
break;
}
break;
}
}
r.MoveToElement(); //Moves the reader back to the element node.
switch ( type )
{
case BoundarySemanticType.SpeedTreeForest:
Forest forest = new Forest(sceneNode, r);
this.AddSemantic(forest);
break;
case BoundarySemanticType.WaterPlane:
WaterPlane water = new WaterPlane(sceneNode, r);
this.AddSemantic(water);
break;
case BoundarySemanticType.Vegetation:
VegetationSemantic vegetationBoundary = new VegetationSemantic(r);
this.AddSemantic(vegetationBoundary);
break;
default:
break;
}
readEnd = false;
break;
}
if (readEnd)
{
// error out if we dont see an end element here
r.Read();
if (r.NodeType != XmlNodeType.EndElement)
{
return;
}
}
}
private void FromXML(XmlTextReader r)
{
while (r.Read())
{
// look for the start of an element
if (r.NodeType == XmlNodeType.Element)
{
// parse that element
ParseElement(r);
}
else if (r.NodeType == XmlNodeType.EndElement)
{
// if we found an end element, it means we are at the end of the terrain description
return;
}
}
}
private void OnBoundaryChange()
{
Close();
foreach (IBoundarySemantic semantic in semantics)
{
semantic.BoundaryChange();
}
}
public void AddPoint(Vector3 point)
{
points.Add(new Vector2(point.x, point.z));
if (autoClose)
{
// if the boundary is already closed, close it again so that all the
// computed data structures get rebuilt
OnBoundaryChange();
}
}
public void InsertPoint(int pointNum, Vector3 newPoint)
{
points.Insert(pointNum, new Vector2(newPoint.x, newPoint.z));
if (autoClose)
{
OnBoundaryChange();
}
}
public void EditPoint(int pointNum, Vector3 newPoint)
{
points[pointNum] = new Vector2(newPoint.x, newPoint.z);
if (autoClose)
{
// if the boundary is already closed, close it again so that all the
// computed data structures get rebuilt
OnBoundaryChange();
}
}
public void RemovePoint(int pointNum)
{
points.RemoveAt(pointNum);
if (autoClose)
{
// if the boundary is already closed, close it again so that all the
// computed data structures get rebuilt
OnBoundaryChange();
}
}
public void SetPoints(List<Vector3> newPts)
{
points.Clear();
foreach (Vector3 v in newPts)
{
points.Add(new Vector2(v.x, v.z));
}
OnBoundaryChange();
}
private void Triangulate()
{
tris = new List<int []>();
bool ret;
ret = TriangleTessellation.Process(points, tris);
if ( ret == false ) {
// try swapping the order of the points and re-running the tessellation
List<Vector2> newPoints = new List<Vector2>();
for(int i = points.Count - 1; i >= 0; i-- )
{
newPoints.Add(points[i]);
}
// clear out the triangle list before we try again
tris.Clear();
ret = TriangleTessellation.Process(newPoints, tris);
if (ret == false)
{
// dump out point coords that are failing
Console.WriteLine("Boundary triangle tessellation failed in both directions.");
foreach (Vector2 point in points)
{
Console.WriteLine("{0}, {1}", point.x, point.y);
}
}
else
{
// adjust result list to take into account previous vertex reversal
int lastVert = points.Count - 1;
for (int i = 0; i < tris.Count; i++)
{
tris[i][0] = lastVert - tris[i][0];
tris[i][1] = lastVert - tris[i][1];
tris[i][2] = lastVert - tris[i][2];
}
}
Debug.Assert(ret == true);
}
}
private void ComputeBounds()
{
float minX = Single.MaxValue;
float maxX = Single.MinValue;
float minZ = Single.MaxValue;
float maxZ = Single.MinValue;
foreach (Vector2 point in points)
{
if (point.x > maxX)
{
maxX = point.x;
}
if (point.x < minX)
{
minX = point.x;
}
if (point.y > maxZ)
{
maxZ = point.y;
}
if (point.y < minZ)
{
minZ = point.y;
}
}
bounds = new AxisAlignedBox(new Vector3(minX, 0, minZ), new Vector3(maxX, 0, maxZ));
}
private void ComputeArea()
{
// XXX
}
private void UnClose()
{
touchedPages.Clear();
tris = null;
bounds = null;
closed = false;
}
public void Close()
{
if (closed)
{
UnClose();
}
autoClose = true;
closed = true;
if (points.Count >= 3)
{
ComputeBounds();
Triangulate();
ComputeArea();
ComputeTouchedPages();
SetPageHilights(hilight);
}
}
public bool PointIn(Vector3 p3)
{
Debug.Assert(closed, "Boundary not closed");
int crossings = 0;
Vector2 point = new Vector2(p3.x, p3.z);
p3.y = 0;
// see if the point falls within the bounding box
if (bounds.Intersects(p3)) // XXX
{
Vector2 topPoint = new Vector2(point.x, bounds.Maximum.z);
for (int i = 0; i < ( points.Count - 1 ); i++)
{
if (IntersectSegments(points[i], points[i + 1], point, topPoint))
{
crossings++;
}
}
// check final segment
if (IntersectSegments(points[points.Count - 1], points[0], point, topPoint))
{
crossings++;
}
// odd number of crossings means the point is inside
return (crossings & 1) == 1;
}
return false;
}
public List<Triangle> Clip(AxisAlignedBox box)
{
Debug.Assert(closed, "Boundary not closed");
// XXX
return null;
}
// see if the given square intersects with this boundary
public bool IntersectSquare(Vector3 loc, int size)
{
float x1, x2, y1, y2;
x1 = loc.x;
x2 = loc.x + size * TerrainManager.oneMeter;
y1 = loc.z;
y2 = loc.z + size * TerrainManager.oneMeter;
// if the square is outside the bounding box of the boundary, then it can't intersect
if (bounds.Minimum.x > x2 || bounds.Maximum.x < x1 || bounds.Minimum.z > y2 || bounds.Maximum.z < y1)
{
return false;
}
// if the first point of the boundary is inside the square, then there is an intersection.
// This test is done because if the entire boundary is inside this square, then the intersection
// tests below will fail.
if (points.Count > 0)
{
float px = points[0].x;
float py = points[0].y;
if (px >= x1 && px <= x2 && py >= y1 && py <= y2)
{
return true;
}
}
if (PointIn(loc))
{
// the origin is in the boundary, so we intersect
return true;
}
// check each edge of the square to see if it intersects with the boundary
if (IntersectSegment(new Vector2(x1, y1), new Vector2(x2, y1)))
{
return true;
}
if (IntersectSegment(new Vector2(x2, y1), new Vector2(x2, y2)))
{
return true;
}
if (IntersectSegment(new Vector2(x2, y2), new Vector2(x1, y2)))
{
return true;
}
if (IntersectSegment(new Vector2(x1, y2), new Vector2(x1, y1)))
{
return true;
}
return false;
}
// check intersection of a segment with the segments of the boundary
private bool IntersectSegment(Vector2 p1, Vector2 p2)
{
for (int i = 0; i < points.Count - 1; i++)
{
if (IntersectSegments(p1, p2, points[i], points[i + 1]))
{
return true;
}
}
if (IntersectSegments(p1, p2, points[points.Count - 1], points[0]))
{
return true;
}
return false;
}
// check if 2 segments intersect
private static bool IntersectSegments(Vector2 p1, Vector2 p2, Vector2 p3, Vector2 p4)
{
float den = ((p4.y - p3.y) * (p2.x - p1.x)) - ((p4.x - p3.x) * (p2.y - p1.y));
float t1num = ((p4.x - p3.x) * (p1.y - p3.y)) - ((p4.y - p3.y) * (p1.x - p3.x));
float t2num = ((p2.x - p1.x) * (p1.y - p3.y)) - ((p2.y - p1.y) * (p1.x - p3.x));
if ( den == 0 ) {
return false;
}
float t1 = t1num / den;
float t2 = t2num / den;
// note that we include the endpoint of the second line in the intersection
// test, but not the endpoint of the first line.
if ((t1 >= 0) && (t1 < 1) && (t2 >= 0) && (t2 <= 1))
{
return true;
}
return false;
}
public List<int []> Triangles
{
get
{
Debug.Assert(closed, "Boundary not closed");
return tris;
}
}
public List<Vector2> Points
{
get
{
Debug.Assert(closed, "Boundary not closed");
return points;
}
}
public AxisAlignedBox Bounds
{
get
{
Debug.Assert(closed, "Boundary not closed");
return bounds;
}
}
// public float Area
//{
// get
// {
// Debug.Assert(closed, "Boundary not closed");
// return area;
// }
//}
public int PageSize
{
get
{
return pageSize;
}
}
public bool AutoClose
{
get
{
return autoClose;
}
set
{
autoClose = value;
}
}
private void FillSpan(byte[] seedImage, int y, int x1, int x2)
{
int startX;
int endX;
if (y >= 0 && y < pageSize)
{ // span crosses this page
if (x1 < x2)
{
startX = x1;
endX = x2;
}
else
{
startX = x2;
endX = x1;
}
if (startX < pageSize && endX > 0)
{ // ensure span crosses the page
if (startX < 0)
{
startX = 0;
}
if (endX > pageSize)
{
endX = pageSize;
}
int offset = y * pageSize;
for (int x = startX; x < endX; x++)
{
seedImage[offset + x] = 255;
}
}
}
}
// p0, p1, and p2 are sorted
private void RasterizeTriangle(Vector3 pageLoc, Vector2 p0, Vector2 p1, Vector2 p2, byte[] seedImage)
{
float x0 = (float)Math.Floor((p0.x - pageLoc.x) / TerrainManager.oneMeter);
int y0 = (int)Math.Floor((p0.y - pageLoc.z) / TerrainManager.oneMeter);
float x1 = (float)Math.Floor((p1.x - pageLoc.x) / TerrainManager.oneMeter);
int y1 = (int)Math.Floor((p1.y - pageLoc.z) / TerrainManager.oneMeter);
float x2 = (float)Math.Floor((p2.x - pageLoc.x) / TerrainManager.oneMeter);
int y2 = (int)Math.Floor((p2.y - pageLoc.z) / TerrainManager.oneMeter);
if (y2 < 0 || y0 >= pageSize)
{ // triangle is outside of the page in y coord range
return;
}
float dx0 = (x1 - x0) / (y1 - y0);
float dx1 = (x2 - x0) / (y2 - y0);
float dx2 = (x2 - x1) / (y2 - y1);
float xEdge0 = x0;
float xEdge1 = x0;
for (int y = y0; y < y1; y++)
{
FillSpan(seedImage, y, (int)Math.Floor(xEdge0), (int)Math.Floor(xEdge1));
xEdge0 += dx0;
xEdge1 += dx1;
}
for (int y = y1; y <= y2; y++)
{
FillSpan(seedImage, y, (int)Math.Floor(xEdge0), (int)Math.Floor(xEdge1));
xEdge0 += dx2;
xEdge1 += dx1;
}
return;
}
private Image BuildPageMask(Vector3 loc)
{
byte[] seedImage = new byte[pageSize * pageSize];
Debug.Assert(closed);
foreach (int[] tri in tris)
{
Vector2 p0 = new Vector2(points[tri[0]].x, points[tri[0]].y);
Vector2 p1 = new Vector2(points[tri[1]].x, points[tri[1]].y);
Vector2 p2 = new Vector2(points[tri[2]].x, points[tri[2]].y);
Vector2 ptmp;
//
// sort by y coordinate
//
if (p1.y < p0.y)
{
// swap p0 and p1
ptmp = p0;
p0 = p1;
p1 = ptmp;
}
if (p2.y < p0.y)
{
// move p2 to the front
ptmp = p1;
p1 = p0;
p0 = p2;
p2 = ptmp;
}
else if (p2.y < p1.y)
{
// swap p1 and p2
ptmp = p1;
p1 = p2;
p2 = ptmp;
}
RasterizeTriangle(loc, p0, p1, p2, seedImage);
}
return Image.FromDynamicImage(seedImage, pageSize, pageSize, PixelFormat.A8);
}
private Texture PageMaskTexture(PageCoord pc)
{
Image i = BuildPageMask(pc.WorldLocation(pageSize));
String texName = String.Format("{0}-{1}", name, pc.ToString());
Texture t = TextureManager.Instance.LoadImage(texName, i);
return t;
}
private void ComputeTouchedPages()
{
Debug.Assert(closed);
// compute the min and max page coord of the pages that this boundary may intersect with
boundsMinPage = new PageCoord(bounds.Minimum, pageSize);
boundsMaxPage = new PageCoord(bounds.Maximum, pageSize);
touchedPages.Clear();
// iterate over the pages and see which intersect with the boundary, and add
// those to the list
for (int x = boundsMinPage.X; x <= boundsMaxPage.X; x++)
{
for (int z = boundsMinPage.Z; z <= boundsMaxPage.Z; z++)
{
PageCoord pc = new PageCoord(x, z);
if (IntersectSquare(pc.WorldLocation(pageSize), pageSize))
{
touchedPages.Add(pc);
}
}
}
Console.WriteLine("boundary {0} touches pages:", name);
foreach (PageCoord tp in touchedPages)
{
Console.WriteLine(" {0}", tp.ToString());
}
}
public bool Hilight
{
get
{
return hilight;
}
set
{
hilight = value;
if (closed)
{
SetPageHilights(value);
}
}
}
public void AddSemantic(IBoundarySemantic semantic)
{
semantics.Add(semantic);
semantic.AddToBoundary(this);
}
public void RemoveSemantic(IBoundarySemantic semantic)
{
semantics.Remove(semantic);
semantic.RemoveFromBoundary();
}
public List<IBoundarySemantic> GetSemantics(string type)
{
List<IBoundarySemantic> ret = new List<IBoundarySemantic>();
foreach (IBoundarySemantic bs in semantics)
{
if (bs.Type == type)
{
ret.Add(bs);
}
}
return ret;
}
public void PerFrameSemantics(float time, Camera camera)
{
foreach (IBoundarySemantic semantic in semantics)
{
semantic.PerFrameProcessing(time, camera);
}
}
public void PageShift()
{
// set the visible flag if any of part of this boundary overlaps the visible region around the camera
UpdateVisibility();
if (hilight && visible)
{ // display hilights pages that are visible and overlap the boundary
SetPageHilights(true);
}
// notify all boundary semantics of the page shift
foreach (IBoundarySemantic semantic in semantics)
{
semantic.PageShift();
}
}
private void UpdateVisibility()
{
PageCoord minVis = TerrainManager.Instance.MinVisiblePage;
PageCoord maxVis = TerrainManager.Instance.MaxVisiblePage;
visible = false;
if (maxVis.X < boundsMinPage.X || minVis.X > boundsMaxPage.X || maxVis.Z < boundsMinPage.Z || minVis.Z > boundsMaxPage.Z)
{
// this boundary doesn't overlap with the visible area around the camera.
return;
}
foreach (PageCoord tp in touchedPages)
{
if (tp.X >= minVis.X && tp.X <= maxVis.X && tp.Z >= minVis.Z && tp.Z <= maxVis.Z)
{
// tp page is visible
visible = true;
}
}
}
private void SetPageHilights(bool value)
{
PageCoord minVis = TerrainManager.Instance.MinVisiblePage;
PageCoord maxVis = TerrainManager.Instance.MaxVisiblePage;
foreach (PageCoord tp in touchedPages)
{
if (tp.X >= minVis.X && tp.X <= maxVis.X && tp.Z >= minVis.Z && tp.Z <= maxVis.Z)
{
// tp page is visible
visible = true;
PageCoord pageOff = tp - minVis;
Page page = TerrainManager.Instance.LookupPage(pageOff.X, pageOff.Z);
if (value)
{
page.TerrainPage.HilightMask = PageMaskTexture(tp);
page.TerrainPage.HilightType = TerrainPage.PageHilightType.Colorized;
}
else
{
page.TerrainPage.HilightType = TerrainPage.PageHilightType.None;
// if there is an existing hilight mask, make sure we free it properly
Texture t = page.TerrainPage.HilightMask;
if (t != null)
{
page.TerrainPage.HilightMask = null;
t.Dispose();
}
}
}
}
}
public bool IntersectPage(PageCoord pc)
{
// check if page intersects bounds first
if (pc.X < boundsMinPage.X || pc.X > boundsMaxPage.X || pc.Z < boundsMinPage.Z || pc.Z > boundsMaxPage.Z)
{
return false;
}
foreach (PageCoord tp in touchedPages)
{
if (tp == pc)
{
return true;
}
}
return false;
}
public bool Visible
{
get
{
return visible;
}
}
public void FindObstaclesInBox(AxisAlignedBox box,
CollisionTileManager.AddTreeObstaclesCallback callback)
{
Debug.Assert(bounds != null, "When calling FindObstaclesInBox, bounds must be non-null");
if (bounds.Intersects(box)) {
foreach (IBoundarySemantic semantic in semantics) {
Forest f = semantic as Forest;
if (f != null) {
f.FindObstaclesInBox(box, callback);
}
}
}
}
public class Triangle
{
Vector3 [] verts;
Triangle(Vector3 v1, Vector3 v2, Vector3 v3)
{
verts = new Vector3[3];
verts[0] = v1;
verts[1] = v2;
verts[2] = v3;
}
public Vector3 this[int i] {
get {
return verts[i];
}
set
{
verts[i] = value;
}
}
}
public void ToXML(XmlTextWriter w)
{
w.WriteStartElement("boundary");
w.WriteElementString("name", name);
w.WriteStartElement("points");
foreach (Vector2 p in points)
{
w.WriteStartElement("point");
w.WriteAttributeString("x", p.x.ToString());
w.WriteAttributeString("y", p.y.ToString());
w.WriteEndElement();
}
w.WriteEndElement();
foreach (IBoundarySemantic semantic in semantics)
{
semantic.ToXML(w);
}
w.WriteEndElement();
}
#region IDisposable Members
public void Dispose()
{
foreach (IBoundarySemantic semantic in semantics)
{
semantic.Dispose();
}
sceneNode.Creator.DestroySceneNode(sceneNode.Name);
}
#endregion
}
public enum BoundarySemanticType
{
None,
SpeedTreeForest,
TerrainTexture,
WaterPlane,
Vegetation
}
public class TouchedPage : IDisposable
{
private PageCoord coord;
private Texture mask;
public TouchedPage(PageCoord coord, Texture mask)
{
this.coord = coord;
this.mask = mask;
}
public PageCoord Coord
{
get
{
return coord;
}
}
public Texture Mask
{
get
{
return mask;
}
}
#region IDisposable Members
public void Dispose()
{
if (mask != null)
{
mask.Dispose();
}
}
#endregion
}
}
| |
// Copyright 2010 Google Inc. All Rights Reserved.
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Text;
using Google.Analytics;
using Google.GData.Analytics;
using Google.GData.Client;
using Google.GData.Extensions;
namespace SampleAnalyticsClient
{
public class DataFeedExample
{
private const String CLIENT_USERNAME = "INSERT_LOGIN_EMAIL_HERE";
private const String CLIENT_PASS = "INSERT_PASSWORD_HERE";
private const String TABLE_ID = "INSERT_TABLE_ID_HERE";
public DataFeed feed;
public DataFeed feed2;
public static void Main(String[] args)
{
DataFeedExample example;
try
{
example = new DataFeedExample();
}
catch (AuthenticationException e)
{
Console.Error.WriteLine("Authentication failed : " + e.Message);
return;
}
catch (Google.GData.Client.GDataRequestException e)
{
Console.Error.WriteLine("Authentication failed : " + e.Message);
return;
}
example.printFeedData();
example.printFeedDataSources();
example.printFeedAggregates();
example.printSegmentInfo();
example.printDataForOneEntry();
Console.WriteLine(example.getEntriesAsTable());
}
/**
* Creates a new service object, attempts to authorize using the Client Login
* authorization mechanism and requests data from the Google Analytics API.
*/
public DataFeedExample()
{
// Configure GA API.
AnalyticsService asv = new AnalyticsService("gaExportAPI_acctSample_v2.0");
// Client Login Authorization.
asv.setUserCredentials(CLIENT_USERNAME, CLIENT_PASS);
// GA Data Feed query uri.
String baseUrl = "https://www.google.com/analytics/feeds/data";
DataQuery query = new DataQuery(baseUrl);
query.Ids = TABLE_ID;
query.Dimensions = "ga:source,ga:medium";
query.Metrics = "ga:visits,ga:bounces";
query.Segment = "gaid::-11";
query.Filters = "ga:medium==referral";
query.Sort = "-ga:visits";
query.NumberToRetrieve = 5;
query.GAStartDate = "2010-03-01";
query.GAEndDate = "2010-03-15";
Uri url = query.Uri;
Console.WriteLine("URL: " + url.ToString());
// Send our request to the Analytics API and wait for the results to
// come back.
feed = asv.Query(query);
}
/**
* Prints the important Google Analytics relates data in the Data Feed.
*/
public void printFeedData()
{
Console.WriteLine("\n-------- Important Feed Information --------");
Console.WriteLine(
"\nFeed Title = " + feed.Title.Text +
"\nFeed ID = " + feed.Id.Uri +
"\nTotal Results = " + feed.TotalResults +
"\nSart Index = " + feed.StartIndex +
"\nItems Per Page = " + feed.ItemsPerPage
);
}
/**
* Prints the important information about the data sources in the feed.
* Note: the GA Export API currently has exactly one data source.
*/
public void printFeedDataSources()
{
DataSource gaDataSource = feed.DataSource;
Console.WriteLine("\n-------- Data Source Information --------");
Console.WriteLine(
"\nTable Name = " + gaDataSource.TableName +
"\nTable ID = " + gaDataSource.TableId +
"\nWeb Property Id = " + gaDataSource.WebPropertyId +
"\nProfile Id = " + gaDataSource.ProfileId +
"\nAccount Name = " + gaDataSource.AccountName);
}
/**
* Prints all the metric names and values of the aggregate data. The
* aggregate metrics represent the sum of the requested metrics across all
* of the entries selected by the query and not just the rows returned.
*/
public void printFeedAggregates()
{
Console.WriteLine("\n-------- Aggregate Metric Values --------");
Aggregates aggregates = feed.Aggregates;
foreach (Metric metric in aggregates.Metrics)
{
Console.WriteLine(
"\nMetric Name = " + metric.Name +
"\nMetric Value = " + metric.Value +
"\nMetric Type = " + metric.Type +
"\nMetric CI = " + metric.ConfidenceInterval);
}
}
/**
* Prints segment information if the query has an advanced segment defined.
*/
public void printSegmentInfo()
{
if (feed.Segments.Count > 0)
{
Console.WriteLine("\n-------- Advanced Segments Information --------");
foreach (Segment segment in feed.Segments)
{
Console.WriteLine(
"\nSegment Name = " + segment.Name +
"\nSegment ID = " + segment.Id +
"\nSegment Definition = " + segment.Definition.Value);
}
}
}
/**
* Prints all the important information from the first entry in the
* data feed.
*/
public void printDataForOneEntry()
{
Console.WriteLine("\n-------- Important Entry Information --------\n");
if (feed.Entries.Count == 0)
{
Console.WriteLine("No entries found");
}
else
{
DataEntry singleEntry = feed.Entries[0] as DataEntry;
// Properties specific to all the entries returned in the feed.
Console.WriteLine("Entry ID = " + singleEntry.Id.Uri);
Console.WriteLine("Entry Title = " + singleEntry.Title.Text);
// Iterate through all the dimensions.
foreach (Dimension dimension in singleEntry.Dimensions)
{
Console.WriteLine("Dimension Name = " + dimension.Name);
Console.WriteLine("Dimension Value = " + dimension.Value);
}
// Iterate through all the metrics.
foreach (Metric metric in singleEntry.Metrics)
{
Console.WriteLine("Metric Name = " + metric.Name);
Console.WriteLine("Metric Value = " + metric.Value);
Console.WriteLine("Metric Type = " + metric.Type);
Console.WriteLine("Metric CI = " + metric.ConfidenceInterval);
}
}
}
/**
* Get the data feed values in the feed as a string.
* @return {String} This returns the contents of the feed.
*/
public String getEntriesAsTable()
{
if (feed.Entries.Count == 0)
{
return "No entries found";
}
DataEntry singleEntry = feed.Entries[0] as DataEntry;
StringBuilder feedDataLines = new StringBuilder("\n-------- All Entries In A Table --------\n");
// Put all the dimension and metric names into an array.
foreach (Dimension dimension in singleEntry.Dimensions)
{
String[] args = { dimension.Name, dimension.Value };
feedDataLines.AppendLine(String.Format("\n{0} \t= {1}", args));
}
foreach (Metric metric in singleEntry.Metrics)
{
String[] args = { metric.Name, metric.Value };
feedDataLines.AppendLine(String.Format("\n{0} \t= {1}", args));
}
feedDataLines.Append("\n");
return feedDataLines.ToString();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System
{
// Represents a Globally Unique Identifier.
[StructLayout(LayoutKind.Sequential)]
[Serializable]
[Runtime.Versioning.NonVersionable] // This only applies to field layout
[TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public partial struct Guid : IFormattable, IComparable, IComparable<Guid>, IEquatable<Guid>
{
public static readonly Guid Empty = new Guid();
////////////////////////////////////////////////////////////////////////////////
// Member variables
////////////////////////////////////////////////////////////////////////////////
private int _a; // Do not rename (binary serialization)
private short _b; // Do not rename (binary serialization)
private short _c; // Do not rename (binary serialization)
private byte _d; // Do not rename (binary serialization)
private byte _e; // Do not rename (binary serialization)
private byte _f; // Do not rename (binary serialization)
private byte _g; // Do not rename (binary serialization)
private byte _h; // Do not rename (binary serialization)
private byte _i; // Do not rename (binary serialization)
private byte _j; // Do not rename (binary serialization)
private byte _k; // Do not rename (binary serialization)
////////////////////////////////////////////////////////////////////////////////
// Constructors
////////////////////////////////////////////////////////////////////////////////
// Creates a new guid from an array of bytes.
public Guid(byte[] b) :
this(new ReadOnlySpan<byte>(b ?? throw new ArgumentNullException(nameof(b))))
{
}
// Creates a new guid from a read-only span.
public Guid(ReadOnlySpan<byte> b)
{
if (b.Length != 16)
throw new ArgumentException(SR.Format(SR.Arg_GuidArrayCtor, "16"), nameof(b));
_a = b[3] << 24 | b[2] << 16 | b[1] << 8 | b[0];
_b = (short)(b[5] << 8 | b[4]);
_c = (short)(b[7] << 8 | b[6]);
_d = b[8];
_e = b[9];
_f = b[10];
_g = b[11];
_h = b[12];
_i = b[13];
_j = b[14];
_k = b[15];
}
[CLSCompliant(false)]
public Guid(uint a, ushort b, ushort c, byte d, byte e, byte f, byte g, byte h, byte i, byte j, byte k)
{
_a = (int)a;
_b = (short)b;
_c = (short)c;
_d = d;
_e = e;
_f = f;
_g = g;
_h = h;
_i = i;
_j = j;
_k = k;
}
// Creates a new GUID initialized to the value represented by the arguments.
//
public Guid(int a, short b, short c, byte[] d)
{
if (d == null)
throw new ArgumentNullException(nameof(d));
// Check that array is not too big
if (d.Length != 8)
throw new ArgumentException(SR.Format(SR.Arg_GuidArrayCtor, "8"), nameof(d));
Contract.EndContractBlock();
_a = a;
_b = b;
_c = c;
_d = d[0];
_e = d[1];
_f = d[2];
_g = d[3];
_h = d[4];
_i = d[5];
_j = d[6];
_k = d[7];
}
// Creates a new GUID initialized to the value represented by the
// arguments. The bytes are specified like this to avoid endianness issues.
//
public Guid(int a, short b, short c, byte d, byte e, byte f, byte g, byte h, byte i, byte j, byte k)
{
_a = a;
_b = b;
_c = c;
_d = d;
_e = e;
_f = f;
_g = g;
_h = h;
_i = i;
_j = j;
_k = k;
}
[Flags]
private enum GuidStyles
{
None = 0x00000000,
AllowParenthesis = 0x00000001, //Allow the guid to be enclosed in parens
AllowBraces = 0x00000002, //Allow the guid to be enclosed in braces
AllowDashes = 0x00000004, //Allow the guid to contain dash group separators
AllowHexPrefix = 0x00000008, //Allow the guid to contain {0xdd,0xdd}
RequireParenthesis = 0x00000010, //Require the guid to be enclosed in parens
RequireBraces = 0x00000020, //Require the guid to be enclosed in braces
RequireDashes = 0x00000040, //Require the guid to contain dash group separators
RequireHexPrefix = 0x00000080, //Require the guid to contain {0xdd,0xdd}
HexFormat = RequireBraces | RequireHexPrefix, /* X */
NumberFormat = None, /* N */
DigitFormat = RequireDashes, /* D */
BraceFormat = RequireBraces | RequireDashes, /* B */
ParenthesisFormat = RequireParenthesis | RequireDashes, /* P */
Any = AllowParenthesis | AllowBraces | AllowDashes | AllowHexPrefix,
}
private enum GuidParseThrowStyle
{
None = 0,
All = 1,
AllButOverflow = 2
}
private enum ParseFailureKind
{
None = 0,
ArgumentNull = 1,
Format = 2,
FormatWithParameter = 3,
NativeException = 4,
FormatWithInnerException = 5
}
// This will store the result of the parsing. And it will eventually be used to construct a Guid instance.
private struct GuidResult
{
internal Guid _parsedGuid;
internal GuidParseThrowStyle _throwStyle;
private ParseFailureKind _failure;
private string _failureMessageID;
private object _failureMessageFormatArgument;
private string _failureArgumentName;
private Exception _innerException;
internal void Init(GuidParseThrowStyle canThrow)
{
_throwStyle = canThrow;
}
internal void SetFailure(Exception nativeException)
{
_failure = ParseFailureKind.NativeException;
_innerException = nativeException;
}
internal void SetFailure(ParseFailureKind failure, string failureMessageID)
{
SetFailure(failure, failureMessageID, null, null, null);
}
internal void SetFailure(ParseFailureKind failure, string failureMessageID, object failureMessageFormatArgument)
{
SetFailure(failure, failureMessageID, failureMessageFormatArgument, null, null);
}
internal void SetFailure(ParseFailureKind failure, string failureMessageID, object failureMessageFormatArgument,
string failureArgumentName, Exception innerException)
{
Debug.Assert(failure != ParseFailureKind.NativeException, "ParseFailureKind.NativeException should not be used with this overload");
_failure = failure;
_failureMessageID = failureMessageID;
_failureMessageFormatArgument = failureMessageFormatArgument;
_failureArgumentName = failureArgumentName;
_innerException = innerException;
if (_throwStyle != GuidParseThrowStyle.None)
{
throw GetGuidParseException();
}
}
internal Exception GetGuidParseException()
{
switch (_failure)
{
case ParseFailureKind.ArgumentNull:
return new ArgumentNullException(_failureArgumentName, SR.GetResourceString(_failureMessageID));
case ParseFailureKind.FormatWithInnerException:
return new FormatException(SR.GetResourceString(_failureMessageID), _innerException);
case ParseFailureKind.FormatWithParameter:
return new FormatException(SR.Format(SR.GetResourceString(_failureMessageID), _failureMessageFormatArgument));
case ParseFailureKind.Format:
return new FormatException(SR.GetResourceString(_failureMessageID));
case ParseFailureKind.NativeException:
return _innerException;
default:
Debug.Assert(false, "Unknown GuidParseFailure: " + _failure);
return new FormatException(SR.Format_GuidUnrecognized);
}
}
}
// Creates a new guid based on the value in the string. The value is made up
// of hex digits speared by the dash ("-"). The string may begin and end with
// brackets ("{", "}").
//
// The string must be of the form dddddddd-dddd-dddd-dddd-dddddddddddd. where
// d is a hex digit. (That is 8 hex digits, followed by 4, then 4, then 4,
// then 12) such as: "CA761232-ED42-11CE-BACD-00AA0057B223"
//
public Guid(string g)
{
if (g == null)
{
throw new ArgumentNullException(nameof(g));
}
Contract.EndContractBlock();
GuidResult result = new GuidResult();
result.Init(GuidParseThrowStyle.All);
if (TryParseGuid(g, GuidStyles.Any, ref result))
{
this = result._parsedGuid;
}
else
{
throw result.GetGuidParseException();
}
}
public static Guid Parse(string input)
{
if (input == null)
{
throw new ArgumentNullException(nameof(input));
}
Contract.EndContractBlock();
GuidResult result = new GuidResult();
result.Init(GuidParseThrowStyle.AllButOverflow);
if (TryParseGuid(input, GuidStyles.Any, ref result))
{
return result._parsedGuid;
}
else
{
throw result.GetGuidParseException();
}
}
public static bool TryParse(string input, out Guid result)
{
GuidResult parseResult = new GuidResult();
parseResult.Init(GuidParseThrowStyle.None);
if (TryParseGuid(input, GuidStyles.Any, ref parseResult))
{
result = parseResult._parsedGuid;
return true;
}
else
{
result = Empty;
return false;
}
}
public static Guid ParseExact(string input, string format)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
if (format == null)
throw new ArgumentNullException(nameof(format));
if (format.Length != 1)
{
// all acceptable format strings are of length 1
throw new FormatException(SR.Format_InvalidGuidFormatSpecification);
}
GuidStyles style;
char formatCh = format[0];
if (formatCh == 'D' || formatCh == 'd')
{
style = GuidStyles.DigitFormat;
}
else if (formatCh == 'N' || formatCh == 'n')
{
style = GuidStyles.NumberFormat;
}
else if (formatCh == 'B' || formatCh == 'b')
{
style = GuidStyles.BraceFormat;
}
else if (formatCh == 'P' || formatCh == 'p')
{
style = GuidStyles.ParenthesisFormat;
}
else if (formatCh == 'X' || formatCh == 'x')
{
style = GuidStyles.HexFormat;
}
else
{
throw new FormatException(SR.Format_InvalidGuidFormatSpecification);
}
GuidResult result = new GuidResult();
result.Init(GuidParseThrowStyle.AllButOverflow);
if (TryParseGuid(input, style, ref result))
{
return result._parsedGuid;
}
else
{
throw result.GetGuidParseException();
}
}
public static bool TryParseExact(string input, string format, out Guid result)
{
if (format == null || format.Length != 1)
{
result = Empty;
return false;
}
GuidStyles style;
char formatCh = format[0];
if (formatCh == 'D' || formatCh == 'd')
{
style = GuidStyles.DigitFormat;
}
else if (formatCh == 'N' || formatCh == 'n')
{
style = GuidStyles.NumberFormat;
}
else if (formatCh == 'B' || formatCh == 'b')
{
style = GuidStyles.BraceFormat;
}
else if (formatCh == 'P' || formatCh == 'p')
{
style = GuidStyles.ParenthesisFormat;
}
else if (formatCh == 'X' || formatCh == 'x')
{
style = GuidStyles.HexFormat;
}
else
{
// invalid guid format specification
result = Empty;
return false;
}
GuidResult parseResult = new GuidResult();
parseResult.Init(GuidParseThrowStyle.None);
if (TryParseGuid(input, style, ref parseResult))
{
result = parseResult._parsedGuid;
return true;
}
else
{
result = Empty;
return false;
}
}
private static bool TryParseGuid(string g, GuidStyles flags, ref GuidResult result)
{
if (g == null)
{
result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidUnrecognized));
return false;
}
string guidString = g.Trim(); //Remove Whitespace
if (guidString.Length == 0)
{
result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidUnrecognized));
return false;
}
// Check for dashes
bool dashesExistInString = (guidString.IndexOf('-', 0) >= 0);
if (dashesExistInString)
{
if ((flags & (GuidStyles.AllowDashes | GuidStyles.RequireDashes)) == 0)
{
// dashes are not allowed
result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidUnrecognized));
return false;
}
}
else
{
if ((flags & GuidStyles.RequireDashes) != 0)
{
// dashes are required
result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidUnrecognized));
return false;
}
}
// Check for braces
bool bracesExistInString = (guidString.IndexOf('{', 0) >= 0);
if (bracesExistInString)
{
if ((flags & (GuidStyles.AllowBraces | GuidStyles.RequireBraces)) == 0)
{
// braces are not allowed
result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidUnrecognized));
return false;
}
}
else
{
if ((flags & GuidStyles.RequireBraces) != 0)
{
// braces are required
result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidUnrecognized));
return false;
}
}
// Check for parenthesis
bool parenthesisExistInString = (guidString.IndexOf('(', 0) >= 0);
if (parenthesisExistInString)
{
if ((flags & (GuidStyles.AllowParenthesis | GuidStyles.RequireParenthesis)) == 0)
{
// parenthesis are not allowed
result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidUnrecognized));
return false;
}
}
else
{
if ((flags & GuidStyles.RequireParenthesis) != 0)
{
// parenthesis are required
result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidUnrecognized));
return false;
}
}
try
{
// let's get on with the parsing
if (dashesExistInString)
{
// Check if it's of the form [{|(]dddddddd-dddd-dddd-dddd-dddddddddddd[}|)]
return TryParseGuidWithDashes(guidString, ref result);
}
else if (bracesExistInString)
{
// Check if it's of the form {0xdddddddd,0xdddd,0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}
return TryParseGuidWithHexPrefix(guidString, ref result);
}
else
{
// Check if it's of the form dddddddddddddddddddddddddddddddd
return TryParseGuidWithNoStyle(guidString, ref result);
}
}
catch (IndexOutOfRangeException ex)
{
result.SetFailure(ParseFailureKind.FormatWithInnerException, nameof(SR.Format_GuidUnrecognized), null, null, ex);
return false;
}
catch (ArgumentException ex)
{
result.SetFailure(ParseFailureKind.FormatWithInnerException, nameof(SR.Format_GuidUnrecognized), null, null, ex);
return false;
}
}
// Check if it's of the form {0xdddddddd,0xdddd,0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}
private static bool TryParseGuidWithHexPrefix(string guidString, ref GuidResult result)
{
int numStart = 0;
int numLen = 0;
// Eat all of the whitespace
guidString = EatAllWhitespace(guidString);
// Check for leading '{'
if (string.IsNullOrEmpty(guidString) || guidString[0] != '{')
{
result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidBrace));
return false;
}
// Check for '0x'
if (!IsHexPrefix(guidString, 1))
{
result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidHexPrefix), "{0xdddddddd, etc}");
return false;
}
// Find the end of this hex number (since it is not fixed length)
numStart = 3;
numLen = guidString.IndexOf(',', numStart) - numStart;
if (numLen <= 0)
{
result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidComma));
return false;
}
if (!StringToInt(guidString.Substring(numStart, numLen) /*first DWORD*/, -1, ParseNumbers.IsTight, out result._parsedGuid._a, ref result))
return false;
// Check for '0x'
if (!IsHexPrefix(guidString, numStart + numLen + 1))
{
result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidHexPrefix), "{0xdddddddd, 0xdddd, etc}");
return false;
}
// +3 to get by ',0x'
numStart = numStart + numLen + 3;
numLen = guidString.IndexOf(',', numStart) - numStart;
if (numLen <= 0)
{
result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidComma));
return false;
}
// Read in the number
if (!StringToShort(guidString.Substring(numStart, numLen) /*first DWORD*/, -1, ParseNumbers.IsTight, out result._parsedGuid._b, ref result))
return false;
// Check for '0x'
if (!IsHexPrefix(guidString, numStart + numLen + 1))
{
result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidHexPrefix), "{0xdddddddd, 0xdddd, 0xdddd, etc}");
return false;
}
// +3 to get by ',0x'
numStart = numStart + numLen + 3;
numLen = guidString.IndexOf(',', numStart) - numStart;
if (numLen <= 0)
{
result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidComma));
return false;
}
// Read in the number
if (!StringToShort(guidString.Substring(numStart, numLen) /*first DWORD*/, -1, ParseNumbers.IsTight, out result._parsedGuid._c, ref result))
return false;
// Check for '{'
if (guidString.Length <= numStart + numLen + 1 || guidString[numStart + numLen + 1] != '{')
{
result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidBrace));
return false;
}
// Prepare for loop
numLen++;
byte[] bytes = new byte[8];
for (int i = 0; i < 8; i++)
{
// Check for '0x'
if (!IsHexPrefix(guidString, numStart + numLen + 1))
{
result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidHexPrefix), "{... { ... 0xdd, ...}}");
return false;
}
// +3 to get by ',0x' or '{0x' for first case
numStart = numStart + numLen + 3;
// Calculate number length
if (i < 7) // first 7 cases
{
numLen = guidString.IndexOf(',', numStart) - numStart;
if (numLen <= 0)
{
result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidComma));
return false;
}
}
else // last case ends with '}', not ','
{
numLen = guidString.IndexOf('}', numStart) - numStart;
if (numLen <= 0)
{
result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidBraceAfterLastNumber));
return false;
}
}
// Read in the number
int signedNumber;
if (!StringToInt(guidString.Substring(numStart, numLen), -1, ParseNumbers.IsTight, out signedNumber, ref result))
{
return false;
}
uint number = (uint)signedNumber;
// check for overflow
if (number > 255)
{
result.SetFailure(ParseFailureKind.Format, nameof(SR.Overflow_Byte));
return false;
}
bytes[i] = (byte)number;
}
result._parsedGuid._d = bytes[0];
result._parsedGuid._e = bytes[1];
result._parsedGuid._f = bytes[2];
result._parsedGuid._g = bytes[3];
result._parsedGuid._h = bytes[4];
result._parsedGuid._i = bytes[5];
result._parsedGuid._j = bytes[6];
result._parsedGuid._k = bytes[7];
// Check for last '}'
if (numStart + numLen + 1 >= guidString.Length || guidString[numStart + numLen + 1] != '}')
{
result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidEndBrace));
return false;
}
// Check if we have extra characters at the end
if (numStart + numLen + 1 != guidString.Length - 1)
{
result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_ExtraJunkAtEnd));
return false;
}
return true;
}
// Check if it's of the form dddddddddddddddddddddddddddddddd
private static bool TryParseGuidWithNoStyle(string guidString, ref GuidResult result)
{
int startPos = 0;
int temp;
long templ;
int currentPos = 0;
if (guidString.Length != 32)
{
result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidInvLen));
return false;
}
for (int i = 0; i < guidString.Length; i++)
{
char ch = guidString[i];
if (ch >= '0' && ch <= '9')
{
continue;
}
else
{
char upperCaseCh = char.ToUpperInvariant(ch);
if (upperCaseCh >= 'A' && upperCaseCh <= 'F')
{
continue;
}
}
result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidInvalidChar));
return false;
}
if (!StringToInt(guidString.Substring(startPos, 8) /*first DWORD*/, -1, ParseNumbers.IsTight, out result._parsedGuid._a, ref result))
return false;
startPos += 8;
if (!StringToShort(guidString.Substring(startPos, 4), -1, ParseNumbers.IsTight, out result._parsedGuid._b, ref result))
return false;
startPos += 4;
if (!StringToShort(guidString.Substring(startPos, 4), -1, ParseNumbers.IsTight, out result._parsedGuid._c, ref result))
return false;
startPos += 4;
if (!StringToInt(guidString.Substring(startPos, 4), -1, ParseNumbers.IsTight, out temp, ref result))
return false;
startPos += 4;
currentPos = startPos;
if (!StringToLong(guidString, ref currentPos, ParseNumbers.NoSpace, out templ, ref result))
return false;
if (currentPos - startPos != 12)
{
result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidInvLen));
return false;
}
result._parsedGuid._d = (byte)(temp >> 8);
result._parsedGuid._e = (byte)(temp);
temp = (int)(templ >> 32);
result._parsedGuid._f = (byte)(temp >> 8);
result._parsedGuid._g = (byte)(temp);
temp = (int)(templ);
result._parsedGuid._h = (byte)(temp >> 24);
result._parsedGuid._i = (byte)(temp >> 16);
result._parsedGuid._j = (byte)(temp >> 8);
result._parsedGuid._k = (byte)(temp);
return true;
}
// Check if it's of the form [{|(]dddddddd-dddd-dddd-dddd-dddddddddddd[}|)]
private static bool TryParseGuidWithDashes(string guidString, ref GuidResult result)
{
int startPos = 0;
int temp;
long templ;
int currentPos = 0;
// check to see that it's the proper length
if (guidString[0] == '{')
{
if (guidString.Length != 38 || guidString[37] != '}')
{
result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidInvLen));
return false;
}
startPos = 1;
}
else if (guidString[0] == '(')
{
if (guidString.Length != 38 || guidString[37] != ')')
{
result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidInvLen));
return false;
}
startPos = 1;
}
else if (guidString.Length != 36)
{
result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidInvLen));
return false;
}
if (guidString[8 + startPos] != '-' ||
guidString[13 + startPos] != '-' ||
guidString[18 + startPos] != '-' ||
guidString[23 + startPos] != '-')
{
result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidDashes));
return false;
}
currentPos = startPos;
if (!StringToInt(guidString, ref currentPos, 8, ParseNumbers.NoSpace, out temp, ref result))
return false;
result._parsedGuid._a = temp;
++currentPos; //Increment past the '-';
if (!StringToInt(guidString, ref currentPos, 4, ParseNumbers.NoSpace, out temp, ref result))
return false;
result._parsedGuid._b = (short)temp;
++currentPos; //Increment past the '-';
if (!StringToInt(guidString, ref currentPos, 4, ParseNumbers.NoSpace, out temp, ref result))
return false;
result._parsedGuid._c = (short)temp;
++currentPos; //Increment past the '-';
if (!StringToInt(guidString, ref currentPos, 4, ParseNumbers.NoSpace, out temp, ref result))
return false;
++currentPos; //Increment past the '-';
startPos = currentPos;
if (!StringToLong(guidString, ref currentPos, ParseNumbers.NoSpace, out templ, ref result))
return false;
if (currentPos - startPos != 12)
{
result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidInvLen));
return false;
}
result._parsedGuid._d = (byte)(temp >> 8);
result._parsedGuid._e = (byte)(temp);
temp = (int)(templ >> 32);
result._parsedGuid._f = (byte)(temp >> 8);
result._parsedGuid._g = (byte)(temp);
temp = (int)(templ);
result._parsedGuid._h = (byte)(temp >> 24);
result._parsedGuid._i = (byte)(temp >> 16);
result._parsedGuid._j = (byte)(temp >> 8);
result._parsedGuid._k = (byte)(temp);
return true;
}
private static bool StringToShort(string str, int requiredLength, int flags, out short result, ref GuidResult parseResult)
{
int parsePos = 0;
return StringToShort(str, ref parsePos, requiredLength, flags, out result, ref parseResult);
}
private static bool StringToShort(string str, ref int parsePos, int requiredLength, int flags, out short result, ref GuidResult parseResult)
{
result = 0;
int x;
bool retValue = StringToInt(str, ref parsePos, requiredLength, flags, out x, ref parseResult);
result = (short)x;
return retValue;
}
private static bool StringToInt(string str, int requiredLength, int flags, out int result, ref GuidResult parseResult)
{
int parsePos = 0;
return StringToInt(str, ref parsePos, requiredLength, flags, out result, ref parseResult);
}
private static bool StringToInt(string str, ref int parsePos, int requiredLength, int flags, out int result, ref GuidResult parseResult)
{
result = 0;
int currStart = parsePos;
try
{
result = ParseNumbers.StringToInt(str, 16, flags, ref parsePos);
}
catch (OverflowException ex)
{
if (parseResult._throwStyle == GuidParseThrowStyle.All)
{
throw;
}
else if (parseResult._throwStyle == GuidParseThrowStyle.AllButOverflow)
{
throw new FormatException(SR.Format_GuidUnrecognized, ex);
}
else
{
parseResult.SetFailure(ex);
return false;
}
}
catch (Exception ex)
{
if (parseResult._throwStyle == GuidParseThrowStyle.None)
{
parseResult.SetFailure(ex);
return false;
}
else
{
throw;
}
}
//If we didn't parse enough characters, there's clearly an error.
if (requiredLength != -1 && parsePos - currStart != requiredLength)
{
parseResult.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidInvalidChar));
return false;
}
return true;
}
private static unsafe bool StringToLong(string str, ref int parsePos, int flags, out long result, ref GuidResult parseResult)
{
result = 0;
try
{
result = ParseNumbers.StringToLong(str, 16, flags, ref parsePos);
}
catch (OverflowException ex)
{
if (parseResult._throwStyle == GuidParseThrowStyle.All)
{
throw;
}
else if (parseResult._throwStyle == GuidParseThrowStyle.AllButOverflow)
{
throw new FormatException(SR.Format_GuidUnrecognized, ex);
}
else
{
parseResult.SetFailure(ex);
return false;
}
}
catch (Exception ex)
{
if (parseResult._throwStyle == GuidParseThrowStyle.None)
{
parseResult.SetFailure(ex);
return false;
}
else
{
throw;
}
}
return true;
}
private static string EatAllWhitespace(string str)
{
int newLength = 0;
char[] chArr = new char[str.Length];
char curChar;
// Now get each char from str and if it is not whitespace add it to chArr
for (int i = 0; i < str.Length; i++)
{
curChar = str[i];
if (!char.IsWhiteSpace(curChar))
{
chArr[newLength++] = curChar;
}
}
// Return a new string based on chArr
return new string(chArr, 0, newLength);
}
private static bool IsHexPrefix(string str, int i)
{
if (str.Length > i + 1 && str[i] == '0' && (char.ToLowerInvariant(str[i + 1]) == 'x'))
return true;
else
return false;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void WriteByteHelper(Span<byte> destination)
{
destination[0] = (byte)(_a);
destination[1] = (byte)(_a >> 8);
destination[2] = (byte)(_a >> 16);
destination[3] = (byte)(_a >> 24);
destination[4] = (byte)(_b);
destination[5] = (byte)(_b >> 8);
destination[6] = (byte)(_c);
destination[7] = (byte)(_c >> 8);
destination[8] = _d;
destination[9] = _e;
destination[10] = _f;
destination[11] = _g;
destination[12] = _h;
destination[13] = _i;
destination[14] = _j;
destination[15] = _k;
}
// Returns an unsigned byte array containing the GUID.
public byte[] ToByteArray()
{
var g = new byte[16];
WriteByteHelper(g);
return g;
}
// Returns whether bytes are sucessfully written to given span.
public bool TryWriteBytes(Span<byte> destination)
{
if (destination.Length < 16)
return false;
WriteByteHelper(destination);
return true;
}
// Returns the guid in "registry" format.
public override string ToString()
{
return ToString("D", null);
}
public override int GetHashCode()
{
// Simply XOR all the bits of the GUID 32 bits at a time.
return _a ^ Unsafe.Add(ref _a, 1) ^ Unsafe.Add(ref _a, 2) ^ Unsafe.Add(ref _a, 3);
}
// Returns true if and only if the guid represented
// by o is the same as this instance.
public override bool Equals(object o)
{
Guid g;
// Check that o is a Guid first
if (o == null || !(o is Guid))
return false;
else g = (Guid)o;
// Now compare each of the elements
return g._a == _a &&
Unsafe.Add(ref g._a, 1) == Unsafe.Add(ref _a, 1) &&
Unsafe.Add(ref g._a, 2) == Unsafe.Add(ref _a, 2) &&
Unsafe.Add(ref g._a, 3) == Unsafe.Add(ref _a, 3);
}
public bool Equals(Guid g)
{
// Now compare each of the elements
return g._a == _a &&
Unsafe.Add(ref g._a, 1) == Unsafe.Add(ref _a, 1) &&
Unsafe.Add(ref g._a, 2) == Unsafe.Add(ref _a, 2) &&
Unsafe.Add(ref g._a, 3) == Unsafe.Add(ref _a, 3);
}
private int GetResult(uint me, uint them)
{
if (me < them)
{
return -1;
}
return 1;
}
public int CompareTo(object value)
{
if (value == null)
{
return 1;
}
if (!(value is Guid))
{
throw new ArgumentException(SR.Arg_MustBeGuid, nameof(value));
}
Guid g = (Guid)value;
if (g._a != _a)
{
return GetResult((uint)_a, (uint)g._a);
}
if (g._b != _b)
{
return GetResult((uint)_b, (uint)g._b);
}
if (g._c != _c)
{
return GetResult((uint)_c, (uint)g._c);
}
if (g._d != _d)
{
return GetResult(_d, g._d);
}
if (g._e != _e)
{
return GetResult(_e, g._e);
}
if (g._f != _f)
{
return GetResult(_f, g._f);
}
if (g._g != _g)
{
return GetResult(_g, g._g);
}
if (g._h != _h)
{
return GetResult(_h, g._h);
}
if (g._i != _i)
{
return GetResult(_i, g._i);
}
if (g._j != _j)
{
return GetResult(_j, g._j);
}
if (g._k != _k)
{
return GetResult(_k, g._k);
}
return 0;
}
public int CompareTo(Guid value)
{
if (value._a != _a)
{
return GetResult((uint)_a, (uint)value._a);
}
if (value._b != _b)
{
return GetResult((uint)_b, (uint)value._b);
}
if (value._c != _c)
{
return GetResult((uint)_c, (uint)value._c);
}
if (value._d != _d)
{
return GetResult(_d, value._d);
}
if (value._e != _e)
{
return GetResult(_e, value._e);
}
if (value._f != _f)
{
return GetResult(_f, value._f);
}
if (value._g != _g)
{
return GetResult(_g, value._g);
}
if (value._h != _h)
{
return GetResult(_h, value._h);
}
if (value._i != _i)
{
return GetResult(_i, value._i);
}
if (value._j != _j)
{
return GetResult(_j, value._j);
}
if (value._k != _k)
{
return GetResult(_k, value._k);
}
return 0;
}
public static bool operator ==(Guid a, Guid b)
{
// Now compare each of the elements
return a._a == b._a &&
Unsafe.Add(ref a._a, 1) == Unsafe.Add(ref b._a, 1) &&
Unsafe.Add(ref a._a, 2) == Unsafe.Add(ref b._a, 2) &&
Unsafe.Add(ref a._a, 3) == Unsafe.Add(ref b._a, 3);
}
public static bool operator !=(Guid a, Guid b)
{
// Now compare each of the elements
return a._a != b._a ||
Unsafe.Add(ref a._a, 1) != Unsafe.Add(ref b._a, 1) ||
Unsafe.Add(ref a._a, 2) != Unsafe.Add(ref b._a, 2) ||
Unsafe.Add(ref a._a, 3) != Unsafe.Add(ref b._a, 3);
}
public string ToString(string format)
{
return ToString(format, null);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static char HexToChar(int a)
{
a = a & 0xf;
return (char)((a > 9) ? a - 10 + 0x61 : a + 0x30);
}
unsafe private static int HexsToChars(char* guidChars, int a, int b)
{
guidChars[0] = HexToChar(a >> 4);
guidChars[1] = HexToChar(a);
guidChars[2] = HexToChar(b >> 4);
guidChars[3] = HexToChar(b);
return 4;
}
unsafe private static int HexsToCharsHexOutput(char* guidChars, int a, int b)
{
guidChars[0] = '0';
guidChars[1] = 'x';
guidChars[2] = HexToChar(a >> 4);
guidChars[3] = HexToChar(a);
guidChars[4] = ',';
guidChars[5] = '0';
guidChars[6] = 'x';
guidChars[7] = HexToChar(b >> 4);
guidChars[8] = HexToChar(b);
return 9;
}
// IFormattable interface
// We currently ignore provider
public string ToString(string format, IFormatProvider provider)
{
if (format == null || format.Length == 0)
format = "D";
// all acceptable format strings are of length 1
if (format.Length != 1)
throw new FormatException(SR.Format_InvalidGuidFormatSpecification);
int guidSize;
switch (format[0])
{
case 'D':
case 'd':
guidSize = 36;
break;
case 'N':
case 'n':
guidSize = 32;
break;
case 'B':
case 'b':
case 'P':
case 'p':
guidSize = 38;
break;
case 'X':
case 'x':
guidSize = 68;
break;
default:
throw new FormatException(SR.Format_InvalidGuidFormatSpecification);
}
string guidString = string.FastAllocateString(guidSize);
int bytesWritten;
bool result = TryFormat(new Span<char>(ref guidString.GetRawStringData(), guidString.Length), out bytesWritten, format);
Debug.Assert(result && bytesWritten == guidString.Length, "Formatting guid should have succeeded.");
return guidString;
}
// Returns whether the guid is successfully formatted as a span.
public bool TryFormat(Span<char> destination, out int charsWritten, string format = null)
{
if (format == null || format.Length == 0)
format = "D";
// all acceptable format strings are of length 1
if (format.Length != 1)
throw new FormatException(SR.Format_InvalidGuidFormatSpecification);
bool dash = true;
bool hex = false;
int braces = 0;
int guidSize;
switch (format[0])
{
case 'D':
case 'd':
guidSize = 36;
break;
case 'N':
case 'n':
dash = false;
guidSize = 32;
break;
case 'B':
case 'b':
braces = '{' + ('}' << 16);
guidSize = 38;
break;
case 'P':
case 'p':
braces = '(' + (')' << 16);
guidSize = 38;
break;
case 'X':
case 'x':
braces = '{' + ('}' << 16);
dash = false;
hex = true;
guidSize = 68;
break;
default:
throw new FormatException(SR.Format_InvalidGuidFormatSpecification);
}
if (destination.Length < guidSize)
{
charsWritten = 0;
return false;
}
unsafe
{
fixed (char* guidChars = &destination.DangerousGetPinnableReference())
{
char * p = guidChars;
if (braces != 0)
*p++ = (char)braces;
if (hex)
{
// {0xdddddddd,0xdddd,0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}
*p++ = '0';
*p++ = 'x';
p += HexsToChars(p, _a >> 24, _a >> 16);
p += HexsToChars(p, _a >> 8, _a);
*p++ = ',';
*p++ = '0';
*p++ = 'x';
p += HexsToChars(p, _b >> 8, _b);
*p++ = ',';
*p++ = '0';
*p++ = 'x';
p += HexsToChars(p, _c >> 8, _c);
*p++ = ',';
*p++ = '{';
p += HexsToCharsHexOutput(p, _d, _e);
*p++ = ',';
p += HexsToCharsHexOutput(p, _f, _g);
*p++ = ',';
p += HexsToCharsHexOutput(p, _h, _i);
*p++ = ',';
p += HexsToCharsHexOutput(p, _j, _k);
*p++ = '}';
}
else
{
// [{|(]dddddddd[-]dddd[-]dddd[-]dddd[-]dddddddddddd[}|)]
p += HexsToChars(p, _a >> 24, _a >> 16);
p += HexsToChars(p, _a >> 8, _a);
if (dash)
*p++ = '-';
p += HexsToChars(p, _b >> 8, _b);
if (dash)
*p++ = '-';
p += HexsToChars(p, _c >> 8, _c);
if (dash)
*p++ = '-';
p += HexsToChars(p, _d, _e);
if (dash)
*p++ = '-';
p += HexsToChars(p, _f, _g);
p += HexsToChars(p, _h, _i);
p += HexsToChars(p, _j, _k);
}
if (braces != 0)
*p++ = (char)(braces >> 16);
Debug.Assert(p - guidChars == guidSize);
}
}
charsWritten = guidSize;
return true;
}
}
}
| |
/********************************************************************************************
Copyright (c) Microsoft Corporation
All rights reserved.
Microsoft Public License:
This license governs use of the accompanying software. If you use the software, you
accept this license. If you do not accept the license, do not use the software.
1. Definitions
The terms "reproduce," "reproduction," "derivative works," and "distribution" have the
same meaning here as under U.S. copyright law.
A "contribution" is the original software, or any additions or changes to the software.
A "contributor" is any person that distributes its contribution under this license.
"Licensed patents" are a contributor's patent claims that read directly on its contribution.
2. Grant of Rights
(A) Copyright Grant- Subject to the terms of this license, including the license conditions
and limitations in section 3, each contributor grants you a non-exclusive, worldwide,
royalty-free copyright license to reproduce its contribution, prepare derivative works of
its contribution, and distribute its contribution or any derivative works that you create.
(B) Patent Grant- Subject to the terms of this license, including the license conditions
and limitations in section 3, each contributor grants you a non-exclusive, worldwide,
royalty-free license under its licensed patents to make, have made, use, sell, offer for
sale, import, and/or otherwise dispose of its contribution in the software or derivative
works of the contribution in the software.
3. Conditions and Limitations
(A) No Trademark License- This license does not grant you rights to use any contributors'
name, logo, or trademarks.
(B) If you bring a patent claim against any contributor over patents that you claim are
infringed by the software, your patent license from such contributor to the software ends
automatically.
(C) If you distribute any portion of the software, you must retain all copyright, patent,
trademark, and attribution notices that are present in the software.
(D) If you distribute any portion of the software in source code form, you may do so only
under this license by including a complete copy of this license with your distribution.
If you distribute any portion of the software in compiled or object code form, you may only
do so under a license that complies with this license.
(E) The software is licensed "as-is." You bear the risk of using it. The contributors give
no express warranties, guarantees or conditions. You may have additional consumer rights
under your local laws which this license cannot change. To the extent permitted under your
local laws, the contributors exclude the implied warranties of merchantability, fitness for
a particular purpose and non-infringement.
********************************************************************************************/
using System;
using System.Windows.Forms.Design;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Text;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Windows.Threading;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TextManager.Interop;
using Microsoft.Win32;
using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
namespace Microsoft.VisualStudio.Project
{
/// <summary>
/// This class implements an MSBuild logger that output events to VS outputwindow and tasklist.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "IDE")]
internal class IDEBuildLogger : Logger
{
#region fields
// TODO: Remove these constants when we have a version that supports getting the verbosity using automation.
private string buildVerbosityRegistryRoot = @"Software\Microsoft\VisualStudio\10.0";
private const string buildVerbosityRegistrySubKey = @"General";
private const string buildVerbosityRegistryKey = "MSBuildLoggerVerbosity";
private int currentIndent;
private IVsOutputWindowPane outputWindowPane;
private string errorString = SR.GetString(SR.Error, CultureInfo.CurrentUICulture);
private string warningString = SR.GetString(SR.Warning, CultureInfo.CurrentUICulture);
private TaskProvider taskProvider;
private IVsHierarchy hierarchy;
private IServiceProvider serviceProvider;
private Dispatcher dispatcher;
private bool haveCachedVerbosity = false;
// Queues to manage Tasks and Error output plus message logging
private ConcurrentQueue<Func<ErrorTask>> taskQueue;
private ConcurrentQueue<string> outputQueue;
#endregion
#region properties
public IServiceProvider ServiceProvider
{
get { return this.serviceProvider; }
}
public string WarningString
{
get { return this.warningString; }
set { this.warningString = value; }
}
public string ErrorString
{
get { return this.errorString; }
set { this.errorString = value; }
}
/// <summary>
/// When the build is not a "design time" (background or secondary) build this is True
/// </summary>
/// <remarks>
/// The only known way to detect an interactive build is to check this.outputWindowPane for null.
/// </remarks>
protected bool InteractiveBuild
{
get { return this.outputWindowPane != null; }
}
/// <summary>
/// When building from within VS, setting this will
/// enable the logger to retrive the verbosity from
/// the correct registry hive.
/// </summary>
internal string BuildVerbosityRegistryRoot
{
get { return this.buildVerbosityRegistryRoot; }
set
{
this.buildVerbosityRegistryRoot = value;
}
}
/// <summary>
/// Set to null to avoid writing to the output window
/// </summary>
internal IVsOutputWindowPane OutputWindowPane
{
get { return this.outputWindowPane; }
set { this.outputWindowPane = value; }
}
#endregion
#region ctors
/// <summary>
/// Constructor. Inititialize member data.
/// </summary>
public IDEBuildLogger(IVsOutputWindowPane output, TaskProvider taskProvider, IVsHierarchy hierarchy)
{
if (taskProvider == null)
throw new ArgumentNullException("taskProvider");
if (hierarchy == null)
throw new ArgumentNullException("hierarchy");
Trace.WriteLineIf(Thread.CurrentThread.GetApartmentState() != ApartmentState.STA, "WARNING: IDEBuildLogger constructor running on the wrong thread.");
IOleServiceProvider site;
Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(hierarchy.GetSite(out site));
this.taskProvider = taskProvider;
this.outputWindowPane = output;
this.hierarchy = hierarchy;
this.serviceProvider = new ServiceProvider(site);
this.dispatcher = Dispatcher.CurrentDispatcher;
}
#endregion
#region overridden methods
/// <summary>
/// Overridden from the Logger class.
/// </summary>
public override void Initialize(IEventSource eventSource)
{
if (null == eventSource)
{
throw new ArgumentNullException("eventSource");
}
this.taskQueue = new ConcurrentQueue<Func<ErrorTask>>();
this.outputQueue = new ConcurrentQueue<string>();
eventSource.BuildStarted += new BuildStartedEventHandler(BuildStartedHandler);
eventSource.BuildFinished += new BuildFinishedEventHandler(BuildFinishedHandler);
eventSource.ProjectStarted += new ProjectStartedEventHandler(ProjectStartedHandler);
eventSource.ProjectFinished += new ProjectFinishedEventHandler(ProjectFinishedHandler);
eventSource.TargetStarted += new TargetStartedEventHandler(TargetStartedHandler);
eventSource.TargetFinished += new TargetFinishedEventHandler(TargetFinishedHandler);
eventSource.TaskStarted += new TaskStartedEventHandler(TaskStartedHandler);
eventSource.TaskFinished += new TaskFinishedEventHandler(TaskFinishedHandler);
eventSource.CustomEventRaised += new CustomBuildEventHandler(CustomHandler);
eventSource.ErrorRaised += new BuildErrorEventHandler(ErrorHandler);
eventSource.WarningRaised += new BuildWarningEventHandler(WarningHandler);
eventSource.MessageRaised += new BuildMessageEventHandler(MessageHandler);
}
#endregion
#region event delegates
/// <summary>
/// This is the delegate for BuildStartedHandler events.
/// </summary>
protected virtual void BuildStartedHandler(object sender, BuildStartedEventArgs buildEvent)
{
// NOTE: This may run on a background thread!
ClearCachedVerbosity();
ClearQueuedOutput();
ClearQueuedTasks();
QueueOutputEvent(MessageImportance.Low, buildEvent);
}
/// <summary>
/// This is the delegate for BuildFinishedHandler events.
/// </summary>
/// <param name="sender"></param>
/// <param name="buildEvent"></param>
protected virtual void BuildFinishedHandler(object sender, BuildFinishedEventArgs buildEvent)
{
// NOTE: This may run on a background thread!
MessageImportance importance = buildEvent.Succeeded ? MessageImportance.Low : MessageImportance.High;
QueueOutputText(importance, Environment.NewLine);
QueueOutputEvent(importance, buildEvent);
// flush output and error queues
ReportQueuedOutput();
ReportQueuedTasks();
}
/// <summary>
/// This is the delegate for ProjectStartedHandler events.
/// </summary>
protected virtual void ProjectStartedHandler(object sender, ProjectStartedEventArgs buildEvent)
{
// NOTE: This may run on a background thread!
QueueOutputEvent(MessageImportance.Low, buildEvent);
}
/// <summary>
/// This is the delegate for ProjectFinishedHandler events.
/// </summary>
protected virtual void ProjectFinishedHandler(object sender, ProjectFinishedEventArgs buildEvent)
{
// NOTE: This may run on a background thread!
QueueOutputEvent(buildEvent.Succeeded ? MessageImportance.Low : MessageImportance.High, buildEvent);
}
/// <summary>
/// This is the delegate for TargetStartedHandler events.
/// </summary>
protected virtual void TargetStartedHandler(object sender, TargetStartedEventArgs buildEvent)
{
// NOTE: This may run on a background thread!
QueueOutputEvent(MessageImportance.Low, buildEvent);
IndentOutput();
}
/// <summary>
/// This is the delegate for TargetFinishedHandler events.
/// </summary>
protected virtual void TargetFinishedHandler(object sender, TargetFinishedEventArgs buildEvent)
{
// NOTE: This may run on a background thread!
UnindentOutput();
QueueOutputEvent(MessageImportance.Low, buildEvent);
}
/// <summary>
/// This is the delegate for TaskStartedHandler events.
/// </summary>
protected virtual void TaskStartedHandler(object sender, TaskStartedEventArgs buildEvent)
{
// NOTE: This may run on a background thread!
QueueOutputEvent(MessageImportance.Low, buildEvent);
IndentOutput();
}
/// <summary>
/// This is the delegate for TaskFinishedHandler events.
/// </summary>
protected virtual void TaskFinishedHandler(object sender, TaskFinishedEventArgs buildEvent)
{
// NOTE: This may run on a background thread!
UnindentOutput();
QueueOutputEvent(MessageImportance.Low, buildEvent);
}
/// <summary>
/// This is the delegate for CustomHandler events.
/// </summary>
/// <param name="sender"></param>
/// <param name="buildEvent"></param>
protected virtual void CustomHandler(object sender, CustomBuildEventArgs buildEvent)
{
// NOTE: This may run on a background thread!
QueueOutputEvent(MessageImportance.High, buildEvent);
}
/// <summary>
/// This is the delegate for error events.
/// </summary>
protected virtual void ErrorHandler(object sender, BuildErrorEventArgs errorEvent)
{
// NOTE: This may run on a background thread!
QueueOutputText(GetFormattedErrorMessage(errorEvent.File, errorEvent.LineNumber, errorEvent.ColumnNumber, false, errorEvent.Code, errorEvent.Message));
QueueTaskEvent(errorEvent);
}
/// <summary>
/// This is the delegate for warning events.
/// </summary>
protected virtual void WarningHandler(object sender, BuildWarningEventArgs warningEvent)
{
// NOTE: This may run on a background thread!
QueueOutputText(MessageImportance.High, GetFormattedErrorMessage(warningEvent.File, warningEvent.LineNumber, warningEvent.ColumnNumber, true, warningEvent.Code, warningEvent.Message));
QueueTaskEvent(warningEvent);
}
/// <summary>
/// This is the delegate for Message event types
/// </summary>
protected virtual void MessageHandler(object sender, BuildMessageEventArgs messageEvent)
{
// NOTE: This may run on a background thread!
QueueOutputEvent(messageEvent.Importance, messageEvent);
if(messageEvent.Importance == MessageImportance.High)
QueueTaskEvent(messageEvent);
}
#endregion
#region output queue
protected void QueueOutputEvent(MessageImportance importance, BuildEventArgs buildEvent)
{
// NOTE: This may run on a background thread!
if (LogAtImportance(importance) && !string.IsNullOrEmpty(buildEvent.Message))
{
StringBuilder message = new StringBuilder(this.currentIndent + buildEvent.Message.Length);
if (this.currentIndent > 0)
{
message.Append('\t', this.currentIndent);
}
message.AppendLine(buildEvent.Message);
QueueOutputText(message.ToString());
}
}
protected void QueueOutputText(MessageImportance importance, string text)
{
// NOTE: This may run on a background thread!
if (LogAtImportance(importance))
{
QueueOutputText(text);
}
}
protected void QueueOutputText(string text)
{
// NOTE: This may run on a background thread!
if (this.OutputWindowPane != null)
{
// Enqueue the output text
this.outputQueue.Enqueue(text);
// We want to interactively report the output. But we dont want to dispatch
// more than one at a time, otherwise we might overflow the main thread's
// message queue. So, we only report the output if the queue was empty.
if (this.outputQueue.Count == 1)
{
ReportQueuedOutput();
}
}
}
private void IndentOutput()
{
// NOTE: This may run on a background thread!
this.currentIndent++;
}
private void UnindentOutput()
{
// NOTE: This may run on a background thread!
this.currentIndent--;
}
private void ReportQueuedOutput()
{
// NOTE: This may run on a background thread!
// We need to output this on the main thread. We must use BeginInvoke because the main thread may not be pumping events yet.
BeginInvokeWithErrorMessage(this.serviceProvider, this.dispatcher, () =>
{
if (this.OutputWindowPane != null)
{
string outputString;
while (this.outputQueue.TryDequeue(out outputString))
{
Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(this.OutputWindowPane.OutputString(outputString));
}
}
});
}
private void ClearQueuedOutput()
{
// NOTE: This may run on a background thread!
this.outputQueue = new ConcurrentQueue<string>();
}
#endregion output queue
#region task queue
protected void QueueTaskEvent(BuildEventArgs errorEvent)
{
this.taskQueue.Enqueue(() =>
{
ErrorTask task = new ErrorTask();
if (errorEvent is BuildErrorEventArgs)
{
BuildErrorEventArgs errorArgs = (BuildErrorEventArgs)errorEvent;
task.Document = errorArgs.File;
task.ErrorCategory = TaskErrorCategory.Error;
task.Line = errorArgs.LineNumber - 1; // The task list does +1 before showing this number.
task.Column = errorArgs.ColumnNumber;
task.Priority = TaskPriority.High;
}
else if (errorEvent is BuildWarningEventArgs)
{
BuildWarningEventArgs warningArgs = (BuildWarningEventArgs)errorEvent;
task.Document = warningArgs.File;
task.ErrorCategory = TaskErrorCategory.Warning;
task.Line = warningArgs.LineNumber - 1; // The task list does +1 before showing this number.
task.Column = warningArgs.ColumnNumber;
task.Priority = TaskPriority.Normal;
}
else if (errorEvent is BuildMessageEventArgs)
{
BuildMessageEventArgs messageArgs = (BuildMessageEventArgs)errorEvent;
task.ErrorCategory = TaskErrorCategory.Message;
task.Priority = TaskPriority.Normal;
}
task.Text = errorEvent.Message;
task.Category = TaskCategory.BuildCompile;
task.HierarchyItem = hierarchy;
return task;
});
// NOTE: Unlike output we dont want to interactively report the tasks. So we never queue
// call ReportQueuedTasks here. We do this when the build finishes.
}
private void ReportQueuedTasks()
{
// NOTE: This may run on a background thread!
// We need to output this on the main thread. We must use BeginInvoke because the main thread may not be pumping events yet.
BeginInvokeWithErrorMessage(this.serviceProvider, this.dispatcher, () =>
{
this.taskProvider.SuspendRefresh();
try
{
Func<ErrorTask> taskFunc;
while (this.taskQueue.TryDequeue(out taskFunc))
{
// Create the error task
ErrorTask task = taskFunc();
// Log the task
this.taskProvider.Tasks.Add(task);
}
}
finally
{
this.taskProvider.ResumeRefresh();
}
});
}
private void ClearQueuedTasks()
{
// NOTE: This may run on a background thread!
this.taskQueue = new ConcurrentQueue<Func<ErrorTask>>();
if (this.InteractiveBuild)
{
// We need to clear this on the main thread. We must use BeginInvoke because the main thread may not be pumping events yet.
BeginInvokeWithErrorMessage(this.serviceProvider, this.dispatcher, () =>
{
this.taskProvider.Tasks.Clear();
});
}
}
#endregion task queue
#region helpers
/// <summary>
/// This method takes a MessageImportance and returns true if messages
/// at importance i should be logged. Otherwise return false.
/// </summary>
private bool LogAtImportance(MessageImportance importance)
{
// If importance is too low for current settings, ignore the event
bool logIt = false;
this.SetVerbosity();
switch (this.Verbosity)
{
case LoggerVerbosity.Quiet:
logIt = false;
break;
case LoggerVerbosity.Minimal:
logIt = (importance == MessageImportance.High);
break;
case LoggerVerbosity.Normal:
// Falling through...
case LoggerVerbosity.Detailed:
logIt = (importance != MessageImportance.Low);
break;
case LoggerVerbosity.Diagnostic:
logIt = true;
break;
default:
Debug.Fail("Unknown Verbosity level. Ignoring will cause everything to be logged");
break;
}
return logIt;
}
/// <summary>
/// Format error messages for the task list
/// </summary>
private string GetFormattedErrorMessage(
string fileName,
int line,
int column,
bool isWarning,
string errorNumber,
string errorText)
{
string errorCode = isWarning ? this.WarningString : this.ErrorString;
StringBuilder message = new StringBuilder();
if (!string.IsNullOrEmpty(fileName))
{
message.AppendFormat(CultureInfo.CurrentCulture, "{0}({1},{2}):", fileName, line, column);
}
message.AppendFormat(CultureInfo.CurrentCulture, " {0} {1}: {2}", errorCode, errorNumber, errorText);
message.AppendLine();
return message.ToString();
}
/// <summary>
/// Sets the verbosity level.
/// </summary>
private void SetVerbosity()
{
// TODO: This should be replaced when we have a version that supports automation.
if (!this.haveCachedVerbosity)
{
string verbosityKey = String.Format(CultureInfo.InvariantCulture, @"{0}\{1}", BuildVerbosityRegistryRoot, buildVerbosityRegistrySubKey);
using (RegistryKey subKey = Registry.CurrentUser.OpenSubKey(verbosityKey))
{
if (subKey != null)
{
object valueAsObject = subKey.GetValue(buildVerbosityRegistryKey);
if (valueAsObject != null)
{
this.Verbosity = (LoggerVerbosity)((int)valueAsObject);
}
}
}
this.haveCachedVerbosity = true;
}
}
/// <summary>
/// Clear the cached verbosity, so that it will be re-evaluated from the build verbosity registry key.
/// </summary>
private void ClearCachedVerbosity()
{
this.haveCachedVerbosity = false;
}
#endregion helpers
#region exception handling helpers
/// <summary>
/// Call Dispatcher.BeginInvoke, showing an error message if there was a non-critical exception.
/// </summary>
/// <param name="serviceProvider">service provider</param>
/// <param name="dispatcher">dispatcher</param>
/// <param name="action">action to invoke</param>
private static void BeginInvokeWithErrorMessage(IServiceProvider serviceProvider, Dispatcher dispatcher, Action action)
{
dispatcher.BeginInvoke(new Action(() => CallWithErrorMessage(serviceProvider, action)));
}
/// <summary>
/// Show error message if exception is caught when invoking a method
/// </summary>
/// <param name="serviceProvider">service provider</param>
/// <param name="action">action to invoke</param>
private static void CallWithErrorMessage(IServiceProvider serviceProvider, Action action)
{
try
{
action();
}
catch (Exception ex)
{
if (Microsoft.VisualStudio.ErrorHandler.IsCriticalException(ex))
{
throw;
}
ShowErrorMessage(serviceProvider, ex);
}
}
/// <summary>
/// Show error window about the exception
/// </summary>
/// <param name="serviceProvider">service provider</param>
/// <param name="exception">exception</param>
private static void ShowErrorMessage(IServiceProvider serviceProvider, Exception exception)
{
IUIService UIservice = (IUIService)serviceProvider.GetService(typeof(IUIService));
if (UIservice != null && exception != null)
{
UIservice.ShowError(exception);
}
}
#endregion exception handling helpers
}
}
| |
/*
* Copyright 2007 ZXing 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.Generic;
using ZXing.Common;
using ZXing.Common.Detector;
namespace ZXing.QrCode.Internal
{
/// <summary>
/// <p>Encapsulates logic that can detect a QR Code in an image, even if the QR Code
/// is rotated or skewed, or partially obscured.</p>
/// </summary>
/// <author>Sean Owen</author>
public class Detector
{
private readonly BitMatrix image;
private ResultPointCallback resultPointCallback;
/// <summary>
/// Initializes a new instance of the <see cref="Detector"/> class.
/// </summary>
/// <param name="image">The image.</param>
public Detector(BitMatrix image)
{
this.image = image;
}
/// <summary>
/// Gets the image.
/// </summary>
virtual protected internal BitMatrix Image
{
get
{
return image;
}
}
/// <summary>
/// Gets the result point callback.
/// </summary>
virtual protected internal ResultPointCallback ResultPointCallback
{
get
{
return resultPointCallback;
}
}
/// <summary>
/// <p>Detects a QR Code in an image, simply.</p>
/// </summary>
/// <returns>
/// <see cref="DetectorResult"/> encapsulating results of detecting a QR Code
/// </returns>
public virtual DetectorResult detect()
{
return detect(null);
}
/// <summary>
/// <p>Detects a QR Code in an image, simply.</p>
/// </summary>
/// <param name="hints">optional hints to detector</param>
/// <returns>
/// <see cref="DetectorResult"/> encapsulating results of detecting a QR Code
/// </returns>
public virtual DetectorResult detect(IDictionary<DecodeHintType, object> hints)
{
resultPointCallback = hints == null || !hints.ContainsKey(DecodeHintType.NEED_RESULT_POINT_CALLBACK) ? null : (ResultPointCallback)hints[DecodeHintType.NEED_RESULT_POINT_CALLBACK];
FinderPatternFinder finder = new FinderPatternFinder(image, resultPointCallback);
FinderPatternInfo info = finder.find(hints);
if (info == null)
return null;
return processFinderPatternInfo(info);
}
/// <summary>
/// Processes the finder pattern info.
/// </summary>
/// <param name="info">The info.</param>
/// <returns></returns>
protected internal virtual DetectorResult processFinderPatternInfo(FinderPatternInfo info)
{
FinderPattern topLeft = info.TopLeft;
FinderPattern topRight = info.TopRight;
FinderPattern bottomLeft = info.BottomLeft;
float moduleSize = calculateModuleSize(topLeft, topRight, bottomLeft);
if (moduleSize < 1.0f)
{
return null;
}
int dimension;
if (!computeDimension(topLeft, topRight, bottomLeft, moduleSize, out dimension))
return null;
Internal.Version provisionalVersion = Internal.Version.getProvisionalVersionForDimension(dimension);
if (provisionalVersion == null)
return null;
int modulesBetweenFPCenters = provisionalVersion.DimensionForVersion - 7;
AlignmentPattern alignmentPattern = null;
// Anything above version 1 has an alignment pattern
if (provisionalVersion.AlignmentPatternCenters.Length > 0)
{
// Guess where a "bottom right" finder pattern would have been
float bottomRightX = topRight.X - topLeft.X + bottomLeft.X;
float bottomRightY = topRight.Y - topLeft.Y + bottomLeft.Y;
// Estimate that alignment pattern is closer by 3 modules
// from "bottom right" to known top left location
//UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
float correctionToTopLeft = 1.0f - 3.0f / (float)modulesBetweenFPCenters;
//UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
int estAlignmentX = (int)(topLeft.X + correctionToTopLeft * (bottomRightX - topLeft.X));
//UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
int estAlignmentY = (int)(topLeft.Y + correctionToTopLeft * (bottomRightY - topLeft.Y));
// Kind of arbitrary -- expand search radius before giving up
for (int i = 4; i <= 16; i <<= 1)
{
alignmentPattern = findAlignmentInRegion(moduleSize, estAlignmentX, estAlignmentY, (float)i);
if (alignmentPattern == null)
continue;
break;
}
// If we didn't find alignment pattern... well try anyway without it
}
PerspectiveTransform transform = createTransform(topLeft, topRight, bottomLeft, alignmentPattern, dimension);
BitMatrix bits = sampleGrid(image, transform, dimension);
if (bits == null)
return null;
ResultPoint[] points;
if (alignmentPattern == null)
{
points = new ResultPoint[] { bottomLeft, topLeft, topRight };
}
else
{
points = new ResultPoint[] { bottomLeft, topLeft, topRight, alignmentPattern };
}
return new DetectorResult(bits, points);
}
private static PerspectiveTransform createTransform(ResultPoint topLeft, ResultPoint topRight, ResultPoint bottomLeft, ResultPoint alignmentPattern, int dimension)
{
//UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
float dimMinusThree = (float)dimension - 3.5f;
float bottomRightX;
float bottomRightY;
float sourceBottomRightX;
float sourceBottomRightY;
if (alignmentPattern != null)
{
bottomRightX = alignmentPattern.X;
bottomRightY = alignmentPattern.Y;
sourceBottomRightX = sourceBottomRightY = dimMinusThree - 3.0f;
}
else
{
// Don't have an alignment pattern, just make up the bottom-right point
bottomRightX = (topRight.X - topLeft.X) + bottomLeft.X;
bottomRightY = (topRight.Y - topLeft.Y) + bottomLeft.Y;
sourceBottomRightX = sourceBottomRightY = dimMinusThree;
}
return PerspectiveTransform.quadrilateralToQuadrilateral(
3.5f,
3.5f,
dimMinusThree,
3.5f,
sourceBottomRightX,
sourceBottomRightY,
3.5f,
dimMinusThree,
topLeft.X,
topLeft.Y,
topRight.X,
topRight.Y,
bottomRightX,
bottomRightY,
bottomLeft.X,
bottomLeft.Y);
}
private static BitMatrix sampleGrid(BitMatrix image, PerspectiveTransform transform, int dimension)
{
GridSampler sampler = GridSampler.Instance;
return sampler.sampleGrid(image, dimension, dimension, transform);
}
/// <summary> <p>Computes the dimension (number of modules on a size) of the QR Code based on the position
/// of the finder patterns and estimated module size.</p>
/// </summary>
private static bool computeDimension(ResultPoint topLeft, ResultPoint topRight, ResultPoint bottomLeft, float moduleSize, out int dimension)
{
int tltrCentersDimension = MathUtils.round(ResultPoint.distance(topLeft, topRight) / moduleSize);
int tlblCentersDimension = MathUtils.round(ResultPoint.distance(topLeft, bottomLeft) / moduleSize);
dimension = ((tltrCentersDimension + tlblCentersDimension) >> 1) + 7;
switch (dimension & 0x03)
{
// mod 4
case 0:
dimension++;
break;
// 1? do nothing
case 2:
dimension--;
break;
case 3:
return true;
}
return true;
}
/// <summary> <p>Computes an average estimated module size based on estimated derived from the positions
/// of the three finder patterns.</p>
/// </summary>
protected internal virtual float calculateModuleSize(ResultPoint topLeft, ResultPoint topRight, ResultPoint bottomLeft)
{
// Take the average
return (calculateModuleSizeOneWay(topLeft, topRight) + calculateModuleSizeOneWay(topLeft, bottomLeft)) / 2.0f;
}
/// <summary> <p>Estimates module size based on two finder patterns -- it uses
/// {@link #sizeOfBlackWhiteBlackRunBothWays(int, int, int, int)} to figure the
/// width of each, measuring along the axis between their centers.</p>
/// </summary>
private float calculateModuleSizeOneWay(ResultPoint pattern, ResultPoint otherPattern)
{
//UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
float moduleSizeEst1 = sizeOfBlackWhiteBlackRunBothWays((int)pattern.X, (int)pattern.Y, (int)otherPattern.X, (int)otherPattern.Y);
//UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
float moduleSizeEst2 = sizeOfBlackWhiteBlackRunBothWays((int)otherPattern.X, (int)otherPattern.Y, (int)pattern.X, (int)pattern.Y);
if (Single.IsNaN(moduleSizeEst1))
{
return moduleSizeEst2 / 7.0f;
}
if (Single.IsNaN(moduleSizeEst2))
{
return moduleSizeEst1 / 7.0f;
}
// Average them, and divide by 7 since we've counted the width of 3 black modules,
// and 1 white and 1 black module on either side. Ergo, divide sum by 14.
return (moduleSizeEst1 + moduleSizeEst2) / 14.0f;
}
/// <summary> See {@link #sizeOfBlackWhiteBlackRun(int, int, int, int)}; computes the total width of
/// a finder pattern by looking for a black-white-black run from the center in the direction
/// of another point (another finder pattern center), and in the opposite direction too.
/// </summary>
private float sizeOfBlackWhiteBlackRunBothWays(int fromX, int fromY, int toX, int toY)
{
float result = sizeOfBlackWhiteBlackRun(fromX, fromY, toX, toY);
// Now count other way -- don't run off image though of course
float scale = 1.0f;
int otherToX = fromX - (toX - fromX);
if (otherToX < 0)
{
//UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
scale = (float)fromX / (float)(fromX - otherToX);
otherToX = 0;
}
else if (otherToX >= image.Width)
{
//UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
scale = (float)(image.Width - 1 - fromX) / (float)(otherToX - fromX);
otherToX = image.Width - 1;
}
//UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
int otherToY = (int)(fromY - (toY - fromY) * scale);
scale = 1.0f;
if (otherToY < 0)
{
//UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
scale = (float)fromY / (float)(fromY - otherToY);
otherToY = 0;
}
else if (otherToY >= image.Height)
{
//UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
scale = (float)(image.Height - 1 - fromY) / (float)(otherToY - fromY);
otherToY = image.Height - 1;
}
//UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
otherToX = (int)(fromX + (otherToX - fromX) * scale);
result += sizeOfBlackWhiteBlackRun(fromX, fromY, otherToX, otherToY);
return result - 1.0f; // -1 because we counted the middle pixel twice
}
/// <summary> <p>This method traces a line from a point in the image, in the direction towards another point.
/// It begins in a black region, and keeps going until it finds white, then black, then white again.
/// It reports the distance from the start to this point.</p>
///
/// <p>This is used when figuring out how wide a finder pattern is, when the finder pattern
/// may be skewed or rotated.</p>
/// </summary>
private float sizeOfBlackWhiteBlackRun(int fromX, int fromY, int toX, int toY)
{
// Mild variant of Bresenham's algorithm;
// see http://en.wikipedia.org/wiki/Bresenham's_line_algorithm
bool steep = Math.Abs(toY - fromY) > Math.Abs(toX - fromX);
if (steep)
{
int temp = fromX;
fromX = fromY;
fromY = temp;
temp = toX;
toX = toY;
toY = temp;
}
int dx = Math.Abs(toX - fromX);
int dy = Math.Abs(toY - fromY);
int error = -dx >> 1;
int xstep = fromX < toX ? 1 : -1;
int ystep = fromY < toY ? 1 : -1;
// In black pixels, looking for white, first or second time.
int state = 0;
// Loop up until x == toX, but not beyond
int xLimit = toX + xstep;
for (int x = fromX, y = fromY; x != xLimit; x += xstep)
{
int realX = steep ? y : x;
int realY = steep ? x : y;
// Does current pixel mean we have moved white to black or vice versa?
// Scanning black in state 0,2 and white in state 1, so if we find the wrong
// color, advance to next state or end if we are in state 2 already
if ((state == 1) == image[realX, realY])
{
if (state == 2)
{
return MathUtils.distance(x, y, fromX, fromY);
}
state++;
}
error += dy;
if (error > 0)
{
if (y == toY)
{
break;
}
y += ystep;
error -= dx;
}
}
// Found black-white-black; give the benefit of the doubt that the next pixel outside the image
// is "white" so this last point at (toX+xStep,toY) is the right ending. This is really a
// small approximation; (toX+xStep,toY+yStep) might be really correct. Ignore this.
if (state == 2)
{
return MathUtils.distance(toX + xstep, toY, fromX, fromY);
}
// else we didn't find even black-white-black; no estimate is really possible
return Single.NaN;
}
/// <summary>
/// <p>Attempts to locate an alignment pattern in a limited region of the image, which is
/// guessed to contain it. This method uses {@link AlignmentPattern}.</p>
/// </summary>
/// <param name="overallEstModuleSize">estimated module size so far</param>
/// <param name="estAlignmentX">x coordinate of center of area probably containing alignment pattern</param>
/// <param name="estAlignmentY">y coordinate of above</param>
/// <param name="allowanceFactor">number of pixels in all directions to search from the center</param>
/// <returns>
/// <see cref="AlignmentPattern"/> if found, or null otherwise
/// </returns>
protected AlignmentPattern findAlignmentInRegion(float overallEstModuleSize, int estAlignmentX, int estAlignmentY, float allowanceFactor)
{
// Look for an alignment pattern (3 modules in size) around where it
// should be
//UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
int allowance = (int)(allowanceFactor * overallEstModuleSize);
int alignmentAreaLeftX = Math.Max(0, estAlignmentX - allowance);
int alignmentAreaRightX = Math.Min(image.Width - 1, estAlignmentX + allowance);
if (alignmentAreaRightX - alignmentAreaLeftX < overallEstModuleSize * 3)
{
return null;
}
int alignmentAreaTopY = Math.Max(0, estAlignmentY - allowance);
int alignmentAreaBottomY = Math.Min(image.Height - 1, estAlignmentY + allowance);
var alignmentFinder = new AlignmentPatternFinder(
image,
alignmentAreaLeftX,
alignmentAreaTopY,
alignmentAreaRightX - alignmentAreaLeftX,
alignmentAreaBottomY - alignmentAreaTopY,
overallEstModuleSize,
resultPointCallback);
return alignmentFinder.find();
}
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
namespace EduHub.Data.Entities
{
/// <summary>
/// Subjects
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class SU : EduHubEntity
{
#region Navigation Property Cache
private KSF Cache_FACULTY_KSF;
private SU Cache_PROMOTE_SU;
private KCY Cache_SUBJECT_ACADEMIC_YEAR_KCY;
private SA Cache_FEE_CODE_SA;
#endregion
#region Foreign Navigation Properties
private IReadOnlyList<DFF> Cache_SUKEY_DFF_SUBJECT;
private IReadOnlyList<SC> Cache_SUKEY_SC_SUBJ01;
private IReadOnlyList<SC> Cache_SUKEY_SC_SUBJ02;
private IReadOnlyList<SC> Cache_SUKEY_SC_SUBJ03;
private IReadOnlyList<SC> Cache_SUKEY_SC_SUBJ04;
private IReadOnlyList<SC> Cache_SUKEY_SC_SUBJ05;
private IReadOnlyList<SC> Cache_SUKEY_SC_SUBJ06;
private IReadOnlyList<SC> Cache_SUKEY_SC_SUBJ07;
private IReadOnlyList<SC> Cache_SUKEY_SC_SUBJ08;
private IReadOnlyList<SC> Cache_SUKEY_SC_SUBJ09;
private IReadOnlyList<SC> Cache_SUKEY_SC_SUBJ10;
private IReadOnlyList<SC> Cache_SUKEY_SC_SUBJ11;
private IReadOnlyList<SC> Cache_SUKEY_SC_SUBJ12;
private IReadOnlyList<SC> Cache_SUKEY_SC_SUBJ13;
private IReadOnlyList<SC> Cache_SUKEY_SC_SUBJ14;
private IReadOnlyList<SC> Cache_SUKEY_SC_SUBJ15;
private IReadOnlyList<SC> Cache_SUKEY_SC_SUBJ16;
private IReadOnlyList<SC> Cache_SUKEY_SC_SUBJ17;
private IReadOnlyList<SC> Cache_SUKEY_SC_SUBJ18;
private IReadOnlyList<SC> Cache_SUKEY_SC_SUBJ19;
private IReadOnlyList<SC> Cache_SUKEY_SC_SUBJ20;
private IReadOnlyList<SCL> Cache_SUKEY_SCL_SUBJECT;
private IReadOnlyList<SF> Cache_SUKEY_SF_SUBJECT01;
private IReadOnlyList<SF> Cache_SUKEY_SF_SUBJECT02;
private IReadOnlyList<SF> Cache_SUKEY_SF_SUBJECT03;
private IReadOnlyList<SF> Cache_SUKEY_SF_SUBJECT04;
private IReadOnlyList<SF> Cache_SUKEY_SF_SUBJECT05;
private IReadOnlyList<SF> Cache_SUKEY_SF_SUBJECT06;
private IReadOnlyList<SF> Cache_SUKEY_SF_SUBJECT07;
private IReadOnlyList<SF> Cache_SUKEY_SF_SUBJECT08;
private IReadOnlyList<SF> Cache_SUKEY_SF_SUBJECT09;
private IReadOnlyList<SF> Cache_SUKEY_SF_SUBJECT10;
private IReadOnlyList<SGSC> Cache_SUKEY_SGSC_SULINK;
private IReadOnlyList<STMA> Cache_SUKEY_STMA_MKEY;
private IReadOnlyList<SU> Cache_SUKEY_SU_PROMOTE;
private IReadOnlyList<SUBL> Cache_SUKEY_SUBL_BLKEY;
private IReadOnlyList<SUPR> Cache_SUKEY_SUPR_SUPRKEY;
private IReadOnlyList<SUPR> Cache_SUKEY_SUPR_PREREQUISITE;
private IReadOnlyList<TCTB> Cache_SUKEY_TCTB_SUBJ;
private IReadOnlyList<TCTQ> Cache_SUKEY_TCTQ_SUBJ;
private IReadOnlyList<TE> Cache_SUKEY_TE_SUBJ;
private IReadOnlyList<THTQ> Cache_SUKEY_THTQ_SUBJ;
private IReadOnlyList<TTES> Cache_SUKEY_TTES_SUBJ;
private IReadOnlyList<TTTG> Cache_SUKEY_TTTG_SUBJ;
private IReadOnlyList<TXAS> Cache_SUKEY_TXAS_SUBJECT;
#endregion
/// <inheritdoc />
public override DateTime? EntityLastModified
{
get
{
return LW_DATE;
}
}
#region Field Properties
/// <summary>
/// Subject code
/// [Uppercase Alphanumeric (5)]
/// </summary>
public string SUKEY { get; internal set; }
/// <summary>
/// Subject name
/// [Titlecase (30)]
/// </summary>
public string FULLNAME { get; internal set; }
/// <summary>
/// Subject short name for screen displays and reports
/// [Alphanumeric (10)]
/// </summary>
public string SHORTNAME { get; internal set; }
/// <summary>
/// Faculty
/// [Uppercase Alphanumeric (10)]
/// </summary>
public string FACULTY { get; internal set; }
/// <summary>
/// Subject that normally follows this subject in a course (eg Physics 11 is followed by Physics 12)
/// [Uppercase Alphanumeric (5)]
/// </summary>
public string PROMOTE { get; internal set; }
/// <summary>
/// Description of subject for parents
/// [Memo]
/// </summary>
public string OVERVIEW { get; internal set; }
/// <summary>
/// Dummy field to enable recording of subject priority
/// </summary>
public short? PRIORITY { get; internal set; }
/// <summary>
/// (Was ACADEMIC_YEAR) Offered to students at this year level: if blank or matches one of the values in a TT record, the subject is eligible for that template
/// [Uppercase Alphanumeric (4)]
/// </summary>
public string SUBJECT_ACADEMIC_YEAR { get; internal set; }
/// <summary>
/// (Was SEMESTER_OFFERED) Semester/term/quarter in which offered: if 0 or matches the value in a TT record, the subject is eligible for that template
/// </summary>
public short? SEMESTER { get; internal set; }
/// <summary>
/// Ultranet. T=Term, S=Semester (default), Y=Year
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string DURATION { get; internal set; }
/// <summary>
/// Is this subject currently active (available for use in timetabling)? (U=Active, other value=Inactive)
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string SUBJECT_TYPE { get; internal set; }
/// <summary>
/// Used to Order Subjects for BarCode Printing
/// </summary>
public short? PRINT_SEQ_NO { get; internal set; }
/// <summary>
/// Core or elective flag
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string ELECTIVE { get; internal set; }
/// <summary>
/// VCAA code of this subject for use in VASS export
/// [Uppercase Alphanumeric (5)]
/// </summary>
public string VCAA_ID { get; internal set; }
/// <summary>
/// Fee code
/// [Uppercase Alphanumeric (10)]
/// </summary>
public string FEE_CODE { get; internal set; }
/// <summary>
/// Last write date
/// </summary>
public DateTime? LW_DATE { get; internal set; }
/// <summary>
/// Last write time
/// </summary>
public short? LW_TIME { get; internal set; }
/// <summary>
/// Last write operator
/// [Uppercase Alphanumeric (128)]
/// </summary>
public string LW_USER { get; internal set; }
#endregion
#region Navigation Properties
/// <summary>
/// KSF (Faculties) related entity by [SU.FACULTY]->[KSF.KSFKEY]
/// Faculty
/// </summary>
public KSF FACULTY_KSF
{
get
{
if (FACULTY == null)
{
return null;
}
if (Cache_FACULTY_KSF == null)
{
Cache_FACULTY_KSF = Context.KSF.FindByKSFKEY(FACULTY);
}
return Cache_FACULTY_KSF;
}
}
/// <summary>
/// SU (Subjects) related entity by [SU.PROMOTE]->[SU.SUKEY]
/// Subject that normally follows this subject in a course (eg Physics 11 is followed by Physics 12)
/// </summary>
public SU PROMOTE_SU
{
get
{
if (PROMOTE == null)
{
return null;
}
if (Cache_PROMOTE_SU == null)
{
Cache_PROMOTE_SU = Context.SU.FindBySUKEY(PROMOTE);
}
return Cache_PROMOTE_SU;
}
}
/// <summary>
/// KCY (Year Levels) related entity by [SU.SUBJECT_ACADEMIC_YEAR]->[KCY.KCYKEY]
/// (Was ACADEMIC_YEAR) Offered to students at this year level: if blank or matches one of the values in a TT record, the subject is eligible for that template
/// </summary>
public KCY SUBJECT_ACADEMIC_YEAR_KCY
{
get
{
if (SUBJECT_ACADEMIC_YEAR == null)
{
return null;
}
if (Cache_SUBJECT_ACADEMIC_YEAR_KCY == null)
{
Cache_SUBJECT_ACADEMIC_YEAR_KCY = Context.KCY.FindByKCYKEY(SUBJECT_ACADEMIC_YEAR);
}
return Cache_SUBJECT_ACADEMIC_YEAR_KCY;
}
}
/// <summary>
/// SA (Fees) related entity by [SU.FEE_CODE]->[SA.SAKEY]
/// Fee code
/// </summary>
public SA FEE_CODE_SA
{
get
{
if (FEE_CODE == null)
{
return null;
}
if (Cache_FEE_CODE_SA == null)
{
Cache_FEE_CODE_SA = Context.SA.FindBySAKEY(FEE_CODE);
}
return Cache_FEE_CODE_SA;
}
}
#endregion
#region Foreign Navigation Properties
/// <summary>
/// DFF (Family Financial Transactions) related entities by [SU.SUKEY]->[DFF.SUBJECT]
/// Subject code
/// </summary>
public IReadOnlyList<DFF> SUKEY_DFF_SUBJECT
{
get
{
if (Cache_SUKEY_DFF_SUBJECT == null &&
!Context.DFF.TryFindBySUBJECT(SUKEY, out Cache_SUKEY_DFF_SUBJECT))
{
Cache_SUKEY_DFF_SUBJECT = new List<DFF>().AsReadOnly();
}
return Cache_SUKEY_DFF_SUBJECT;
}
}
/// <summary>
/// SC (Courses) related entities by [SU.SUKEY]->[SC.SUBJ01]
/// Subject code
/// </summary>
public IReadOnlyList<SC> SUKEY_SC_SUBJ01
{
get
{
if (Cache_SUKEY_SC_SUBJ01 == null &&
!Context.SC.TryFindBySUBJ01(SUKEY, out Cache_SUKEY_SC_SUBJ01))
{
Cache_SUKEY_SC_SUBJ01 = new List<SC>().AsReadOnly();
}
return Cache_SUKEY_SC_SUBJ01;
}
}
/// <summary>
/// SC (Courses) related entities by [SU.SUKEY]->[SC.SUBJ02]
/// Subject code
/// </summary>
public IReadOnlyList<SC> SUKEY_SC_SUBJ02
{
get
{
if (Cache_SUKEY_SC_SUBJ02 == null &&
!Context.SC.TryFindBySUBJ02(SUKEY, out Cache_SUKEY_SC_SUBJ02))
{
Cache_SUKEY_SC_SUBJ02 = new List<SC>().AsReadOnly();
}
return Cache_SUKEY_SC_SUBJ02;
}
}
/// <summary>
/// SC (Courses) related entities by [SU.SUKEY]->[SC.SUBJ03]
/// Subject code
/// </summary>
public IReadOnlyList<SC> SUKEY_SC_SUBJ03
{
get
{
if (Cache_SUKEY_SC_SUBJ03 == null &&
!Context.SC.TryFindBySUBJ03(SUKEY, out Cache_SUKEY_SC_SUBJ03))
{
Cache_SUKEY_SC_SUBJ03 = new List<SC>().AsReadOnly();
}
return Cache_SUKEY_SC_SUBJ03;
}
}
/// <summary>
/// SC (Courses) related entities by [SU.SUKEY]->[SC.SUBJ04]
/// Subject code
/// </summary>
public IReadOnlyList<SC> SUKEY_SC_SUBJ04
{
get
{
if (Cache_SUKEY_SC_SUBJ04 == null &&
!Context.SC.TryFindBySUBJ04(SUKEY, out Cache_SUKEY_SC_SUBJ04))
{
Cache_SUKEY_SC_SUBJ04 = new List<SC>().AsReadOnly();
}
return Cache_SUKEY_SC_SUBJ04;
}
}
/// <summary>
/// SC (Courses) related entities by [SU.SUKEY]->[SC.SUBJ05]
/// Subject code
/// </summary>
public IReadOnlyList<SC> SUKEY_SC_SUBJ05
{
get
{
if (Cache_SUKEY_SC_SUBJ05 == null &&
!Context.SC.TryFindBySUBJ05(SUKEY, out Cache_SUKEY_SC_SUBJ05))
{
Cache_SUKEY_SC_SUBJ05 = new List<SC>().AsReadOnly();
}
return Cache_SUKEY_SC_SUBJ05;
}
}
/// <summary>
/// SC (Courses) related entities by [SU.SUKEY]->[SC.SUBJ06]
/// Subject code
/// </summary>
public IReadOnlyList<SC> SUKEY_SC_SUBJ06
{
get
{
if (Cache_SUKEY_SC_SUBJ06 == null &&
!Context.SC.TryFindBySUBJ06(SUKEY, out Cache_SUKEY_SC_SUBJ06))
{
Cache_SUKEY_SC_SUBJ06 = new List<SC>().AsReadOnly();
}
return Cache_SUKEY_SC_SUBJ06;
}
}
/// <summary>
/// SC (Courses) related entities by [SU.SUKEY]->[SC.SUBJ07]
/// Subject code
/// </summary>
public IReadOnlyList<SC> SUKEY_SC_SUBJ07
{
get
{
if (Cache_SUKEY_SC_SUBJ07 == null &&
!Context.SC.TryFindBySUBJ07(SUKEY, out Cache_SUKEY_SC_SUBJ07))
{
Cache_SUKEY_SC_SUBJ07 = new List<SC>().AsReadOnly();
}
return Cache_SUKEY_SC_SUBJ07;
}
}
/// <summary>
/// SC (Courses) related entities by [SU.SUKEY]->[SC.SUBJ08]
/// Subject code
/// </summary>
public IReadOnlyList<SC> SUKEY_SC_SUBJ08
{
get
{
if (Cache_SUKEY_SC_SUBJ08 == null &&
!Context.SC.TryFindBySUBJ08(SUKEY, out Cache_SUKEY_SC_SUBJ08))
{
Cache_SUKEY_SC_SUBJ08 = new List<SC>().AsReadOnly();
}
return Cache_SUKEY_SC_SUBJ08;
}
}
/// <summary>
/// SC (Courses) related entities by [SU.SUKEY]->[SC.SUBJ09]
/// Subject code
/// </summary>
public IReadOnlyList<SC> SUKEY_SC_SUBJ09
{
get
{
if (Cache_SUKEY_SC_SUBJ09 == null &&
!Context.SC.TryFindBySUBJ09(SUKEY, out Cache_SUKEY_SC_SUBJ09))
{
Cache_SUKEY_SC_SUBJ09 = new List<SC>().AsReadOnly();
}
return Cache_SUKEY_SC_SUBJ09;
}
}
/// <summary>
/// SC (Courses) related entities by [SU.SUKEY]->[SC.SUBJ10]
/// Subject code
/// </summary>
public IReadOnlyList<SC> SUKEY_SC_SUBJ10
{
get
{
if (Cache_SUKEY_SC_SUBJ10 == null &&
!Context.SC.TryFindBySUBJ10(SUKEY, out Cache_SUKEY_SC_SUBJ10))
{
Cache_SUKEY_SC_SUBJ10 = new List<SC>().AsReadOnly();
}
return Cache_SUKEY_SC_SUBJ10;
}
}
/// <summary>
/// SC (Courses) related entities by [SU.SUKEY]->[SC.SUBJ11]
/// Subject code
/// </summary>
public IReadOnlyList<SC> SUKEY_SC_SUBJ11
{
get
{
if (Cache_SUKEY_SC_SUBJ11 == null &&
!Context.SC.TryFindBySUBJ11(SUKEY, out Cache_SUKEY_SC_SUBJ11))
{
Cache_SUKEY_SC_SUBJ11 = new List<SC>().AsReadOnly();
}
return Cache_SUKEY_SC_SUBJ11;
}
}
/// <summary>
/// SC (Courses) related entities by [SU.SUKEY]->[SC.SUBJ12]
/// Subject code
/// </summary>
public IReadOnlyList<SC> SUKEY_SC_SUBJ12
{
get
{
if (Cache_SUKEY_SC_SUBJ12 == null &&
!Context.SC.TryFindBySUBJ12(SUKEY, out Cache_SUKEY_SC_SUBJ12))
{
Cache_SUKEY_SC_SUBJ12 = new List<SC>().AsReadOnly();
}
return Cache_SUKEY_SC_SUBJ12;
}
}
/// <summary>
/// SC (Courses) related entities by [SU.SUKEY]->[SC.SUBJ13]
/// Subject code
/// </summary>
public IReadOnlyList<SC> SUKEY_SC_SUBJ13
{
get
{
if (Cache_SUKEY_SC_SUBJ13 == null &&
!Context.SC.TryFindBySUBJ13(SUKEY, out Cache_SUKEY_SC_SUBJ13))
{
Cache_SUKEY_SC_SUBJ13 = new List<SC>().AsReadOnly();
}
return Cache_SUKEY_SC_SUBJ13;
}
}
/// <summary>
/// SC (Courses) related entities by [SU.SUKEY]->[SC.SUBJ14]
/// Subject code
/// </summary>
public IReadOnlyList<SC> SUKEY_SC_SUBJ14
{
get
{
if (Cache_SUKEY_SC_SUBJ14 == null &&
!Context.SC.TryFindBySUBJ14(SUKEY, out Cache_SUKEY_SC_SUBJ14))
{
Cache_SUKEY_SC_SUBJ14 = new List<SC>().AsReadOnly();
}
return Cache_SUKEY_SC_SUBJ14;
}
}
/// <summary>
/// SC (Courses) related entities by [SU.SUKEY]->[SC.SUBJ15]
/// Subject code
/// </summary>
public IReadOnlyList<SC> SUKEY_SC_SUBJ15
{
get
{
if (Cache_SUKEY_SC_SUBJ15 == null &&
!Context.SC.TryFindBySUBJ15(SUKEY, out Cache_SUKEY_SC_SUBJ15))
{
Cache_SUKEY_SC_SUBJ15 = new List<SC>().AsReadOnly();
}
return Cache_SUKEY_SC_SUBJ15;
}
}
/// <summary>
/// SC (Courses) related entities by [SU.SUKEY]->[SC.SUBJ16]
/// Subject code
/// </summary>
public IReadOnlyList<SC> SUKEY_SC_SUBJ16
{
get
{
if (Cache_SUKEY_SC_SUBJ16 == null &&
!Context.SC.TryFindBySUBJ16(SUKEY, out Cache_SUKEY_SC_SUBJ16))
{
Cache_SUKEY_SC_SUBJ16 = new List<SC>().AsReadOnly();
}
return Cache_SUKEY_SC_SUBJ16;
}
}
/// <summary>
/// SC (Courses) related entities by [SU.SUKEY]->[SC.SUBJ17]
/// Subject code
/// </summary>
public IReadOnlyList<SC> SUKEY_SC_SUBJ17
{
get
{
if (Cache_SUKEY_SC_SUBJ17 == null &&
!Context.SC.TryFindBySUBJ17(SUKEY, out Cache_SUKEY_SC_SUBJ17))
{
Cache_SUKEY_SC_SUBJ17 = new List<SC>().AsReadOnly();
}
return Cache_SUKEY_SC_SUBJ17;
}
}
/// <summary>
/// SC (Courses) related entities by [SU.SUKEY]->[SC.SUBJ18]
/// Subject code
/// </summary>
public IReadOnlyList<SC> SUKEY_SC_SUBJ18
{
get
{
if (Cache_SUKEY_SC_SUBJ18 == null &&
!Context.SC.TryFindBySUBJ18(SUKEY, out Cache_SUKEY_SC_SUBJ18))
{
Cache_SUKEY_SC_SUBJ18 = new List<SC>().AsReadOnly();
}
return Cache_SUKEY_SC_SUBJ18;
}
}
/// <summary>
/// SC (Courses) related entities by [SU.SUKEY]->[SC.SUBJ19]
/// Subject code
/// </summary>
public IReadOnlyList<SC> SUKEY_SC_SUBJ19
{
get
{
if (Cache_SUKEY_SC_SUBJ19 == null &&
!Context.SC.TryFindBySUBJ19(SUKEY, out Cache_SUKEY_SC_SUBJ19))
{
Cache_SUKEY_SC_SUBJ19 = new List<SC>().AsReadOnly();
}
return Cache_SUKEY_SC_SUBJ19;
}
}
/// <summary>
/// SC (Courses) related entities by [SU.SUKEY]->[SC.SUBJ20]
/// Subject code
/// </summary>
public IReadOnlyList<SC> SUKEY_SC_SUBJ20
{
get
{
if (Cache_SUKEY_SC_SUBJ20 == null &&
!Context.SC.TryFindBySUBJ20(SUKEY, out Cache_SUKEY_SC_SUBJ20))
{
Cache_SUKEY_SC_SUBJ20 = new List<SC>().AsReadOnly();
}
return Cache_SUKEY_SC_SUBJ20;
}
}
/// <summary>
/// SCL (Subject Classes) related entities by [SU.SUKEY]->[SCL.SUBJECT]
/// Subject code
/// </summary>
public IReadOnlyList<SCL> SUKEY_SCL_SUBJECT
{
get
{
if (Cache_SUKEY_SCL_SUBJECT == null &&
!Context.SCL.TryFindBySUBJECT(SUKEY, out Cache_SUKEY_SCL_SUBJECT))
{
Cache_SUKEY_SCL_SUBJECT = new List<SCL>().AsReadOnly();
}
return Cache_SUKEY_SCL_SUBJECT;
}
}
/// <summary>
/// SF (Staff) related entities by [SU.SUKEY]->[SF.SUBJECT01]
/// Subject code
/// </summary>
public IReadOnlyList<SF> SUKEY_SF_SUBJECT01
{
get
{
if (Cache_SUKEY_SF_SUBJECT01 == null &&
!Context.SF.TryFindBySUBJECT01(SUKEY, out Cache_SUKEY_SF_SUBJECT01))
{
Cache_SUKEY_SF_SUBJECT01 = new List<SF>().AsReadOnly();
}
return Cache_SUKEY_SF_SUBJECT01;
}
}
/// <summary>
/// SF (Staff) related entities by [SU.SUKEY]->[SF.SUBJECT02]
/// Subject code
/// </summary>
public IReadOnlyList<SF> SUKEY_SF_SUBJECT02
{
get
{
if (Cache_SUKEY_SF_SUBJECT02 == null &&
!Context.SF.TryFindBySUBJECT02(SUKEY, out Cache_SUKEY_SF_SUBJECT02))
{
Cache_SUKEY_SF_SUBJECT02 = new List<SF>().AsReadOnly();
}
return Cache_SUKEY_SF_SUBJECT02;
}
}
/// <summary>
/// SF (Staff) related entities by [SU.SUKEY]->[SF.SUBJECT03]
/// Subject code
/// </summary>
public IReadOnlyList<SF> SUKEY_SF_SUBJECT03
{
get
{
if (Cache_SUKEY_SF_SUBJECT03 == null &&
!Context.SF.TryFindBySUBJECT03(SUKEY, out Cache_SUKEY_SF_SUBJECT03))
{
Cache_SUKEY_SF_SUBJECT03 = new List<SF>().AsReadOnly();
}
return Cache_SUKEY_SF_SUBJECT03;
}
}
/// <summary>
/// SF (Staff) related entities by [SU.SUKEY]->[SF.SUBJECT04]
/// Subject code
/// </summary>
public IReadOnlyList<SF> SUKEY_SF_SUBJECT04
{
get
{
if (Cache_SUKEY_SF_SUBJECT04 == null &&
!Context.SF.TryFindBySUBJECT04(SUKEY, out Cache_SUKEY_SF_SUBJECT04))
{
Cache_SUKEY_SF_SUBJECT04 = new List<SF>().AsReadOnly();
}
return Cache_SUKEY_SF_SUBJECT04;
}
}
/// <summary>
/// SF (Staff) related entities by [SU.SUKEY]->[SF.SUBJECT05]
/// Subject code
/// </summary>
public IReadOnlyList<SF> SUKEY_SF_SUBJECT05
{
get
{
if (Cache_SUKEY_SF_SUBJECT05 == null &&
!Context.SF.TryFindBySUBJECT05(SUKEY, out Cache_SUKEY_SF_SUBJECT05))
{
Cache_SUKEY_SF_SUBJECT05 = new List<SF>().AsReadOnly();
}
return Cache_SUKEY_SF_SUBJECT05;
}
}
/// <summary>
/// SF (Staff) related entities by [SU.SUKEY]->[SF.SUBJECT06]
/// Subject code
/// </summary>
public IReadOnlyList<SF> SUKEY_SF_SUBJECT06
{
get
{
if (Cache_SUKEY_SF_SUBJECT06 == null &&
!Context.SF.TryFindBySUBJECT06(SUKEY, out Cache_SUKEY_SF_SUBJECT06))
{
Cache_SUKEY_SF_SUBJECT06 = new List<SF>().AsReadOnly();
}
return Cache_SUKEY_SF_SUBJECT06;
}
}
/// <summary>
/// SF (Staff) related entities by [SU.SUKEY]->[SF.SUBJECT07]
/// Subject code
/// </summary>
public IReadOnlyList<SF> SUKEY_SF_SUBJECT07
{
get
{
if (Cache_SUKEY_SF_SUBJECT07 == null &&
!Context.SF.TryFindBySUBJECT07(SUKEY, out Cache_SUKEY_SF_SUBJECT07))
{
Cache_SUKEY_SF_SUBJECT07 = new List<SF>().AsReadOnly();
}
return Cache_SUKEY_SF_SUBJECT07;
}
}
/// <summary>
/// SF (Staff) related entities by [SU.SUKEY]->[SF.SUBJECT08]
/// Subject code
/// </summary>
public IReadOnlyList<SF> SUKEY_SF_SUBJECT08
{
get
{
if (Cache_SUKEY_SF_SUBJECT08 == null &&
!Context.SF.TryFindBySUBJECT08(SUKEY, out Cache_SUKEY_SF_SUBJECT08))
{
Cache_SUKEY_SF_SUBJECT08 = new List<SF>().AsReadOnly();
}
return Cache_SUKEY_SF_SUBJECT08;
}
}
/// <summary>
/// SF (Staff) related entities by [SU.SUKEY]->[SF.SUBJECT09]
/// Subject code
/// </summary>
public IReadOnlyList<SF> SUKEY_SF_SUBJECT09
{
get
{
if (Cache_SUKEY_SF_SUBJECT09 == null &&
!Context.SF.TryFindBySUBJECT09(SUKEY, out Cache_SUKEY_SF_SUBJECT09))
{
Cache_SUKEY_SF_SUBJECT09 = new List<SF>().AsReadOnly();
}
return Cache_SUKEY_SF_SUBJECT09;
}
}
/// <summary>
/// SF (Staff) related entities by [SU.SUKEY]->[SF.SUBJECT10]
/// Subject code
/// </summary>
public IReadOnlyList<SF> SUKEY_SF_SUBJECT10
{
get
{
if (Cache_SUKEY_SF_SUBJECT10 == null &&
!Context.SF.TryFindBySUBJECT10(SUKEY, out Cache_SUKEY_SF_SUBJECT10))
{
Cache_SUKEY_SF_SUBJECT10 = new List<SF>().AsReadOnly();
}
return Cache_SUKEY_SF_SUBJECT10;
}
}
/// <summary>
/// SGSC (Subject/Class Eligibility Criteria) related entities by [SU.SUKEY]->[SGSC.SULINK]
/// Subject code
/// </summary>
public IReadOnlyList<SGSC> SUKEY_SGSC_SULINK
{
get
{
if (Cache_SUKEY_SGSC_SULINK == null &&
!Context.SGSC.TryFindBySULINK(SUKEY, out Cache_SUKEY_SGSC_SULINK))
{
Cache_SUKEY_SGSC_SULINK = new List<SGSC>().AsReadOnly();
}
return Cache_SUKEY_SGSC_SULINK;
}
}
/// <summary>
/// STMA (Subject Selections & Marks) related entities by [SU.SUKEY]->[STMA.MKEY]
/// Subject code
/// </summary>
public IReadOnlyList<STMA> SUKEY_STMA_MKEY
{
get
{
if (Cache_SUKEY_STMA_MKEY == null &&
!Context.STMA.TryFindByMKEY(SUKEY, out Cache_SUKEY_STMA_MKEY))
{
Cache_SUKEY_STMA_MKEY = new List<STMA>().AsReadOnly();
}
return Cache_SUKEY_STMA_MKEY;
}
}
/// <summary>
/// SU (Subjects) related entities by [SU.SUKEY]->[SU.PROMOTE]
/// Subject code
/// </summary>
public IReadOnlyList<SU> SUKEY_SU_PROMOTE
{
get
{
if (Cache_SUKEY_SU_PROMOTE == null &&
!Context.SU.TryFindByPROMOTE(SUKEY, out Cache_SUKEY_SU_PROMOTE))
{
Cache_SUKEY_SU_PROMOTE = new List<SU>().AsReadOnly();
}
return Cache_SUKEY_SU_PROMOTE;
}
}
/// <summary>
/// SUBL (Subject Book List) related entities by [SU.SUKEY]->[SUBL.BLKEY]
/// Subject code
/// </summary>
public IReadOnlyList<SUBL> SUKEY_SUBL_BLKEY
{
get
{
if (Cache_SUKEY_SUBL_BLKEY == null &&
!Context.SUBL.TryFindByBLKEY(SUKEY, out Cache_SUKEY_SUBL_BLKEY))
{
Cache_SUKEY_SUBL_BLKEY = new List<SUBL>().AsReadOnly();
}
return Cache_SUKEY_SUBL_BLKEY;
}
}
/// <summary>
/// SUPR (Subject Prerequisites) related entities by [SU.SUKEY]->[SUPR.SUPRKEY]
/// Subject code
/// </summary>
public IReadOnlyList<SUPR> SUKEY_SUPR_SUPRKEY
{
get
{
if (Cache_SUKEY_SUPR_SUPRKEY == null &&
!Context.SUPR.TryFindBySUPRKEY(SUKEY, out Cache_SUKEY_SUPR_SUPRKEY))
{
Cache_SUKEY_SUPR_SUPRKEY = new List<SUPR>().AsReadOnly();
}
return Cache_SUKEY_SUPR_SUPRKEY;
}
}
/// <summary>
/// SUPR (Subject Prerequisites) related entities by [SU.SUKEY]->[SUPR.PREREQUISITE]
/// Subject code
/// </summary>
public IReadOnlyList<SUPR> SUKEY_SUPR_PREREQUISITE
{
get
{
if (Cache_SUKEY_SUPR_PREREQUISITE == null &&
!Context.SUPR.TryFindByPREREQUISITE(SUKEY, out Cache_SUKEY_SUPR_PREREQUISITE))
{
Cache_SUKEY_SUPR_PREREQUISITE = new List<SUPR>().AsReadOnly();
}
return Cache_SUKEY_SUPR_PREREQUISITE;
}
}
/// <summary>
/// TCTB (Teacher Absences) related entities by [SU.SUKEY]->[TCTB.SUBJ]
/// Subject code
/// </summary>
public IReadOnlyList<TCTB> SUKEY_TCTB_SUBJ
{
get
{
if (Cache_SUKEY_TCTB_SUBJ == null &&
!Context.TCTB.TryFindBySUBJ(SUKEY, out Cache_SUKEY_TCTB_SUBJ))
{
Cache_SUKEY_TCTB_SUBJ = new List<TCTB>().AsReadOnly();
}
return Cache_SUKEY_TCTB_SUBJ;
}
}
/// <summary>
/// TCTQ (Calendar Class Information) related entities by [SU.SUKEY]->[TCTQ.SUBJ]
/// Subject code
/// </summary>
public IReadOnlyList<TCTQ> SUKEY_TCTQ_SUBJ
{
get
{
if (Cache_SUKEY_TCTQ_SUBJ == null &&
!Context.TCTQ.TryFindBySUBJ(SUKEY, out Cache_SUKEY_TCTQ_SUBJ))
{
Cache_SUKEY_TCTQ_SUBJ = new List<TCTQ>().AsReadOnly();
}
return Cache_SUKEY_TCTQ_SUBJ;
}
}
/// <summary>
/// TE (Calendar Events) related entities by [SU.SUKEY]->[TE.SUBJ]
/// Subject code
/// </summary>
public IReadOnlyList<TE> SUKEY_TE_SUBJ
{
get
{
if (Cache_SUKEY_TE_SUBJ == null &&
!Context.TE.TryFindBySUBJ(SUKEY, out Cache_SUKEY_TE_SUBJ))
{
Cache_SUKEY_TE_SUBJ = new List<TE>().AsReadOnly();
}
return Cache_SUKEY_TE_SUBJ;
}
}
/// <summary>
/// THTQ (Timetable Quilt Entries) related entities by [SU.SUKEY]->[THTQ.SUBJ]
/// Subject code
/// </summary>
public IReadOnlyList<THTQ> SUKEY_THTQ_SUBJ
{
get
{
if (Cache_SUKEY_THTQ_SUBJ == null &&
!Context.THTQ.TryFindBySUBJ(SUKEY, out Cache_SUKEY_THTQ_SUBJ))
{
Cache_SUKEY_THTQ_SUBJ = new List<THTQ>().AsReadOnly();
}
return Cache_SUKEY_THTQ_SUBJ;
}
}
/// <summary>
/// TTES (Exam Subjects) related entities by [SU.SUKEY]->[TTES.SUBJ]
/// Subject code
/// </summary>
public IReadOnlyList<TTES> SUKEY_TTES_SUBJ
{
get
{
if (Cache_SUKEY_TTES_SUBJ == null &&
!Context.TTES.TryFindBySUBJ(SUKEY, out Cache_SUKEY_TTES_SUBJ))
{
Cache_SUKEY_TTES_SUBJ = new List<TTES>().AsReadOnly();
}
return Cache_SUKEY_TTES_SUBJ;
}
}
/// <summary>
/// TTTG (Grid Subjects) related entities by [SU.SUKEY]->[TTTG.SUBJ]
/// Subject code
/// </summary>
public IReadOnlyList<TTTG> SUKEY_TTTG_SUBJ
{
get
{
if (Cache_SUKEY_TTTG_SUBJ == null &&
!Context.TTTG.TryFindBySUBJ(SUKEY, out Cache_SUKEY_TTTG_SUBJ))
{
Cache_SUKEY_TTTG_SUBJ = new List<TTTG>().AsReadOnly();
}
return Cache_SUKEY_TTTG_SUBJ;
}
}
/// <summary>
/// TXAS (Actual Sessions) related entities by [SU.SUKEY]->[TXAS.SUBJECT]
/// Subject code
/// </summary>
public IReadOnlyList<TXAS> SUKEY_TXAS_SUBJECT
{
get
{
if (Cache_SUKEY_TXAS_SUBJECT == null &&
!Context.TXAS.TryFindBySUBJECT(SUKEY, out Cache_SUKEY_TXAS_SUBJECT))
{
Cache_SUKEY_TXAS_SUBJECT = new List<TXAS>().AsReadOnly();
}
return Cache_SUKEY_TXAS_SUBJECT;
}
}
#endregion
}
}
| |
//
// 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.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.AzureStack.Management;
using Microsoft.AzureStack.Management.Models;
namespace Microsoft.AzureStack.Management
{
public static partial class ManagedOfferOperationsExtensions
{
/// <summary>
/// Returns the created or updated offer
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IManagedOfferOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. Resource group name
/// </param>
/// <param name='parameters'>
/// Required. Offer properties
/// </param>
/// <returns>
/// Result of the create or update operation of offer
/// </returns>
public static ManagedOfferCreateOrUpdateResult CreateOrUpdate(this IManagedOfferOperations operations, string resourceGroupName, ManagedOfferCreateOrUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IManagedOfferOperations)s).CreateOrUpdateAsync(resourceGroupName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns the created or updated offer
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IManagedOfferOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. Resource group name
/// </param>
/// <param name='parameters'>
/// Required. Offer properties
/// </param>
/// <returns>
/// Result of the create or update operation of offer
/// </returns>
public static Task<ManagedOfferCreateOrUpdateResult> CreateOrUpdateAsync(this IManagedOfferOperations operations, string resourceGroupName, ManagedOfferCreateOrUpdateParameters parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, parameters, CancellationToken.None);
}
/// <summary>
/// Delete operation on the offer
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IManagedOfferOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. Resource group name
/// </param>
/// <param name='offerId'>
/// Required. Offer name
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse Delete(this IManagedOfferOperations operations, string resourceGroupName, string offerId)
{
return Task.Factory.StartNew((object s) =>
{
return ((IManagedOfferOperations)s).DeleteAsync(resourceGroupName, offerId);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Delete operation on the offer
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IManagedOfferOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. Resource group name
/// </param>
/// <param name='offerId'>
/// Required. Offer name
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> DeleteAsync(this IManagedOfferOperations operations, string resourceGroupName, string offerId)
{
return operations.DeleteAsync(resourceGroupName, offerId, CancellationToken.None);
}
/// <summary>
/// Gets the administrator view of the offer
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IManagedOfferOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. Resource group name
/// </param>
/// <param name='offerId'>
/// Required. Offer name
/// </param>
/// <returns>
/// Result of the offer Get operation
/// </returns>
public static ManagedOfferGetResult Get(this IManagedOfferOperations operations, string resourceGroupName, string offerId)
{
return Task.Factory.StartNew((object s) =>
{
return ((IManagedOfferOperations)s).GetAsync(resourceGroupName, offerId);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets the administrator view of the offer
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IManagedOfferOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. Resource group name
/// </param>
/// <param name='offerId'>
/// Required. Offer name
/// </param>
/// <returns>
/// Result of the offer Get operation
/// </returns>
public static Task<ManagedOfferGetResult> GetAsync(this IManagedOfferOperations operations, string resourceGroupName, string offerId)
{
return operations.GetAsync(resourceGroupName, offerId, CancellationToken.None);
}
/// <summary>
/// Lists the offers under the specified resource group
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IManagedOfferOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. Resource group name
/// </param>
/// <param name='includeDetails'>
/// Required. Flag to specify whether to include details
/// </param>
/// <returns>
/// Result of the offer list operation
/// </returns>
public static ManagedOfferListResult List(this IManagedOfferOperations operations, string resourceGroupName, bool includeDetails)
{
return Task.Factory.StartNew((object s) =>
{
return ((IManagedOfferOperations)s).ListAsync(resourceGroupName, includeDetails);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists the offers under the specified resource group
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.AzureStack.Management.IManagedOfferOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. Resource group name
/// </param>
/// <param name='includeDetails'>
/// Required. Flag to specify whether to include details
/// </param>
/// <returns>
/// Result of the offer list operation
/// </returns>
public static Task<ManagedOfferListResult> ListAsync(this IManagedOfferOperations operations, string resourceGroupName, bool includeDetails)
{
return operations.ListAsync(resourceGroupName, includeDetails, CancellationToken.None);
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gagr = Google.Api.Gax.ResourceNames;
using gcfv = Google.Cloud.Functions.V1;
using sys = System;
namespace Google.Cloud.Functions.V1
{
/// <summary>Resource name for the <c>CloudFunction</c> resource.</summary>
public sealed partial class CloudFunctionName : gax::IResourceName, sys::IEquatable<CloudFunctionName>
{
/// <summary>The possible contents of <see cref="CloudFunctionName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>projects/{project}/locations/{location}/functions/{function}</c>.
/// </summary>
ProjectLocationFunction = 1,
}
private static gax::PathTemplate s_projectLocationFunction = new gax::PathTemplate("projects/{project}/locations/{location}/functions/{function}");
/// <summary>Creates a <see cref="CloudFunctionName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="CloudFunctionName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static CloudFunctionName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new CloudFunctionName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="CloudFunctionName"/> with the pattern
/// <c>projects/{project}/locations/{location}/functions/{function}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="functionId">The <c>Function</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="CloudFunctionName"/> constructed from the provided ids.</returns>
public static CloudFunctionName FromProjectLocationFunction(string projectId, string locationId, string functionId) =>
new CloudFunctionName(ResourceNameType.ProjectLocationFunction, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), functionId: gax::GaxPreconditions.CheckNotNullOrEmpty(functionId, nameof(functionId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="CloudFunctionName"/> with pattern
/// <c>projects/{project}/locations/{location}/functions/{function}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="functionId">The <c>Function</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="CloudFunctionName"/> with pattern
/// <c>projects/{project}/locations/{location}/functions/{function}</c>.
/// </returns>
public static string Format(string projectId, string locationId, string functionId) =>
FormatProjectLocationFunction(projectId, locationId, functionId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="CloudFunctionName"/> with pattern
/// <c>projects/{project}/locations/{location}/functions/{function}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="functionId">The <c>Function</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="CloudFunctionName"/> with pattern
/// <c>projects/{project}/locations/{location}/functions/{function}</c>.
/// </returns>
public static string FormatProjectLocationFunction(string projectId, string locationId, string functionId) =>
s_projectLocationFunction.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(functionId, nameof(functionId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="CloudFunctionName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/locations/{location}/functions/{function}</c></description></item>
/// </list>
/// </remarks>
/// <param name="cloudFunctionName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="CloudFunctionName"/> if successful.</returns>
public static CloudFunctionName Parse(string cloudFunctionName) => Parse(cloudFunctionName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="CloudFunctionName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/locations/{location}/functions/{function}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="cloudFunctionName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="CloudFunctionName"/> if successful.</returns>
public static CloudFunctionName Parse(string cloudFunctionName, bool allowUnparsed) =>
TryParse(cloudFunctionName, allowUnparsed, out CloudFunctionName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="CloudFunctionName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/locations/{location}/functions/{function}</c></description></item>
/// </list>
/// </remarks>
/// <param name="cloudFunctionName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="CloudFunctionName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string cloudFunctionName, out CloudFunctionName result) =>
TryParse(cloudFunctionName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="CloudFunctionName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/locations/{location}/functions/{function}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="cloudFunctionName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="CloudFunctionName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string cloudFunctionName, bool allowUnparsed, out CloudFunctionName result)
{
gax::GaxPreconditions.CheckNotNull(cloudFunctionName, nameof(cloudFunctionName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationFunction.TryParseName(cloudFunctionName, out resourceName))
{
result = FromProjectLocationFunction(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(cloudFunctionName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private CloudFunctionName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string functionId = null, string locationId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
FunctionId = functionId;
LocationId = locationId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="CloudFunctionName"/> class from the component parts of pattern
/// <c>projects/{project}/locations/{location}/functions/{function}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="functionId">The <c>Function</c> ID. Must not be <c>null</c> or empty.</param>
public CloudFunctionName(string projectId, string locationId, string functionId) : this(ResourceNameType.ProjectLocationFunction, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), functionId: gax::GaxPreconditions.CheckNotNullOrEmpty(functionId, nameof(functionId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Function</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string FunctionId { get; }
/// <summary>
/// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectLocationFunction: return s_projectLocationFunction.Expand(ProjectId, LocationId, FunctionId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as CloudFunctionName);
/// <inheritdoc/>
public bool Equals(CloudFunctionName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(CloudFunctionName a, CloudFunctionName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(CloudFunctionName a, CloudFunctionName b) => !(a == b);
}
/// <summary>Resource name for the <c>Repository</c> resource.</summary>
public sealed partial class RepositoryName : gax::IResourceName, sys::IEquatable<RepositoryName>
{
/// <summary>The possible contents of <see cref="RepositoryName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>projects/{project}/locations/{location}/repositories/{repository}</c>.
/// </summary>
ProjectLocationRepository = 1,
}
private static gax::PathTemplate s_projectLocationRepository = new gax::PathTemplate("projects/{project}/locations/{location}/repositories/{repository}");
/// <summary>Creates a <see cref="RepositoryName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="RepositoryName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static RepositoryName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new RepositoryName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="RepositoryName"/> with the pattern
/// <c>projects/{project}/locations/{location}/repositories/{repository}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="repositoryId">The <c>Repository</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="RepositoryName"/> constructed from the provided ids.</returns>
public static RepositoryName FromProjectLocationRepository(string projectId, string locationId, string repositoryId) =>
new RepositoryName(ResourceNameType.ProjectLocationRepository, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), repositoryId: gax::GaxPreconditions.CheckNotNullOrEmpty(repositoryId, nameof(repositoryId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="RepositoryName"/> with pattern
/// <c>projects/{project}/locations/{location}/repositories/{repository}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="repositoryId">The <c>Repository</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="RepositoryName"/> with pattern
/// <c>projects/{project}/locations/{location}/repositories/{repository}</c>.
/// </returns>
public static string Format(string projectId, string locationId, string repositoryId) =>
FormatProjectLocationRepository(projectId, locationId, repositoryId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="RepositoryName"/> with pattern
/// <c>projects/{project}/locations/{location}/repositories/{repository}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="repositoryId">The <c>Repository</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="RepositoryName"/> with pattern
/// <c>projects/{project}/locations/{location}/repositories/{repository}</c>.
/// </returns>
public static string FormatProjectLocationRepository(string projectId, string locationId, string repositoryId) =>
s_projectLocationRepository.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(repositoryId, nameof(repositoryId)));
/// <summary>Parses the given resource name string into a new <see cref="RepositoryName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/locations/{location}/repositories/{repository}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="repositoryName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="RepositoryName"/> if successful.</returns>
public static RepositoryName Parse(string repositoryName) => Parse(repositoryName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="RepositoryName"/> instance; optionally allowing
/// an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/locations/{location}/repositories/{repository}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="repositoryName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="RepositoryName"/> if successful.</returns>
public static RepositoryName Parse(string repositoryName, bool allowUnparsed) =>
TryParse(repositoryName, allowUnparsed, out RepositoryName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="RepositoryName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/locations/{location}/repositories/{repository}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="repositoryName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="RepositoryName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string repositoryName, out RepositoryName result) =>
TryParse(repositoryName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="RepositoryName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/locations/{location}/repositories/{repository}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="repositoryName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="RepositoryName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string repositoryName, bool allowUnparsed, out RepositoryName result)
{
gax::GaxPreconditions.CheckNotNull(repositoryName, nameof(repositoryName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationRepository.TryParseName(repositoryName, out resourceName))
{
result = FromProjectLocationRepository(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(repositoryName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private RepositoryName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string locationId = null, string projectId = null, string repositoryId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
LocationId = locationId;
ProjectId = projectId;
RepositoryId = repositoryId;
}
/// <summary>
/// Constructs a new instance of a <see cref="RepositoryName"/> class from the component parts of pattern
/// <c>projects/{project}/locations/{location}/repositories/{repository}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="repositoryId">The <c>Repository</c> ID. Must not be <c>null</c> or empty.</param>
public RepositoryName(string projectId, string locationId, string repositoryId) : this(ResourceNameType.ProjectLocationRepository, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), repositoryId: gax::GaxPreconditions.CheckNotNullOrEmpty(repositoryId, nameof(repositoryId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The <c>Repository</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string RepositoryId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectLocationRepository: return s_projectLocationRepository.Expand(ProjectId, LocationId, RepositoryId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as RepositoryName);
/// <inheritdoc/>
public bool Equals(RepositoryName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(RepositoryName a, RepositoryName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(RepositoryName a, RepositoryName b) => !(a == b);
}
/// <summary>Resource name for the <c>CryptoKey</c> resource.</summary>
public sealed partial class CryptoKeyName : gax::IResourceName, sys::IEquatable<CryptoKeyName>
{
/// <summary>The possible contents of <see cref="CryptoKeyName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}</c>.
/// </summary>
ProjectLocationKeyRingCryptoKey = 1,
}
private static gax::PathTemplate s_projectLocationKeyRingCryptoKey = new gax::PathTemplate("projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}");
/// <summary>Creates a <see cref="CryptoKeyName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="CryptoKeyName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static CryptoKeyName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new CryptoKeyName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="CryptoKeyName"/> with the pattern
/// <c>projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="keyRingId">The <c>KeyRing</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="cryptoKeyId">The <c>CryptoKey</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="CryptoKeyName"/> constructed from the provided ids.</returns>
public static CryptoKeyName FromProjectLocationKeyRingCryptoKey(string projectId, string locationId, string keyRingId, string cryptoKeyId) =>
new CryptoKeyName(ResourceNameType.ProjectLocationKeyRingCryptoKey, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), keyRingId: gax::GaxPreconditions.CheckNotNullOrEmpty(keyRingId, nameof(keyRingId)), cryptoKeyId: gax::GaxPreconditions.CheckNotNullOrEmpty(cryptoKeyId, nameof(cryptoKeyId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="CryptoKeyName"/> with pattern
/// <c>projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="keyRingId">The <c>KeyRing</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="cryptoKeyId">The <c>CryptoKey</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="CryptoKeyName"/> with pattern
/// <c>projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}</c>.
/// </returns>
public static string Format(string projectId, string locationId, string keyRingId, string cryptoKeyId) =>
FormatProjectLocationKeyRingCryptoKey(projectId, locationId, keyRingId, cryptoKeyId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="CryptoKeyName"/> with pattern
/// <c>projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="keyRingId">The <c>KeyRing</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="cryptoKeyId">The <c>CryptoKey</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="CryptoKeyName"/> with pattern
/// <c>projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}</c>.
/// </returns>
public static string FormatProjectLocationKeyRingCryptoKey(string projectId, string locationId, string keyRingId, string cryptoKeyId) =>
s_projectLocationKeyRingCryptoKey.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(keyRingId, nameof(keyRingId)), gax::GaxPreconditions.CheckNotNullOrEmpty(cryptoKeyId, nameof(cryptoKeyId)));
/// <summary>Parses the given resource name string into a new <see cref="CryptoKeyName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="cryptoKeyName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="CryptoKeyName"/> if successful.</returns>
public static CryptoKeyName Parse(string cryptoKeyName) => Parse(cryptoKeyName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="CryptoKeyName"/> instance; optionally allowing
/// an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="cryptoKeyName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="CryptoKeyName"/> if successful.</returns>
public static CryptoKeyName Parse(string cryptoKeyName, bool allowUnparsed) =>
TryParse(cryptoKeyName, allowUnparsed, out CryptoKeyName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="CryptoKeyName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="cryptoKeyName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="CryptoKeyName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string cryptoKeyName, out CryptoKeyName result) => TryParse(cryptoKeyName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="CryptoKeyName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="cryptoKeyName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="CryptoKeyName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string cryptoKeyName, bool allowUnparsed, out CryptoKeyName result)
{
gax::GaxPreconditions.CheckNotNull(cryptoKeyName, nameof(cryptoKeyName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationKeyRingCryptoKey.TryParseName(cryptoKeyName, out resourceName))
{
result = FromProjectLocationKeyRingCryptoKey(resourceName[0], resourceName[1], resourceName[2], resourceName[3]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(cryptoKeyName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private CryptoKeyName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string cryptoKeyId = null, string keyRingId = null, string locationId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
CryptoKeyId = cryptoKeyId;
KeyRingId = keyRingId;
LocationId = locationId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="CryptoKeyName"/> class from the component parts of pattern
/// <c>projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="keyRingId">The <c>KeyRing</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="cryptoKeyId">The <c>CryptoKey</c> ID. Must not be <c>null</c> or empty.</param>
public CryptoKeyName(string projectId, string locationId, string keyRingId, string cryptoKeyId) : this(ResourceNameType.ProjectLocationKeyRingCryptoKey, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), keyRingId: gax::GaxPreconditions.CheckNotNullOrEmpty(keyRingId, nameof(keyRingId)), cryptoKeyId: gax::GaxPreconditions.CheckNotNullOrEmpty(cryptoKeyId, nameof(cryptoKeyId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>CryptoKey</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CryptoKeyId { get; }
/// <summary>
/// The <c>KeyRing</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string KeyRingId { get; }
/// <summary>
/// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectLocationKeyRingCryptoKey: return s_projectLocationKeyRingCryptoKey.Expand(ProjectId, LocationId, KeyRingId, CryptoKeyId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as CryptoKeyName);
/// <inheritdoc/>
public bool Equals(CryptoKeyName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(CryptoKeyName a, CryptoKeyName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(CryptoKeyName a, CryptoKeyName b) => !(a == b);
}
public partial class CloudFunction
{
/// <summary>
/// <see cref="gcfv::CloudFunctionName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcfv::CloudFunctionName CloudFunctionName
{
get => string.IsNullOrEmpty(Name) ? null : gcfv::CloudFunctionName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="CryptoKeyName"/>-typed view over the <see cref="KmsKeyName"/> resource name property.
/// </summary>
public CryptoKeyName KmsKeyNameAsCryptoKeyName
{
get => string.IsNullOrEmpty(KmsKeyName) ? null : CryptoKeyName.Parse(KmsKeyName, allowUnparsed: true);
set => KmsKeyName = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="RepositoryName"/>-typed view over the <see cref="DockerRepository"/> resource name property.
/// </summary>
public RepositoryName DockerRepositoryAsRepositoryName
{
get => string.IsNullOrEmpty(DockerRepository) ? null : RepositoryName.Parse(DockerRepository, allowUnparsed: true);
set => DockerRepository = value?.ToString() ?? "";
}
}
public partial class CreateFunctionRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Location"/> resource name property.
/// </summary>
public gagr::LocationName LocationAsLocationName
{
get => string.IsNullOrEmpty(Location) ? null : gagr::LocationName.Parse(Location, allowUnparsed: true);
set => Location = value?.ToString() ?? "";
}
}
public partial class GetFunctionRequest
{
/// <summary>
/// <see cref="gcfv::CloudFunctionName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcfv::CloudFunctionName CloudFunctionName
{
get => string.IsNullOrEmpty(Name) ? null : gcfv::CloudFunctionName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class ListFunctionsRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class DeleteFunctionRequest
{
/// <summary>
/// <see cref="gcfv::CloudFunctionName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcfv::CloudFunctionName CloudFunctionName
{
get => string.IsNullOrEmpty(Name) ? null : gcfv::CloudFunctionName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class CallFunctionRequest
{
/// <summary>
/// <see cref="gcfv::CloudFunctionName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcfv::CloudFunctionName CloudFunctionName
{
get => string.IsNullOrEmpty(Name) ? null : gcfv::CloudFunctionName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
using Lucene.Net.Documents;
using Lucene.Net.Index.Extensions;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Text;
using Assert = Lucene.Net.TestFramework.Assert;
namespace Lucene.Net.Index
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using IBits = Lucene.Net.Util.IBits;
using BytesRef = Lucene.Net.Util.BytesRef;
using Directory = Lucene.Net.Store.Directory;
using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator;
using Document = Documents.Document;
using Field = Field;
using FieldType = FieldType;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer;
using TestUtil = Lucene.Net.Util.TestUtil;
using TextField = TextField;
[TestFixture]
public class TestDocsAndPositions : LuceneTestCase
{
private string fieldName;
[SetUp]
public override void SetUp()
{
base.SetUp();
fieldName = "field" + Random.Next();
}
/// <summary>
/// Simple testcase for <seealso cref="DocsAndPositionsEnum"/>
/// </summary>
[Test]
public virtual void TestPositionsSimple()
{
Directory directory = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(Random, directory, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)));
for (int i = 0; i < 39; i++)
{
Document doc = new Document();
FieldType customType = new FieldType(TextField.TYPE_NOT_STORED);
customType.OmitNorms = true;
doc.Add(NewField(fieldName, "1 2 3 4 5 6 7 8 9 10 " + "1 2 3 4 5 6 7 8 9 10 " + "1 2 3 4 5 6 7 8 9 10 " + "1 2 3 4 5 6 7 8 9 10", customType));
writer.AddDocument(doc);
}
IndexReader reader = writer.GetReader();
writer.Dispose();
int num = AtLeast(13);
for (int i = 0; i < num; i++)
{
BytesRef bytes = new BytesRef("1");
IndexReaderContext topReaderContext = reader.Context;
foreach (AtomicReaderContext atomicReaderContext in topReaderContext.Leaves)
{
DocsAndPositionsEnum docsAndPosEnum = GetDocsAndPositions((AtomicReader)atomicReaderContext.Reader, bytes, null);
Assert.IsNotNull(docsAndPosEnum);
if (atomicReaderContext.Reader.MaxDoc == 0)
{
continue;
}
int advance = docsAndPosEnum.Advance(Random.Next(atomicReaderContext.Reader.MaxDoc));
do
{
string msg = "Advanced to: " + advance + " current doc: " + docsAndPosEnum.DocID; // TODO: + " usePayloads: " + usePayload;
Assert.AreEqual(4, docsAndPosEnum.Freq, msg);
Assert.AreEqual(0, docsAndPosEnum.NextPosition(), msg);
Assert.AreEqual(4, docsAndPosEnum.Freq, msg);
Assert.AreEqual(10, docsAndPosEnum.NextPosition(), msg);
Assert.AreEqual(4, docsAndPosEnum.Freq, msg);
Assert.AreEqual(20, docsAndPosEnum.NextPosition(), msg);
Assert.AreEqual(4, docsAndPosEnum.Freq, msg);
Assert.AreEqual(30, docsAndPosEnum.NextPosition(), msg);
} while (docsAndPosEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
}
}
reader.Dispose();
directory.Dispose();
}
public virtual DocsAndPositionsEnum GetDocsAndPositions(AtomicReader reader, BytesRef bytes, IBits liveDocs)
{
Terms terms = reader.GetTerms(fieldName);
if (terms != null)
{
TermsEnum te = terms.GetEnumerator();
if (te.SeekExact(bytes))
{
return te.DocsAndPositions(liveDocs, null);
}
}
return null;
}
/// <summary>
/// this test indexes random numbers within a range into a field and checks
/// their occurrences by searching for a number from that range selected at
/// random. All positions for that number are saved up front and compared to
/// the enums positions.
/// </summary>
[Test]
public virtual void TestRandomPositions()
{
Directory dir = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(Random, dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)).SetMergePolicy(NewLogMergePolicy()));
int numDocs = AtLeast(47);
int max = 1051;
int term = Random.Next(max);
int?[][] positionsInDoc = new int?[numDocs][];
FieldType customType = new FieldType(TextField.TYPE_NOT_STORED);
customType.OmitNorms = true;
for (int i = 0; i < numDocs; i++)
{
Document doc = new Document();
List<int?> positions = new List<int?>();
StringBuilder builder = new StringBuilder();
int num = AtLeast(131);
for (int j = 0; j < num; j++)
{
int nextInt = Random.Next(max);
builder.Append(nextInt).Append(" ");
if (nextInt == term)
{
positions.Add(Convert.ToInt32(j));
}
}
if (positions.Count == 0)
{
builder.Append(term);
positions.Add(num);
}
doc.Add(NewField(fieldName, builder.ToString(), customType));
positionsInDoc[i] = positions.ToArray();
writer.AddDocument(doc);
}
IndexReader reader = writer.GetReader();
writer.Dispose();
int num_ = AtLeast(13);
for (int i = 0; i < num_; i++)
{
BytesRef bytes = new BytesRef("" + term);
IndexReaderContext topReaderContext = reader.Context;
foreach (AtomicReaderContext atomicReaderContext in topReaderContext.Leaves)
{
DocsAndPositionsEnum docsAndPosEnum = GetDocsAndPositions((AtomicReader)atomicReaderContext.Reader, bytes, null);
Assert.IsNotNull(docsAndPosEnum);
int initDoc = 0;
int maxDoc = atomicReaderContext.Reader.MaxDoc;
// initially advance or do next doc
if (Random.NextBoolean())
{
initDoc = docsAndPosEnum.NextDoc();
}
else
{
initDoc = docsAndPosEnum.Advance(Random.Next(maxDoc));
}
// now run through the scorer and check if all positions are there...
do
{
int docID = docsAndPosEnum.DocID;
if (docID == DocIdSetIterator.NO_MORE_DOCS)
{
break;
}
int?[] pos = positionsInDoc[atomicReaderContext.DocBase + docID];
Assert.AreEqual(pos.Length, docsAndPosEnum.Freq);
// number of positions read should be random - don't read all of them
// allways
int howMany = Random.Next(20) == 0 ? pos.Length - Random.Next(pos.Length) : pos.Length;
for (int j = 0; j < howMany; j++)
{
Assert.AreEqual(pos[j], docsAndPosEnum.NextPosition(), "iteration: " + i + " initDoc: " + initDoc + " doc: " + docID + " base: " + atomicReaderContext.DocBase + " positions: " + pos); /* TODO: + " usePayloads: "
+ usePayload*/
}
if (Random.Next(10) == 0) // once is a while advance
{
if (docsAndPosEnum.Advance(docID + 1 + Random.Next((maxDoc - docID))) == DocIdSetIterator.NO_MORE_DOCS)
{
break;
}
}
} while (docsAndPosEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
}
}
reader.Dispose();
dir.Dispose();
}
[Test]
public virtual void TestRandomDocs()
{
Directory dir = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(Random, dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)).SetMergePolicy(NewLogMergePolicy()));
int numDocs = AtLeast(49);
int max = 15678;
int term = Random.Next(max);
int[] freqInDoc = new int[numDocs];
FieldType customType = new FieldType(TextField.TYPE_NOT_STORED);
customType.OmitNorms = true;
for (int i = 0; i < numDocs; i++)
{
Document doc = new Document();
StringBuilder builder = new StringBuilder();
for (int j = 0; j < 199; j++)
{
int nextInt = Random.Next(max);
builder.Append(nextInt).Append(' ');
if (nextInt == term)
{
freqInDoc[i]++;
}
}
doc.Add(NewField(fieldName, builder.ToString(), customType));
writer.AddDocument(doc);
}
IndexReader reader = writer.GetReader();
writer.Dispose();
int num = AtLeast(13);
for (int i = 0; i < num; i++)
{
BytesRef bytes = new BytesRef("" + term);
IndexReaderContext topReaderContext = reader.Context;
foreach (AtomicReaderContext context in topReaderContext.Leaves)
{
int maxDoc = context.AtomicReader.MaxDoc;
DocsEnum docsEnum = TestUtil.Docs(Random, context.Reader, fieldName, bytes, null, null, DocsFlags.FREQS);
if (FindNext(freqInDoc, context.DocBase, context.DocBase + maxDoc) == int.MaxValue)
{
Assert.IsNull(docsEnum);
continue;
}
Assert.IsNotNull(docsEnum);
docsEnum.NextDoc();
for (int j = 0; j < maxDoc; j++)
{
if (freqInDoc[context.DocBase + j] != 0)
{
Assert.AreEqual(j, docsEnum.DocID);
Assert.AreEqual(docsEnum.Freq, freqInDoc[context.DocBase + j]);
if (i % 2 == 0 && Random.Next(10) == 0)
{
int next = FindNext(freqInDoc, context.DocBase + j + 1, context.DocBase + maxDoc) - context.DocBase;
int advancedTo = docsEnum.Advance(next);
if (next >= maxDoc)
{
Assert.AreEqual(DocIdSetIterator.NO_MORE_DOCS, advancedTo);
}
else
{
Assert.IsTrue(next >= advancedTo, "advanced to: " + advancedTo + " but should be <= " + next);
}
}
else
{
docsEnum.NextDoc();
}
}
}
Assert.AreEqual(DocIdSetIterator.NO_MORE_DOCS, docsEnum.DocID, "DocBase: " + context.DocBase + " maxDoc: " + maxDoc + " " + docsEnum.GetType());
}
}
reader.Dispose();
dir.Dispose();
}
private static int FindNext(int[] docs, int pos, int max)
{
for (int i = pos; i < max; i++)
{
if (docs[i] != 0)
{
return i;
}
}
return int.MaxValue;
}
/// <summary>
/// tests retrieval of positions for terms that have a large number of
/// occurrences to force test of buffer refill during positions iteration.
/// </summary>
[Test]
public virtual void TestLargeNumberOfPositions()
{
Directory dir = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(Random, dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)));
int howMany = 1000;
FieldType customType = new FieldType(TextField.TYPE_NOT_STORED);
customType.OmitNorms = true;
for (int i = 0; i < 39; i++)
{
Document doc = new Document();
StringBuilder builder = new StringBuilder();
for (int j = 0; j < howMany; j++)
{
if (j % 2 == 0)
{
builder.Append("even ");
}
else
{
builder.Append("odd ");
}
}
doc.Add(NewField(fieldName, builder.ToString(), customType));
writer.AddDocument(doc);
}
// now do searches
IndexReader reader = writer.GetReader();
writer.Dispose();
int num = AtLeast(13);
for (int i = 0; i < num; i++)
{
BytesRef bytes = new BytesRef("even");
IndexReaderContext topReaderContext = reader.Context;
foreach (AtomicReaderContext atomicReaderContext in topReaderContext.Leaves)
{
DocsAndPositionsEnum docsAndPosEnum = GetDocsAndPositions((AtomicReader)atomicReaderContext.Reader, bytes, null);
Assert.IsNotNull(docsAndPosEnum);
int initDoc = 0;
int maxDoc = atomicReaderContext.Reader.MaxDoc;
// initially advance or do next doc
if (Random.NextBoolean())
{
initDoc = docsAndPosEnum.NextDoc();
}
else
{
initDoc = docsAndPosEnum.Advance(Random.Next(maxDoc));
}
string msg = "Iteration: " + i + " initDoc: " + initDoc; // TODO: + " payloads: " + usePayload;
Assert.AreEqual(howMany / 2, docsAndPosEnum.Freq);
for (int j = 0; j < howMany; j += 2)
{
Assert.AreEqual(j, docsAndPosEnum.NextPosition(), "position missmatch index: " + j + " with freq: " + docsAndPosEnum.Freq + " -- " + msg);
}
}
}
reader.Dispose();
dir.Dispose();
}
[Test]
public virtual void TestDocsEnumStart()
{
Directory dir = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, dir);
Document doc = new Document();
doc.Add(NewStringField("foo", "bar", Field.Store.NO));
writer.AddDocument(doc);
DirectoryReader reader = writer.GetReader();
AtomicReader r = GetOnlySegmentReader(reader);
DocsEnum disi = TestUtil.Docs(Random, r, "foo", new BytesRef("bar"), null, null, DocsFlags.NONE);
int docid = disi.DocID;
Assert.AreEqual(-1, docid);
Assert.IsTrue(disi.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
// now reuse and check again
TermsEnum te = r.GetTerms("foo").GetEnumerator();
Assert.IsTrue(te.SeekExact(new BytesRef("bar")));
disi = TestUtil.Docs(Random, te, null, disi, DocsFlags.NONE);
docid = disi.DocID;
Assert.AreEqual(-1, docid);
Assert.IsTrue(disi.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
writer.Dispose();
r.Dispose();
dir.Dispose();
}
[Test]
public virtual void TestDocsAndPositionsEnumStart()
{
Directory dir = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, dir);
Document doc = new Document();
doc.Add(NewTextField("foo", "bar", Field.Store.NO));
writer.AddDocument(doc);
DirectoryReader reader = writer.GetReader();
AtomicReader r = GetOnlySegmentReader(reader);
DocsAndPositionsEnum disi = r.GetTermPositionsEnum(new Term("foo", "bar"));
int docid = disi.DocID;
Assert.AreEqual(-1, docid);
Assert.IsTrue(disi.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
// now reuse and check again
TermsEnum te = r.GetTerms("foo").GetEnumerator();
Assert.IsTrue(te.SeekExact(new BytesRef("bar")));
disi = te.DocsAndPositions(null, disi);
docid = disi.DocID;
Assert.AreEqual(-1, docid);
Assert.IsTrue(disi.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
writer.Dispose();
r.Dispose();
dir.Dispose();
}
}
}
| |
using System;
namespace NMoney
{
/// <summary>
/// This structure provides a amount of money in some currency
/// </summary>
public readonly struct Money : IComparable<Money>, IEquatable<Money>
{
/// <summary>
/// amount of money
/// </summary>
public decimal Amount { get; }
/// <summary>
/// currency
/// </summary>
public ICurrency Currency { get; }
/// <summary>
/// creates a amount of money in any currency
/// </summary>
/// <param name="amount">
/// amount of money
/// </param>
/// <param name="currency">
/// currency
/// </param>
public Money(decimal amount, ICurrency currency)
:this()
{
Amount = amount;
Currency = currency ?? throw new ArgumentNullException(nameof(currency));
}
/// <summary>
/// show amount and character code of currency
/// </summary>
public override string ToString()
{
if (noCurrency)
return "0";
return $"{Amount:G} {Currency.CharCode}";
}
/// <summary>
/// contains an integer number of currency units
/// </summary>
public bool IsRounded
{
get
{
if (noCurrency || Currency.MinorUnit == 0m)
return true;
var mu = Amount/Currency.MinorUnit;
return decimal.Truncate(mu) == mu;
}
}
/// <summary>
/// the total number minot of unit of currency
/// </summary>
public decimal TotalMinorUnit
{
get
{
if (noCurrency)
return 0m;
if(Currency.MinorUnit == 0m)
throw new InvalidOperationException(string.Format("undefined minor unit in {0} currency", Currency.CharCode));
return Amount/Currency.MinorUnit;
}
}
/// <summary>
/// Returns the largest integer less than or equal to minor of unit of this money.
/// </summary>
/// <returns>
/// a new instance with the required amount or the current instance if the operation is not possible
/// </returns>
public Money FloorMinorUnit()
{
if (noCurrency)
return Zero;
if(Currency.MinorUnit == 0m)
return this;
return new Money(decimal.Floor(Amount/Currency.MinorUnit)*Currency.MinorUnit, Currency);
}
/// <summary>
/// Returns the largest integer less than or equal to this money.
/// </summary>
/// <returns>
/// a new instance with the required amount or the current instance if the operation is not possible
/// </returns>
public Money FloorMajorUnit()
{
if (noCurrency)
return Zero;
return new Money(decimal.Floor(Amount), Currency);
}
/// <summary>
/// Returns the smallest integral value that is greater than or equal to minor of unit of this money.
/// </summary>
/// <returns>
/// a new instance with the required amount or the current instance if the operation is not possible
/// </returns>
public Money CeilingMinorUnit()
{
if (noCurrency)
return Zero;
if(Currency.MinorUnit == 0m)
return this;
return new Money(decimal.Ceiling(Amount/Currency.MinorUnit)*Currency.MinorUnit, Currency);
}
/// <summary>
/// Returns the smallest integral value that is greater than or equal to this money.
/// </summary>
/// <returns>
/// a new instance with the required amount or the current instance if the operation is not possible
/// </returns>
public Money CeilingMajorUnit()
{
if (noCurrency)
return Zero;
return new Money(decimal.Ceiling(Amount), Currency);
}
/// <summary>
/// mutiply amount
/// </summary>
public static Money operator *(Money lhs, decimal rhs)
{
if (lhs.noCurrency)
return Zero;
return new Money(rhs * lhs.Amount, lhs.Currency);
}
/// <summary>
/// mutiply amount
/// </summary>
public static Money operator *(decimal lhs, Money rhs)
{
if (rhs.noCurrency)
return Zero;
return new Money(lhs * rhs.Amount, rhs.Currency);
}
/// <summary>
/// divide amount
/// </summary>
public static Money operator /(Money lhs, decimal rhs)
{
if (lhs.noCurrency)
return Zero;
return new Money(lhs.Amount / rhs, lhs.Currency);
}
/// <summary>
/// Determines whether the specified System.Object is equal to the current Money.
/// </summary>
public override bool Equals(object obj)
{
if (!(obj is Money))
return false;
return Equals((Money)obj);
}
/// <summary>
/// Determines whether the specified Money is equal to the current Money.
/// </summary>
public bool Equals(Money other)
{
return Amount == other.Amount &&
ReferenceEquals(Currency, other.Currency);
}
/// <summary>
/// Compares two Money structures.
/// </summary>
public static bool operator ==(Money x, Money y)
{
return x.Equals(y);
}
/// <summary>
/// Compares two Money structures.
/// </summary>
public static bool operator !=(Money x, Money y)
{
return !x.Equals(y);
}
/// <summary>
/// Serves as a hash function for a particular type.
/// </summary>
/// <returns></returns>
public override int GetHashCode()
{
return Amount.GetHashCode() ^ (noCurrency ? 0 : Currency.GetHashCode());
}
/// <summary>
/// Compares this instance to a specified AbbyyLS.Payments.Money object and returns a
/// comparison of their relative values.
/// </summary>
public int CompareTo(Money other)
{
if(noCurrency)
return 0m.CompareTo(other.Amount);
if (other.noCurrency)
return Amount.CompareTo(0m);
if (!ReferenceEquals(Currency, other.Currency))
throw new InvalidOperationException("mismatch currency");
return Amount.CompareTo(other.Amount);
}
/// <summary>
/// operator Less
/// </summary>
public static bool operator <(Money lhs, Money rhs)
{
return lhs.CompareTo(rhs) < 0;
}
/// <summary>
/// operator Less or Equal
/// </summary>
public static bool operator <=(Money lhs, Money rhs)
{
return lhs.CompareTo(rhs) <= 0;
}
/// <summary>
/// operator Great
/// </summary>
public static bool operator >(Money lhs, Money rhs)
{
return lhs.CompareTo(rhs) > 0;
}
/// <summary>
/// operator Greate or Equal
/// </summary>
public static bool operator >=(Money lhs, Money rhs)
{
return lhs.CompareTo(rhs) >= 0;
}
/// <summary>
/// sum amount
/// </summary>
public static Money operator +(Money lhs, Money rhs)
{
if (lhs.noCurrency)
return rhs;
if (rhs.noCurrency)
return lhs;
if (!ReferenceEquals(lhs.Currency, rhs.Currency))
throw new InvalidOperationException("mismatch currency");
return new Money(lhs.Amount + rhs.Amount, lhs.Currency);
}
/// <summary>
/// subtraction amount
/// </summary>
public static Money operator -(Money lhs, Money rhs)
{
if (rhs.noCurrency)
return lhs;
if (lhs.noCurrency)
return new Money(- rhs.Amount, rhs.Currency);
if (!ReferenceEquals(lhs.Currency, rhs.Currency))
throw new InvalidOperationException("mismatch currency");
return new Money(lhs.Amount - rhs.Amount, lhs.Currency);
}
private bool noCurrency => Equals(Currency, null);
/// <summary>
/// Default value
/// </summary>
public static readonly Money Zero = new Money();
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Alvas.Audio;
using System.Runtime.InteropServices;
using System.IO;
namespace EffectsCs
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
Init();
}
protected override void UpdateDefaultButton()
{
Control ctrl = FindFocusedControl(splitContainer1);
if (ctrl != null && ctrl.Tag != null)
{
propertyGrid1.SelectedObject = (ctrl != null) ? ctrl.Tag : null;
}
}
public static Control FindFocusedControl(Control container)
{
foreach (Control childControl in container.Controls)
{
if (childControl.Focused)
{
return childControl;
}
}
foreach (Control childControl in container.Controls)
{
Control maybeFocusedControl = FindFocusedControl(childControl);
if (maybeFocusedControl != null)
{
return maybeFocusedControl;
}
}
return null; // Couldn't find any, darn!
}
private void Init()
{
sfdAudio.Filter = "*.wav|*.wav";
sfdAudio.DefaultExt = "wav";
ofdAudio.Filter = "*.wav|*.wav|*.mp3|*.mp3|*.avi|*.avi|*.wma;*.wmv;*.asf;*.mpg;*.aif;*.au;*.snd;*.mid;*.rmi;*.ogg;*.flac;*.cda;*.ac3;*.dts;*.mka;*.mkv;*.mpc;*.m4a;*.aac;*.mpa;*.mp2;*.m1a;*.m2a|*.wma;*.wmv;*.asf;*.mpg;*.aif;*.au;*.snd;*.mid;*.rmi;*.ogg;*.flac;*.cda;*.ac3;*.dts;*.mka;*.mkv;*.mpc;*.m4a;*.aac;*.mpa;*.mp2;*.m1a;*.m2a|*.*|*.*";
btnPlay.Enabled = false;
btnStop.Enabled = false;
btnSave.Enabled = false;
ChorusAudioEffect aeChorus = AudioEffect.CreateChorusAudioEffect();
NewTab(aeChorus, "Chorus");
CompressorAudioEffect aeCompressor = AudioEffect.CreateCompressorAudioEffect();
NewTab(aeCompressor, "Compressor");
DistortionAudioEffect aeDistortion = AudioEffect.CreateDistortionAudioEffect();
NewTab(aeDistortion, "Distortion");
EchoAudioEffect aeEcho = AudioEffect.CreateEchoAudioEffect();
NewTab(aeEcho, "Echo");
FlangerAudioEffect aeFlanger = AudioEffect.CreateFlangerAudioEffect();
NewTab(aeFlanger, "Flanger");
GargleAudioEffect aeGargle = AudioEffect.CreateGargleAudioEffect();
NewTab(aeGargle, "Gargle");
I3DL2ReverbAudioEffect aeI3DL2Reverb = AudioEffect.CreateI3DL2ReverbAudioEffect();
NewTab(aeI3DL2Reverb, "I3DL2Reverb");
ParamEqAudioEffect aeParamEq = AudioEffect.CreateParamEqAudioEffect();
NewTab(aeParamEq, "ParamEq");
WavesReverbAudioEffect aeWavesReverb = AudioEffect.CreateWavesReverbAudioEffect();
NewTab(aeWavesReverb, "WavesReverb");
}
private void NewTab(AudioEffect ae, string name)
{
TabPage tab = InitParams(ae, name);
tcEffects.TabPages.Add(tab);
}
private TabPage InitParams(AudioEffect ae, string name)
{
TabPage tp = new TabPage(name);
TableLayoutPanel tl = new TableLayoutPanel();
tl.Dock = DockStyle.Top;
tl.ColumnCount = 2 + 1;
tl.AutoSizeMode = AutoSizeMode.GrowOnly;
tl.AutoSize = true;
tp.Controls.Add(tl);
tl.RowCount = ae.Params.Length;
for (int i = 0; i < ae.Params.Length; i++)
{
DmoParam param = ae.Params[i];
CheckBox cb = new CheckBox();
cb.Text = "Default";
cb.DataBindings.Add("Checked", param, "IsDefaultValue");
tl.Controls.Add(cb);
Label l = new Label();
l.Text = ae.Params[i].Name + ((ae.Params[i].Unit == "") ? "" : ", " + ae.Params[i].Unit);
tl.Controls.Add(l);
if (param is DmoBoolParam)
{
CheckBox ctrl = new CheckBox();
ctrl.Tag = param;
ctrl.DataBindings.Add("Checked", param, "Value", false, DataSourceUpdateMode.OnPropertyChanged);
tl.Controls.Add(ctrl);
}
else if (param is DmoEnumParam)
{
DmoEnumParam paramEnum = (DmoEnumParam)param;
ComboBox ctrl = new ComboBox();
ctrl.DropDownStyle = ComboBoxStyle.DropDownList;
ctrl.Items.AddRange(paramEnum.Items);
ctrl.Tag = param;
ctrl.DataBindings.Add("SelectedIndex", param, "Value", false, DataSourceUpdateMode.OnPropertyChanged);
tl.Controls.Add(ctrl);
}
else if (param is DmoFloatParam)
{
DmoFloatParam paramFloat = (DmoFloatParam)param;
NumericUpDown ctrl = new NumericUpDown();
ctrl.DecimalPlaces = 3;
ctrl.Increment = 0.001M;
ctrl.Minimum = (decimal)paramFloat.Minimum;
ctrl.Maximum = (decimal)paramFloat.Maximum;
ctrl.Tag = param;
ctrl.DataBindings.Add("Value", param, "Value", false, DataSourceUpdateMode.OnPropertyChanged);
tl.Controls.Add(ctrl);
}
else if (param is DmoIntParam)
{
DmoIntParam paramInt = (DmoIntParam)param;
TrackBar ctrl = new TrackBar();
ctrl.Minimum = paramInt.Minimum;
ctrl.Maximum = paramInt.Maximum;
ctrl.Tag = param;
ctrl.DataBindings.Add("Value", param, "Value", false, DataSourceUpdateMode.OnPropertyChanged);
tl.Controls.Add(ctrl);
}
else
{
Label ctrl = new Label();
ctrl.Tag = param;
tl.Controls.Add(ctrl);
}
}
for (int i = 0; i < tl.RowCount; i++)
{
tl.RowStyles.Add(new RowStyle(SizeType.Absolute, 26f));
}
tl.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));
tl.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));
tl.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, .5f));
tp.Tag = ae;
return tp;
}
PlayerEx plex = new PlayerEx();
private void btnPlay_Click(object sender, EventArgs e)
{
AudioEffect af = tcEffects.SelectedTab.Tag as AudioEffect;
byte[] data = null;
IntPtr format = IntPtr.Zero;
Prepare(arw, af, ref format, ref data);
Play(format, data);
tcEffectsEnabled = false;
btnPlay.Enabled = false;
btnOpen.Enabled = false;
btnStop.Enabled = true;
}
public void Prepare(IAudioReader wr, AudioEffect af, ref IntPtr format, ref byte[] data)
{
format = wr.ReadFormat();
WaveFormat wf1 = AudioCompressionManager.GetWaveFormat(format);
Console.WriteLine("{0},{1},{2}-{3}", wf1.nChannels, wf1.wBitsPerSample, wf1.nSamplesPerSec, wf1.wFormatTag);
data = wr.ReadData();
if (wf1.wFormatTag != 1)
{
IntPtr formatNew = IntPtr.Zero;
byte[] dataNew = null;
AudioCompressionManager.ToPcm(format, data, ref formatNew, ref dataNew);
format = formatNew;
data = dataNew;
WaveFormat wf2 = AudioCompressionManager.GetWaveFormat(format);
Console.WriteLine("{0},{1},{2}-{3}", wf2.nChannels, wf2.wBitsPerSample, wf2.nSamplesPerSec, wf2.wFormatTag);
}
else if (wf1.wBitsPerSample != 16)
{
WaveFormat wf = AudioCompressionManager.GetWaveFormat(format);
IntPtr formatNew = AudioCompressionManager.GetPcmFormat(wf.nChannels, 16, wf.nSamplesPerSec);
byte[] dataNew = AudioCompressionManager.Convert(format, formatNew, data, false);
format = formatNew;
data = dataNew;
WaveFormat wf2 = AudioCompressionManager.GetWaveFormat(format);
Console.WriteLine("{0},{1},{2}-{3}", wf2.nChannels, wf2.wBitsPerSample, wf2.nSamplesPerSec, wf2.wFormatTag);
}
//wr.Close();
if (af != null)
{
bool hasProcessInPlace = af.HasProcessInPlace;
//af.GetSupportedOutputFormats();
GCHandle src = GCHandle.Alloc(data, GCHandleType.Pinned);
IntPtr formatPtr = src.AddrOfPinnedObject();
bool res = af.ProcessInPlace(format, data);
src.Free();
if (!res)
{
MessageBox.Show("Unable to convert the audio data");
return;
}
}
}
private void Play(IntPtr format, byte[] data)
{
if (plex.State != DeviceState.Closed)
{
plex.ClosePlayer();
}
//Console.WriteLine(plex.State);
plex.OpenPlayer(format);
plex.AddData(data);
plex.StartPlay();
}
private void btnStop_Click(object sender, EventArgs e)
{
if (plex.State != DeviceState.Closed)
{
plex.ClosePlayer();
}
tcEffectsEnabled = true;
btnPlay.Enabled = true;
btnOpen.Enabled = true;
btnStop.Enabled = false;
Console.WriteLine("{0} STOP", plex.State);
}
IAudioReader arw;
private bool tcEffectsEnabled = true;
private void btnOpen_Click(object sender, EventArgs e)
{
if (ofdAudio.ShowDialog() == DialogResult.OK)
{
if (arw != null)
{
arw.Close();
arw = null;
}
string fileName = ofdAudio.FileName;
arw = null;
switch (Path.GetExtension(fileName.ToLower()))
{
case ".avi":
arw = new AviReader(File.Open(fileName, FileMode.Open, FileAccess.ReadWrite));
if (!((AviReader)arw).HasAudio)
{
MessageBox.Show(string.Format("'{0}' file is not contains audio data", fileName));
return;
}
break;
case ".au":
case ".snd":
arw = new AuReader(File.OpenRead(fileName));
break;
case ".wav":
arw = new WaveReadWriter(File.Open(fileName, FileMode.Open, FileAccess.ReadWrite));
break;
case ".mp3":
arw = new Mp3ReadWriter(File.Open(fileName, FileMode.Open, FileAccess.ReadWrite));
break;
default:
arw = new DsReader(fileName);
if (!((DsReader)arw).HasAudio)
{
arw = null;
MessageBox.Show(string.Format("'{0}' file is not contains audio data", fileName));
}
break;
}
btnPlay.Enabled = arw != null;
btnSave.Enabled = arw != null;
}
}
private void tcEffects_Selecting(object sender, TabControlCancelEventArgs e)
{
e.Cancel = !tcEffectsEnabled;
}
private void btnSave_Click(object sender, EventArgs e)
{
if (sfdAudio.ShowDialog() == DialogResult.OK)
{
Save(sfdAudio.FileName);
}
}
private void Save(IntPtr format, byte[] data, string fileName)
{
//string fileName = string.Format(@"e:\Down\wav\{0}.wav", name);
WaveWriter ww = new WaveWriter(File.Create(fileName),
AudioCompressionManager.FormatBytes(format));
ww.WriteData(data);
ww.Close();
}
private void Save(string fileName)
{
AudioEffect af = tcEffects.SelectedTab.Tag as AudioEffect;
byte[] data = null;
IntPtr format = IntPtr.Zero;
Prepare(arw, af, ref format, ref data);
Save(format, data, fileName);
}
}
}
| |
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using vNextDemo.Data;
namespace vNextDemo.Data.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("00000000000000_CreateIdentitySchema")]
partial class CreateIdentitySchema
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "1.0.0-rc2-20901");
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole", b =>
{
b.Property<string>("Id");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Name")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.HasName("RoleNameIndex");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("RoleId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider");
b.Property<string>("ProviderKey");
b.Property<string>("ProviderDisplayName");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.HasIndex("UserId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("LoginProvider");
b.Property<string>("Name");
b.Property<string>("Value");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("vNextDemo.Models.ApplicationUser", b =>
{
b.Property<string>("Id");
b.Property<int>("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Email")
.HasAnnotation("MaxLength", 256);
b.Property<bool>("EmailConfirmed");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("NormalizedEmail")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedUserName")
.HasAnnotation("MaxLength", 256);
b.Property<string>("PasswordHash");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("SecurityStamp");
b.Property<bool>("TwoFactorEnabled");
b.Property<string>("UserName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasName("EmailIndex");
b.HasIndex("NormalizedUserName")
.HasName("UserNameIndex");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole")
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b =>
{
b.HasOne("vNextDemo.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b =>
{
b.HasOne("vNextDemo.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole")
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("vNextDemo.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using Signum.Utilities;
using Signum.Utilities.Reflection;
using System.Runtime.Serialization;
namespace Signum.Entities
{
/// <summary>
/// Represents a PrimaryKey of type int, long, Guid or string, for example.
/// Its a struct to avoid another object in heap
/// The default value represents an invalid state.
/// </summary>
[Serializable, TypeConverter(typeof(PrimaryKeyTypeConverter))]
public struct PrimaryKey : IEquatable<PrimaryKey>, IComparable, IComparable<PrimaryKey>, ISerializable
{
public static Polymorphic<Type> PrimaryKeyType = new Polymorphic<Type>(minimumType: typeof(Entity));
public static Type Type(Type entityType)
{
return PrimaryKeyType.GetValue(entityType);
}
public static void SetType(Type entityType, Type primaryKeyType)
{
PrimaryKeyType.SetDefinition(entityType, primaryKeyType);
}
public static Dictionary<Type, Type> Export()
{
return PrimaryKeyType.ExportDefinitions();
}
public static void Import(Dictionary<Type, Type> dic)
{
PrimaryKeyType.ImportDefinitions(dic);
}
public readonly string? VariableName; //Used for Sync scenarios
public readonly IComparable Object;
public PrimaryKey(IComparable obj)
{
this.Object = obj ?? throw new ArgumentNullException(nameof(obj));
this.VariableName = null;
}
public PrimaryKey(IComparable obj, string variableName)
{
this.Object = obj ?? throw new ArgumentNullException(nameof(obj));
this.VariableName = variableName;
}
public override string ToString()
{
return Object.ToString()!;
}
public override bool Equals(object? obj)
{
return obj is PrimaryKey pk && this.Equals(pk);
}
public override int GetHashCode()
{
return Object.GetHashCode();
}
public bool Equals(PrimaryKey other)
{
if (other.Object.GetType() != this.Object.GetType())
throw new InvalidOperationException("Comparing PrimaryKey of types {0} with anotherone of the {1}".FormatWith(other.Object.GetType(), this.Object.GetType()));
return other.Object.Equals(this.Object);
}
public int CompareTo(object? obj)
{
return CompareTo((PrimaryKey)obj!);
}
public int CompareTo(PrimaryKey other)
{
if (other.Object.GetType() != this.Object.GetType())
throw new InvalidOperationException("Comparing PrimaryKey of types {0} with anotherone of the {1}".FormatWith(other.Object.GetType(), this.Object.GetType()));
return this.Object.CompareTo(other.Object);
}
public static implicit operator PrimaryKey(int id)
{
return new PrimaryKey(id);
}
public static implicit operator PrimaryKey?(int? id)
{
if (id == null)
return null;
return new PrimaryKey(id.Value);
}
public static implicit operator PrimaryKey(long id)
{
return new PrimaryKey(id);
}
public static implicit operator PrimaryKey?(long? id)
{
if (id == null)
return null;
return new PrimaryKey(id.Value);
}
public static implicit operator PrimaryKey(Guid id)
{
return new PrimaryKey(id);
}
public static implicit operator PrimaryKey?(Guid? id)
{
if (id == null)
return null;
return new PrimaryKey(id.Value);
}
public static implicit operator PrimaryKey(DateTime id)
{
return new PrimaryKey(id);
}
public static implicit operator PrimaryKey? (DateTime? id)
{
if (id == null)
return null;
return new PrimaryKey(id.Value);
}
public static explicit operator int(PrimaryKey key)
{
return (int)key.Object;
}
public static explicit operator int?(PrimaryKey? key)
{
if (key == null)
return null;
return (int)key.Value.Object;
}
public static explicit operator long(PrimaryKey key)
{
return (long)key.Object;
}
public static explicit operator long?(PrimaryKey? key)
{
if (key == null)
return null;
return (long)key.Value.Object;
}
public static explicit operator Guid(PrimaryKey key)
{
return (Guid)key.Object;
}
public static explicit operator Guid?(PrimaryKey? key)
{
if (key == null)
return null;
return (Guid)key.Value.Object;
}
public static explicit operator DateTime(PrimaryKey key)
{
return (DateTime)key.Object;
}
public static explicit operator DateTime? (PrimaryKey? key)
{
if (key == null)
return null;
return (DateTime)key.Value.Object;
}
public static bool operator ==(PrimaryKey a, PrimaryKey b)
{
return a.Equals(b);
}
public static bool operator !=(PrimaryKey a, PrimaryKey b)
{
return !a.Equals(b);
}
public static bool operator <=(PrimaryKey a, PrimaryKey b)
{
return a.Object.CompareTo(b.Object) <= 0;
}
public static bool operator <(PrimaryKey a, PrimaryKey b)
{
return a.Object.CompareTo(b.Object) < 0;
}
public static bool operator >=(PrimaryKey a, PrimaryKey b)
{
return a.Object.CompareTo(b.Object) >= 0;
}
public static bool operator >(PrimaryKey a, PrimaryKey b)
{
return a.Object.CompareTo(b.Object) > 0;
}
public static bool TryParse(string value, Type entityType, out PrimaryKey id)
{
if (ReflectionTools.TryParse(value, Type(entityType), out object? val))
{
id = new PrimaryKey((IComparable)val!);
return true;
}
else
{
id = default(PrimaryKey);
return false;
}
}
public static PrimaryKey Parse(string value, Type entityType)
{
return new PrimaryKey((IComparable)ReflectionTools.Parse(value, Type(entityType))!);
}
public static PrimaryKey? Wrap(IComparable value)
{
if (value == null)
return null;
return new PrimaryKey(value);
}
public static IComparable? Unwrap(PrimaryKey? id)
{
if (id == null)
return null;
return id.Value.Object;
}
public static string? UnwrapToString(PrimaryKey? id)
{
if (id == null)
return null;
return id.Value.Object.ToString();
}
public string ToString(string format)
{
return ((IFormattable)this.Object).ToString(format, CultureInfo.CurrentCulture);
}
private PrimaryKey(SerializationInfo info, StreamingContext ctxt)
{
this.Object = null!;
this.VariableName = null!;
foreach (SerializationEntry item in info)
{
switch (item.Name)
{
case "Object": this.Object = (IComparable)item.Value!; break;
}
}
if (this.Object == null)
throw new SerializationException("Object not set");
}
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("Object", this.Object);
}
}
class PrimaryKeyTypeConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return
sourceType == typeof(int) || sourceType == typeof(int?) ||
sourceType == typeof(long) || sourceType == typeof(long?) ||
sourceType == typeof(Guid) || sourceType == typeof(Guid?);
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
return
destinationType == typeof(int) || destinationType == typeof(int?) ||
destinationType == typeof(long) || destinationType == typeof(long?) ||
destinationType == typeof(Guid) || destinationType == typeof(Guid?);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
return new PrimaryKey((IComparable)value);
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
return ((PrimaryKey)value).Object;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using JetBrains.Annotations;
using Joinrpg.AspNetCore.Helpers;
using JoinRpg.Data.Interfaces;
using JoinRpg.DataModel;
using JoinRpg.Domain;
using JoinRpg.Portal.Infrastructure;
using JoinRpg.Portal.Infrastructure.Authorization;
using JoinRpg.Services.Interfaces;
using JoinRpg.Web.Helpers;
using JoinRpg.Web.Models;
using JoinRpg.Web.Models.Characters;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace JoinRpg.Portal.Controllers
{
[Route("{projectId}/character/{characterid}/[action]")]
public class CharacterController : Common.ControllerGameBase
{
private IPlotRepository PlotRepository { get; }
private ICharacterRepository CharacterRepository { get; }
private IUriService UriService { get; }
private ICharacterService CharacterService { get; }
public CharacterController(
IProjectRepository projectRepository,
IProjectService projectService,
IPlotRepository plotRepository,
ICharacterRepository characterRepository,
IUriService uriService,
IUserRepository userRepository,
ICharacterService characterService)
: base(projectRepository, projectService, userRepository)
{
PlotRepository = plotRepository;
CharacterRepository = characterRepository;
UriService = uriService;
CharacterService = characterService;
}
[HttpGet("~/{projectId}/character/{characterid}/")]
[HttpGet("~/{projectId}/character/{characterid}/details")]
[AllowAnonymous]
public async Task<ActionResult> Details(int projectid, int characterid)
{
var field = await CharacterRepository.GetCharacterWithGroups(projectid, characterid);
return (field?.Project == null ? NotFound() : null) ?? await ShowCharacter(field);
}
private async Task<ActionResult> ShowCharacter(Character character)
{
var plots = character.HasPlotViewAccess(CurrentUserIdOrDefault)
? await ShowPlotsForCharacter(character)
: Enumerable.Empty<PlotElement>();
return View("Details",
new CharacterDetailsViewModel(CurrentUserIdOrDefault,
character,
plots.ToList(),
UriService));
}
private async Task<IReadOnlyList<PlotElement>> ShowPlotsForCharacter(Character character) =>
character.GetOrderedPlots(await PlotRepository.GetPlotsForCharacter(character));
[HttpGet, MasterAuthorize(Permission.CanEditRoles)]
public async Task<ActionResult> Edit(int projectId, int characterId)
{
var field = await CharacterRepository.GetCharacterWithDetails(projectId, characterId);
return View(new EditCharacterViewModel()
{
ProjectId = field.ProjectId,
CharacterId = field.CharacterId,
IsPublic = field.IsPublic,
ProjectName = field.Project.ProjectName,
IsAcceptingClaims = field.IsAcceptingClaims,
HidePlayerForCharacter = field.HidePlayerForCharacter,
Name = field.CharacterName,
ParentCharacterGroupIds = field.Groups.Where(gr => !gr.IsSpecial).Select(pg => pg.CharacterGroupId).ToArray(),
IsHot = field.IsHot,
}.Fill(field, CurrentUserId));
}
[HttpPost, MasterAuthorize(Permission.CanEditRoles), ValidateAntiForgeryToken]
public async Task<ActionResult> Edit(EditCharacterViewModel viewModel)
{
var field =
await CharacterRepository.GetCharacterAsync(viewModel.ProjectId,
viewModel.CharacterId);
try
{
if (!ModelState.IsValid)
{
return View(viewModel.Fill(field, CurrentUserId));
}
await CharacterService.EditCharacter(
CurrentUserId,
viewModel.CharacterId,
viewModel.ProjectId,
viewModel.Name,
viewModel.IsPublic,
viewModel.ParentCharacterGroupIds,
viewModel.IsAcceptingClaims &&
field.ApprovedClaim == null,
viewModel.HidePlayerForCharacter,
Request.GetDynamicValuesFromPost(FieldValueViewModel.HtmlIdPrefix),
viewModel.IsHot);
return RedirectToAction("Details",
new { viewModel.ProjectId, viewModel.CharacterId });
}
catch (Exception exception)
{
ModelState.AddException(exception);
return View(viewModel.Fill(field, CurrentUserId));
}
}
[HttpGet("~/{ProjectId}/character/create")]
[MasterAuthorize(Permission.CanEditRoles)]
public async Task<ActionResult> Create(int projectid, int? charactergroupid, bool continueCreating = false)
{
CharacterGroup characterGroup;
if (charactergroupid is null)
{
characterGroup = await ProjectRepository.GetRootGroupAsync(projectid);
}
else
{
characterGroup = await ProjectRepository.GetGroupAsync(projectid, charactergroupid.Value);
}
if (characterGroup == null)
{
return NotFound();
}
return View(new AddCharacterViewModel()
{
ProjectId = projectid,
ProjectName = characterGroup.Project.ProjectName,
ParentCharacterGroupIds = new[] { characterGroup.CharacterGroupId },
ContinueCreating = continueCreating,
}.Fill(characterGroup, CurrentUserId));
}
[HttpPost("~/{ProjectId}/character/create")]
[MasterAuthorize(Permission.CanEditRoles)]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create(AddCharacterViewModel viewModel)
{
var characterGroupId = viewModel.ParentCharacterGroupIds.FirstOrDefault();
try
{
await CharacterService.AddCharacter(new AddCharacterRequest(
ProjectId: viewModel.ProjectId,
Name: viewModel.Name,
IsAcceptingClaims: viewModel.IsAcceptingClaims,
ParentCharacterGroupIds: viewModel.ParentCharacterGroupIds,
HidePlayerForCharacter: viewModel.HidePlayerForCharacter,
IsHot: viewModel.IsHot,
IsPublic: viewModel.IsPublic,
FieldValues: Request.GetDynamicValuesFromPost(FieldValueViewModel.HtmlIdPrefix)
));
if (viewModel.ContinueCreating)
{
return RedirectToAction("Create",
new { viewModel.ProjectId, characterGroupId, viewModel.ContinueCreating });
}
return RedirectToIndex(viewModel.ProjectId, characterGroupId);
}
catch (Exception exception)
{
ModelState.AddException(exception);
CharacterGroup characterGroup;
if (characterGroupId == 0)
{
characterGroup = (await ProjectRepository.GetProjectAsync(viewModel.ProjectId))
.RootGroup;
}
else
{
characterGroup =
await ProjectRepository.GetGroupAsync(viewModel.ProjectId,
characterGroupId);
}
return View(viewModel.Fill(characterGroup, CurrentUserId));
}
}
[HttpGet, MasterAuthorize(Permission.CanEditRoles)]
public async Task<ActionResult> Delete(int projectid, int characterid)
{
var field = await CharacterRepository.GetCharacterAsync(projectid, characterid);
if (field == null)
{
return NotFound();
}
return View(field);
}
[HttpPost, MasterAuthorize(Permission.CanEditRoles), ValidateAntiForgeryToken]
public async Task<ActionResult> Delete(int projectId,
int characterId,
[UsedImplicitly]
IFormCollection form)
{
var field = await CharacterRepository.GetCharacterAsync(projectId, characterId);
try
{
await CharacterService.DeleteCharacter(projectId, characterId, CurrentUserId);
return RedirectToIndex(field.Project);
}
catch
{
return View(field);
}
}
[HttpGet, MasterAuthorize(Permission.CanEditRoles)]
public Task<ActionResult> MoveUp(int projectid,
int characterid,
int parentcharactergroupid,
int currentrootgroupid) => MoveImpl(projectid,
characterid,
parentcharactergroupid,
currentrootgroupid,
direction: -1);
[HttpGet, MasterAuthorize(Permission.CanEditRoles)]
public Task<ActionResult> MoveDown(int projectid,
int characterid,
int parentcharactergroupid,
int currentrootgroupid) => MoveImpl(projectid,
characterid,
parentcharactergroupid,
currentrootgroupid,
direction: +1);
private async Task<ActionResult> MoveImpl(int projectId,
int characterId,
int parentCharacterGroupId,
int currentRootGroupId,
short direction)
{
try
{
await CharacterService.MoveCharacter(CurrentUserId,
projectId,
characterId,
parentCharacterGroupId,
direction);
return RedirectToIndex(projectId, currentRootGroupId);
}
catch
{
//TODO Show Error
return RedirectToIndex(projectId, currentRootGroupId);
}
}
}
}
| |
using System;
using System.Runtime.InteropServices;
using System.Diagnostics;
using MO.Common.Lang;
using MO.Core.Window.Api;
using MO.Core.Window.Context;
namespace MO.Core.Window.Core {
public class RModule {
public static Nullable<SImageDosHeader> GetDosHeader(IntPtr hModule) {
SImageDosHeader header = (SImageDosHeader)Marshal.PtrToStructure(hModule, typeof(SImageDosHeader));
if (header.e_magic != (uint)EImageSignature.Dos) {
return null;
}
return header;
}
public static Nullable<SImageNtHeaders> GetNtHeaders(IntPtr hModule) {
Nullable<SImageDosHeader> dosHeader = GetDosHeader(hModule);
if (dosHeader.HasValue) {
IntPtr pHeader = (IntPtr)(hModule.ToInt32() + dosHeader.Value.e_lfanew);
SImageNtHeaders ntHeaders = (SImageNtHeaders)Marshal.PtrToStructure(pHeader, typeof(SImageNtHeaders));
if (ntHeaders.Signature != (uint)EImageSignature.Nt) {
return null;
}
return ntHeaders;
}
return null;
}
public static FModuleInfoCollection ListProcess(int processId) {
FModuleInfoCollection modules = new FModuleInfoCollection();
List(modules, processId);
return modules;
}
public static bool List(FModuleInfoCollection modules) {
return List(modules, Process.GetCurrentProcess().Id);
}
public static bool List(FModuleInfoCollection modules, int processId) {
modules.Clear();
IntPtr hSnap = RKernel32.CreateToolhelp32Snapshot(ETh32cs.SnapModule, processId);
if (!RApi.IsValidHandle(hSnap)) {
return false;
}
SModuleEntry32 me32 = new SModuleEntry32();
me32.dwSize = Marshal.SizeOf(me32);
bool next = RKernel32.Module32First(hSnap, ref me32);
while (next) {
FModuleInfo module = new FModuleInfo();
module.Handle = me32.hModule;
module.Name = me32.szModule;
module.Location = me32.szExePath;
module.BaseAddress = me32.modBaseAddr;
module.BaseSize = me32.modBaseSize;
module.ModuleID = me32.th32ModuleID;
module.GlblcntUsage = me32.GlblcntUsage;
module.ProccntUsage = me32.ProccntUsage;
modules.Push(module);
next = RKernel32.Module32Next(hSnap, ref me32);
}
RKernel32.CloseHandle(hSnap);
return true;
}
public static SModuleEntry32[] ListAll() {
return ListAll(Process.GetCurrentProcess().Id);
}
public static SModuleEntry32[] ListAll(int processId) {
IntPtr hSnap = RKernel32.CreateToolhelp32Snapshot(ETh32cs.SnapModule, processId);
if (!RApi.IsValidHandle(hSnap)) {
return null;
}
FObjects<SModuleEntry32> modules = new FObjects<SModuleEntry32>();
SModuleEntry32 me32 = new SModuleEntry32();
me32.dwSize = Marshal.SizeOf(me32);
bool next = RKernel32.Module32First(hSnap, ref me32);
while (next) {
SModuleEntry32 module = new SModuleEntry32();
module = me32;
modules.Push(module);
next = RKernel32.Module32Next(hSnap, ref me32);
}
RKernel32.CloseHandle(hSnap);
return modules.ToArray();
}
public static SModuleEntry32[] ListModule(IntPtr hModule) {
FObjects<SModuleEntry32> mes = new FObjects<SModuleEntry32>();
Nullable<SImageNtHeaders> ntHeaders = GetNtHeaders(hModule);
SImageDataDirectory idd = ntHeaders.Value.OptionalHeader.DataDirectory[(int)EImageDirectoryEntry.Import];
if (idd.VirtualAddress == 0) {
return mes.ToArray();
}
// Import
uint maddress = (uint)hModule.ToInt32();
IntPtr pIdHeader = (IntPtr)(maddress + idd.VirtualAddress);
int idSize = Marshal.SizeOf(typeof(SImageImportDescriptor));
while (true) {
SImageImportDescriptor impDesc = (SImageImportDescriptor)Marshal.PtrToStructure(pIdHeader, typeof(SImageImportDescriptor));
if (impDesc.Name == 0) {
break;
}
IntPtr namePtr = (IntPtr)(maddress + impDesc.Name);
SModuleEntry32 me = new SModuleEntry32();
me.modBaseAddr = impDesc.FirstThunk;
me.szModule = Marshal.PtrToStringAnsi(namePtr, 260);
mes.Push(me);
pIdHeader = (IntPtr)(pIdHeader.ToInt32() + idSize);
}
return mes.ToArray();
}
public static Nullable<SModuleEntry32> Find(string name) {
IntPtr hSnap = RKernel32.CreateToolhelp32Snapshot(ETh32cs.SnapModule, 0);
if (!RApi.IsValidHandle(hSnap)) {
return null;
}
Nullable<SModuleEntry32> module = null;
SModuleEntry32 me32 = new SModuleEntry32();
me32.dwSize = Marshal.SizeOf(me32);
bool next = RKernel32.Module32First(hSnap, ref me32);
while (next) {
if (me32.szModule == name) {
module = me32;
break;
}
next = RKernel32.Module32Next(hSnap, ref me32);
}
RKernel32.CloseHandle(hSnap);
return module;
}
public static FTrunkInfo[] FetchTrunks(IntPtr hModule) {
Nullable<SImageNtHeaders> ntHeaders = GetNtHeaders(hModule);
SImageDataDirectory idd = ntHeaders.Value.OptionalHeader.DataDirectory[(int)EImageDirectoryEntry.Import];
if (idd.VirtualAddress == 0) {
return null;
}
// Import
uint maddress = (uint)hModule.ToInt32();
IntPtr pIdHeader = (IntPtr)(maddress + idd.VirtualAddress);
SImageImportDescriptor impDesc = (SImageImportDescriptor)Marshal.PtrToStructure(pIdHeader, typeof(SImageImportDescriptor));
if (impDesc.Name == 0) {
return null;
}
// Get module Name
// IntPtr moduleNamePtr = (IntPtr)(maddress + impDesc.Name);
// Trunk
IntPtr pOrgFt = (IntPtr)(maddress + impDesc.OriginalFirstThunk);
IntPtr pFt = (IntPtr)(maddress + impDesc.FirstThunk);
int ftSize = Marshal.SizeOf(typeof(SImageThunkData32));
int miSize = Marshal.SizeOf(typeof(SMemoryBasicInformation));
FObjects<FTrunkInfo> infos = new FObjects<FTrunkInfo>();
while (true) {
SImageThunkData32 origThunk = (SImageThunkData32)Marshal.PtrToStructure(pOrgFt, typeof(SImageThunkData32));
SImageThunkData32 realThunk = (SImageThunkData32)Marshal.PtrToStructure(pFt, typeof(SImageThunkData32));
if (origThunk.Function == 0) {
break;
}
if ((origThunk.Ordinal & 0x80000000) == 0x80000000) {
break;
}
/*uint arrd = (uint)(maddress + origThunk.AddressOfData);
if ((arrd & 0x80000000) == 0x80000000) {
break;
}*/
// Read name
IntPtr pName = (IntPtr)(maddress + origThunk.AddressOfData);
SImageImportByName byName = (SImageImportByName)Marshal.PtrToStructure(pName, typeof(SImageImportByName));
if (byName.Name[0] == 0) {
break;
}
// Read memory state
SMemoryBasicInformation mbi = new SMemoryBasicInformation();
//RKernel32.VirtualQuery((uint)pFt.ToInt32(), ref mbi, miSize);
RKernel32.VirtualQuery(realThunk.Function, ref mbi, miSize);
// TrunkInfo
FTrunkInfo info = new FTrunkInfo();
info.Name = RAscii.GetString(byName.Name);
info.Address = origThunk.Function;
//info.Entry = (IntPtr)(maddress + origThunk.Function);
info.Entry = (IntPtr)realThunk.Function;
info.Hint = byName.Hint;
info.MemAllocationBase = mbi.AllocationBase;
info.MemAllocationProtect = mbi.AllocationProtect;
info.MemBaseAddress = mbi.BaseAddress;
info.MemProtect = mbi.Protect;
info.MemRegionSize = mbi.RegionSize;
info.MemState = mbi.State;
info.MemType = mbi.Type;
infos.Push(info);
// Loop
pOrgFt = (IntPtr)(pOrgFt.ToInt32() + ftSize);
pFt = (IntPtr)(pFt.ToInt32() + ftSize);
}
return infos.ToArray();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using OLEDB.Test.ModuleCore;
namespace System.Xml.Tests
{
/////////////////////////////////////////////////////////////////////////
// TestCase ReadOuterXml
//
/////////////////////////////////////////////////////////////////////////
[InheritRequired()]
public abstract partial class TCReadOuterXml : TCXMLReaderBaseGeneral
{
// Element names to test ReadOuterXml on
private static string s_EMP1 = "EMPTY1";
private static string s_EMP2 = "EMPTY2";
private static string s_EMP3 = "EMPTY3";
private static string s_EMP4 = "EMPTY4";
private static string s_ENT1 = "ENTITY1";
private static string s_NEMP0 = "NONEMPTY0";
private static string s_NEMP1 = "NONEMPTY1";
private static string s_NEMP2 = "NONEMPTY2";
private static string s_ELEM1 = "CHARS2";
private static string s_ELEM2 = "SKIP3";
private static string s_ELEM3 = "CONTENT";
private static string s_ELEM4 = "COMPLEX";
// Element names after the ReadOuterXml call
private static string s_NEXT1 = "COMPLEX";
private static string s_NEXT2 = "ACT2";
private static string s_NEXT3 = "CHARS_ELEM1";
private static string s_NEXT4 = "AFTERSKIP3";
private static string s_NEXT5 = "TITLE";
private static string s_NEXT6 = "ENTITY2";
private static string s_NEXT7 = "DUMMY";
// Expected strings returned by ReadOuterXml
private static string s_EXP_EMP1 = "<EMPTY1 />";
private static string s_EXP_EMP2 = "<EMPTY2 val=\"abc\" />";
private static string s_EXP_EMP3 = "<EMPTY3></EMPTY3>";
private static string s_EXP_EMP4 = "<EMPTY4 val=\"abc\"></EMPTY4>";
private static string s_EXP_NEMP1 = "<NONEMPTY1>ABCDE</NONEMPTY1>";
private static string s_EXP_NEMP2 = "<NONEMPTY2 val=\"abc\">1234</NONEMPTY2>";
private static string s_EXP_ELEM1 = "<CHARS2>xxx<MARKUP />yyy</CHARS2>";
private static string s_EXP_ELEM2 = "<SKIP3><ELEM1 /><ELEM2>xxx yyy</ELEM2><ELEM3 /></SKIP3>";
private static string s_EXP_ELEM3 = "<CONTENT><e1 a1='a1value' a2='a2value'><e2 a1='a1value' a2='a2value'><e3 a1='a1value' a2='a2value'>leave</e3></e2></e1></CONTENT>";
private static string s_EXP_ELEM4 = "<COMPLEX>Text<!-- comment --><![CDATA[cdata]]></COMPLEX>";
private static string s_EXP_ELEM4_XSLT = "<COMPLEX>Text<!-- comment -->cdata</COMPLEX>";
private static string s_EXP_ENT1_EXPAND_ALL = "<ENTITY1 att1=\"xxx<xxxAxxxCxxxNO_REFERENCEe1;xxx\">xxx>xxxBxxxDxxxNO_REFERENCEe1;xxx</ENTITY1>";
private static string s_EXP_ENT1_EXPAND_CHAR = "<ENTITY1 att1=\"xxx<xxxAxxxCxxx&e1;xxx\">xxx>xxxBxxxDxxx&e1;xxx</ENTITY1>";
private int TestOuterOnElement(string strElem, string strOuterXml, string strNextElemName, bool bWhitespace)
{
ReloadSource();
DataReader.PositionOnElement(strElem);
CError.Compare(DataReader.ReadOuterXml(), strOuterXml, "outer");
if (bWhitespace)
{
if (!(IsXsltReader() || IsXPathNavigatorReader()))// xslt doesn't return whitespace
{
if (IsCoreReader())
{
CError.Compare(DataReader.VerifyNode(XmlNodeType.Whitespace, string.Empty, "\n"), true, "vn");
}
else
{
CError.Compare(DataReader.VerifyNode(XmlNodeType.Whitespace, string.Empty, "\r\n"), true, "vn");
}
DataReader.Read();
}
}
CError.Compare(DataReader.VerifyNode(XmlNodeType.Element, strNextElemName, string.Empty), true, "vn2");
return TEST_PASS;
}
private int TestOuterOnAttribute(string strElem, string strName, string strValue)
{
ReloadSource();
DataReader.PositionOnElement(strElem);
DataReader.MoveToAttribute(DataReader.AttributeCount / 2);
string strExpected = string.Format("{0}=\"{1}\"", strName, strValue);
CError.Compare(DataReader.ReadOuterXml(), strExpected, "outer");
CError.Compare(DataReader.VerifyNode(XmlNodeType.Attribute, strName, strValue), true, "vn");
return TEST_PASS;
}
private int TestOuterOnNodeType(XmlNodeType nt)
{
ReloadSource();
PositionOnNodeType(nt);
DataReader.Read();
XmlNodeType expNt = DataReader.NodeType;
string expName = DataReader.Name;
string expValue = DataReader.Value;
ReloadSource();
PositionOnNodeType(nt);
CError.Compare(DataReader.ReadOuterXml(), string.Empty, "outer");
CError.Compare(DataReader.VerifyNode(expNt, expName, expValue), true, "vn");
return TEST_PASS;
}
////////////////////////////////////////////////////////////////
// Variations
////////////////////////////////////////////////////////////////
[Variation("ReadOuterXml on empty element w/o attributes", Pri = 0)]
public int ReadOuterXml1()
{
if (IsBinaryReader())
{
return TEST_SKIPPED;
}
return TestOuterOnElement(s_EMP1, s_EXP_EMP1, s_EMP2, true);
}
[Variation("ReadOuterXml on empty element w/ attributes", Pri = 0)]
public int ReadOuterXml2()
{
if (IsBinaryReader())
{
return TEST_SKIPPED;
}
return TestOuterOnElement(s_EMP2, s_EXP_EMP2, s_EMP3, true);
}
[Variation("ReadOuterXml on full empty element w/o attributes")]
public int ReadOuterXml3()
{
return TestOuterOnElement(s_EMP3, s_EXP_EMP3, s_NEMP0, true);
}
[Variation("ReadOuterXml on full empty element w/ attributes")]
public int ReadOuterXml4()
{
return TestOuterOnElement(s_EMP4, s_EXP_EMP4, s_NEXT1, true);
}
[Variation("ReadOuterXml on element with text content", Pri = 0)]
public int ReadOuterXml5()
{
return TestOuterOnElement(s_NEMP1, s_EXP_NEMP1, s_NEMP2, true);
}
[Variation("ReadOuterXml on element with attributes", Pri = 0)]
public int ReadOuterXml6()
{
return TestOuterOnElement(s_NEMP2, s_EXP_NEMP2, s_NEXT2, true);
}
[Variation("ReadOuterXml on element with text and markup content")]
public int ReadOuterXml7()
{
if (IsBinaryReader())
{
return TEST_SKIPPED;
}
return TestOuterOnElement(s_ELEM1, s_EXP_ELEM1, s_NEXT3, true);
}
[Variation("ReadOuterXml with multiple level of elements")]
public int ReadOuterXml8()
{
if (IsBinaryReader())
{
return TEST_SKIPPED;
}
return TestOuterOnElement(s_ELEM2, s_EXP_ELEM2, s_NEXT4, false);
}
[Variation("ReadOuterXml with multiple level of elements, text and attributes", Pri = 0)]
public int ReadOuterXml9()
{
string strExpected = s_EXP_ELEM3;
strExpected = strExpected.Replace('\'', '"');
return TestOuterOnElement(s_ELEM3, strExpected, s_NEXT5, true);
}
[Variation("ReadOuterXml on element with complex content (CDATA, PIs, Comments)", Pri = 0)]
public int ReadOuterXml10()
{
if (IsXsltReader() || IsXPathNavigatorReader())
return TestOuterOnElement(s_ELEM4, s_EXP_ELEM4_XSLT, s_NEXT7, true);
else
return TestOuterOnElement(s_ELEM4, s_EXP_ELEM4, s_NEXT7, true);
}
[Variation("ReadOuterXml on element with entities, EntityHandling = ExpandEntities")]
public int ReadOuterXml11()
{
string strExpected;
if (IsXsltReader() || IsXmlNodeReader() || IsXmlNodeReaderDataDoc() || IsXmlValidatingReader() || IsCoreReader() || IsXPathNavigatorReader())
{
strExpected = s_EXP_ENT1_EXPAND_ALL;
}
else
{
strExpected = s_EXP_ENT1_EXPAND_CHAR;
}
return TestOuterOnElement(s_ENT1, strExpected, s_NEXT6, false);
}
[Variation("ReadOuterXml on attribute node of empty element")]
public int ReadOuterXml12()
{
return TestOuterOnAttribute(s_EMP2, "val", "abc");
}
[Variation("ReadOuterXml on attribute node of full empty element")]
public int ReadOuterXml13()
{
return TestOuterOnAttribute(s_EMP4, "val", "abc");
}
[Variation("ReadOuterXml on attribute node", Pri = 0)]
public int ReadOuterXml14()
{
return TestOuterOnAttribute(s_NEMP2, "val", "abc");
}
[Variation("ReadOuterXml on attribute with entities, EntityHandling = ExpandEntities", Pri = 0)]
public int ReadOuterXml15()
{
ReloadSource();
DataReader.PositionOnElement(s_ENT1);
DataReader.MoveToAttribute(DataReader.AttributeCount / 2);
string strExpected;
if (IsXsltReader() || IsXmlNodeReader() || IsXmlNodeReaderDataDoc() || IsXmlValidatingReader() || IsCoreReader() || IsXPathNavigatorReader())
strExpected = "att1=\"xxx<xxxAxxxCxxxNO_REFERENCEe1;xxx\"";
else
{
strExpected = "att1=\"xxx<xxxAxxxCxxx&e1;xxx\"";
}
CError.Compare(DataReader.ReadOuterXml(), strExpected, "outer");
if (IsXmlTextReader())
CError.Compare(DataReader.VerifyNode(XmlNodeType.Attribute, "att1", ST_ENT1_ATT_EXPAND_CHAR_ENTITIES), true, "vn");
else
CError.Compare(DataReader.VerifyNode(XmlNodeType.Attribute, "att1", ST_ENT1_ATT_EXPAND_ENTITIES), true, "vn");
return TEST_PASS;
}
[Variation("ReadOuterXml on Comment")]
public int ReadOuterXml16()
{
return TestOuterOnNodeType(XmlNodeType.Comment);
}
[Variation("ReadOuterXml on ProcessingInstruction")]
public int ReadOuterXml17()
{
return TestOuterOnNodeType(XmlNodeType.ProcessingInstruction);
}
[Variation("ReadOuterXml on DocumentType")]
public int ReadOuterXml18()
{
if (IsXsltReader() || IsXPathNavigatorReader() || IsSubtreeReader())
return TEST_SKIPPED;
return TestOuterOnNodeType(XmlNodeType.DocumentType);
}
[Variation("ReadOuterXml on XmlDeclaration")]
public int ReadOuterXml19()
{
if (IsXsltReader() || IsXPathNavigatorReader() || IsSubtreeReader())
return TEST_SKIPPED;
return TestOuterOnNodeType(XmlNodeType.XmlDeclaration);
}
[Variation("ReadOuterXml on EndElement")]
public int ReadOuterXml20()
{
return TestOuterOnNodeType(XmlNodeType.EndElement);
}
[Variation("ReadOuterXml on Text")]
public int ReadOuterXml21()
{
return TestOuterOnNodeType(XmlNodeType.Text);
}
[Variation("ReadOuterXml on EntityReference")]
public int ReadOuterXml22()
{
if (IsXsltReader() || IsXmlNodeReaderDataDoc() || IsCoreReader() || IsXPathNavigatorReader())
return TEST_SKIPPED;
return TestOuterOnNodeType(XmlNodeType.EntityReference);
}
[Variation("ReadOuterXml on EndEntity")]
public int ReadOuterXml23()
{
if (IsXmlTextReader() || IsXsltReader() || IsXmlNodeReaderDataDoc() || IsCoreReader() || IsXPathNavigatorReader())
return TEST_SKIPPED;
return TestOuterOnNodeType(XmlNodeType.EndEntity);
}
[Variation("ReadOuterXml on CDATA")]
public int ReadOuterXml24()
{
if (IsXsltReader() || IsXPathNavigatorReader())
return TEST_SKIPPED;
return TestOuterOnNodeType(XmlNodeType.CDATA);
}
[Variation("ReadOuterXml on XmlDeclaration attributes")]
public int ReadOuterXml25()
{
if (IsXsltReader() || IsXPathNavigatorReader() || IsSubtreeReader())
return TEST_SKIPPED;
ReloadSource();
DataReader.PositionOnNodeType(XmlNodeType.XmlDeclaration);
DataReader.MoveToAttribute(DataReader.AttributeCount / 2);
CError.Compare(DataReader.ReadOuterXml().ToLower(), "encoding=\"utf-8\"", "outer");
if (IsBinaryReader())
CError.Compare(DataReader.VerifyNode(XmlNodeType.Attribute, "encoding", "utf-8"), true, "vn");
else
CError.Compare(DataReader.VerifyNode(XmlNodeType.Attribute, "encoding", "UTF-8"), true, "vn");
return TEST_PASS;
}
[Variation("ReadOuterXml on DocumentType attributes")]
public int ReadOuterXml26()
{
if (IsXsltReader() || IsXPathNavigatorReader() || IsSubtreeReader())
return TEST_SKIPPED;
ReloadSource();
DataReader.PositionOnNodeType(XmlNodeType.DocumentType);
DataReader.MoveToAttribute(DataReader.AttributeCount / 2);
CError.Compare(DataReader.ReadOuterXml(), "SYSTEM=\"AllNodeTypes.dtd\"", "outer");
CError.Compare(DataReader.VerifyNode(XmlNodeType.Attribute, "SYSTEM", "AllNodeTypes.dtd"), true, "vn");
return TEST_PASS;
}
[Variation("ReadOuterXml on element with entities, EntityHandling = ExpandCharEntities")]
public int TRReadOuterXml27()
{
string strExpected;
if (IsXsltReader() || IsXmlNodeReaderDataDoc() || IsCoreReader() || IsXPathNavigatorReader())
strExpected = s_EXP_ENT1_EXPAND_ALL;
else
{
if (IsXmlNodeReader())
{
strExpected = s_EXP_ENT1_EXPAND_CHAR;
}
else
{
strExpected = s_EXP_ENT1_EXPAND_CHAR;
}
}
ReloadSource();
DataReader.PositionOnElement(s_ENT1);
CError.Compare(DataReader.ReadOuterXml(), strExpected, "outer");
CError.Compare(DataReader.VerifyNode(XmlNodeType.Element, s_NEXT6, string.Empty), true, "vn");
return TEST_PASS;
}
[Variation("ReadOuterXml on attribute with entities, EntityHandling = ExpandCharEntites")]
public int TRReadOuterXml28()
{
string strExpected;
if (IsXsltReader() || IsXmlNodeReaderDataDoc() || IsCoreReader() || IsXPathNavigatorReader())
strExpected = "att1=\"xxx<xxxAxxxCxxxNO_REFERENCEe1;xxx\"";
else
{
if (IsXmlNodeReader())
{
strExpected = "att1=\"xxx<xxxAxxxCxxxNO_REFERENCEe1;xxx\"";
}
else
{
strExpected = "att1=\"xxx<xxxAxxxCxxxNO_REFERENCEe1;xxx\"";
}
}
ReloadSource();
DataReader.PositionOnElement(s_ENT1);
DataReader.MoveToAttribute(DataReader.AttributeCount / 2);
CError.Compare(DataReader.ReadOuterXml(), strExpected, "outer");
if (IsXmlTextReader())
CError.Compare(DataReader.VerifyNode(XmlNodeType.Attribute, "att1", ST_ENT1_ATT_EXPAND_CHAR_ENTITIES), true, "vn");
else
CError.Compare(DataReader.VerifyNode(XmlNodeType.Attribute, "att1", ST_ENT1_ATT_EXPAND_ENTITIES), true, "vn");
return TEST_PASS;
}
[Variation("One large element")]
public int TestTextReadOuterXml29()
{
string strp = "a ";
strp += strp;
strp += strp;
strp += strp;
strp += strp;
strp += strp;
strp += strp;
strp += strp;
string strxml = "<Name a=\"b\">" + strp + " </Name>";
ReloadSourceStr(strxml);
DataReader.Read();
CError.Compare(DataReader.ReadOuterXml(), strxml, "rox");
return TEST_PASS;
}
[Variation("Read OuterXml when Namespaces=false and has an attribute xmlns")]
public int ReadOuterXmlWhenNamespacesIgnoredWorksWithXmlns()
{
ReloadSourceStr("<?xml version='1.0' encoding='utf-8' ?> <foo xmlns='testing'><bar id='1'/></foo>");
if (IsXmlTextReader() || IsXmlValidatingReader())
DataReader.Namespaces = false;
DataReader.MoveToContent();
CError.WriteLine(DataReader.ReadOuterXml());
return TEST_PASS;
}
[Variation("XmlReader.ReadOuterXml outputs multiple namespace declarations if called within multiple XmlReader.ReadSubtree() calls")]
public int SubtreeXmlReaderOutputsSingleNamespaceDeclaration()
{
string xml = @"<root xmlns = ""http://www.test.com/""> <device> <thing>1</thing> </device></root>";
ReloadSourceStr(xml);
DataReader.ReadToFollowing("device");
Foo(DataReader.ReadSubtree());
return TEST_PASS;
}
private void Foo(XmlReader reader)
{
reader.Read();
Bar(reader.ReadSubtree());
}
private void Bar(XmlReader reader)
{
reader.Read();
string foo = reader.ReadOuterXml();
CError.Compare(foo, "<device xmlns=\"http://www.test.com/\"> <thing>1</thing> </device>",
"<device xmlns=\"http://www.test.com/\"><thing>1</thing></device>", "mismatch");
}
}
}
| |
/*
* ******************************************************************************
* Copyright 2014-2016 Spectra Logic 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. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* ****************************************************************************
*/
// This code is auto-generated, do not modify
using Ds3.Models;
using System;
using System.Net;
namespace Ds3.Calls
{
public class GetStorageDomainsSpectraS3Request : Ds3Request
{
private string _autoEjectUponCron;
public string AutoEjectUponCron
{
get { return _autoEjectUponCron; }
set { WithAutoEjectUponCron(value); }
}
private bool? _autoEjectUponJobCancellation;
public bool? AutoEjectUponJobCancellation
{
get { return _autoEjectUponJobCancellation; }
set { WithAutoEjectUponJobCancellation(value); }
}
private bool? _autoEjectUponJobCompletion;
public bool? AutoEjectUponJobCompletion
{
get { return _autoEjectUponJobCompletion; }
set { WithAutoEjectUponJobCompletion(value); }
}
private bool? _autoEjectUponMediaFull;
public bool? AutoEjectUponMediaFull
{
get { return _autoEjectUponMediaFull; }
set { WithAutoEjectUponMediaFull(value); }
}
private bool? _lastPage;
public bool? LastPage
{
get { return _lastPage; }
set { WithLastPage(value); }
}
private bool? _mediaEjectionAllowed;
public bool? MediaEjectionAllowed
{
get { return _mediaEjectionAllowed; }
set { WithMediaEjectionAllowed(value); }
}
private string _name;
public string Name
{
get { return _name; }
set { WithName(value); }
}
private int? _pageLength;
public int? PageLength
{
get { return _pageLength; }
set { WithPageLength(value); }
}
private int? _pageOffset;
public int? PageOffset
{
get { return _pageOffset; }
set { WithPageOffset(value); }
}
private string _pageStartMarker;
public string PageStartMarker
{
get { return _pageStartMarker; }
set { WithPageStartMarker(value); }
}
private bool? _secureMediaAllocation;
public bool? SecureMediaAllocation
{
get { return _secureMediaAllocation; }
set { WithSecureMediaAllocation(value); }
}
private WriteOptimization? _writeOptimization;
public WriteOptimization? WriteOptimization
{
get { return _writeOptimization; }
set { WithWriteOptimization(value); }
}
public GetStorageDomainsSpectraS3Request WithAutoEjectUponCron(string autoEjectUponCron)
{
this._autoEjectUponCron = autoEjectUponCron;
if (autoEjectUponCron != null)
{
this.QueryParams.Add("auto_eject_upon_cron", autoEjectUponCron);
}
else
{
this.QueryParams.Remove("auto_eject_upon_cron");
}
return this;
}
public GetStorageDomainsSpectraS3Request WithAutoEjectUponJobCancellation(bool? autoEjectUponJobCancellation)
{
this._autoEjectUponJobCancellation = autoEjectUponJobCancellation;
if (autoEjectUponJobCancellation != null)
{
this.QueryParams.Add("auto_eject_upon_job_cancellation", autoEjectUponJobCancellation.ToString());
}
else
{
this.QueryParams.Remove("auto_eject_upon_job_cancellation");
}
return this;
}
public GetStorageDomainsSpectraS3Request WithAutoEjectUponJobCompletion(bool? autoEjectUponJobCompletion)
{
this._autoEjectUponJobCompletion = autoEjectUponJobCompletion;
if (autoEjectUponJobCompletion != null)
{
this.QueryParams.Add("auto_eject_upon_job_completion", autoEjectUponJobCompletion.ToString());
}
else
{
this.QueryParams.Remove("auto_eject_upon_job_completion");
}
return this;
}
public GetStorageDomainsSpectraS3Request WithAutoEjectUponMediaFull(bool? autoEjectUponMediaFull)
{
this._autoEjectUponMediaFull = autoEjectUponMediaFull;
if (autoEjectUponMediaFull != null)
{
this.QueryParams.Add("auto_eject_upon_media_full", autoEjectUponMediaFull.ToString());
}
else
{
this.QueryParams.Remove("auto_eject_upon_media_full");
}
return this;
}
public GetStorageDomainsSpectraS3Request WithLastPage(bool? lastPage)
{
this._lastPage = lastPage;
if (lastPage != null)
{
this.QueryParams.Add("last_page", lastPage.ToString());
}
else
{
this.QueryParams.Remove("last_page");
}
return this;
}
public GetStorageDomainsSpectraS3Request WithMediaEjectionAllowed(bool? mediaEjectionAllowed)
{
this._mediaEjectionAllowed = mediaEjectionAllowed;
if (mediaEjectionAllowed != null)
{
this.QueryParams.Add("media_ejection_allowed", mediaEjectionAllowed.ToString());
}
else
{
this.QueryParams.Remove("media_ejection_allowed");
}
return this;
}
public GetStorageDomainsSpectraS3Request WithName(string name)
{
this._name = name;
if (name != null)
{
this.QueryParams.Add("name", name);
}
else
{
this.QueryParams.Remove("name");
}
return this;
}
public GetStorageDomainsSpectraS3Request WithPageLength(int? pageLength)
{
this._pageLength = pageLength;
if (pageLength != null)
{
this.QueryParams.Add("page_length", pageLength.ToString());
}
else
{
this.QueryParams.Remove("page_length");
}
return this;
}
public GetStorageDomainsSpectraS3Request WithPageOffset(int? pageOffset)
{
this._pageOffset = pageOffset;
if (pageOffset != null)
{
this.QueryParams.Add("page_offset", pageOffset.ToString());
}
else
{
this.QueryParams.Remove("page_offset");
}
return this;
}
public GetStorageDomainsSpectraS3Request WithPageStartMarker(Guid? pageStartMarker)
{
this._pageStartMarker = pageStartMarker.ToString();
if (pageStartMarker != null)
{
this.QueryParams.Add("page_start_marker", pageStartMarker.ToString());
}
else
{
this.QueryParams.Remove("page_start_marker");
}
return this;
}
public GetStorageDomainsSpectraS3Request WithPageStartMarker(string pageStartMarker)
{
this._pageStartMarker = pageStartMarker;
if (pageStartMarker != null)
{
this.QueryParams.Add("page_start_marker", pageStartMarker);
}
else
{
this.QueryParams.Remove("page_start_marker");
}
return this;
}
public GetStorageDomainsSpectraS3Request WithSecureMediaAllocation(bool? secureMediaAllocation)
{
this._secureMediaAllocation = secureMediaAllocation;
if (secureMediaAllocation != null)
{
this.QueryParams.Add("secure_media_allocation", secureMediaAllocation.ToString());
}
else
{
this.QueryParams.Remove("secure_media_allocation");
}
return this;
}
public GetStorageDomainsSpectraS3Request WithWriteOptimization(WriteOptimization? writeOptimization)
{
this._writeOptimization = writeOptimization;
if (writeOptimization != null)
{
this.QueryParams.Add("write_optimization", writeOptimization.ToString());
}
else
{
this.QueryParams.Remove("write_optimization");
}
return this;
}
public GetStorageDomainsSpectraS3Request()
{
}
internal override HttpVerb Verb
{
get
{
return HttpVerb.GET;
}
}
internal override string Path
{
get
{
return "/_rest_/storage_domain";
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using Abp.Collections.Extensions;
using Abp.Configuration.Startup;
using Abp.Dependency;
using Abp.Reflection;
namespace Abp.Runtime.Validation.Interception
{
/// <summary>
/// This class is used to validate a method call (invocation) for method arguments.
/// </summary>
public class MethodInvocationValidator : ITransientDependency
{
private const int MaxRecursiveParameterValidationDepth = 8;
protected MethodInfo Method { get; private set; }
protected object[] ParameterValues { get; private set; }
protected ParameterInfo[] Parameters { get; private set; }
protected List<ValidationResult> ValidationErrors { get; }
protected List<IShouldNormalize> ObjectsToBeNormalized { get; }
private readonly IValidationConfiguration _configuration;
private readonly IIocResolver _iocResolver;
/// <summary>
/// Creates a new <see cref="MethodInvocationValidator"/> instance.
/// </summary>
public MethodInvocationValidator(IValidationConfiguration configuration, IIocResolver iocResolver)
{
_configuration = configuration;
_iocResolver = iocResolver;
ValidationErrors = new List<ValidationResult>();
ObjectsToBeNormalized = new List<IShouldNormalize>();
}
/// <param name="method">Method to be validated</param>
/// <param name="parameterValues">List of arguments those are used to call the <paramref name="method"/>.</param>
public virtual void Initialize(MethodInfo method, object[] parameterValues)
{
Check.NotNull(method, nameof(method));
Check.NotNull(parameterValues, nameof(parameterValues));
Method = method;
ParameterValues = parameterValues;
Parameters = method.GetParameters();
}
/// <summary>
/// Validates the method invocation.
/// </summary>
public void Validate()
{
CheckInitialized();
if (Parameters.IsNullOrEmpty())
{
return;
}
if (!Method.IsPublic)
{
return;
}
if (IsValidationDisabled())
{
return;
}
if (Parameters.Length != ParameterValues.Length)
{
throw new Exception("Method parameter count does not match with argument count!");
}
if (ValidationErrors.Any() && HasSingleNullArgument())
{
ThrowValidationError();
}
for (var i = 0; i < Parameters.Length; i++)
{
ValidateMethodParameter(Parameters[i], ParameterValues[i]);
}
if (ValidationErrors.Any())
{
ThrowValidationError();
}
foreach (var objectToBeNormalized in ObjectsToBeNormalized)
{
objectToBeNormalized.Normalize();
}
}
protected virtual void CheckInitialized()
{
if (Method == null)
{
throw new AbpException("This object has not been initialized. Call Initialize method first.");
}
}
protected virtual bool IsValidationDisabled()
{
if (Method.IsDefined(typeof(EnableValidationAttribute), true))
{
return false;
}
return ReflectionHelper.GetSingleAttributeOfMemberOrDeclaringTypeOrDefault<DisableValidationAttribute>(Method) != null;
}
protected virtual bool HasSingleNullArgument()
{
return Parameters.Length == 1 && ParameterValues[0] == null;
}
protected virtual void ThrowValidationError()
{
throw new AbpValidationException(
"Method arguments are not valid! See ValidationErrors for details.",
ValidationErrors
);
}
/// <summary>
/// Validates given parameter for given value.
/// </summary>
/// <param name="parameterInfo">Parameter of the method to validate</param>
/// <param name="parameterValue">Value to validate</param>
protected virtual void ValidateMethodParameter(ParameterInfo parameterInfo, object parameterValue)
{
if (parameterValue == null)
{
if (!parameterInfo.IsOptional &&
!parameterInfo.IsOut &&
!TypeHelper.IsPrimitiveExtendedIncludingNullable(parameterInfo.ParameterType))
{
ValidationErrors.Add(new ValidationResult(parameterInfo.Name + " is null!", new[] { parameterInfo.Name }));
}
return;
}
ValidateObjectRecursively(parameterValue, 1);
}
protected virtual void ValidateObjectRecursively(object validatingObject, int currentDepth)
{
if (currentDepth > MaxRecursiveParameterValidationDepth)
{
return;
}
if (validatingObject == null)
{
return;
}
SetDataAnnotationAttributeErrors(validatingObject);
//Validate items of enumerable
if (validatingObject is IEnumerable && !(validatingObject is IQueryable))
{
foreach (var item in (validatingObject as IEnumerable))
{
ValidateObjectRecursively(item, currentDepth + 1);
}
}
//Custom validations
(validatingObject as ICustomValidate)?.AddValidationErrors(
new CustomValidationContext(
ValidationErrors,
_iocResolver
)
);
//Add list to be normalized later
if (validatingObject is IShouldNormalize)
{
ObjectsToBeNormalized.Add(validatingObject as IShouldNormalize);
}
//Do not recursively validate for enumerable objects
if (validatingObject is IEnumerable)
{
return;
}
var validatingObjectType = validatingObject.GetType();
//Do not recursively validate for primitive objects
if (TypeHelper.IsPrimitiveExtendedIncludingNullable(validatingObjectType))
{
return;
}
if (_configuration.IgnoredTypes.Any(t => t.IsInstanceOfType(validatingObject)))
{
return;
}
var properties = TypeDescriptor.GetProperties(validatingObject).Cast<PropertyDescriptor>();
foreach (var property in properties)
{
if (property.Attributes.OfType<DisableValidationAttribute>().Any())
{
continue;
}
ValidateObjectRecursively(property.GetValue(validatingObject), currentDepth + 1);
}
}
/// <summary>
/// Checks all properties for DataAnnotations attributes.
/// </summary>
protected virtual void SetDataAnnotationAttributeErrors(object validatingObject)
{
var properties = TypeDescriptor.GetProperties(validatingObject).Cast<PropertyDescriptor>();
foreach (var property in properties)
{
var validationAttributes = property.Attributes.OfType<ValidationAttribute>().ToArray();
if (validationAttributes.IsNullOrEmpty())
{
continue;
}
var validationContext = new ValidationContext(validatingObject)
{
DisplayName = property.DisplayName,
MemberName = property.Name
};
foreach (var attribute in validationAttributes)
{
var result = attribute.GetValidationResult(property.GetValue(validatingObject), validationContext);
if (result != null)
{
ValidationErrors.Add(result);
}
}
}
if (validatingObject is IValidatableObject)
{
var results = (validatingObject as IValidatableObject).Validate(new ValidationContext(validatingObject));
ValidationErrors.AddRange(results);
}
}
}
}
| |
// MIT License
//
// Copyright (c) 2009-2017 Luca Piccioni
//
// 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.
//
// This file is automatically generated
// ReSharper disable InconsistentNaming
// ReSharper disable InheritdocConsiderUsage
namespace OpenGL
{
public partial class Glx
{
/// <summary>
/// Extension support listing.
/// </summary>
public partial class Extensions
{
/// <summary>
/// Support for extension GLX_ARB_get_proc_address.
/// </summary>
[Extension("GLX_ARB_get_proc_address")]
public bool GetProcAddress_ARB;
/// <summary>
/// Support for extension GLX_ARB_multisample.
/// </summary>
[Extension("GLX_ARB_multisample")]
public bool Multisample_ARB;
/// <summary>
/// Support for extension GLX_ARB_vertex_buffer_object.
/// </summary>
[Extension("GLX_ARB_vertex_buffer_object")]
public bool VertexBufferObject_ARB;
/// <summary>
/// Support for extension GLX_ARB_fbconfig_float.
/// </summary>
[Extension("GLX_ARB_fbconfig_float")]
public bool FbconfigFloat_ARB;
/// <summary>
/// Support for extension GLX_ARB_framebuffer_sRGB.
/// </summary>
[Extension("GLX_ARB_framebuffer_sRGB")]
public bool FramebufferSRGB_ARB;
/// <summary>
/// Support for extension GLX_ARB_create_context.
/// </summary>
[Extension("GLX_ARB_create_context")]
public bool CreateContext_ARB;
/// <summary>
/// Support for extension GLX_ARB_create_context_profile.
/// </summary>
[Extension("GLX_ARB_create_context_profile")]
public bool CreateContextProfile_ARB;
/// <summary>
/// Support for extension GLX_ARB_create_context_robustness.
/// </summary>
[Extension("GLX_ARB_create_context_robustness")]
public bool CreateContextRobustness_ARB;
/// <summary>
/// Support for extension GLX_ARB_robustness_application_isolation.
/// </summary>
[Extension("GLX_ARB_robustness_application_isolation")]
[Extension("GLX_ARB_robustness_share_group_isolation")]
public bool RobustnessApplicationIsolation_ARB;
/// <summary>
/// Support for extension GLX_ARB_context_flush_control.
/// </summary>
[Extension("GLX_ARB_context_flush_control")]
public bool ContextFlushControl_ARB;
/// <summary>
/// Support for extension GLX_ARB_create_context_no_error.
/// </summary>
[Extension("GLX_ARB_create_context_no_error")]
public bool CreateContextNoError_ARB;
/// <summary>
/// Support for extension GLX_SGIS_multisample.
/// </summary>
[Extension("GLX_SGIS_multisample")]
public bool Multisample_SGIS;
/// <summary>
/// Support for extension GLX_EXT_visual_info.
/// </summary>
[Extension("GLX_EXT_visual_info")]
public bool VisualInfo_EXT;
/// <summary>
/// Support for extension GLX_SGI_swap_control.
/// </summary>
[Extension("GLX_SGI_swap_control")]
public bool SwapControl_SGI;
/// <summary>
/// Support for extension GLX_SGI_video_sync.
/// </summary>
[Extension("GLX_SGI_video_sync")]
public bool VideoSync_SGI;
/// <summary>
/// Support for extension GLX_SGI_make_current_read.
/// </summary>
[Extension("GLX_SGI_make_current_read")]
public bool MakeCurrentRead_SGI;
/// <summary>
/// Support for extension GLX_SGIX_video_source.
/// </summary>
[Extension("GLX_SGIX_video_source")]
public bool VideoSource_SGIX;
/// <summary>
/// Support for extension GLX_EXT_visual_rating.
/// </summary>
[Extension("GLX_EXT_visual_rating")]
public bool VisualRating_EXT;
/// <summary>
/// Support for extension GLX_EXT_import_context.
/// </summary>
[Extension("GLX_EXT_import_context")]
public bool ImportContext_EXT;
/// <summary>
/// Support for extension GLX_SGIX_fbconfig.
/// </summary>
[Extension("GLX_SGIX_fbconfig")]
public bool Fbconfig_SGIX;
/// <summary>
/// Support for extension GLX_SGIX_pbuffer.
/// </summary>
[Extension("GLX_SGIX_pbuffer")]
public bool Pbuffer_SGIX;
/// <summary>
/// Support for extension GLX_SGI_cushion.
/// </summary>
[Extension("GLX_SGI_cushion")]
public bool Cushion_SGI;
/// <summary>
/// Support for extension GLX_SGIX_video_resize.
/// </summary>
[Extension("GLX_SGIX_video_resize")]
public bool VideoResize_SGIX;
/// <summary>
/// Support for extension GLX_SGIX_swap_group.
/// </summary>
[Extension("GLX_SGIX_swap_group")]
public bool SwapGroup_SGIX;
/// <summary>
/// Support for extension GLX_SGIX_swap_barrier.
/// </summary>
[Extension("GLX_SGIX_swap_barrier")]
public bool SwapBarrier_SGIX;
/// <summary>
/// Support for extension GLX_SGIS_blended_overlay.
/// </summary>
[Extension("GLX_SGIS_blended_overlay")]
public bool BlendedOverlay_SGIS;
/// <summary>
/// Support for extension GLX_SUN_get_transparent_index.
/// </summary>
[Extension("GLX_SUN_get_transparent_index")]
public bool GetTransparentIndex_SUN;
/// <summary>
/// Support for extension GLX_MESA_copy_sub_buffer.
/// </summary>
[Extension("GLX_MESA_copy_sub_buffer")]
public bool CopySubBuffer_MESA;
/// <summary>
/// Support for extension GLX_MESA_pixmap_colormap.
/// </summary>
[Extension("GLX_MESA_pixmap_colormap")]
public bool PixmapColormap_MESA;
/// <summary>
/// Support for extension GLX_MESA_release_buffers.
/// </summary>
[Extension("GLX_MESA_release_buffers")]
public bool ReleaseBuffers_MESA;
/// <summary>
/// Support for extension GLX_MESA_set_3dfx_mode.
/// </summary>
[Extension("GLX_MESA_set_3dfx_mode")]
public bool Set3dfxMode_MESA;
/// <summary>
/// Support for extension GLX_SGIX_visual_select_group.
/// </summary>
[Extension("GLX_SGIX_visual_select_group")]
public bool VisualSelectGroup_SGIX;
/// <summary>
/// Support for extension GLX_OML_swap_method.
/// </summary>
[Extension("GLX_OML_swap_method")]
public bool SwapMethod_OML;
/// <summary>
/// Support for extension GLX_OML_sync_control.
/// </summary>
[Extension("GLX_OML_sync_control")]
public bool SyncControl_OML;
/// <summary>
/// Support for extension GLX_SGIX_hyperpipe.
/// </summary>
[Extension("GLX_SGIX_hyperpipe")]
public bool Hyperpipe_SGIX;
/// <summary>
/// Support for extension GLX_MESA_agp_offset.
/// </summary>
[Extension("GLX_MESA_agp_offset")]
public bool AgpOffset_MESA;
/// <summary>
/// Support for extension GLX_EXT_fbconfig_packed_float.
/// </summary>
[Extension("GLX_EXT_fbconfig_packed_float")]
public bool FbconfigPackedFloat_EXT;
/// <summary>
/// Support for extension GLX_EXT_framebuffer_sRGB.
/// </summary>
[Extension("GLX_EXT_framebuffer_sRGB")]
public bool FramebufferSRGB_EXT;
/// <summary>
/// Support for extension GLX_EXT_texture_from_pixmap.
/// </summary>
[Extension("GLX_EXT_texture_from_pixmap")]
public bool TextureFromPixmap_EXT;
/// <summary>
/// Support for extension GLX_NV_present_video.
/// </summary>
[Extension("GLX_NV_present_video")]
public bool PresentVideo_NV;
/// <summary>
/// Support for extension GLX_NV_video_out.
/// </summary>
[Extension("GLX_NV_video_out")]
public bool VideoOut_NV;
/// <summary>
/// Support for extension GLX_NV_swap_group.
/// </summary>
[Extension("GLX_NV_swap_group")]
public bool SwapGroup_NV;
/// <summary>
/// Support for extension GLX_NV_video_capture.
/// </summary>
[Extension("GLX_NV_video_capture")]
public bool VideoCapture_NV;
/// <summary>
/// Support for extension GLX_NV_copy_image.
/// </summary>
[Extension("GLX_NV_copy_image")]
public bool CopyImage_NV;
/// <summary>
/// Support for extension GLX_INTEL_swap_event.
/// </summary>
[Extension("GLX_INTEL_swap_event")]
public bool SwapEvent_INTEL;
/// <summary>
/// Support for extension GLX_AMD_gpu_association.
/// </summary>
[Extension("GLX_AMD_gpu_association")]
public bool GpuAssociation_AMD;
/// <summary>
/// Support for extension GLX_EXT_create_context_es_profile.
/// </summary>
[Extension("GLX_EXT_create_context_es_profile")]
[Extension("GLX_EXT_create_context_es2_profile")]
public bool CreateContextEsProfile_EXT;
/// <summary>
/// Support for extension GLX_EXT_swap_control_tear.
/// </summary>
[Extension("GLX_EXT_swap_control_tear")]
public bool SwapControlTear_EXT;
/// <summary>
/// Support for extension GLX_EXT_buffer_age.
/// </summary>
[Extension("GLX_EXT_buffer_age")]
public bool BufferAge_EXT;
/// <summary>
/// Support for extension GLX_NV_delay_before_swap.
/// </summary>
[Extension("GLX_NV_delay_before_swap")]
public bool DelayBeforeSwap_NV;
/// <summary>
/// Support for extension GLX_MESA_query_renderer.
/// </summary>
[Extension("GLX_MESA_query_renderer")]
public bool QueryRenderer_MESA;
/// <summary>
/// Support for extension GLX_NV_copy_buffer.
/// </summary>
[Extension("GLX_NV_copy_buffer")]
public bool CopyBuffer_NV;
/// <summary>
/// Support for extension GLX_3DFX_multisample.
/// </summary>
[Extension("GLX_3DFX_multisample")]
public bool Multisample_3DFX;
/// <summary>
/// Support for extension GLX_MESA_swap_control.
/// </summary>
[Extension("GLX_MESA_swap_control")]
public bool SwapControl_MESA;
/// <summary>
/// Support for extension GLX_NV_float_buffer.
/// </summary>
[Extension("GLX_NV_float_buffer")]
public bool FloatBuffer_NV;
/// <summary>
/// Support for extension GLX_NV_multisample_coverage.
/// </summary>
[Extension("GLX_NV_multisample_coverage")]
public bool MultisampleCoverage_NV;
/// <summary>
/// Support for extension GLX_NV_robustness_video_memory_purge.
/// </summary>
[Extension("GLX_NV_robustness_video_memory_purge")]
public bool RobustnessVideoMemoryPurge_NV;
/// <summary>
/// Support for extension GLX_SGIS_shared_multisample.
/// </summary>
[Extension("GLX_SGIS_shared_multisample")]
public bool SharedMultisample_SGIS;
/// <summary>
/// Support for extension GLX_SGIX_dmbuffer.
/// </summary>
[Extension("GLX_SGIX_dmbuffer")]
public bool Dmbuffer_SGIX;
/// <summary>
/// Support for extension GLX_EXT_swap_control.
/// </summary>
[Extension("GLX_EXT_swap_control")]
public bool SwapControl_EXT;
/// <summary>
/// Support for extension GLX_EXT_stereo_tree.
/// </summary>
[Extension("GLX_EXT_stereo_tree")]
public bool StereoTree_EXT;
/// <summary>
/// Support for extension GLX_EXT_no_config_context.
/// </summary>
[Extension("GLX_EXT_no_config_context")]
public bool NoConfigContext_EXT;
/// <summary>
/// Support for extension GLX_EXT_libglvnd.
/// </summary>
[Extension("GLX_EXT_libglvnd")]
public bool Libglvnd_EXT;
}
}
}
| |
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using System.ComponentModel;
using System.Threading;
using System.Collections;
using PubNubMessaging.Core;
namespace PubNubMessaging.Tests
{
[TestFixture]
public class WhenDetailedHistoryIsRequested
{
ManualResetEvent mreDetailedHistory = new ManualResetEvent(false);
ManualResetEvent mreMessageCount10ReverseTrue = new ManualResetEvent(false);
ManualResetEvent mreMessageStartReverseTrue = new ManualResetEvent(false);
ManualResetEvent mrePublish = new ManualResetEvent(false);
ManualResetEvent grantManualEvent = new ManualResetEvent(false);
const string messageForNoStorePublish = "Pubnub Messaging With No Storage";
const string messageForPublish = "Pubnub Messaging API 1";
bool messageReceived = false;
bool message10ReverseTrueReceived = false;
bool messageStartReverseTrue = false;
bool receivedGrantMessage = false;
int expectedCountAtStartTimeWithReverseTrue=0;
long startTimeWithReverseTrue = 0;
bool isPublished = false;
long publishTimetokenForHistory = 0;
string currentTestCase = "";
int manualResetEventsWaitTimeout = 310 * 1000;
int[] firstPublishSet;
double[] secondPublishSet;
long starttime = Int64.MaxValue;
long midtime = Int64.MaxValue;
long endtime = Int64.MaxValue;
Pubnub pubnub = null;
[TestFixtureSetUp]
public void Init()
{
if (!PubnubCommon.PAMEnabled) return;
receivedGrantMessage = false;
pubnub = new Pubnub(PubnubCommon.PublishKey, PubnubCommon.SubscribeKey, PubnubCommon.SecretKey, "", false);
PubnubUnitTest unitTest = new PubnubUnitTest();
unitTest.TestClassName = "GrantRequestUnitTest";
unitTest.TestCaseName = "Init";
pubnub.PubnubUnitTest = unitTest;
string channel = "hello_my_channel";
pubnub.GrantAccess<string>(channel, true, true, 20, ThenDetailedHistoryInitializeShouldReturnGrantMessage, DummyErrorCallback);
Thread.Sleep(1000);
grantManualEvent.WaitOne();
pubnub.EndPendingRequests();
pubnub.PubnubUnitTest = null;
pubnub = null;
Assert.IsTrue(receivedGrantMessage, "WhenDetailedHistoryIsRequested Grant access failed.");
}
[Test]
public void DetailHistoryNoStoreShouldNotGetMessage()
{
messageReceived = true;
isPublished = false;
pubnub = new Pubnub(PubnubCommon.PublishKey, PubnubCommon.SubscribeKey, "", "", false);
PubnubUnitTest unitTest = new PubnubUnitTest();
unitTest.TestClassName = "WhenDetailedHistoryIsRequested";
unitTest.TestCaseName = "DetailHistoryNoStoreShouldNotGetMessage";
pubnub.PubnubUnitTest = unitTest;
string channel = "hello_my_channel";
string message = messageForNoStorePublish;
mrePublish = new ManualResetEvent(false);
pubnub.Publish<string>(channel, message, false, ReturnRegularPublishCodeCallback, DummyErrorCallback);
manualResetEventsWaitTimeout = (unitTest.EnableStubTest) ? 1000 : 310 * 1000;
mrePublish.WaitOne(manualResetEventsWaitTimeout);
if (!isPublished)
{
Assert.IsTrue(isPublished, "No Store Publish Failed");
}
else
{
Thread.Sleep(1000);
mreDetailedHistory = new ManualResetEvent(false);
pubnub.DetailedHistory<string>(channel, -1, publishTimetokenForHistory, -1, false, CaptureNoStoreDetailedHistoryCallback, DummyErrorCallback);
mreDetailedHistory.WaitOne(manualResetEventsWaitTimeout);
Assert.IsTrue(!messageReceived, "Message stored for Publish when no store is expected");
}
pubnub.EndPendingRequests();
pubnub.PubnubUnitTest = null;
pubnub = null;
}
[Test]
public void DetailHistoryShouldReturnDecryptMessage()
{
messageReceived = false;
isPublished = false;
pubnub = new Pubnub(PubnubCommon.PublishKey, PubnubCommon.SubscribeKey, "", "enigma", false);
PubnubUnitTest unitTest = new PubnubUnitTest();
unitTest.TestClassName = "WhenDetailedHistoryIsRequested";
unitTest.TestCaseName = "DetailHistoryShouldReturnDecryptMessage";
pubnub.PubnubUnitTest = unitTest;
string channel = "hello_my_channel";
string message = messageForPublish;
mrePublish = new ManualResetEvent(false);
pubnub.Publish<string>(channel, message, true, ReturnRegularPublishCodeCallback, DummyErrorCallback);
manualResetEventsWaitTimeout = (unitTest.EnableStubTest) ? 1000 : 310 * 1000;
mrePublish.WaitOne(manualResetEventsWaitTimeout);
if (!isPublished)
{
Assert.IsTrue(isPublished, "Encrypted message Publish Failed");
}
else
{
Thread.Sleep(1000);
mreDetailedHistory = new ManualResetEvent(false);
pubnub.DetailedHistory<string>(channel, publishTimetokenForHistory-1, publishTimetokenForHistory,1, false, CaptureRegularDetailedHistoryCallback, DummyErrorCallback);
mreDetailedHistory.WaitOne(manualResetEventsWaitTimeout);
Assert.IsTrue(messageReceived, "Encrypted message not showed up in history");
}
pubnub.EndPendingRequests();
pubnub.PubnubUnitTest = null;
pubnub = null;
}
[Test]
public void DetailHistoryCount10ReturnsRecords()
{
messageReceived = false;
pubnub = new Pubnub(PubnubCommon.PublishKey, PubnubCommon.SubscribeKey, "", "", false);
PubnubUnitTest unitTest = new PubnubUnitTest();
unitTest.TestClassName = "WhenDetailedHistoryIsRequested";
unitTest.TestCaseName = "DetailHistoryCount10ReturnsRecords";
pubnub.PubnubUnitTest = unitTest;
string channel = "hello_my_channel";
pubnub.DetailedHistory<string>(channel, 10, DetailedHistoryCount10Callback, DummyErrorCallback);
mreDetailedHistory.WaitOne(310 * 1000);
pubnub.EndPendingRequests();
pubnub.PubnubUnitTest = null;
pubnub = null;
Assert.IsTrue(messageReceived, "Detailed History Failed");
}
[Test]
public void DetailHistoryCount10ReverseTrueReturnsRecords()
{
message10ReverseTrueReceived = false;
pubnub = new Pubnub(PubnubCommon.PublishKey, PubnubCommon.SubscribeKey, "", "", false);
PubnubUnitTest unitTest = new PubnubUnitTest();
unitTest.TestClassName = "WhenDetailedHistoryIsRequested";
unitTest.TestCaseName = "DetailHistoryCount10ReverseTrueReturnsRecords";
pubnub.PubnubUnitTest = unitTest;
string channel = "hello_my_channel";
pubnub.DetailedHistory<string>(channel, -1, -1, 10, true, DetailedHistoryCount10ReverseTrueCallback, DummyErrorCallback);
mreMessageCount10ReverseTrue.WaitOne(310 * 1000);
pubnub.EndPendingRequests();
pubnub.PubnubUnitTest = null;
pubnub = null;
Assert.IsTrue(message10ReverseTrueReceived, "Detailed History Failed");
}
[Test]
public void DetailedHistoryStartWithReverseTrue()
{
expectedCountAtStartTimeWithReverseTrue = 0;
messageStartReverseTrue = false;
pubnub = new Pubnub(PubnubCommon.PublishKey, PubnubCommon.SubscribeKey, "", "", false);
PubnubUnitTest unitTest = new PubnubUnitTest();
unitTest.TestClassName = "WhenDetailedHistoryIsRequested";
unitTest.TestCaseName = "DetailedHistoryStartWithReverseTrue";
pubnub.PubnubUnitTest = unitTest;
string channel = "hello_my_channel";
//startTimeWithReverseTrue = Pubnub.TranslateDateTimeToPubnubUnixNanoSeconds(new DateTime(2012, 12, 1));
startTimeWithReverseTrue = 0;
pubnub.Time<string>((s) => { List<object> m = pubnub.JsonPluggableLibrary.DeserializeToListOfObject(s); startTimeWithReverseTrue = Convert.ToInt64(m[0]); }, (e) => { });
for (int index = 0; index < 10; index++)
{
mrePublish = new ManualResetEvent(false);
pubnub.Publish<string>(channel,
string.Format("DetailedHistoryStartTimeWithReverseTrue {0}", index),
DetailedHistorySamplePublishCallback, DummyErrorCallback);
mrePublish.WaitOne();
}
Thread.Sleep(2000);
mreMessageStartReverseTrue = new ManualResetEvent(false);
pubnub.DetailedHistory<string>(channel, startTimeWithReverseTrue, DetailedHistoryStartWithReverseTrueCallback, DummyErrorCallback, true);
Thread.Sleep(2000);
mreMessageStartReverseTrue.WaitOne(310 * 1000);
pubnub.EndPendingRequests();
pubnub.PubnubUnitTest = null;
pubnub = null;
Assert.IsTrue(messageStartReverseTrue, "Detailed History with Start and Reverse True Failed");
}
[Test]
public void DetailHistoryWithNullKeysReturnsError()
{
currentTestCase = "DetailHistoryWithNullKeysReturnsError";
messageReceived = false;
pubnub = new Pubnub(null, null, null, null, false);
PubnubUnitTest unitTest = new PubnubUnitTest();
unitTest.TestClassName = "WhenDetailedHistoryIsRequested";
unitTest.TestCaseName = "DetailHistoryWithNullKeysReturnsError";
pubnub.PubnubUnitTest = unitTest;
string channel = "hello_my_channel";
mreDetailedHistory = new ManualResetEvent(false);
pubnub.DetailedHistory<string>(channel, -1, -1, 10, true, DetailHistoryWithNullKeyseDummyCallback, DummyErrorCallback);
mreDetailedHistory.WaitOne(310 * 1000);
pubnub.EndPendingRequests();
pubnub.PubnubUnitTest = null;
pubnub = null;
Assert.IsTrue(messageReceived, "Detailed History With Null Keys Failed");
}
[Test]
public void DetailHistoryShouldReturnUnencrypedSecretMessage()
{
messageReceived = false;
CommonDetailedHistoryShouldReturnUnencryptedMessageBasedOnParams(PubnubCommon.SecretKey, "", false);
Assert.IsTrue(messageReceived, "DetailHistoryShouldReturnUnencrypedSecretMessage - Detailed History Result not expected");
}
[Test]
public void DetailHistoryShouldReturnUnencrypedMessage()
{
messageReceived = false;
CommonDetailedHistoryShouldReturnUnencryptedMessageBasedOnParams("", "", false);
Assert.IsTrue(messageReceived, "DetailHistoryShouldReturnUnencrypedMessage - Detailed History Result not expected");
}
[Test]
public void DetailHistoryShouldReturnUnencrypedSecretSSLMessage()
{
messageReceived = false;
CommonDetailedHistoryShouldReturnUnencryptedMessageBasedOnParams(PubnubCommon.SecretKey, "", true);
Assert.IsTrue(messageReceived, "DetailHistoryShouldReturnUnencrypedSecretSSLMessage - Detailed History Result not expected");
}
[Test]
public void DetailHistoryShouldReturnUnencrypedSSLMessage()
{
messageReceived = false;
CommonDetailedHistoryShouldReturnUnencryptedMessageBasedOnParams("", "", true);
Assert.IsTrue(messageReceived, "DetailHistoryShouldReturnUnencrypedSSLMessage - Detailed History Result not expected");
}
[Test]
public void DetailHistoryShouldReturnEncrypedMessage()
{
messageReceived = false;
CommonDetailedHistoryShouldReturnEncryptedMessageBasedOnParams("", "enigma", false);
Assert.IsTrue(messageReceived, "DetailHistoryShouldReturnEncrypedMessage - Detailed History Result not expected");
}
[Test]
public void DetailHistoryShouldReturnEncrypedSecretMessage()
{
messageReceived = false;
CommonDetailedHistoryShouldReturnEncryptedMessageBasedOnParams(PubnubCommon.SecretKey, "enigma", false);
Assert.IsTrue(messageReceived, "DetailHistoryShouldReturnEncrypedSecretMessage - Detailed History Result not expected");
}
[Test]
public void DetailHistoryShouldReturnEncrypedSecretSSLMessage()
{
messageReceived = false;
CommonDetailedHistoryShouldReturnEncryptedMessageBasedOnParams(PubnubCommon.SecretKey, "enigma", true);
Assert.IsTrue(messageReceived, "DetailHistoryShouldReturnEncrypedSecretSSLMessage - Detailed History Result not expected");
}
[Test]
public void DetailHistoryShouldReturnEncrypedSSLMessage()
{
messageReceived = false;
CommonDetailedHistoryShouldReturnEncryptedMessageBasedOnParams("", "enigma", true);
Assert.IsTrue(messageReceived, "DetailHistoryShouldReturnEncrypedSSLMessage - Detailed History Result not expected");
}
private void CommonDetailedHistoryShouldReturnEncryptedMessageBasedOnParams(string secretKey, string cipherKey, bool ssl)
{
messageReceived = false;
isPublished = false;
int totalMessages = 10;
starttime = 0;
midtime = 0;
endtime = 0;
pubnub = new Pubnub(PubnubCommon.PublishKey, PubnubCommon.SubscribeKey, secretKey, cipherKey, ssl);
pubnub.SessionUUID = "myuuid";
string channel = "hello_my_channel";
PubnubUnitTest unitTest = new PubnubUnitTest();
unitTest.TestClassName = "WhenDetailedHistoryIsRequested";
unitTest.TestCaseName = "DetailHistoryShouldReturnServerTime1";
pubnub.PubnubUnitTest = unitTest;
pubnub.Time<string>((s) => { List<object> m = pubnub.JsonPluggableLibrary.DeserializeToListOfObject(s); starttime = Convert.ToInt64(m[0]); }, (e) => { });
Thread.Sleep(1000);
Console.WriteLine(string.Format("Start Time = {0}", starttime));
firstPublishSet = new int[totalMessages / 2];
unitTest = new PubnubUnitTest();
unitTest.TestClassName = "WhenDetailedHistoryIsRequested";
unitTest.TestCaseName = "DetailedHistoryShouldReturnEncryptedMessageBasedOnParams";
pubnub.PubnubUnitTest = unitTest;
for (int index = 0; index < totalMessages / 2; index++)
{
object message = index;
firstPublishSet[index] = index;
mrePublish = new ManualResetEvent(false);
Thread.Sleep(1000);
pubnub.Publish<string>(channel, message, true, ReturnRegularPublishCodeCallback, DummyErrorCallback);
manualResetEventsWaitTimeout = (unitTest.EnableStubTest) ? 1000 : 310 * 1000;
mrePublish.WaitOne(manualResetEventsWaitTimeout);
Console.WriteLine(string.Format("Message #{0} publish {1}", index, (isPublished) ? "SUCCESS" : "FAILED"));
}
unitTest = new PubnubUnitTest();
unitTest.TestClassName = "WhenDetailedHistoryIsRequested";
unitTest.TestCaseName = "DetailHistoryShouldReturnServerTime2";
pubnub.PubnubUnitTest = unitTest;
pubnub.Time<string>((s) => { List<object> m = pubnub.JsonPluggableLibrary.DeserializeToListOfObject(s); midtime = Convert.ToInt64(m[0]); }, (e) => { });
Thread.Sleep(1000);
Console.WriteLine(string.Format("Mid Time = {0}", midtime));
secondPublishSet = new double[totalMessages / 2];
int arrayIndex = 0;
unitTest = new PubnubUnitTest();
unitTest.TestClassName = "WhenDetailedHistoryIsRequested";
unitTest.TestCaseName = "DetailedHistoryShouldReturnEncryptedMessageBasedOnParams";
pubnub.PubnubUnitTest = unitTest;
for (int index = totalMessages / 2; index < totalMessages; index++)
{
object message = (double)index + 0.1D;
secondPublishSet[arrayIndex] = (double)index + 0.1D;
arrayIndex++;
mrePublish = new ManualResetEvent(false);
Thread.Sleep(1000);
pubnub.Publish<string>(channel, message, true, ReturnRegularPublishCodeCallback, DummyErrorCallback);
manualResetEventsWaitTimeout = (unitTest.EnableStubTest) ? 1000 : 310 * 1000;
mrePublish.WaitOne(manualResetEventsWaitTimeout);
Console.WriteLine(string.Format("Message #{0} publish {1}", index, (isPublished) ? "SUCCESS" : "FAILED"));
}
unitTest = new PubnubUnitTest();
unitTest.TestClassName = "WhenDetailedHistoryIsRequested";
unitTest.TestCaseName = "DetailHistoryShouldReturnServerTime3";
pubnub.PubnubUnitTest = unitTest;
pubnub.Time<string>((s) => { List<object> m = pubnub.JsonPluggableLibrary.DeserializeToListOfObject(s); endtime = Convert.ToInt64(m[0]); }, (e) => { });
Thread.Sleep(1000);
Console.WriteLine(string.Format("End Time = {0}", endtime));
unitTest = new PubnubUnitTest();
unitTest.TestClassName = "WhenDetailedHistoryIsRequested";
unitTest.TestCaseName = "DetailedHistoryShouldReturnEncryptedMessageBasedOnParams";
pubnub.PubnubUnitTest = unitTest;
Console.WriteLine("Detailed History with Start & End");
mreDetailedHistory = new ManualResetEvent(false);
pubnub.DetailedHistory<string>(channel, starttime, midtime, totalMessages / 2, true, CaptureFirstPublishSetRegularDetailedHistoryCallback, DummyErrorCallback);
mreDetailedHistory.WaitOne(manualResetEventsWaitTimeout);
if (messageReceived)
{
Console.WriteLine("DetailedHistory with start & reverse = true");
mreDetailedHistory = new ManualResetEvent(false);
pubnub.DetailedHistory<string>(channel, midtime - 1, -1, totalMessages / 2, true, CaptureSecondPublishSetRegularDetailedHistoryCallback, DummyErrorCallback);
mreDetailedHistory.WaitOne(manualResetEventsWaitTimeout);
}
if (messageReceived)
{
Console.WriteLine("DetailedHistory with start & reverse = false");
mreDetailedHistory = new ManualResetEvent(false);
pubnub.DetailedHistory<string>(channel, midtime - 1, -1, totalMessages / 2, false, CaptureFirstPublishSetRegularDetailedHistoryCallback, DummyErrorCallback);
mreDetailedHistory.WaitOne(manualResetEventsWaitTimeout);
}
pubnub.EndPendingRequests();
pubnub.PubnubUnitTest = null;
pubnub = null;
}
private void CommonDetailedHistoryShouldReturnUnencryptedMessageBasedOnParams(string secretKey, string cipherKey, bool ssl)
{
messageReceived = false;
isPublished = false;
int totalMessages = 10;
starttime = 0;
midtime = 0;
endtime = 0;
pubnub = new Pubnub(PubnubCommon.PublishKey, PubnubCommon.SubscribeKey, secretKey, cipherKey, ssl);
pubnub.SessionUUID = "myuuid";
string channel = "hello_my_channel";
PubnubUnitTest unitTest = new PubnubUnitTest();
unitTest.TestClassName = "WhenDetailedHistoryIsRequested";
unitTest.TestCaseName = "DetailHistoryShouldReturnServerTime1";
pubnub.PubnubUnitTest = unitTest;
pubnub.Time<string>((s) => { List<object> m = pubnub.JsonPluggableLibrary.DeserializeToListOfObject(s); starttime = Convert.ToInt64(m[0]); }, (e) => { });
Console.WriteLine(string.Format("Start Time = {0}", starttime));
firstPublishSet = new int[totalMessages / 2];
unitTest = new PubnubUnitTest();
unitTest.TestClassName = "WhenDetailedHistoryIsRequested";
unitTest.TestCaseName = "DetailedHistoryShouldReturnUnencryptedMessageBasedOnParams";
pubnub.PubnubUnitTest = unitTest;
for (int index = 0; index < totalMessages / 2; index++)
{
object message = index;
firstPublishSet[index] = index;
mrePublish = new ManualResetEvent(false);
Thread.Sleep(1000);
pubnub.Publish<string>(channel, message, true, ReturnRegularPublishCodeCallback, DummyErrorCallback);
manualResetEventsWaitTimeout = (unitTest.EnableStubTest) ? 1000 : 310 * 1000;
mrePublish.WaitOne(manualResetEventsWaitTimeout);
Console.WriteLine(string.Format("Message #{0} publish {1}", index, (isPublished) ? "SUCCESS" : "FAILED"));
}
unitTest = new PubnubUnitTest();
unitTest.TestClassName = "WhenDetailedHistoryIsRequested";
unitTest.TestCaseName = "DetailHistoryShouldReturnServerTime2";
pubnub.PubnubUnitTest = unitTest;
pubnub.Time<string>((s) => { List<object> m = pubnub.JsonPluggableLibrary.DeserializeToListOfObject(s); midtime = Convert.ToInt64(m[0]); }, (e) => { });
Console.WriteLine(string.Format("Mid Time = {0}", midtime));
secondPublishSet = new double[totalMessages / 2];
int arrayIndex = 0;
unitTest = new PubnubUnitTest();
unitTest.TestClassName = "WhenDetailedHistoryIsRequested";
unitTest.TestCaseName = "DetailedHistoryShouldReturnUnencryptedMessageBasedOnParams";
pubnub.PubnubUnitTest = unitTest;
for (int index = totalMessages / 2; index < totalMessages; index++)
{
object message = (double)index + 0.1D;
secondPublishSet[arrayIndex] = (double)index + 0.1D;
arrayIndex++;
mrePublish = new ManualResetEvent(false);
Thread.Sleep(1000);
pubnub.Publish<string>(channel, message, true, ReturnRegularPublishCodeCallback, DummyErrorCallback);
manualResetEventsWaitTimeout = (unitTest.EnableStubTest) ? 1000 : 310 * 1000;
mrePublish.WaitOne(manualResetEventsWaitTimeout);
Console.WriteLine(string.Format("Message #{0} publish {1}", index, (isPublished) ? "SUCCESS" : "FAILED"));
}
unitTest = new PubnubUnitTest();
unitTest.TestClassName = "WhenDetailedHistoryIsRequested";
unitTest.TestCaseName = "DetailHistoryShouldReturnServerTime3";
pubnub.PubnubUnitTest = unitTest;
pubnub.Time<string>((s) => { List<object> m = pubnub.JsonPluggableLibrary.DeserializeToListOfObject(s); endtime = Convert.ToInt64(m[0]); }, (e) => { });
Console.WriteLine(string.Format("End Time = {0}", endtime));
Thread.Sleep(1000);
unitTest = new PubnubUnitTest();
unitTest.TestClassName = "WhenDetailedHistoryIsRequested";
unitTest.TestCaseName = "DetailedHistoryShouldReturnUnencryptedMessageBasedOnParams";
pubnub.PubnubUnitTest = unitTest;
Console.WriteLine("Detailed History with Start & End");
mreDetailedHistory = new ManualResetEvent(false);
pubnub.DetailedHistory<string>(channel, starttime, midtime, totalMessages / 2, true, CaptureFirstPublishSetRegularDetailedHistoryCallback, DummyErrorCallback);
mreDetailedHistory.WaitOne(manualResetEventsWaitTimeout);
Console.WriteLine("DetailedHistory with start & reverse = true");
mreDetailedHistory = new ManualResetEvent(false);
pubnub.DetailedHistory<string>(channel, midtime - 1, -1, totalMessages / 2, true, CaptureSecondPublishSetRegularDetailedHistoryCallback, DummyErrorCallback);
mreDetailedHistory.WaitOne(manualResetEventsWaitTimeout);
Console.WriteLine("DetailedHistory with start & reverse = false");
mreDetailedHistory = new ManualResetEvent(false);
pubnub.DetailedHistory<string>(channel, midtime - 1, -1, totalMessages / 2, false, CaptureFirstPublishSetRegularDetailedHistoryCallback, DummyErrorCallback);
mreDetailedHistory.WaitOne(manualResetEventsWaitTimeout);
pubnub.EndPendingRequests();
pubnub.PubnubUnitTest = null;
pubnub = null;
}
void ThenDetailedHistoryInitializeShouldReturnGrantMessage(string receivedMessage)
{
try
{
if (!string.IsNullOrEmpty(receivedMessage) && !string.IsNullOrEmpty(receivedMessage.Trim()))
{
List<object> serializedMessage = pubnub.JsonPluggableLibrary.DeserializeToListOfObject(receivedMessage);
if (serializedMessage != null && serializedMessage.Count > 0)
{
Dictionary<string, object> dictionary = pubnub.JsonPluggableLibrary.ConvertToDictionaryObject(serializedMessage[0]);
if (dictionary != null)
{
var status = dictionary["status"].ToString();
if (status == "200")
{
receivedGrantMessage = true;
}
}
}
}
}
catch { }
finally
{
grantManualEvent.Set();
}
}
void ReturnRegularPublishCodeCallback(string result)
{
try
{
Console.WriteLine(string.Format("ReturnRegularPublishCodeCallback result = {0}", result));
if (!string.IsNullOrEmpty(result) && !string.IsNullOrEmpty(result.Trim()))
{
List<object> deserializedMessage = pubnub.JsonPluggableLibrary.DeserializeToListOfObject(result);
if (deserializedMessage != null && deserializedMessage.Count > 0)
{
long statusCode = Int64.Parse(deserializedMessage[0].ToString());
string statusMessage = (string)deserializedMessage[1];
if (statusCode == 1 && statusMessage.ToLower() == "sent")
{
publishTimetokenForHistory = Convert.ToInt64(deserializedMessage[2].ToString());
isPublished = true;
}
}
}
}
catch { }
finally
{
mrePublish.Set();
}
}
void CaptureNoStoreDetailedHistoryCallback(string result)
{
if (!string.IsNullOrEmpty(result) && !string.IsNullOrEmpty(result.Trim()))
{
List<object> deserializedMessage = pubnub.JsonPluggableLibrary.DeserializeToListOfObject(result);
if (deserializedMessage != null && deserializedMessage.Count > 0)
{
if (deserializedMessage[0].ToString() == "[]")
{
messageReceived = false;
}
else
{
object[] message = pubnub.JsonPluggableLibrary.ConvertToObjectArray(deserializedMessage[0]);
if (message != null && message.Length >= 0)
{
if (!message.Contains(messageForNoStorePublish))
{
messageReceived = false;
}
}
}
}
}
mreDetailedHistory.Set();
}
void CaptureRegularDetailedHistoryCallback(string result)
{
if (!string.IsNullOrEmpty(result) && !string.IsNullOrEmpty(result.Trim()))
{
List<object> deserializedMessage = pubnub.JsonPluggableLibrary.DeserializeToListOfObject(result);
if (deserializedMessage != null && deserializedMessage.Count > 0)
{
object[] message = pubnub.JsonPluggableLibrary.ConvertToObjectArray(deserializedMessage[0]);
if (message != null && message.Length >= 0)
{
if (message.Contains(messageForPublish))
{
messageReceived = true;
}
}
}
}
mreDetailedHistory.Set();
}
void DetailedHistoryCount10Callback(string result)
{
if (!string.IsNullOrEmpty(result) && !string.IsNullOrEmpty(result.Trim()))
{
List<object> deserializedMessage = pubnub.JsonPluggableLibrary.DeserializeToListOfObject(result);
if (deserializedMessage != null && deserializedMessage.Count > 0)
{
object[] message = pubnub.JsonPluggableLibrary.ConvertToObjectArray(deserializedMessage[0]);
if (message != null)
{
if (message.Length >= 0)
{
messageReceived = true;
}
}
}
}
mreDetailedHistory.Set();
}
void DetailedHistoryCount10ReverseTrueCallback(string result)
{
if (!string.IsNullOrEmpty(result) && !string.IsNullOrEmpty(result.Trim()))
{
List<object> deserializedMessage = pubnub.JsonPluggableLibrary.DeserializeToListOfObject(result);
if (deserializedMessage != null && deserializedMessage.Count > 0)
{
object[] message = pubnub.JsonPluggableLibrary.ConvertToObjectArray(deserializedMessage[0]);
if (message != null)
{
if (message.Length >= 0)
{
message10ReverseTrueReceived = true;
}
}
}
}
mreMessageCount10ReverseTrue.Set();
}
void DetailedHistoryStartWithReverseTrueCallback(string result)
{
int actualCountAtStartTimeWithReverseFalse = 0;
if (!string.IsNullOrEmpty(result) && !string.IsNullOrEmpty(result.Trim()))
{
Console.WriteLine(string.Format("DetailedHistoryStartWithReverseTrueCallback result = {0}", result));
List<object> deserializedMessage = pubnub.JsonPluggableLibrary.DeserializeToListOfObject(result);
if (deserializedMessage != null && deserializedMessage.Count > 0)
{
object[] message = pubnub.JsonPluggableLibrary.ConvertToObjectArray(deserializedMessage[0]);
if (message != null)
{
if (message.Length >= expectedCountAtStartTimeWithReverseTrue)
{
foreach (object item in message)
{
if (item.ToString().Contains("DetailedHistoryStartTimeWithReverseTrue"))
{
actualCountAtStartTimeWithReverseFalse++;
}
}
if (actualCountAtStartTimeWithReverseFalse >= expectedCountAtStartTimeWithReverseTrue)
{
messageStartReverseTrue = true;
}
}
}
}
}
mreMessageStartReverseTrue.Set();
}
void DetailedHistorySamplePublishCallback(string result)
{
if (!string.IsNullOrEmpty(result) && !string.IsNullOrEmpty(result.Trim()))
{
Console.WriteLine(string.Format("DetailedHistorySamplePublishCallback result = {0}", result));
List<object> deserializedMessage = pubnub.JsonPluggableLibrary.DeserializeToListOfObject(result);
if (deserializedMessage != null && deserializedMessage.Count > 0)
{
int statusCode = Int32.Parse(deserializedMessage[0].ToString());
string statusMessage = (string)deserializedMessage[1];
if (statusCode == 1 && statusMessage.ToLower() == "sent")
{
expectedCountAtStartTimeWithReverseTrue++;
}
}
}
mrePublish.Set();
}
void DetailHistoryWithNullKeyseDummyCallback(string result)
{
mreDetailedHistory.Set();
}
void CaptureFirstPublishSetRegularDetailedHistoryCallback(string result)
{
if (!string.IsNullOrEmpty(result) && !string.IsNullOrEmpty(result.Trim()))
{
Console.WriteLine(string.Format("CaptureFirstPublishSetRegularDetailedHistoryCallback result = {0}", result));
List<object> deserializedMessage = pubnub.JsonPluggableLibrary.DeserializeToListOfObject(result);
if (deserializedMessage != null && deserializedMessage.Count > 0)
{
object[] message = pubnub.JsonPluggableLibrary.ConvertToObjectArray(deserializedMessage[0]);
if (message != null && message.Length >= 0 && firstPublishSet != null && firstPublishSet.Length == message.Length)
{
for (int index = 0; index < message.Length; index++)
{
if (firstPublishSet[index].ToString() != message[index].ToString())
{
messageReceived = false;
break;
}
messageReceived = true;
}
}
}
}
mreDetailedHistory.Set();
}
void CaptureSecondPublishSetRegularDetailedHistoryCallback(string result)
{
if (!string.IsNullOrEmpty(result) && !string.IsNullOrEmpty(result.Trim()))
{
Console.WriteLine(string.Format("CaptureSecondPublishSetRegularDetailedHistoryCallback result = {0}", result));
List<object> deserializedMessage = pubnub.JsonPluggableLibrary.DeserializeToListOfObject(result);
if (deserializedMessage != null && deserializedMessage.Count > 0)
{
object[] message = pubnub.JsonPluggableLibrary.ConvertToObjectArray(deserializedMessage[0]);
if (message != null && message.Length >= 0 && firstPublishSet != null && firstPublishSet.Length == message.Length)
{
for (int index = 0; index < message.Length; index++)
{
if (secondPublishSet[index].ToString() != message[index].ToString())
{
messageReceived = false;
break;
}
messageReceived = true;
}
}
}
}
mreDetailedHistory.Set();
}
void DummyErrorCallback(PubnubClientError result)
{
if (currentTestCase == "DetailHistoryWithNullKeysReturnsError")
{
messageReceived = true;
mreDetailedHistory.Set();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Runtime.Serialization;
using Max.Domain.Mapping;
using Max.Domain.Mapping.Implementation;
using Sample.Contracts;
namespace Sample.WcfService.Mapping
{
public static partial class GeneratedReverseMapperExtensions
{
#region ReverseMapper extionsions for Contact
public static List<Sample.Business.Contact> MapFromContactCollection(this ReverseMapper mapper, IEnumerable<Contact> source)
{
List<Sample.Business.Contact> result = new List<Sample.Business.Contact>();
foreach(var item in source)
result.Add(mapper.MapFromContact(item));
return result;
}
public static Sample.Business.Contact MapFromContact(this ReverseMapper mapper, Contact source)
{
if (source == null)
return null;
else
return mapper.MapFromContact(source, null);
}
public static Sample.Business.Contact MapFromContact(this ReverseMapper mapper, Contact source, Sample.Business.Contact target)
{
// Null maps to null:
if (source == null) return null;
// Check if object already mapped (as in circular reference scenarios):
object mappedTarget = mapper.GetMappedTarget(source);
if (Object.ReferenceEquals(mappedTarget, null) == false)
return (Sample.Business.Contact)mappedTarget;
// Retrieve target object:
if (target == null)
target = mapper.TryGetTarget<Sample.Business.Contact>(source);
if ((target == null) && (mapper.CanCreate(typeof(Sample.Business.Contact))))
mapper.RegisterAsNewObject(target = new Sample.Business.Contact());
if (target == null)
throw new Max.Domain.Mapping.MappingException(String.Format("Cannot map {0} to an existing instance.", source.GetType().Name));
// Register mapping:
mapper.RegisterMapping(source, target);
// Perform mapping:
if (mapper.CanUpdate(target))
mapper.UpdateContact(source, target);
// Return target:
return target;
}
internal static void UpdateContact(this ReverseMapper mapper, Contact source, Sample.Business.Contact target)
{
// Verify null args:
if (Object.ReferenceEquals(source, null))
return;
else if (Object.ReferenceEquals(target, null))
throw new Max.Domain.Mapping.MappingException("No target provided to map Contact on.");
// Map source to target:
mapper.UpdateBaseObject(source, target);
if (target.ContactID != source.Id)
target.ContactID = source.Id;
if (target.Title != source.Title)
target.Title = (String.IsNullOrWhiteSpace(source.Title)) ? null : source.Title.Trim();
if (target.FirstName != source.FirstName)
target.FirstName = (String.IsNullOrWhiteSpace(source.FirstName)) ? null : source.FirstName.Trim();
if (target.MiddleName != source.MiddleName)
target.MiddleName = (String.IsNullOrWhiteSpace(source.MiddleName)) ? null : source.MiddleName.Trim();
if (target.LastName != source.LastName)
target.LastName = (String.IsNullOrWhiteSpace(source.LastName)) ? null : source.LastName.Trim();
if (target.Suffix != source.Suffix)
target.Suffix = (String.IsNullOrWhiteSpace(source.Suffix)) ? null : source.Suffix.Trim();
if (target.EmailAddress != source.EmailAddress)
target.EmailAddress = (String.IsNullOrWhiteSpace(source.EmailAddress)) ? null : source.EmailAddress.Trim();
if (target.Phone != source.Phone)
target.Phone = (String.IsNullOrWhiteSpace(source.Phone)) ? null : source.Phone.Trim();
// Call partial AfterUpdate method:
AfterUpdateContact(mapper, source, target);
}
static partial void AfterUpdateContact(this ReverseMapper mapper, Contact source, Sample.Business.Contact target);
#endregion
#region ReverseMapper extionsions for Employee
public static List<Sample.Business.Employee> MapFromEmployeeCollection(this ReverseMapper mapper, IEnumerable<Employee> source)
{
List<Sample.Business.Employee> result = new List<Sample.Business.Employee>();
foreach(var item in source)
result.Add(mapper.MapFromEmployee(item));
return result;
}
public static Sample.Business.Employee MapFromEmployee(this ReverseMapper mapper, Employee source)
{
if (source == null)
return null;
else if (source is SalesPerson)
return mapper.MapFromSalesPerson((SalesPerson)source, null);
else
return mapper.MapFromEmployee(source, null);
}
public static Sample.Business.Employee MapFromEmployee(this ReverseMapper mapper, Employee source, Sample.Business.Employee target)
{
// Null maps to null:
if (source == null) return null;
// Check if object already mapped (as in circular reference scenarios):
object mappedTarget = mapper.GetMappedTarget(source);
if (Object.ReferenceEquals(mappedTarget, null) == false)
return (Sample.Business.Employee)mappedTarget;
// Retrieve target object:
if (target == null)
target = mapper.TryGetTarget<Sample.Business.Employee>(source);
if (target == null)
throw new Max.Domain.Mapping.MappingException(String.Format("Cannot map {0} to an existing instance.", source.GetType().Name));
// Register mapping:
mapper.RegisterMapping(source, target);
// Perform mapping:
if (mapper.CanUpdate(target))
mapper.UpdateEmployee(source, target);
// Return target:
return target;
}
internal static void UpdateEmployee(this ReverseMapper mapper, Employee source, Sample.Business.Employee target)
{
// Verify null args:
if (Object.ReferenceEquals(source, null))
return;
else if (Object.ReferenceEquals(target, null))
throw new Max.Domain.Mapping.MappingException("No target provided to map Employee on.");
// Map source to target:
mapper.UpdateSystemObject(source, target);
if (target.EmployeeID != source.Id)
target.EmployeeID = source.Id;
if (target.Gender != source.Gender)
target.Gender = (String.IsNullOrWhiteSpace(source.Gender)) ? null : source.Gender.Trim();
if (target.BirthDate != source.BirthDate)
target.BirthDate = source.BirthDate;
if (target.HireDate != source.HireDate)
target.HireDate = source.HireDate;
if (target.ManagerID != source.ManagerId)
target.ManagerID = source.ManagerId;
// Call partial AfterUpdate method:
AfterUpdateEmployee(mapper, source, target);
}
static partial void AfterUpdateEmployee(this ReverseMapper mapper, Employee source, Sample.Business.Employee target);
#endregion
#region ReverseMapper extionsions for SalesPerson
public static List<Sample.Business.SalesPerson> MapFromSalesPersonCollection(this ReverseMapper mapper, IEnumerable<SalesPerson> source)
{
List<Sample.Business.SalesPerson> result = new List<Sample.Business.SalesPerson>();
foreach(var item in source)
result.Add(mapper.MapFromSalesPerson(item));
return result;
}
public static Sample.Business.SalesPerson MapFromSalesPerson(this ReverseMapper mapper, SalesPerson source)
{
if (source == null)
return null;
else
return mapper.MapFromSalesPerson(source, null);
}
public static Sample.Business.SalesPerson MapFromSalesPerson(this ReverseMapper mapper, SalesPerson source, Sample.Business.SalesPerson target)
{
// Null maps to null:
if (source == null) return null;
// Check if object already mapped (as in circular reference scenarios):
object mappedTarget = mapper.GetMappedTarget(source);
if (Object.ReferenceEquals(mappedTarget, null) == false)
return (Sample.Business.SalesPerson)mappedTarget;
// Retrieve target object:
if (target == null)
target = mapper.TryGetTarget<Sample.Business.SalesPerson>(source);
if (target == null)
throw new Max.Domain.Mapping.MappingException(String.Format("Cannot map {0} to an existing instance.", source.GetType().Name));
// Register mapping:
mapper.RegisterMapping(source, target);
// Perform mapping:
if (mapper.CanUpdate(target))
mapper.UpdateSalesPerson(source, target);
// Return target:
return target;
}
internal static void UpdateSalesPerson(this ReverseMapper mapper, SalesPerson source, Sample.Business.SalesPerson target)
{
// Verify null args:
if (Object.ReferenceEquals(source, null))
return;
else if (Object.ReferenceEquals(target, null))
throw new Max.Domain.Mapping.MappingException("No target provided to map SalesPerson on.");
// Map source to target:
mapper.UpdateEmployee(source, target);
if (target.SalesQuota != source.SalesQuota)
target.SalesQuota = source.SalesQuota;
if (target.Bonus != source.Bonus)
target.Bonus = source.Bonus;
if (target.CommissionPct != source.CommissionPct)
target.CommissionPct = source.CommissionPct;
if (target.SalesYTD != source.SalesYTD)
target.SalesYTD = source.SalesYTD;
// Call partial AfterUpdate method:
AfterUpdateSalesPerson(mapper, source, target);
}
static partial void AfterUpdateSalesPerson(this ReverseMapper mapper, SalesPerson source, Sample.Business.SalesPerson target);
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using CSharpGuidelinesAnalyzer.Extensions;
using JetBrains.Annotations;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Operations;
namespace CSharpGuidelinesAnalyzer.Rules.Maintainability
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public sealed class DoNotAssignToParameterAnalyzer : DiagnosticAnalyzer
{
private const string Title = "Parameter value should not be overwritten in method body";
private const string MessageFormat = "The value of parameter '{0}' is overwritten in its method body";
private const string Description = "Don't use parameters as temporary variables.";
public const string DiagnosticId = "AV1568";
[NotNull]
private static readonly AnalyzerCategory Category = AnalyzerCategory.Maintainability;
[NotNull]
private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, Category.DisplayName,
DiagnosticSeverity.Info, true, Description, Category.GetHelpLinkUri(DiagnosticId));
private static readonly ImmutableArray<SpecialType> SimpleTypes = ImmutableArray.Create(SpecialType.System_Boolean, SpecialType.System_Char,
SpecialType.System_SByte, SpecialType.System_Byte, SpecialType.System_Int16, SpecialType.System_UInt16, SpecialType.System_Int32,
SpecialType.System_UInt32, SpecialType.System_Int64, SpecialType.System_UInt64, SpecialType.System_Decimal, SpecialType.System_Single,
SpecialType.System_Double, SpecialType.System_IntPtr, SpecialType.System_UIntPtr, SpecialType.System_DateTime);
[NotNull]
private static readonly Action<SymbolAnalysisContext> AnalyzeMethodAction = context => context.SkipEmptyName(AnalyzeMethod);
[NotNull]
private static readonly Action<SymbolAnalysisContext> AnalyzePropertyAction = context => context.SkipEmptyName(AnalyzeProperty);
[NotNull]
private static readonly Action<SymbolAnalysisContext> AnalyzeEventAction = context => context.SkipEmptyName(AnalyzeEvent);
[NotNull]
private static readonly Action<OperationAnalysisContext> AnalyzeLocalFunctionAction = context => context.SkipInvalid(AnalyzeLocalFunction);
[NotNull]
private static readonly Action<OperationAnalysisContext> AnalyzeAnonymousFunctionAction = context => context.SkipInvalid(AnalyzeAnonymousFunction);
[ItemNotNull]
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);
public override void Initialize([NotNull] AnalysisContext context)
{
context.EnableConcurrentExecution();
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.RegisterSymbolAction(AnalyzeMethodAction, SymbolKind.Method);
context.RegisterSymbolAction(AnalyzePropertyAction, SymbolKind.Property);
context.RegisterSymbolAction(AnalyzeEventAction, SymbolKind.Event);
context.RegisterOperationAction(AnalyzeLocalFunctionAction, OperationKind.LocalFunction);
context.RegisterOperationAction(AnalyzeAnonymousFunctionAction, OperationKind.AnonymousFunction);
}
private static void AnalyzeMethod(SymbolAnalysisContext context)
{
var method = (IMethodSymbol)context.Symbol;
if (ShouldSkip(method) || method.IsPropertyOrEventAccessor())
{
return;
}
using var collector = new DiagnosticCollector(context.ReportDiagnostic);
InnerAnalyzeMethod(context.Wrap(method), collector);
}
private static void AnalyzeProperty(SymbolAnalysisContext context)
{
var property = (IPropertySymbol)context.Symbol;
using var collector = new DiagnosticCollector(context.ReportDiagnostic);
AnalyzeAccessorMethod(property.GetMethod, collector, context);
AnalyzeAccessorMethod(property.SetMethod, collector, context);
FilterDuplicateLocations(collector.Diagnostics);
}
private static void AnalyzeEvent(SymbolAnalysisContext context)
{
var @event = (IEventSymbol)context.Symbol;
using var collector = new DiagnosticCollector(context.ReportDiagnostic);
AnalyzeAccessorMethod(@event.AddMethod, collector, context);
AnalyzeAccessorMethod(@event.RemoveMethod, collector, context);
FilterDuplicateLocations(collector.Diagnostics);
}
private static void AnalyzeAccessorMethod([CanBeNull] IMethodSymbol accessorMethod, [NotNull] DiagnosticCollector collector,
SymbolAnalysisContext context)
{
if (accessorMethod == null || ShouldSkip(accessorMethod))
{
return;
}
InnerAnalyzeMethod(context.Wrap(accessorMethod), collector);
}
private static void FilterDuplicateLocations([NotNull] [ItemNotNull] ICollection<Diagnostic> diagnostics)
{
while (true)
{
if (!RemoveNextDuplicate(diagnostics))
{
return;
}
}
}
private static bool RemoveNextDuplicate([NotNull] [ItemNotNull] ICollection<Diagnostic> diagnostics)
{
foreach (Diagnostic diagnostic in diagnostics)
{
Diagnostic[] duplicates = diagnostics.Where(nextDiagnostic =>
!ReferenceEquals(nextDiagnostic, diagnostic) && nextDiagnostic.Location == diagnostic.Location).ToArray();
if (duplicates.Any())
{
RemoveRange(diagnostics, duplicates);
return true;
}
}
return false;
}
private static void RemoveRange<T>([NotNull] [ItemNotNull] ICollection<T> source, [NotNull] [ItemNotNull] ICollection<T> elementsToRemove)
{
foreach (T elementToRemove in elementsToRemove)
{
source.Remove(elementToRemove);
}
}
private static void AnalyzeLocalFunction(OperationAnalysisContext context)
{
var localFunction = (ILocalFunctionOperation)context.Operation;
if (ShouldSkip(localFunction.Symbol))
{
return;
}
using var collector = new DiagnosticCollector(context.ReportDiagnostic);
InnerAnalyzeMethod(context.Wrap(localFunction.Symbol), collector);
}
private static void AnalyzeAnonymousFunction(OperationAnalysisContext context)
{
var anonymousFunction = (IAnonymousFunctionOperation)context.Operation;
if (ShouldSkip(anonymousFunction.Symbol))
{
return;
}
using var collector = new DiagnosticCollector(context.ReportDiagnostic);
InnerAnalyzeMethod(context.Wrap(anonymousFunction.Symbol), collector);
}
private static bool ShouldSkip([NotNull] IMethodSymbol method)
{
return method.IsAbstract || method.IsSynthesized() || !method.Parameters.Any();
}
private static void InnerAnalyzeMethod(BaseAnalysisContext<IMethodSymbol> context, [NotNull] DiagnosticCollector collector)
{
SyntaxNode bodySyntax = context.Target.TryGetBodySyntaxForMethod(context.CancellationToken);
if (bodySyntax == null)
{
return;
}
AnalyzeParametersInMethod(context.WithTarget(context.Target.Parameters), bodySyntax, collector);
}
private static void AnalyzeParametersInMethod(BaseAnalysisContext<ImmutableArray<IParameterSymbol>> context, [NotNull] SyntaxNode bodySyntax,
[NotNull] DiagnosticCollector collector)
{
IGrouping<bool, IParameterSymbol>[] parameterGrouping = context.Target
.Where(parameter => parameter.RefKind == RefKind.None && !parameter.IsSynthesized()).GroupBy(IsUserDefinedStruct).ToArray();
ICollection<IParameterSymbol> ordinaryParameters = parameterGrouping.Where(group => !group.Key).SelectMany(group => group).ToArray();
if (ordinaryParameters.Any())
{
AnalyzeOrdinaryParameters(context.WithTarget(ordinaryParameters), bodySyntax, collector);
}
ICollection<IParameterSymbol> structParameters = parameterGrouping.Where(group => group.Key).SelectMany(group => group).ToArray();
if (structParameters.Any())
{
AnalyzeStructParameters(context.WithTarget(structParameters), bodySyntax, collector);
}
}
private static bool IsUserDefinedStruct([NotNull] IParameterSymbol parameter)
{
return parameter.Type.TypeKind == TypeKind.Struct && !IsSimpleType(parameter.Type);
}
private static bool IsSimpleType([NotNull] ITypeSymbol type)
{
return type.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T || SimpleTypes.Contains(type.SpecialType);
}
private static void AnalyzeOrdinaryParameters(BaseAnalysisContext<ICollection<IParameterSymbol>> context, [NotNull] SyntaxNode bodySyntax,
[NotNull] DiagnosticCollector collector)
{
DataFlowAnalysis dataFlowAnalysis = TryAnalyzeDataFlow(bodySyntax, context.Compilation);
if (dataFlowAnalysis == null)
{
return;
}
foreach (IParameterSymbol parameter in context.Target)
{
if (dataFlowAnalysis.WrittenInside.Contains(parameter))
{
collector.Add(Diagnostic.Create(Rule, parameter.Locations[0], parameter.Name));
}
}
}
[CanBeNull]
private static DataFlowAnalysis TryAnalyzeDataFlow([NotNull] SyntaxNode bodySyntax, [NotNull] Compilation compilation)
{
SemanticModel model = compilation.GetSemanticModel(bodySyntax.SyntaxTree);
return model.SafeAnalyzeDataFlow(bodySyntax);
}
private static void AnalyzeStructParameters(BaseAnalysisContext<ICollection<IParameterSymbol>> context, [NotNull] SyntaxNode bodySyntax,
[NotNull] DiagnosticCollector collector)
{
// A user-defined struct can reassign its 'this' parameter on invocation. That's why the compiler dataflow
// analysis reports all access as writes. Because that's not very practical, we run our own assignment analysis.
SemanticModel model = context.Compilation.GetSemanticModel(bodySyntax.SyntaxTree);
IOperation bodyOperation = model.GetOperation(bodySyntax);
if (bodyOperation == null || bodyOperation.HasErrors(context.Compilation, context.CancellationToken))
{
return;
}
CollectAssignedStructParameters(context.Target, bodyOperation, collector);
}
private static void CollectAssignedStructParameters([NotNull] [ItemNotNull] ICollection<IParameterSymbol> parameters,
[NotNull] IOperation bodyOperation, [NotNull] DiagnosticCollector collector)
{
var walker = new AssignmentWalker(parameters);
walker.Visit(bodyOperation);
foreach (IParameterSymbol parameter in walker.ParametersAssigned)
{
collector.Add(Diagnostic.Create(Rule, parameter.Locations[0], parameter.Name));
}
}
private sealed class AssignmentWalker : ExplicitOperationWalker
{
[NotNull]
private readonly IDictionary<IParameterSymbol, bool> seenAssignmentPerParameter = new Dictionary<IParameterSymbol, bool>();
[NotNull]
[ItemNotNull]
public ICollection<IParameterSymbol> ParametersAssigned => seenAssignmentPerParameter.Where(pair => pair.Value).Select(pair => pair.Key).ToArray();
public AssignmentWalker([NotNull] [ItemNotNull] ICollection<IParameterSymbol> parameters)
{
Guard.NotNull(parameters, nameof(parameters));
foreach (IParameterSymbol parameter in parameters)
{
seenAssignmentPerParameter[parameter] = false;
}
}
public override void VisitSimpleAssignment([NotNull] ISimpleAssignmentOperation operation)
{
RegisterAssignmentToParameter(operation.Target);
base.VisitSimpleAssignment(operation);
}
public override void VisitCompoundAssignment([NotNull] ICompoundAssignmentOperation operation)
{
RegisterAssignmentToParameter(operation.Target);
base.VisitCompoundAssignment(operation);
}
public override void VisitIncrementOrDecrement([NotNull] IIncrementOrDecrementOperation operation)
{
RegisterAssignmentToParameter(operation.Target);
base.VisitIncrementOrDecrement(operation);
}
public override void VisitDeconstructionAssignment([NotNull] IDeconstructionAssignmentOperation operation)
{
if (operation.Target is ITupleOperation tuple)
{
foreach (IOperation element in tuple.Elements)
{
RegisterAssignmentToParameter(element);
}
}
base.VisitDeconstructionAssignment(operation);
}
public override void VisitArgument([NotNull] IArgumentOperation operation)
{
if (operation.Parameter.RefKind == RefKind.Ref || operation.Parameter.RefKind == RefKind.Out)
{
RegisterAssignmentToParameter(operation.Value);
}
base.VisitArgument(operation);
}
private void RegisterAssignmentToParameter([NotNull] IOperation operation)
{
if (operation is IParameterReferenceOperation parameterReference)
{
IParameterSymbol parameter = parameterReference.Parameter;
if (seenAssignmentPerParameter.ContainsKey(parameter))
{
seenAssignmentPerParameter[parameter] = true;
}
}
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="filewebrequest.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Net {
using System.IO;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Threading;
using System.Runtime.Versioning;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Tracing;
[Serializable]
public class FileWebRequest : WebRequest, ISerializable {
private static WaitCallback s_GetRequestStreamCallback = new WaitCallback(GetRequestStreamCallback);
private static WaitCallback s_GetResponseCallback = new WaitCallback(GetResponseCallback);
private static ContextCallback s_WrappedGetRequestStreamCallback = new ContextCallback(GetRequestStreamCallback);
private static ContextCallback s_WrappedResponseCallback = new ContextCallback(GetResponseCallback);
// fields
string m_connectionGroupName;
long m_contentLength;
ICredentials m_credentials;
FileAccess m_fileAccess;
WebHeaderCollection m_headers;
string m_method = "GET";
bool m_preauthenticate;
IWebProxy m_proxy;
ManualResetEvent m_readerEvent;
bool m_readPending;
WebResponse m_response;
Stream m_stream;
bool m_syncHint;
int m_timeout = WebRequest.DefaultTimeout;
Uri m_uri;
bool m_writePending;
bool m_writing;
private LazyAsyncResult m_WriteAResult;
private LazyAsyncResult m_ReadAResult;
private int m_Aborted;
// constructors
internal FileWebRequest(Uri uri)
{
if ((object)uri.Scheme != (object)Uri.UriSchemeFile)
throw new ArgumentOutOfRangeException("uri");
m_uri = uri;
m_fileAccess = FileAccess.Read;
m_headers = new WebHeaderCollection(WebHeaderCollectionType.FileWebRequest);
}
//
// ISerializable constructor
//
[Obsolete("Serialization is obsoleted for this type. http://go.microsoft.com/fwlink/?linkid=14202")]
protected FileWebRequest(SerializationInfo serializationInfo, StreamingContext streamingContext):base(serializationInfo, streamingContext) {
m_headers = (WebHeaderCollection)serializationInfo.GetValue("headers", typeof(WebHeaderCollection));
m_proxy = (IWebProxy)serializationInfo.GetValue("proxy", typeof(IWebProxy));
m_uri = (Uri)serializationInfo.GetValue("uri", typeof(Uri));
m_connectionGroupName = serializationInfo.GetString("connectionGroupName");
m_method = serializationInfo.GetString("method");
m_contentLength = serializationInfo.GetInt64("contentLength");
m_timeout = serializationInfo.GetInt32("timeout");
m_fileAccess = (FileAccess )serializationInfo.GetInt32("fileAccess");
}
//
// ISerializable method
//
/// <internalonly/>
[SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Justification = "System.dll is still using pre-v4 security model and needs this demand")]
[SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.SerializationFormatter, SerializationFormatter=true)]
void ISerializable.GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
GetObjectData(serializationInfo, streamingContext);
}
//
// FxCop: provide some way for derived classes to access GetObjectData even if the derived class
// explicitly re-inherits ISerializable.
//
[SecurityPermission(SecurityAction.Demand, SerializationFormatter=true)]
protected override void GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
serializationInfo.AddValue("headers", m_headers, typeof(WebHeaderCollection));
serializationInfo.AddValue("proxy", m_proxy, typeof(IWebProxy));
serializationInfo.AddValue("uri", m_uri, typeof(Uri));
serializationInfo.AddValue("connectionGroupName", m_connectionGroupName);
serializationInfo.AddValue("method", m_method);
serializationInfo.AddValue("contentLength", m_contentLength);
serializationInfo.AddValue("timeout", m_timeout);
serializationInfo.AddValue("fileAccess", m_fileAccess);
//we're leaving this for legacy. V1.1 and V1.0 had this field in the serialization constructor
serializationInfo.AddValue("preauthenticate", false);
base.GetObjectData(serializationInfo, streamingContext);
}
// properties
internal bool Aborted {
get {
return m_Aborted != 0;
}
}
public override string ConnectionGroupName {
get {
return m_connectionGroupName;
}
set {
m_connectionGroupName = value;
}
}
public override long ContentLength {
get {
return m_contentLength;
}
set {
if (value < 0) {
throw new ArgumentException(SR.GetString(SR.net_clsmall), "value");
}
m_contentLength = value;
}
}
public override string ContentType {
get {
return m_headers["Content-Type"];
}
set {
m_headers["Content-Type"] = value;
}
}
public override ICredentials Credentials {
get {
return m_credentials;
}
set {
m_credentials = value;
}
}
public override WebHeaderCollection Headers {
get {
return m_headers;
}
}
public override string Method {
get {
return m_method;
}
set {
if (ValidationHelper.IsBlankString(value)) {
throw new ArgumentException(SR.GetString(SR.net_badmethod), "value");
}
m_method = value;
}
}
public override bool PreAuthenticate {
get {
return m_preauthenticate;
}
set {
m_preauthenticate = true;
}
}
public override IWebProxy Proxy {
get {
return m_proxy;
}
set {
m_proxy = value;
}
}
//UEUE changed default from infinite to 100 seconds
public override int Timeout {
get {
return m_timeout;
}
set {
if ((value < 0) && (value != System.Threading.Timeout.Infinite)) {
throw new ArgumentOutOfRangeException("value", SR.GetString(SR.net_io_timeout_use_ge_zero));
}
m_timeout = value;
}
}
public override Uri RequestUri {
get {
return m_uri;
}
}
// methods
[HostProtection(ExternalThreading=true)]
public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state)
{
GlobalLog.Enter("FileWebRequest::BeginGetRequestStream");
try {
if (Aborted)
throw ExceptionHelper.RequestAbortedException;
if (!CanGetRequestStream()) {
Exception e = new ProtocolViolationException(SR.GetString(SR.net_nouploadonget));
GlobalLog.LeaveException("FileWebRequest::BeginGetRequestStream", e);
throw e;
}
if (m_response != null) {
Exception e = new InvalidOperationException(SR.GetString(SR.net_reqsubmitted));
GlobalLog.LeaveException("FileWebRequest::BeginGetRequestStream", e);
throw e;
}
lock(this) {
if (m_writePending) {
Exception e = new InvalidOperationException(SR.GetString(SR.net_repcall));
GlobalLog.LeaveException("FileWebRequest::BeginGetRequestStream", e);
throw e;
}
m_writePending = true;
}
//we need to force the capture of the identity and context to make sure the
//posted callback doesn't inavertently gain access to something it shouldn't.
m_ReadAResult = new LazyAsyncResult(this, state, callback);
ThreadPool.QueueUserWorkItem(s_GetRequestStreamCallback, m_ReadAResult);
} catch (Exception exception) {
if(Logging.On)Logging.Exception(Logging.Web, this, "BeginGetRequestStream", exception);
throw;
} finally {
GlobalLog.Leave("FileWebRequest::BeginGetRequestSteam");
}
string suri;
if (FrameworkEventSource.Log.IsEnabled(EventLevel.Verbose, FrameworkEventSource.Keywords.NetClient))
suri = this.RequestUri.ToString();
else
suri = this.RequestUri.OriginalString;
if (FrameworkEventSource.Log.IsEnabled()) LogBeginGetRequestStream(suri);
return m_ReadAResult;
}
[HostProtection(ExternalThreading=true)]
public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state)
{
GlobalLog.Enter("FileWebRequest::BeginGetResponse");
try {
if (Aborted)
throw ExceptionHelper.RequestAbortedException;
lock(this) {
if (m_readPending) {
Exception e = new InvalidOperationException(SR.GetString(SR.net_repcall));
GlobalLog.LeaveException("FileWebRequest::BeginGetResponse", e);
throw e;
}
m_readPending = true;
}
m_WriteAResult = new LazyAsyncResult(this,state,callback);
ThreadPool.QueueUserWorkItem(s_GetResponseCallback,m_WriteAResult);
} catch (Exception exception) {
if(Logging.On)Logging.Exception(Logging.Web, this, "BeginGetResponse", exception);
throw;
} finally {
GlobalLog.Leave("FileWebRequest::BeginGetResponse");
}
string suri;
if (FrameworkEventSource.Log.IsEnabled(EventLevel.Verbose, FrameworkEventSource.Keywords.NetClient))
suri = this.RequestUri.ToString();
else
suri = this.RequestUri.OriginalString;
if (FrameworkEventSource.Log.IsEnabled()) LogBeginGetResponse(suri);
return m_WriteAResult;
}
private bool CanGetRequestStream() {
return !KnownHttpVerb.Parse(m_method).ContentBodyNotAllowed;
}
public override Stream EndGetRequestStream(IAsyncResult asyncResult)
{
GlobalLog.Enter("FileWebRequest::EndGetRequestStream");
Stream stream;
try {
LazyAsyncResult ar = asyncResult as LazyAsyncResult;
if (asyncResult == null || ar == null) {
Exception e = asyncResult == null? new ArgumentNullException("asyncResult"): new ArgumentException(SR.GetString(SR.InvalidAsyncResult), "asyncResult");
GlobalLog.LeaveException("FileWebRequest::EndGetRequestStream", e);
throw e;
}
object result = ar.InternalWaitForCompletion();
if(result is Exception){
throw (Exception)result;
}
stream = (Stream) result;
m_writePending = false;
} catch (Exception exception) {
if(Logging.On)Logging.Exception(Logging.Web, this, "EndGetRequestStream", exception);
throw;
} finally {
GlobalLog.Leave("FileWebRequest::EndGetRequestStream");
}
if (FrameworkEventSource.Log.IsEnabled()) LogEndGetRequestStream();
return stream;
}
public override WebResponse EndGetResponse(IAsyncResult asyncResult)
{
GlobalLog.Enter("FileWebRequest::EndGetResponse");
WebResponse response;
try {
LazyAsyncResult ar = asyncResult as LazyAsyncResult;
if (asyncResult == null || ar == null) {
Exception e = asyncResult == null? new ArgumentNullException("asyncResult"): new ArgumentException(SR.GetString(SR.InvalidAsyncResult), "asyncResult");
GlobalLog.LeaveException("FileWebRequest::EndGetRequestStream", e);
throw e;
}
object result = ar.InternalWaitForCompletion();
if(result is Exception){
throw (Exception)result;
}
response = (WebResponse) result;
m_readPending = false;
} catch (Exception exception) {
if(Logging.On)Logging.Exception(Logging.Web, this, "EndGetResponse", exception);
throw;
} finally {
GlobalLog.Leave("FileWebRequest::EndGetResponse");
}
if (FrameworkEventSource.Log.IsEnabled()) LogEndGetResponse();
return response;
}
public override Stream GetRequestStream()
{
GlobalLog.Enter("FileWebRequest::GetRequestStream");
IAsyncResult result;
try {
result = BeginGetRequestStream(null, null);
if ((Timeout != System.Threading.Timeout.Infinite) && !result.IsCompleted) {
if (!result.AsyncWaitHandle.WaitOne(Timeout, false) || !result.IsCompleted) {
if (m_stream != null) {
m_stream.Close();
}
Exception e = new WebException(NetRes.GetWebStatusString(WebExceptionStatus.Timeout), WebExceptionStatus.Timeout);
GlobalLog.LeaveException("FileWebRequest::GetRequestStream", e);
throw e;
}
}
} catch (Exception exception) {
if(Logging.On)Logging.Exception(Logging.Web, this, "GetRequestStream", exception);
throw;
} finally {
GlobalLog.Leave("FileWebRequest::GetRequestStream");
}
return EndGetRequestStream(result);
}
public override WebResponse GetResponse() {
GlobalLog.Enter("FileWebRequest::GetResponse");
m_syncHint = true;
IAsyncResult result;
try {
result = BeginGetResponse(null, null);
if ((Timeout != System.Threading.Timeout.Infinite) && !result.IsCompleted) {
if (!result.AsyncWaitHandle.WaitOne(Timeout, false) || !result.IsCompleted) {
if (m_response != null) {
m_response.Close();
}
Exception e = new WebException(NetRes.GetWebStatusString(WebExceptionStatus.Timeout), WebExceptionStatus.Timeout);
GlobalLog.LeaveException("FileWebRequest::GetResponse", e);
throw e;
}
}
} catch (Exception exception) {
if(Logging.On)Logging.Exception(Logging.Web, this, "GetResponse", exception);
throw;
} finally {
GlobalLog.Leave("FileWebRequest::GetResponse");
}
return EndGetResponse(result);
}
private static void GetRequestStreamCallback(object state)
{
GlobalLog.Enter("FileWebRequest::GetRequestStreamCallback");
LazyAsyncResult asyncResult = (LazyAsyncResult) state;
FileWebRequest request = (FileWebRequest)asyncResult.AsyncObject;
try
{
if (request.m_stream == null)
{
request.m_stream = new FileWebStream(request, request.m_uri.LocalPath, FileMode.Create, FileAccess.Write, FileShare.Read);
request.m_fileAccess = FileAccess.Write;
request.m_writing = true;
}
}
catch (Exception e)
{
// any exceptions previously thrown must be passed to the callback
Exception ex = new WebException(e.Message, e);
GlobalLog.LeaveException("FileWebRequest::GetRequestStreamCallback", ex);
// if the callback throws, correct behavior is to crash the process
asyncResult.InvokeCallback(ex);
return;
}
// if the callback throws, correct behavior is to crash the process
asyncResult.InvokeCallback(request.m_stream);
GlobalLog.Leave("FileWebRequest::GetRequestStreamCallback");
}
private static void GetResponseCallback(object state)
{
GlobalLog.Enter("FileWebRequest::GetResponseCallback");
LazyAsyncResult asyncResult = (LazyAsyncResult) state;
FileWebRequest request = (FileWebRequest)asyncResult.AsyncObject;
if (request.m_writePending || request.m_writing) {
lock(request) {
if (request.m_writePending || request.m_writing) {
request.m_readerEvent = new ManualResetEvent(false);
}
}
}
if (request.m_readerEvent != null)
request.m_readerEvent.WaitOne();
try
{
if (request.m_response == null)
request.m_response = new FileWebResponse(request, request.m_uri, request.m_fileAccess, !request.m_syncHint);
}
catch (Exception e)
{
// any exceptions previously thrown must be passed to the callback
Exception ex = new WebException(e.Message, e);
GlobalLog.LeaveException("FileWebRequest::GetResponseCallback", ex);
// if the callback throws, correct behavior is to crash the process
asyncResult.InvokeCallback(ex);
return;
}
// if the callback throws, the correct behavior is to crash the process
asyncResult.InvokeCallback(request.m_response);
GlobalLog.Leave("FileWebRequest::GetResponseCallback");
}
internal void UnblockReader() {
GlobalLog.Enter("FileWebRequest::UnblockReader");
lock(this) {
if (m_readerEvent != null) {
m_readerEvent.Set();
}
}
m_writing = false;
GlobalLog.Leave("FileWebRequest::UnblockReader");
}
// NOT SUPPORTED method
public override bool UseDefaultCredentials {
get {
throw ExceptionHelper.PropertyNotSupportedException;
}
set {
throw ExceptionHelper.PropertyNotSupportedException;
}
}
public override void Abort()
{
GlobalLog.Enter("FileWebRequest::Abort");
if(Logging.On)Logging.PrintWarning(Logging.Web, NetRes.GetWebStatusString("net_requestaborted", WebExceptionStatus.RequestCanceled));
try {
if (Interlocked.Increment(ref m_Aborted) == 1)
{
LazyAsyncResult readAResult = m_ReadAResult;
LazyAsyncResult writeAResult = m_WriteAResult;
WebException webException = new WebException(NetRes.GetWebStatusString("net_requestaborted", WebExceptionStatus.RequestCanceled), WebExceptionStatus.RequestCanceled);
Stream requestStream = m_stream;
if (readAResult != null && !readAResult.IsCompleted)
readAResult.InvokeCallback(webException);
if (writeAResult != null && !writeAResult.IsCompleted)
writeAResult.InvokeCallback(webException);
if (requestStream != null)
if (requestStream is ICloseEx)
((ICloseEx)requestStream).CloseEx(CloseExState.Abort);
else
requestStream.Close();
if (m_response != null)
((ICloseEx)m_response).CloseEx(CloseExState.Abort);
}
} catch (Exception exception) {
if(Logging.On)Logging.Exception(Logging.Web, this, "Abort", exception);
throw;
} finally {
GlobalLog.Leave("FileWebRequest::Abort");
}
}
}
internal class FileWebRequestCreator : IWebRequestCreate {
internal FileWebRequestCreator() {
}
public WebRequest Create(Uri uri) {
return new FileWebRequest(uri);
}
}
internal sealed class FileWebStream : FileStream, ICloseEx {
FileWebRequest m_request;
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public FileWebStream(FileWebRequest request, string path, FileMode mode, FileAccess access, FileShare sharing)
: base(path, mode, access, sharing)
{
GlobalLog.Enter("FileWebStream::FileWebStream");
m_request = request;
GlobalLog.Leave("FileWebStream::FileWebStream");
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public FileWebStream(FileWebRequest request, string path, FileMode mode, FileAccess access, FileShare sharing, int length, bool async)
: base(path, mode, access, sharing, length, async)
{
GlobalLog.Enter("FileWebStream::FileWebStream");
m_request = request;
GlobalLog.Leave("FileWebStream::FileWebStream");
}
protected override void Dispose(bool disposing) {
GlobalLog.Enter("FileWebStream::Close");
try {
if (disposing && m_request != null) {
m_request.UnblockReader();
}
}
finally {
base.Dispose(disposing);
}
GlobalLog.Leave("FileWebStream::Close");
}
void ICloseEx.CloseEx(CloseExState closeState) {
if ((closeState & CloseExState.Abort) != 0)
SafeFileHandle.Close();
else
Close();
}
public override int Read(byte[] buffer, int offset, int size) {
CheckError();
try {
return base.Read(buffer, offset, size);
}
catch {
CheckError();
throw;
}
}
public override void Write(byte[] buffer, int offset, int size) {
CheckError();
try {
base.Write(buffer, offset, size);
}
catch {
CheckError();
throw;
}
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback callback, Object state) {
CheckError();
try {
return base.BeginRead(buffer, offset, size, callback, state);
}
catch {
CheckError();
throw;
}
}
public override int EndRead(IAsyncResult ar) {
try {
return base.EndRead(ar);
}
catch {
CheckError();
throw;
}
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback callback, Object state) {
CheckError();
try {
return base.BeginWrite(buffer, offset, size, callback, state);
}
catch {
CheckError();
throw;
}
}
public override void EndWrite(IAsyncResult ar) {
try {
base.EndWrite(ar);
}
catch {
CheckError();
throw;
}
}
private void CheckError() {
if (m_request.Aborted) {
throw new WebException(
NetRes.GetWebStatusString(
"net_requestaborted",
WebExceptionStatus.RequestCanceled),
WebExceptionStatus.RequestCanceled);
}
}
}
}
| |
using System.Compiler;
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.Zing
{
public class Duplicator : System.Compiler.Duplicator
{
/// <param name="module">The module into which the duplicate IR will be grafted.</param>
/// <param name="type">The type into which the duplicate Member will be grafted. Ignored if entire type, or larger unit is duplicated.</param>
public Duplicator(Module module, TypeNode type)
: base(module, type)
{
}
public override Node VisitUnknownNodeType(Node node)
{
if (node == null) return null;
switch (((ZingNodeType)node.NodeType))
{
case ZingNodeType.Array:
return this.VisitArray((ZArray)node);
case ZingNodeType.Accept:
return this.VisitAccept((AcceptStatement)node);
case ZingNodeType.Assert:
return this.VisitAssert((AssertStatement)node);
case ZingNodeType.Assume:
return this.VisitAssume((AssumeStatement)node);
case ZingNodeType.Async:
return this.VisitAsync((AsyncMethodCall)node);
case ZingNodeType.Atomic:
return this.VisitAtomic((AtomicBlock)node);
case ZingNodeType.AttributedStatement:
return this.VisitAttributedStatement((AttributedStatement)node);
case ZingNodeType.Chan:
return this.VisitChan((Chan)node);
case ZingNodeType.Choose:
return this.VisitChoose((UnaryExpression)node);
case ZingNodeType.EventPattern:
return this.VisitEventPattern((EventPattern)node);
case ZingNodeType.Event:
return this.VisitEventStatement((EventStatement)node);
case ZingNodeType.In:
return this.VisitIn((BinaryExpression)node);
case ZingNodeType.JoinStatement:
return this.VisitJoinStatement((JoinStatement)node);
case ZingNodeType.InvokePlugin:
return this.VisitInvokePlugin((InvokePluginStatement)node);
case ZingNodeType.Range:
return this.VisitRange((Range)node);
case ZingNodeType.ReceivePattern:
return this.VisitReceivePattern((ReceivePattern)node);
case ZingNodeType.Select:
return this.VisitSelect((Select)node);
case ZingNodeType.Send:
return this.VisitSend((SendStatement)node);
case ZingNodeType.Set:
return this.VisitSet((Set)node);
case ZingNodeType.Trace:
return this.VisitTrace((TraceStatement)node);
case ZingNodeType.TimeoutPattern:
return this.VisitTimeoutPattern((TimeoutPattern)node);
case ZingNodeType.Try:
return this.VisitZTry((ZTry)node);
case ZingNodeType.WaitPattern:
return this.VisitWaitPattern((WaitPattern)node);
case ZingNodeType.With:
return this.VisitWith((With)node);
default:
return base.Visit(node);
}
}
public override Method VisitMethod(Method method)
{
if (method == null) return null;
ZMethod result = (ZMethod)base.VisitMethod(method);
result.ResetLocals();
return result;
}
//
// BUGBUG: temporary workaround for CCI bug
//
public override TypeAlias VisitTypeAlias(TypeAlias tAlias)
{
if (tAlias == null) return null;
TypeAlias dup = (TypeAlias)this.DuplicateFor[tAlias.UniqueKey];
if (dup != null) return dup;
this.DuplicateFor[tAlias.UniqueKey] = dup = (TypeAlias)tAlias.Clone();
dup.Name = tAlias.Name;
if (tAlias.AliasedType is ConstrainedType)
//The type alias defines the constrained type, rather than just referencing it
dup.AliasedType = this.VisitConstrainedType((ConstrainedType)tAlias.AliasedType);
else
dup.AliasedType = this.VisitTypeReference(tAlias.AliasedType);
dup.DeclaringType = this.TargetType;
dup.DeclaringModule = this.TargetModule;
dup.ProvideMembers();
return dup;
}
private ZArray VisitArray(ZArray array)
{
if (array == null) return null;
ZArray result = (ZArray)base.VisitTypeNode((ArrayType)array);
result.LowerBounds = (int[])array.LowerBounds.Clone();
result.Sizes = (int[])array.Sizes.Clone();
result.domainType = this.VisitTypeNode(array.domainType);
return result;
}
private AssertStatement VisitAssert(AssertStatement assert)
{
if (assert == null) return null;
AssertStatement result = (AssertStatement)assert.Clone();
result.booleanExpr = this.VisitExpression(assert.booleanExpr);
return result;
}
private AcceptStatement VisitAccept(AcceptStatement accept)
{
if (accept == null) return null;
AcceptStatement result = (AcceptStatement)accept.Clone();
result.booleanExpr = this.VisitExpression(accept.booleanExpr);
return result;
}
private AssumeStatement VisitAssume(AssumeStatement assume)
{
if (assume == null) return null;
AssumeStatement result = (AssumeStatement)assume.Clone();
result.booleanExpr = this.VisitExpression(assume.booleanExpr);
return result;
}
private EventPattern VisitEventPattern(EventPattern ep)
{
if (ep == null) return null;
EventPattern result = (EventPattern)ep.Clone();
result.channelNumber = this.VisitExpression(ep.channelNumber);
result.messageType = this.VisitExpression(ep.messageType);
result.direction = this.VisitExpression(ep.direction);
return result;
}
private EventStatement VisitEventStatement(EventStatement Event)
{
if (Event == null) return null;
EventStatement result = (EventStatement)Event.Clone();
result.channelNumber = this.VisitExpression(Event.channelNumber);
result.messageType = this.VisitExpression(Event.messageType);
result.direction = this.VisitExpression(Event.direction);
return result;
}
private InvokePluginStatement VisitInvokePlugin(InvokePluginStatement InvokePlugin)
{
if (InvokePlugin == null) return null;
InvokePluginStatement result = (InvokePluginStatement)InvokePlugin.Clone();
result.Operands = this.VisitExpressionList(InvokePlugin.Operands);
return result;
}
private InvokeSchedulerStatement VisitInvokeSched(InvokeSchedulerStatement InvokeSched)
{
if (InvokeSched == null) return null;
InvokeSchedulerStatement result = (InvokeSchedulerStatement)InvokeSched.Clone();
result.Operands = this.VisitExpressionList(InvokeSched.Operands);
return result;
}
private TraceStatement VisitTrace(TraceStatement trace)
{
if (trace == null) return null;
TraceStatement result = (TraceStatement)trace.Clone();
result.Operands = this.VisitExpressionList(trace.Operands);
return result;
}
private AsyncMethodCall VisitAsync(AsyncMethodCall async)
{
if (async == null) return null;
AsyncMethodCall result = (AsyncMethodCall)base.VisitExpressionStatement(async);
return result;
}
private AtomicBlock VisitAtomic(AtomicBlock atomic)
{
if (atomic == null) return null;
AtomicBlock result = (AtomicBlock)this.VisitBlock(atomic);
return result;
}
private AttributedStatement VisitAttributedStatement(AttributedStatement attributedStmt)
{
AttributedStatement result = (AttributedStatement)attributedStmt.Clone();
result.Attributes = this.VisitAttributeList(attributedStmt.Attributes);
result.Statement = (Statement)this.Visit(attributedStmt.Statement);
return result;
}
private Chan VisitChan(Chan chan)
{
if (chan == null) return null;
Chan result = (Chan)this.VisitTypeAlias(chan);
return result;
}
private UnaryExpression VisitChoose(UnaryExpression expr)
{
if (expr == null) return null;
UnaryExpression result = (UnaryExpression)base.VisitUnaryExpression(expr);
return result;
}
private BinaryExpression VisitIn(BinaryExpression expr)
{
if (expr == null) return null;
BinaryExpression result = (BinaryExpression)base.VisitBinaryExpression(expr);
return result;
}
private JoinStatement VisitJoinStatement(JoinStatement joinstmt)
{
if (joinstmt == null) return null;
JoinStatement result = (JoinStatement)joinstmt.Clone();
result.joinPatternList = new JoinPatternList();
for (int i = 0, n = joinstmt.joinPatternList.Length; i < n; i++)
result.joinPatternList.Add((JoinPattern)this.Visit(joinstmt.joinPatternList[i]));
result.statement = (Statement)this.Visit(joinstmt.statement);
result.attributes = this.VisitAttributeList(joinstmt.attributes);
return result;
}
private Range VisitRange(Range range)
{
if (range == null) return null;
Range result = (Range)this.VisitConstrainedType(range);
result.Min = this.VisitExpression(range.Min);
result.Max = this.VisitExpression(range.Max);
return result;
}
private ReceivePattern VisitReceivePattern(ReceivePattern rp)
{
if (rp == null) return null;
ReceivePattern result = (ReceivePattern)rp.Clone();
result.channel = this.VisitExpression(rp.channel);
result.data = this.VisitExpression(rp.data);
return result;
}
private Select VisitSelect(Select select)
{
if (select == null) return null;
Select result = (Select)select.Clone();
result.joinStatementList = new JoinStatementList();
for (int i = 0, n = select.joinStatementList.Length; i < n; i++)
result.joinStatementList.Add((JoinStatement)this.VisitJoinStatement(select.joinStatementList[i]));
return result;
}
private SendStatement VisitSend(SendStatement send)
{
if (send == null) return null;
SendStatement result = (SendStatement)send.Clone();
result.channel = this.VisitExpression(send.channel);
result.data = this.VisitExpression(send.data);
return result;
}
private Set VisitSet(Set @set)
{
if (@set == null) return null;
Set result = (Set)this.VisitTypeAlias(@set);
return result;
}
[SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters")]
private TimeoutPattern VisitTimeoutPattern(TimeoutPattern tp)
{
if (tp == null) return null;
return (TimeoutPattern)tp.Clone();
}
private WaitPattern VisitWaitPattern(WaitPattern wp)
{
if (wp == null) return null;
WaitPattern result = (WaitPattern)wp.Clone();
result.expression = this.VisitExpression(wp.expression);
return result;
}
private ZTry VisitZTry(ZTry Try)
{
if (Try == null) return null;
ZTry result = (ZTry)Try.Clone();
result.Body = this.VisitBlock(Try.Body);
result.Catchers = new WithList();
for (int i = 0, n = Try.Catchers.Length; i < n; i++)
result.Catchers.Add(this.VisitWith(Try.Catchers[i]));
return result;
}
private With VisitWith(With with)
{
if (with == null) return null;
With result = (With)with.Clone();
result.Block = this.VisitBlock(with.Block);
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.
// ----------------------------------------------------------------------------------
// Interop library code
//
// Marshalling helpers used by MCG
//
// NOTE:
// These source code are being published to InternalAPIs and consumed by RH builds
// Use PublishInteropAPI.bat to keep the InternalAPI copies in sync
// ----------------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Runtime.InteropServices;
using System.Threading;
using System.Text;
using System.Runtime;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using Internal.NativeFormat;
#if !CORECLR
using Internal.Runtime.Augments;
#endif
#if RHTESTCL
using OutputClass = System.Console;
#else
using OutputClass = System.Diagnostics.Debug;
#endif
namespace System.Runtime.InteropServices
{
/// <summary>
/// Expose functionality from System.Private.CoreLib and forwards calls to InteropExtensions in System.Private.CoreLib
/// </summary>
[CLSCompliant(false)]
public static partial class McgMarshal
{
public static void SaveLastWin32Error()
{
PInvokeMarshal.SaveLastWin32Error();
}
public static void ClearLastWin32Error()
{
PInvokeMarshal.ClearLastWin32Error();
}
public static bool GuidEquals(ref Guid left, ref Guid right)
{
return InteropExtensions.GuidEquals(ref left, ref right);
}
public static bool ComparerEquals<T>(T left, T right)
{
return InteropExtensions.ComparerEquals<T>(left, right);
}
public static T CreateClass<T>() where T : class
{
return InteropExtensions.UncheckedCast<T>(InteropExtensions.RuntimeNewObject(typeof(T).TypeHandle));
}
public static bool IsEnum(object obj)
{
#if RHTESTCL
return false;
#else
return InteropExtensions.IsEnum(obj.GetTypeHandle());
#endif
}
public static bool IsCOMObject(Type type)
{
#if RHTESTCL
return false;
#else
return type.GetTypeInfo().IsSubclassOf(typeof(__ComObject));
#endif
}
public static T FastCast<T>(object value) where T : class
{
// We have an assert here, to verify that a "real" cast would have succeeded.
// However, casting on weakly-typed RCWs modifies their state, by doing a QI and caching
// the result. This often makes things work which otherwise wouldn't work (especially variance).
Debug.Assert(value == null || value is T);
return InteropExtensions.UncheckedCast<T>(value);
}
/// <summary>
/// Converts a managed DateTime to native OLE datetime
/// Used by MCG marshalling code
/// </summary>
public static double ToNativeOleDate(DateTime dateTime)
{
return InteropExtensions.ToNativeOleDate(dateTime);
}
/// <summary>
/// Converts native OLE datetime to managed DateTime
/// Used by MCG marshalling code
/// </summary>
public static DateTime FromNativeOleDate(double nativeOleDate)
{
return InteropExtensions.FromNativeOleDate(nativeOleDate);
}
/// <summary>
/// Used in Marshalling code
/// Call safeHandle.InitializeHandle to set the internal _handle field
/// </summary>
public static void InitializeHandle(SafeHandle safeHandle, IntPtr win32Handle)
{
InteropExtensions.InitializeHandle(safeHandle, win32Handle);
}
/// <summary>
/// Check if obj's type is the same as represented by normalized handle
/// </summary>
[MethodImpl(MethodImplOptions.NoInlining)]
public static bool IsOfType(object obj, RuntimeTypeHandle handle)
{
return obj.IsOfType(handle);
}
#if ENABLE_MIN_WINRT
public static unsafe void SetExceptionErrorCode(Exception exception, int errorCode)
{
InteropExtensions.SetExceptionErrorCode(exception, errorCode);
}
/// <summary>
/// Used in Marshalling code
/// Gets the handle of the CriticalHandle
/// </summary>
public static IntPtr GetHandle(CriticalHandle criticalHandle)
{
return InteropExtensions.GetCriticalHandle(criticalHandle);
}
/// <summary>
/// Used in Marshalling code
/// Sets the handle of the CriticalHandle
/// </summary>
public static void SetHandle(CriticalHandle criticalHandle, IntPtr handle)
{
InteropExtensions.SetCriticalHandle(criticalHandle, handle);
}
#endif
}
/// <summary>
/// McgMarshal helpers exposed to be used by MCG
/// </summary>
public static partial class McgMarshal
{
#region Type marshalling
public static Type TypeNameToType(HSTRING nativeTypeName, int nativeTypeKind)
{
#if ENABLE_WINRT
return McgTypeHelpers.TypeNameToType(nativeTypeName, nativeTypeKind);
#else
throw new NotSupportedException("TypeNameToType");
#endif
}
internal static Type TypeNameToType(string nativeTypeName, int nativeTypeKind)
{
#if ENABLE_WINRT
return McgTypeHelpers.TypeNameToType(nativeTypeName, nativeTypeKind, checkTypeKind: false);
#else
throw new NotSupportedException("TypeNameToType");
#endif
}
public static unsafe void TypeToTypeName(
Type type,
out HSTRING nativeTypeName,
out int nativeTypeKind)
{
#if ENABLE_WINRT
McgTypeHelpers.TypeToTypeName(type, out nativeTypeName, out nativeTypeKind);
#else
throw new NotSupportedException("TypeToTypeName");
#endif
}
/// <summary>
/// Fetch type name
/// </summary>
/// <param name="typeHandle">type</param>
/// <returns>type name</returns>
internal static string TypeToTypeName(RuntimeTypeHandle typeHandle, out int nativeTypeKind)
{
#if ENABLE_WINRT
TypeKind typekind;
string typeName;
McgTypeHelpers.TypeToTypeName(typeHandle, out typeName, out typekind);
nativeTypeKind = (int)typekind;
return typeName;
#else
throw new NotSupportedException("TypeToTypeName");
#endif
}
#endregion
#region String marshalling
[CLSCompliant(false)]
public static unsafe void StringBuilderToUnicodeString(System.Text.StringBuilder stringBuilder, ushort* destination)
{
PInvokeMarshal.StringBuilderToUnicodeString(stringBuilder, destination);
}
[CLSCompliant(false)]
public static unsafe void UnicodeStringToStringBuilder(ushort* newBuffer, System.Text.StringBuilder stringBuilder)
{
PInvokeMarshal.UnicodeStringToStringBuilder(newBuffer, stringBuilder);
}
#if !RHTESTCL
[CLSCompliant(false)]
public static unsafe void StringBuilderToAnsiString(System.Text.StringBuilder stringBuilder, byte* pNative,
bool bestFit, bool throwOnUnmappableChar)
{
PInvokeMarshal.StringBuilderToAnsiString(stringBuilder, pNative, bestFit, throwOnUnmappableChar);
}
[CLSCompliant(false)]
public static unsafe void AnsiStringToStringBuilder(byte* newBuffer, System.Text.StringBuilder stringBuilder)
{
PInvokeMarshal.AnsiStringToStringBuilder(newBuffer, stringBuilder);
}
/// <summary>
/// Convert ANSI string to unicode string, with option to free native memory. Calls generated by MCG
/// </summary>
/// <remarks>Input assumed to be zero terminated. Generates String.Empty for zero length string.
/// This version is more efficient than ConvertToUnicode in src\Interop\System\Runtime\InteropServices\Marshal.cs in that it can skip calling
/// MultiByteToWideChar for ASCII string, and it does not need another char[] buffer</remarks>
[CLSCompliant(false)]
public static unsafe string AnsiStringToString(byte* pchBuffer)
{
return PInvokeMarshal.AnsiStringToString(pchBuffer);
}
/// <summary>
/// Convert UNICODE string to ANSI string.
/// </summary>
/// <remarks>This version is more efficient than StringToHGlobalAnsi in Interop\System\Runtime\InteropServices\Marshal.cs in that
/// it could allocate single byte per character, instead of SystemMaxDBCSCharSize per char, and it can skip calling WideCharToMultiByte for ASCII string</remarks>
[CLSCompliant(false)]
public static unsafe byte* StringToAnsiString(string str, bool bestFit, bool throwOnUnmappableChar)
{
return PInvokeMarshal.StringToAnsiString(str, bestFit, throwOnUnmappableChar);
}
/// <summary>
/// Convert UNICODE wide char array to ANSI ByVal byte array.
/// </summary>
/// <remarks>
/// * This version works with array instead string, it means that there will be NO NULL to terminate the array.
/// * The buffer to store the byte array must be allocated by the caller and must fit managedArray.Length.
/// </remarks>
/// <param name="managedArray">UNICODE wide char array</param>
/// <param name="pNative">Allocated buffer where the ansi characters must be placed. Could NOT be null. Buffer size must fit char[].Length.</param>
[CLSCompliant(false)]
public static unsafe void ByValWideCharArrayToAnsiCharArray(char[] managedArray, byte* pNative, int expectedCharCount,
bool bestFit, bool throwOnUnmappableChar)
{
PInvokeMarshal.ByValWideCharArrayToAnsiCharArray(managedArray, pNative, expectedCharCount, bestFit, throwOnUnmappableChar);
}
[CLSCompliant(false)]
public static unsafe void ByValAnsiCharArrayToWideCharArray(byte* pNative, char[] managedArray)
{
PInvokeMarshal.ByValAnsiCharArrayToWideCharArray(pNative, managedArray);
}
[CLSCompliant(false)]
public static unsafe void WideCharArrayToAnsiCharArray(char[] managedArray, byte* pNative, bool bestFit, bool throwOnUnmappableChar)
{
PInvokeMarshal.WideCharArrayToAnsiCharArray(managedArray, pNative, bestFit, throwOnUnmappableChar);
}
/// <summary>
/// Convert ANSI ByVal byte array to UNICODE wide char array, best fit
/// </summary>
/// <remarks>
/// * This version works with array instead to string, it means that the len must be provided and there will be NO NULL to
/// terminate the array.
/// * The buffer to the UNICODE wide char array must be allocated by the caller.
/// </remarks>
/// <param name="pNative">Pointer to the ANSI byte array. Could NOT be null.</param>
/// <param name="lenInBytes">Maximum buffer size.</param>
/// <param name="managedArray">Wide char array that has already been allocated.</param>
[CLSCompliant(false)]
public static unsafe void AnsiCharArrayToWideCharArray(byte* pNative, char[] managedArray)
{
PInvokeMarshal.AnsiCharArrayToWideCharArray(pNative, managedArray);
}
/// <summary>
/// Convert a single UNICODE wide char to a single ANSI byte.
/// </summary>
/// <param name="managedArray">single UNICODE wide char value</param>
public static unsafe byte WideCharToAnsiChar(char managedValue, bool bestFit, bool throwOnUnmappableChar)
{
return PInvokeMarshal.WideCharToAnsiChar(managedValue, bestFit, throwOnUnmappableChar);
}
/// <summary>
/// Convert a single ANSI byte value to a single UNICODE wide char value, best fit.
/// </summary>
/// <param name="nativeValue">Single ANSI byte value.</param>
public static unsafe char AnsiCharToWideChar(byte nativeValue)
{
return PInvokeMarshal.AnsiCharToWideChar(nativeValue);
}
/// <summary>
/// Convert UNICODE string to ANSI ByVal string.
/// </summary>
/// <remarks>This version is more efficient than StringToHGlobalAnsi in Interop\System\Runtime\InteropServices\Marshal.cs in that
/// it could allocate single byte per character, instead of SystemMaxDBCSCharSize per char, and it can skip calling WideCharToMultiByte for ASCII string</remarks>
/// <param name="str">Unicode string.</param>
/// <param name="pNative"> Allocated buffer where the ansi string must be placed. Could NOT be null. Buffer size must fit str.Length.</param>
[CLSCompliant(false)]
public static unsafe void StringToByValAnsiString(string str, byte* pNative, int charCount, bool bestFit, bool throwOnUnmappableChar)
{
PInvokeMarshal.StringToByValAnsiString(str, pNative, charCount, bestFit, throwOnUnmappableChar);
}
/// <summary>
/// Convert ANSI string to unicode string, with option to free native memory. Calls generated by MCG
/// </summary>
/// <remarks>Input assumed to be zero terminated. Generates String.Empty for zero length string.
/// This version is more efficient than ConvertToUnicode in src\Interop\System\Runtime\InteropServices\Marshal.cs in that it can skip calling
/// MultiByteToWideChar for ASCII string, and it does not need another char[] buffer</remarks>
[CLSCompliant(false)]
public static unsafe string ByValAnsiStringToString(byte* pchBuffer, int charCount)
{
return PInvokeMarshal.ByValAnsiStringToString(pchBuffer, charCount);
}
#endif
#if ENABLE_WINRT
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static unsafe HSTRING StringToHString(string sourceString)
{
if (sourceString == null)
throw new ArgumentNullException(nameof(sourceString), SR.Null_HString);
return StringToHStringInternal(sourceString);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static unsafe HSTRING StringToHStringForField(string sourceString)
{
#if !RHTESTCL
if (sourceString == null)
throw new MarshalDirectiveException(SR.BadMarshalField_Null_HString);
#endif
return StringToHStringInternal(sourceString);
}
private static unsafe HSTRING StringToHStringInternal(string sourceString)
{
HSTRING ret;
int hr = StringToHStringNoNullCheck(sourceString, &ret);
if (hr < 0)
throw Marshal.GetExceptionForHR(hr);
return ret;
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
internal static unsafe int StringToHStringNoNullCheck(string sourceString, HSTRING* hstring)
{
fixed (char* pChars = sourceString)
{
int hr = ExternalInterop.WindowsCreateString(pChars, (uint)sourceString.Length, (void*)hstring);
return hr;
}
}
#endif //ENABLE_WINRT
#endregion
#region COM marshalling
/// <summary>
/// Explicit AddRef for RCWs
/// You can't call IFoo.AddRef anymore as IFoo no longer derive from IUnknown
/// You need to call McgMarshal.AddRef();
/// </summary>
/// <remarks>
/// Used by prefast MCG plugin (mcgimportpft) only
/// </remarks>
[CLSCompliant(false)]
public static int AddRef(__ComObject obj)
{
return obj.AddRef();
}
/// <summary>
/// Explicit Release for RCWs
/// You can't call IFoo.Release anymore as IFoo no longer derive from IUnknown
/// You need to call McgMarshal.Release();
/// </summary>
/// <remarks>
/// Used by prefast MCG plugin (mcgimportpft) only
/// </remarks>
[CLSCompliant(false)]
public static int Release(__ComObject obj)
{
return obj.Release();
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static unsafe int ComAddRef(IntPtr pComItf)
{
return CalliIntrinsics.StdCall__AddRef(((__com_IUnknown*)(void*)pComItf)->pVtable->
pfnAddRef, pComItf);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static unsafe int ComRelease_StdCall(IntPtr pComItf)
{
return CalliIntrinsics.StdCall__Release(((__com_IUnknown*)(void*)pComItf)->pVtable->
pfnRelease, pComItf);
}
/// <summary>
/// Inline version of ComRelease
/// </summary>
[MethodImpl(MethodImplOptions.NoInlining)] //reduces MCG-generated code size
public static unsafe int ComRelease(IntPtr pComItf)
{
IntPtr pRelease = ((__com_IUnknown*)(void*)pComItf)->pVtable->pfnRelease;
// Check if the COM object is implemented by PN Interop code, for which we can call directly
if (pRelease == AddrOfIntrinsics.AddrOf<AddrOfRelease>(__vtable_IUnknown.Release))
{
return __interface_ccw.DirectRelease(pComItf);
}
// Normal slow path, do not inline
return ComRelease_StdCall(pComItf);
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static unsafe int ComSafeRelease(IntPtr pComItf)
{
if (pComItf != default(IntPtr))
{
return ComRelease(pComItf);
}
return 0;
}
public static int FinalReleaseComObject(object o)
{
if (o == null)
throw new ArgumentNullException(nameof(o));
__ComObject co = null;
// Make sure the obj is an __ComObject.
try
{
co = (__ComObject)o;
}
catch (InvalidCastException)
{
throw new ArgumentException(SR.Argument_ObjNotComObject, nameof(o));
}
co.FinalReleaseSelf();
return 0;
}
/// <summary>
/// Returns the cached WinRT factory RCW under the current context
/// </summary>
[CLSCompliant(false)]
public static unsafe __ComObject GetActivationFactory(string className, RuntimeTypeHandle factoryIntf)
{
#if ENABLE_MIN_WINRT
return FactoryCache.Get().GetActivationFactory(className, factoryIntf);
#else
throw new PlatformNotSupportedException("GetActivationFactory");
#endif
}
/// <summary>
/// Used by CCW infrastructure code to return the target object from this pointer
/// </summary>
/// <returns>The target object pointed by this pointer</returns>
public static object ThisPointerToTargetObject(IntPtr pUnk)
{
return ComCallableObject.GetTarget(pUnk);
}
[CLSCompliant(false)]
public static object ComInterfaceToObject_NoUnboxing(
IntPtr pComItf,
RuntimeTypeHandle interfaceType)
{
return McgComHelpers.ComInterfaceToObjectInternal(
pComItf,
interfaceType,
default(RuntimeTypeHandle),
McgComHelpers.CreateComObjectFlags.SkipTypeResolutionAndUnboxing
);
}
/// <summary>
/// Shared CCW Interface To Object
/// </summary>
/// <param name="pComItf"></param>
/// <param name="interfaceType"></param>
/// <param name="classTypeInSignature"></param>
/// <returns></returns>
[CLSCompliant(false)]
public static object ComInterfaceToObject(
System.IntPtr pComItf,
RuntimeTypeHandle interfaceType,
RuntimeTypeHandle classTypeInSignature)
{
#if ENABLE_MIN_WINRT
if (interfaceType.Equals(typeof(object).TypeHandle))
{
return McgMarshal.IInspectableToObject(pComItf);
}
if (interfaceType.Equals(typeof(System.String).TypeHandle))
{
return McgMarshal.HStringToString(pComItf);
}
if (interfaceType.IsComClass())
{
RuntimeTypeHandle defaultInterface = interfaceType.GetDefaultInterface();
Debug.Assert(!defaultInterface.IsNull());
return ComInterfaceToObjectInternal(pComItf, defaultInterface, interfaceType);
}
#endif
return ComInterfaceToObjectInternal(
pComItf,
interfaceType,
classTypeInSignature
);
}
[CLSCompliant(false)]
public static object ComInterfaceToObject(
IntPtr pComItf,
RuntimeTypeHandle interfaceType)
{
return ComInterfaceToObject(pComItf, interfaceType, default(RuntimeTypeHandle));
}
private static object ComInterfaceToObjectInternal(
IntPtr pComItf,
RuntimeTypeHandle interfaceType,
RuntimeTypeHandle classTypeInSignature)
{
object result = McgComHelpers.ComInterfaceToObjectInternal(pComItf, interfaceType, classTypeInSignature, McgComHelpers.CreateComObjectFlags.None);
//
// Make sure the type we returned is actually of the right type
// NOTE: Don't pass null to IsInstanceOfClass as it'll return false
//
if (!classTypeInSignature.IsNull() && result != null)
{
if (!InteropExtensions.IsInstanceOfClass(result, classTypeInSignature))
throw new InvalidCastException();
}
return result;
}
public static unsafe IntPtr ComQueryInterfaceNoThrow(IntPtr pComItf, ref Guid iid)
{
int hr = 0;
return ComQueryInterfaceNoThrow(pComItf, ref iid, out hr);
}
public static unsafe IntPtr ComQueryInterfaceNoThrow(IntPtr pComItf, ref Guid iid, out int hr)
{
IntPtr pComIUnk;
hr = ComQueryInterfaceWithHR(pComItf, ref iid, out pComIUnk);
return pComIUnk;
}
internal static unsafe int ComQueryInterfaceWithHR(IntPtr pComItf, ref Guid iid, out IntPtr ppv)
{
IntPtr pComIUnk;
int hr;
fixed (Guid* unsafe_iid = &iid)
{
hr = CalliIntrinsics.StdCall__QueryInterface(((__com_IUnknown*)(void*)pComItf)->pVtable->
pfnQueryInterface,
pComItf,
new IntPtr(unsafe_iid),
new IntPtr(&pComIUnk));
}
if (hr != 0)
{
ppv = default(IntPtr);
}
else
{
ppv = pComIUnk;
}
return hr;
}
/// <summary>
/// Helper function to copy vTable to native heap on CoreCLR.
/// </summary>
/// <typeparam name="T">Vtbl type</typeparam>
/// <param name="pVtbl">static v-table field , always a valid pointer</param>
/// <param name="pNativeVtbl">Pointer to Vtable on native heap on CoreCLR , on N it's an alias for pVtbl</param>
public static unsafe IntPtr GetCCWVTableCopy(void* pVtbl, ref IntPtr pNativeVtbl, int size)
{
if (pNativeVtbl == default(IntPtr))
{
#if CORECLR
// On CoreCLR copy vTable to native heap , on N VTable is frozen.
IntPtr pv = Marshal.AllocHGlobal(size);
int* pSrc = (int*)pVtbl;
int* pDest = (int*)pv.ToPointer();
int pSize = sizeof(int);
// this should never happen , if a CCW is discarded we never get here.
Debug.Assert(size >= pSize);
for (int i = 0; i < size; i += pSize)
{
*pDest++ = *pSrc++;
}
if (Interlocked.CompareExchange(ref pNativeVtbl, pv, default(IntPtr)) != default(IntPtr))
{
// Another thread sneaked-in and updated pNativeVtbl , just use the update from other thread
Marshal.FreeHGlobal(pv);
}
#else // .NET NATIVE
// Wrap it in an IntPtr
pNativeVtbl = (IntPtr)pVtbl;
#endif // CORECLR
}
return pNativeVtbl;
}
[CLSCompliant(false)]
public static IntPtr ObjectToComInterface(
object obj,
RuntimeTypeHandle typeHnd)
{
#if ENABLE_MIN_WINRT
if (typeHnd.Equals(typeof(object).TypeHandle))
{
return McgMarshal.ObjectToIInspectable(obj);
}
if (typeHnd.Equals(typeof(System.String).TypeHandle))
{
return McgMarshal.StringToHString((string)obj).handle;
}
if (typeHnd.IsComClass())
{
Debug.Assert(obj == null || obj is __ComObject);
///
/// This code path should be executed only for WinRT classes
///
typeHnd = typeHnd.GetDefaultInterface();
Debug.Assert(!typeHnd.IsNull());
}
#endif
return McgComHelpers.ObjectToComInterfaceInternal(
obj,
typeHnd
);
}
public static IntPtr ObjectToIInspectable(Object obj)
{
#if ENABLE_MIN_WINRT
return ObjectToComInterface(obj, InternalTypes.IInspectable);
#else
throw new PlatformNotSupportedException("ObjectToIInspectable");
#endif
}
// This is not a safe function to use for any funtion pointers that do not point
// at a static function. This is due to the behavior of shared generics,
// where instance function entry points may share the exact same address
// but static functions are always represented in delegates with customized
// stubs.
private static bool DelegateTargetMethodEquals(Delegate del, IntPtr pfn)
{
RuntimeTypeHandle thDummy;
return del.GetFunctionPointer(out thDummy) == pfn;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static IntPtr DelegateToComInterface(Delegate del, RuntimeTypeHandle typeHnd)
{
if (del == null)
return default(IntPtr);
IntPtr stubFunctionAddr = typeHnd.GetDelegateInvokeStub();
object targetObj;
//
// If the delegate points to the forward stub for the native delegate,
// then we want the RCW associated with the native interface. Otherwise,
// this is a managed delegate, and we want the CCW associated with it.
//
if (DelegateTargetMethodEquals(del, stubFunctionAddr))
targetObj = del.Target;
else
targetObj = del;
return McgMarshal.ObjectToComInterface(targetObj, typeHnd);
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static Delegate ComInterfaceToDelegate(IntPtr pComItf, RuntimeTypeHandle typeHnd)
{
if (pComItf == default(IntPtr))
return null;
object obj = ComInterfaceToObject(pComItf, typeHnd, /* classIndexInSignature */ default(RuntimeTypeHandle));
//
// If the object we got back was a managed delegate, then we're good. Otherwise,
// the object is an RCW for a native delegate, so we need to wrap it with a managed
// delegate that invokes the correct stub.
//
Delegate del = obj as Delegate;
if (del == null)
{
Debug.Assert(obj is __ComObject);
IntPtr stubFunctionAddr = typeHnd.GetDelegateInvokeStub();
del = InteropExtensions.CreateDelegate(
typeHnd,
stubFunctionAddr,
obj,
/*isStatic:*/ true,
/*isVirtual:*/ false,
/*isOpen:*/ false);
}
return del;
}
/// <summary>
/// Marshal array of objects
/// </summary>
[MethodImplAttribute(MethodImplOptions.NoInlining)]
unsafe public static void ObjectArrayToComInterfaceArray(uint len, System.IntPtr* dst, object[] src, RuntimeTypeHandle typeHnd)
{
for (uint i = 0; i < len; i++)
{
dst[i] = McgMarshal.ObjectToComInterface(src[i], typeHnd);
}
}
/// <summary>
/// Allocate native memory, and then marshal array of objects
/// </summary>
[MethodImplAttribute(MethodImplOptions.NoInlining)]
unsafe public static System.IntPtr* ObjectArrayToComInterfaceArrayAlloc(object[] src, RuntimeTypeHandle typeHnd, out uint len)
{
System.IntPtr* dst = null;
len = 0;
if (src != null)
{
len = (uint)src.Length;
dst = (System.IntPtr*)PInvokeMarshal.CoTaskMemAlloc((System.UIntPtr)(len * (sizeof(System.IntPtr))));
for (uint i = 0; i < len; i++)
{
dst[i] = McgMarshal.ObjectToComInterface(src[i], typeHnd);
}
}
return dst;
}
/// <summary>
/// Get outer IInspectable for managed object deriving from native scenario
/// At this point the inner is not created yet - you need the outer first and pass it to the factory
/// to create the inner
/// </summary>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
[CLSCompliant(false)]
public static IntPtr GetOuterIInspectableForManagedObject(__ComObject managedObject)
{
ComCallableObject ccw = null;
try
{
//
// Create the CCW over the RCW
// Note that they are actually both the same object
// Base class = inner
// Derived class = outer
//
ccw = new ComCallableObject(
managedObject, // The target object = managedObject
managedObject // The inner RCW (as __ComObject) = managedObject
);
//
// Retrieve the outer IInspectable
// Pass skipInterfaceCheck = true to avoid redundant checks
//
return ccw.GetComInterfaceForType_NoCheck(InternalTypes.IInspectable, ref Interop.COM.IID_IInspectable);
}
finally
{
//
// Free the extra ref count initialized by __native_ccw.Init (to protect the CCW from being collected)
//
if (ccw != null)
ccw.Release();
}
}
[CLSCompliant(false)]
public static unsafe IntPtr ManagedObjectToComInterface(Object obj, RuntimeTypeHandle interfaceType)
{
return McgComHelpers.ManagedObjectToComInterface(obj, interfaceType);
}
public static unsafe object IInspectableToObject(IntPtr pComItf)
{
#if ENABLE_WINRT
return ComInterfaceToObject(pComItf, InternalTypes.IInspectable);
#else
throw new PlatformNotSupportedException("IInspectableToObject");
#endif
}
public static unsafe IntPtr CoCreateInstanceEx(Guid clsid, string server)
{
#if ENABLE_WINRT
Interop.COM.MULTI_QI results;
IntPtr pResults = new IntPtr(&results);
fixed (Guid* pIID = &Interop.COM.IID_IUnknown)
{
Guid* pClsid = &clsid;
results.pIID = new IntPtr(pIID);
results.pItf = IntPtr.Zero;
results.hr = 0;
int hr;
// if server name is specified, do remote server activation
if (!String.IsNullOrEmpty(server))
{
Interop.COM.COSERVERINFO serverInfo;
fixed (char* pName = server)
{
serverInfo.Name = new IntPtr(pName);
IntPtr pServerInfo = new IntPtr(&serverInfo);
hr = ExternalInterop.CoCreateInstanceFromApp(pClsid, IntPtr.Zero, (int)Interop.COM.CLSCTX.CLSCTX_REMOTE_SERVER, pServerInfo, 1, pResults);
}
}
else
{
hr = ExternalInterop.CoCreateInstanceFromApp(pClsid, IntPtr.Zero, (int)Interop.COM.CLSCTX.CLSCTX_SERVER, IntPtr.Zero, 1, pResults);
}
if (hr < 0)
{
throw McgMarshal.GetExceptionForHR(hr, /*isWinRTScenario = */ false);
}
if (results.hr < 0)
{
throw McgMarshal.GetExceptionForHR(results.hr, /* isWinRTScenario = */ false);
}
return results.pItf;
}
#else
throw new PlatformNotSupportedException("CoCreateInstanceEx");
#endif
}
public static unsafe IntPtr CoCreateInstanceEx(Guid clsid)
{
return CoCreateInstanceEx(clsid, string.Empty);
}
#endregion
#region Testing
/// <summary>
/// Internal-only method to allow testing of apartment teardown code
/// </summary>
public static void ReleaseRCWsInCurrentApartment()
{
ContextEntry.RemoveCurrentContext();
}
/// <summary>
/// Used by detecting leaks
/// Used in prefast MCG only
/// </summary>
public static int GetTotalComObjectCount()
{
return ComObjectCache.s_comObjectMap.Count;
}
/// <summary>
/// Used by detecting and dumping leaks
/// Used in prefast MCG only
/// </summary>
public static IEnumerable<__ComObject> GetAllComObjects()
{
List<__ComObject> list = new List<__ComObject>();
for (int i = 0; i < ComObjectCache.s_comObjectMap.GetMaxCount(); ++i)
{
IntPtr pHandle = default(IntPtr);
if (ComObjectCache.s_comObjectMap.GetValue(i, ref pHandle) && (pHandle != default(IntPtr)))
{
GCHandle handle = GCHandle.FromIntPtr(pHandle);
list.Add(InteropExtensions.UncheckedCast<__ComObject>(handle.Target));
}
}
return list;
}
#endregion
/// <summary>
/// This method returns HR for the exception being thrown.
/// 1. On Windows8+, WinRT scenarios we do the following.
/// a. Check whether the exception has any IRestrictedErrorInfo associated with it.
/// If so, it means that this exception was actually caused by a native exception in which case we do simply use the same
/// message and stacktrace.
/// b. If not, this is actually a managed exception and in this case we RoOriginateLanguageException with the msg, hresult and the IErrorInfo
/// associated with the managed exception. This helps us to retrieve the same exception in case it comes back to native.
/// 2. On win8 and for classic COM scenarios.
/// a. We create IErrorInfo for the given Exception object and SetErrorInfo with the given IErrorInfo.
/// </summary>
/// <param name="ex"></param>
[MethodImpl(MethodImplOptions.NoInlining)]
public static int GetHRForExceptionWinRT(Exception ex)
{
#if ENABLE_WINRT
return ExceptionHelpers.GetHRForExceptionWithErrorPropogationNoThrow(ex, true);
#else
// TODO : ExceptionHelpers should be platform specific , move it to
// seperate source files
return 0;
//return Marshal.GetHRForException(ex);
#endif
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static int GetHRForException(Exception ex)
{
#if ENABLE_WINRT
return ExceptionHelpers.GetHRForExceptionWithErrorPropogationNoThrow(ex, false);
#else
return ex.HResult;
#endif
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void ThrowOnExternalCallFailed(int hr, System.RuntimeTypeHandle typeHnd)
{
bool isWinRTScenario
#if ENABLE_WINRT
= typeHnd.IsSupportIInspectable();
#else
= false;
#endif
throw McgMarshal.GetExceptionForHR(hr, isWinRTScenario);
}
/// <summary>
/// This method returns a new Exception object given the HR value.
/// </summary>
/// <param name="hr"></param>
/// <param name="isWinRTScenario"></param>
public static Exception GetExceptionForHR(int hr, bool isWinRTScenario)
{
#if ENABLE_WINRT
return ExceptionHelpers.GetExceptionForHRInternalNoThrow(hr, isWinRTScenario, !isWinRTScenario);
#elif CORECLR
return Marshal.GetExceptionForHR(hr);
#else
return new COMException(hr.ToString(), hr);
#endif
}
#region Shared templates
#if ENABLE_MIN_WINRT
public static void CleanupNative<T>(IntPtr pObject)
{
if (typeof(T) == typeof(string))
{
global::System.Runtime.InteropServices.McgMarshal.FreeHString(pObject);
}
else
{
global::System.Runtime.InteropServices.McgMarshal.ComSafeRelease(pObject);
}
}
#endif
#endregion
#if ENABLE_MIN_WINRT
[MethodImpl(MethodImplOptions.NoInlining)]
public static unsafe IntPtr ActivateInstance(string typeName)
{
__ComObject target = McgMarshal.GetActivationFactory(
typeName,
InternalTypes.IActivationFactoryInternal
);
IntPtr pIActivationFactoryInternalItf = target.QueryInterface_NoAddRef_Internal(
InternalTypes.IActivationFactoryInternal,
/* cacheOnly= */ false,
/* throwOnQueryInterfaceFailure= */ true
);
__com_IActivationFactoryInternal* pIActivationFactoryInternal = (__com_IActivationFactoryInternal*)pIActivationFactoryInternalItf;
IntPtr pResult = default(IntPtr);
int hr = CalliIntrinsics.StdCall<int>(
pIActivationFactoryInternal->pVtable->pfnActivateInstance,
pIActivationFactoryInternal,
&pResult
);
GC.KeepAlive(target);
if (hr < 0)
{
throw McgMarshal.GetExceptionForHR(hr, /* isWinRTScenario = */ true);
}
return pResult;
}
#endif
[MethodImpl(MethodImplOptions.NoInlining)]
public static IntPtr GetInterface(
__ComObject obj,
RuntimeTypeHandle typeHnd)
{
return obj.QueryInterface_NoAddRef_Internal(
typeHnd);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static object GetDynamicAdapter(__ComObject obj, RuntimeTypeHandle requestedType, RuntimeTypeHandle existingType)
{
return obj.GetDynamicAdapter(requestedType, existingType);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static object GetDynamicAdapter(__ComObject obj, RuntimeTypeHandle requestedType)
{
return obj.GetDynamicAdapter(requestedType, default(RuntimeTypeHandle));
}
#region "PInvoke Delegate"
public static IntPtr GetStubForPInvokeDelegate(RuntimeTypeHandle delegateType, Delegate dele)
{
#if CORECLR
throw new NotSupportedException();
#else
return PInvokeMarshal.GetStubForPInvokeDelegate(dele);
#endif
}
/// <summary>
/// Retrieve the corresponding P/invoke instance from the stub
/// </summary>
public static Delegate GetPInvokeDelegateForStub(IntPtr pStub, RuntimeTypeHandle delegateType)
{
#if CORECLR
if (pStub == IntPtr.Zero)
return null;
McgPInvokeDelegateData pInvokeDelegateData;
if (!McgModuleManager.GetPInvokeDelegateData(delegateType, out pInvokeDelegateData))
{
return null;
}
return CalliIntrinsics.Call__Delegate(
pInvokeDelegateData.ForwardDelegateCreationStub,
pStub
);
#else
return PInvokeMarshal.GetPInvokeDelegateForStub(pStub, delegateType);
#endif
}
/// <summary>
/// Retrieves the function pointer for the current open static delegate that is being called
/// </summary>
public static IntPtr GetCurrentCalleeOpenStaticDelegateFunctionPointer()
{
#if RHTESTCL || CORECLR || CORERT
throw new NotSupportedException();
#else
return PInvokeMarshal.GetCurrentCalleeOpenStaticDelegateFunctionPointer();
#endif
}
/// <summary>
/// Retrieves the current delegate that is being called
/// </summary>
public static T GetCurrentCalleeDelegate<T>() where T : class // constraint can't be System.Delegate
{
#if RHTESTCL || CORECLR || CORERT
throw new NotSupportedException();
#else
return PInvokeMarshal.GetCurrentCalleeDelegate<T>();
#endif
}
#endregion
}
/// <summary>
/// McgMarshal helpers exposed to be used by MCG
/// </summary>
public static partial class McgMarshal
{
public static object UnboxIfBoxed(object target)
{
return UnboxIfBoxed(target, null);
}
public static object UnboxIfBoxed(object target, string className)
{
//
// If it is a managed wrapper, unbox it
//
object unboxedObj = McgComHelpers.UnboxManagedWrapperIfBoxed(target);
if (unboxedObj != target)
return unboxedObj;
if (className == null)
className = System.Runtime.InteropServices.McgComHelpers.GetRuntimeClassName(target);
if (!String.IsNullOrEmpty(className))
{
IntPtr unboxingStub;
if (McgModuleManager.TryGetUnboxingStub(className, out unboxingStub))
{
object ret = CalliIntrinsics.Call<object>(unboxingStub, target);
if (ret != null)
return ret;
}
#if ENABLE_WINRT
else if(McgModuleManager.UseDynamicInterop)
{
BoxingInterfaceKind boxingInterfaceKind;
RuntimeTypeHandle[] genericTypeArgument;
if (DynamicInteropBoxingHelpers.TryGetBoxingArgumentTypeHandleFromString(className, out boxingInterfaceKind, out genericTypeArgument))
{
Debug.Assert(target is __ComObject);
return DynamicInteropBoxingHelpers.Unboxing(boxingInterfaceKind, genericTypeArgument, target);
}
}
#endif
}
return null;
}
internal static object BoxIfBoxable(object target)
{
return BoxIfBoxable(target, default(RuntimeTypeHandle));
}
/// <summary>
/// Given a boxed value type, return a wrapper supports the IReference interface
/// </summary>
/// <param name="typeHandleOverride">
/// You might want to specify how to box this. For example, any object[] derived array could
/// potentially boxed as object[] if everything else fails
/// </param>
internal static object BoxIfBoxable(object target, RuntimeTypeHandle typeHandleOverride)
{
RuntimeTypeHandle expectedTypeHandle = typeHandleOverride;
if (expectedTypeHandle.Equals(default(RuntimeTypeHandle)))
expectedTypeHandle = target.GetTypeHandle();
RuntimeTypeHandle boxingWrapperType;
IntPtr boxingStub;
int boxingPropertyType;
if (McgModuleManager.TryGetBoxingWrapperType(expectedTypeHandle, target, out boxingWrapperType, out boxingPropertyType, out boxingStub))
{
if (!boxingWrapperType.IsInvalid())
{
//
// IReference<T> / IReferenceArray<T> / IKeyValuePair<K, V>
// All these scenarios require a managed wrapper
//
// Allocate the object
object refImplType = InteropExtensions.RuntimeNewObject(boxingWrapperType);
if (boxingPropertyType >= 0)
{
Debug.Assert(refImplType is BoxedValue);
BoxedValue boxed = InteropExtensions.UncheckedCast<BoxedValue>(refImplType);
// Call ReferenceImpl<T>.Initialize(obj, type);
boxed.Initialize(target, boxingPropertyType);
}
else
{
Debug.Assert(refImplType is BoxedKeyValuePair);
BoxedKeyValuePair boxed = InteropExtensions.UncheckedCast<BoxedKeyValuePair>(refImplType);
// IKeyValuePair<,>, call CLRIKeyValuePairImpl<K,V>.Initialize(object obj);
// IKeyValuePair<,>[], call CLRIKeyValuePairArrayImpl<K,V>.Initialize(object obj);
refImplType = boxed.Initialize(target);
}
return refImplType;
}
else
{
//
// General boxing for projected types, such as System.Uri
//
return CalliIntrinsics.Call<object>(boxingStub, target);
}
}
return null;
}
}
}
| |
using YAF.Lucene.Net.Support;
using YAF.Lucene.Net.Support.IO;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;// Used only for WRITE_LOCK_NAME in deprecated create=true case:
using System.Runtime.CompilerServices;
namespace YAF.Lucene.Net.Store
{
/*
* 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 Constants = Lucene.Net.Util.Constants;
using IOUtils = Lucene.Net.Util.IOUtils;
/// <summary>
/// Base class for <see cref="Directory"/> implementations that store index
/// files in the file system.
/// <para/>
/// There are currently three core
/// subclasses:
///
/// <list type="bullet">
///
/// <item><description> <see cref="SimpleFSDirectory"/> is a straightforward
/// implementation using <see cref="System.IO.FileStream"/>.
/// However, it has poor concurrent performance
/// (multiple threads will bottleneck) as it
/// synchronizes when multiple threads read from the
/// same file.</description></item>
///
/// <item><description> <see cref="NIOFSDirectory"/> uses java.nio's
/// FileChannel's positional io when reading to avoid
/// synchronization when reading from the same file.
/// Unfortunately, due to a Windows-only <a
/// href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6265734">Sun
/// JRE bug</a> this is a poor choice for Windows, but
/// on all other platforms this is the preferred
/// choice. Applications using <see cref="System.Threading.Thread.Interrupt()"/> or
/// <see cref="System.Threading.Tasks.Task{TResult}"/> should use
/// <see cref="SimpleFSDirectory"/> instead. See <see cref="NIOFSDirectory"/> java doc
/// for details.</description></item>
///
/// <item><description> <see cref="MMapDirectory"/> uses memory-mapped IO when
/// reading. This is a good choice if you have plenty
/// of virtual memory relative to your index size, eg
/// if you are running on a 64 bit runtime, or you are
/// running on a 32 bit runtime but your index sizes are
/// small enough to fit into the virtual memory space.
/// <para/>
/// Applications using <see cref="System.Threading.Thread.Interrupt()"/> or
/// <see cref="System.Threading.Tasks.Task"/> should use
/// <see cref="SimpleFSDirectory"/> instead. See <see cref="MMapDirectory"/>
/// doc for details.</description></item>
/// </list>
///
/// Unfortunately, because of system peculiarities, there is
/// no single overall best implementation. Therefore, we've
/// added the <see cref="Open(string)"/> method (or one of its overloads), to allow Lucene to choose
/// the best <see cref="FSDirectory"/> implementation given your
/// environment, and the known limitations of each
/// implementation. For users who have no reason to prefer a
/// specific implementation, it's best to simply use
/// <see cref="Open(string)"/> (or one of its overloads). For all others, you should instantiate the
/// desired implementation directly.
///
/// <para/>The locking implementation is by default
/// <see cref="NativeFSLockFactory"/>, but can be changed by
/// passing in a custom <see cref="LockFactory"/> instance.
/// </summary>
/// <seealso cref="Directory"/>
public abstract class FSDirectory : BaseDirectory
{
/// <summary>
/// Default read chunk size: 8192 bytes (this is the size up to which the runtime
/// does not allocate additional arrays while reading/writing) </summary>
[Obsolete("this constant is no longer used since Lucene 4.5.")]
public const int DEFAULT_READ_CHUNK_SIZE = 8192;
protected readonly DirectoryInfo m_directory; // The underlying filesystem directory
// LUCENENET specific: No such thing as "stale files" in .NET, since Flush(true) writes everything to disk before
// our FileStream is disposed.
//protected readonly ISet<string> m_staleFiles = new ConcurrentHashSet<string>(); // Files written, but not yet sync'ed
#pragma warning disable 612, 618
private int chunkSize = DEFAULT_READ_CHUNK_SIZE;
#pragma warning restore 612, 618
protected FSDirectory(DirectoryInfo dir)
: this(dir, null)
{
}
/// <summary>
/// Create a new <see cref="FSDirectory"/> for the named location (ctor for subclasses). </summary>
/// <param name="path"> the path of the directory </param>
/// <param name="lockFactory"> the lock factory to use, or null for the default
/// (<seealso cref="NativeFSLockFactory"/>); </param>
/// <exception cref="IOException"> if there is a low-level I/O error </exception>
protected internal FSDirectory(DirectoryInfo path, LockFactory lockFactory)
{
// new ctors use always NativeFSLockFactory as default:
if (lockFactory == null)
{
lockFactory = new NativeFSLockFactory();
}
m_directory = new DirectoryInfo(path.GetCanonicalPath());
if (File.Exists(path.FullName))
{
throw new DirectoryNotFoundException("file '" + path.FullName + "' exists but is not a directory");
}
SetLockFactory(lockFactory);
}
/// <summary>
/// Creates an <see cref="FSDirectory"/> instance, trying to pick the
/// best implementation given the current environment.
/// The directory returned uses the <see cref="NativeFSLockFactory"/>.
///
/// <para/>Currently this returns <see cref="MMapDirectory"/> for most Solaris
/// and Windows 64-bit runtimes, <see cref="NIOFSDirectory"/> for other
/// non-Windows runtimes, and <see cref="SimpleFSDirectory"/> for other
/// runtimes on Windows. It is highly recommended that you consult the
/// implementation's documentation for your platform before
/// using this method.
///
/// <para/><b>NOTE</b>: this method may suddenly change which
/// implementation is returned from release to release, in
/// the event that higher performance defaults become
/// possible; if the precise implementation is important to
/// your application, please instantiate it directly,
/// instead. For optimal performance you should consider using
/// <see cref="MMapDirectory"/> on 64 bit runtimes.
///
/// <para/>See <see cref="FSDirectory"/>.
/// </summary>
public static FSDirectory Open(DirectoryInfo path)
{
return Open(path, null);
}
/// <summary>
/// Just like <see cref="Open(DirectoryInfo)"/>, but
/// allows you to specify the directory as a <see cref="string"/>.
/// </summary>
/// <param name="path">The path (to a directory) to open</param>
/// <returns>An open <see cref="FSDirectory"/></returns>
public static FSDirectory Open(string path) // LUCENENET specific overload for ease of use with .NET
{
return Open(new DirectoryInfo(path), null);
}
/// <summary>
/// Just like <see cref="Open(DirectoryInfo)"/>, but allows you to
/// also specify a custom <see cref="LockFactory"/>.
/// </summary>
public static FSDirectory Open(DirectoryInfo path, LockFactory lockFactory)
{
if ((Constants.WINDOWS || Constants.SUN_OS || Constants.LINUX) && Constants.RUNTIME_IS_64BIT /*&&
MMapDirectory.UNMAP_SUPPORTED*/) // LUCENENET specific - unmap hack not needed
{
return new MMapDirectory(path, lockFactory);
}
else if (Constants.WINDOWS)
{
return new SimpleFSDirectory(path, lockFactory);
}
else
{
return new NIOFSDirectory(path, lockFactory);
}
}
/// <summary>
/// Just like <see cref="Open(DirectoryInfo, LockFactory)"/>, but
/// allows you to specify the directory as a <see cref="string"/>.
/// </summary>
/// <param name="path">The path (to a directory) to open</param>
/// <param name="lockFactory"></param>
/// <returns>An open <see cref="FSDirectory"/></returns>
public static FSDirectory Open(string path, LockFactory lockFactory) // LUCENENET specific overload for ease of use with .NET
{
return Open(new DirectoryInfo(path), lockFactory);
}
public override void SetLockFactory(LockFactory lockFactory)
{
base.SetLockFactory(lockFactory);
// for filesystem based LockFactory, delete the lockPrefix, if the locks are placed
// in index dir. If no index dir is given, set ourselves
if (lockFactory is FSLockFactory)
{
FSLockFactory lf = (FSLockFactory)lockFactory;
DirectoryInfo dir = lf.LockDir;
// if the lock factory has no lockDir set, use the this directory as lockDir
if (dir == null)
{
lf.SetLockDir(m_directory);
lf.LockPrefix = null;
}
else if (dir.GetCanonicalPath().Equals(m_directory.GetCanonicalPath(), StringComparison.Ordinal))
{
lf.LockPrefix = null;
}
}
}
/// <summary>
/// Lists all files (not subdirectories) in the
/// directory. This method never returns <c>null</c> (throws
/// <seealso cref="IOException"/> instead).
/// </summary>
/// <exception cref="DirectoryNotFoundException"> if the directory
/// does not exist, or does exist but is not a
/// directory or is invalid (for example, it is on an unmapped drive). </exception>
/// <exception cref="System.Security.SecurityException">The caller does not have the required permission.</exception>
public static string[] ListAll(DirectoryInfo dir)
{
if (!System.IO.Directory.Exists(dir.FullName))
{
throw new DirectoryNotFoundException("directory '" + dir + "' does not exist");
}
else if (File.Exists(dir.FullName))
{
throw new DirectoryNotFoundException("file '" + dir + "' exists but is not a directory");
}
// Exclude subdirs
FileInfo[] files = dir.EnumerateFiles().ToArray();
string[] result = new string[files.Length];
for (int i = 0; i < files.Length; i++)
{
result[i] = files[i].Name;
}
// LUCENENET NOTE: this can never happen in .NET
//if (result == null)
//{
// throw new System.IO.IOException("directory '" + dir + "' exists and is a directory, but cannot be listed: list() returned null");
//}
return result;
}
/// <summary>
/// Lists all files (not subdirectories) in the
/// directory. </summary>
/// <seealso cref="ListAll(DirectoryInfo)"/>
public override string[] ListAll()
{
EnsureOpen();
return ListAll(m_directory);
}
/// <summary>
/// Returns true iff a file with the given name exists. </summary>
[Obsolete("this method will be removed in 5.0")]
public override bool FileExists(string name)
{
EnsureOpen();
return File.Exists(Path.Combine(m_directory.FullName, name));
}
/// <summary>
/// Returns the length in bytes of a file in the directory. </summary>
public override long FileLength(string name)
{
EnsureOpen();
FileInfo file = new FileInfo(Path.Combine(m_directory.FullName, name));
long len = file.Length;
if (len == 0 && !file.Exists)
{
throw new FileNotFoundException(name);
}
else
{
return len;
}
}
/// <summary>
/// Removes an existing file in the directory. </summary>
public override void DeleteFile(string name)
{
EnsureOpen();
FileInfo file = new FileInfo(Path.Combine(m_directory.FullName, name));
// LUCENENET specific: We need to explicitly throw when the file has already been deleted,
// since FileInfo doesn't do that for us.
// (An enhancement carried over from Lucene 8.2.0)
if (!File.Exists(file.FullName))
{
throw new FileNotFoundException("Cannot delete " + file + " because it doesn't exist.");
}
try
{
file.Delete();
if (File.Exists(file.FullName))
{
throw new IOException("Cannot delete " + file);
}
}
catch (Exception e)
{
throw new IOException("Cannot delete " + file, e);
}
// LUCENENET specific: No such thing as "stale files" in .NET, since Flush(true) writes everything to disk before
// our FileStream is disposed.
//m_staleFiles.Remove(name);
}
/// <summary>
/// Creates an <see cref="IndexOutput"/> for the file with the given name. </summary>
public override IndexOutput CreateOutput(string name, IOContext context)
{
EnsureOpen();
EnsureCanWrite(name);
return new FSIndexOutput(this, name);
}
protected virtual void EnsureCanWrite(string name)
{
if (!m_directory.Exists)
{
try
{
m_directory.Create();
}
catch
{
throw new IOException("Cannot create directory: " + m_directory);
}
}
FileInfo file = new FileInfo(Path.Combine(m_directory.FullName, name));
if (file.Exists) // delete existing, if any
{
try
{
file.Delete();
}
catch
{
throw new IOException("Cannot overwrite: " + file);
}
}
}
protected virtual void OnIndexOutputClosed(FSIndexOutput io)
{
// LUCENENET specific: No such thing as "stale files" in .NET, since Flush(true) writes everything to disk before
// our FileStream is disposed.
//m_staleFiles.Add(io.name);
}
public override void Sync(ICollection<string> names)
{
EnsureOpen();
// LUCENENET specific: No such thing as "stale files" in .NET, since Flush(true) writes everything to disk before
// our FileStream is disposed. Therefore, there is nothing else to do in this method.
//ISet<string> toSync = new HashSet<string>(names);
//toSync.IntersectWith(m_staleFiles);
//// LUCENENET specific: Fsync breaks concurrency here.
//// Part of a solution suggested by Vincent Van Den Berghe: http://apache.markmail.org/message/hafnuhq2ydhfjmi2
////foreach (var name in toSync)
////{
//// Fsync(name);
////}
//// fsync the directory itsself, but only if there was any file fsynced before
//// (otherwise it can happen that the directory does not yet exist)!
//if (toSync.Count > 0)
//{
// IOUtils.Fsync(m_directory.FullName, true);
//}
//m_staleFiles.ExceptWith(toSync);
}
public override string GetLockID()
{
EnsureOpen();
string dirName; // name to be hashed
try
{
dirName = m_directory.GetCanonicalPath();
}
catch (IOException e)
{
throw new Exception(e.ToString(), e);
}
int digest = 0;
for (int charIDX = 0; charIDX < dirName.Length; charIDX++)
{
char ch = dirName[charIDX];
digest = 31*digest + ch;
}
return "lucene-" + digest.ToString("x", CultureInfo.InvariantCulture);
}
/// <summary>
/// Closes the store to future operations. </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
IsOpen = false;
}
}
/// <summary> the underlying filesystem directory </summary>
public virtual DirectoryInfo Directory
{
get
{
EnsureOpen();
return m_directory;
}
}
/// <summary>
/// For debug output. </summary>
public override string ToString()
{
return this.GetType().Name + "@" + m_directory + " lockFactory=" + LockFactory;
}
/// <summary>
/// this setting has no effect anymore. </summary>
[Obsolete("this is no longer used since Lucene 4.5.")]
public int ReadChunkSize
{
set
{
if (value <= 0)
{
throw new System.ArgumentException("chunkSize must be positive");
}
this.chunkSize = value;
}
get { return chunkSize; }
}
///// <summary>
/// Writes output with <see cref="FileStream.Write(byte[], int, int)"/>
/// </summary>
// LUCENENET specific: Since FileStream does its own buffering, this class was refactored
// to do all checksum operations as well as writing to the FileStream. By doing this we elminate
// the extra set of buffers that were only creating unnecessary memory allocations and copy operations.
protected class FSIndexOutput : BufferedIndexOutput
{
private const int CHUNK_SIZE = DEFAULT_BUFFER_SIZE;
private readonly FSDirectory parent;
internal readonly string name;
private readonly FileStream file;
private volatile bool isOpen; // remember if the file is open, so that we don't try to close it more than once
private readonly CRC32 crc = new CRC32();
public FSIndexOutput(FSDirectory parent, string name)
: base(CHUNK_SIZE, null)
{
this.parent = parent;
this.name = name;
file = new FileStream(
path: Path.Combine(parent.m_directory.FullName, name),
mode: FileMode.OpenOrCreate,
access: FileAccess.Write,
share: FileShare.ReadWrite,
bufferSize: CHUNK_SIZE);
isOpen = true;
}
/// <inheritdoc/>
public override void WriteByte(byte b)
{
if (!isOpen)
throw new ObjectDisposedException(nameof(FSIndexOutput));
crc.Update(b);
file.WriteByte(b);
}
/// <inheritdoc/>
public override void WriteBytes(byte[] b, int offset, int length)
{
if (!isOpen)
throw new ObjectDisposedException(nameof(FSIndexOutput));
crc.Update(b, offset, length);
file.Write(b, offset, length);
}
/// <inheritdoc/>
protected internal override void FlushBuffer(byte[] b, int offset, int size)
{
if (!isOpen)
throw new ObjectDisposedException(nameof(FSIndexOutput));
crc.Update(b, offset, size);
file.Write(b, offset, size);
}
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.NoInlining)]
public override void Flush()
{
if (!isOpen)
throw new ObjectDisposedException(nameof(FSIndexOutput));
file.Flush();
}
/// <inheritdoc/>
protected override void Dispose(bool disposing)
{
if (disposing)
{
parent.OnIndexOutputClosed(this);
// only close the file if it has not been closed yet
if (isOpen)
{
IOException priorE = null;
try
{
file.Flush(flushToDisk: true);
}
catch (IOException ioe)
{
priorE = ioe;
}
finally
{
isOpen = false;
IOUtils.DisposeWhileHandlingException(priorE, file);
}
}
}
}
/// <summary>
/// Random-access methods </summary>
[Obsolete("(4.1) this method will be removed in Lucene 5.0")]
public override void Seek(long pos)
{
if (!isOpen)
throw new ObjectDisposedException(nameof(FSIndexOutput));
file.Seek(pos, SeekOrigin.Begin);
}
/// <inheritdoc/>
public override long Length => file.Length;
// LUCENENET NOTE: FileStream doesn't have a way to set length
/// <inheritdoc/>
public override long Checksum => crc.Value; // LUCENENET specific - need to override, since we are buffering locally
/// <inheritdoc/>
public override long GetFilePointer() // LUCENENET specific - need to override, since we are buffering locally
{
return file.Position;
}
}
// LUCENENET specific: Fsync is pointless in .NET, since we are
// calling FileStream.Flush(true) before the stream is disposed
// which means we never need it at the point in Java where it is called.
//protected virtual void Fsync(string name)
//{
// IOUtils.Fsync(Path.Combine(m_directory.FullName, name), false);
//}
}
}
| |
///////////////////////////////////////////////////////////////////////////////////////////////
//
// This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler
//
// Copyright (c) 2005-2008, Jim Heising
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// * Neither the name of Jim Heising nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////////////////////////
namespace CallButler.Manager.ViewControls
{
partial class CallFlowView
{
/// <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(CallFlowView));
this.pnlOuter = new System.Windows.Forms.Panel();
this.diagramControl = new global::Controls.Diagram.DiagramControl();
this.pnlInfo = new global::Controls.RoundedCornerPanel();
this.lblInfoMessage = new System.Windows.Forms.Label();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.toolStrip = new System.Windows.Forms.ToolStrip();
this.btnSaveImage = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.btnMultilingual = new System.Windows.Forms.ToolStripButton();
this.cboLanguage = new System.Windows.Forms.ToolStripComboBox();
this.saveFileDialog = new System.Windows.Forms.SaveFileDialog();
this.btnOrientation = new System.Windows.Forms.ToolStripSplitButton();
this.mnuHorizontal = new System.Windows.Forms.ToolStripMenuItem();
this.mnuVertical = new System.Windows.Forms.ToolStripMenuItem();
this.pnlOuter.SuspendLayout();
this.pnlInfo.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.toolStrip.SuspendLayout();
this.SuspendLayout();
//
// pnlOuter
//
this.pnlOuter.Controls.Add(this.diagramControl);
this.pnlOuter.Controls.Add(this.pnlInfo);
this.pnlOuter.Controls.Add(this.toolStrip);
resources.ApplyResources(this.pnlOuter, "pnlOuter");
this.pnlOuter.Name = "pnlOuter";
//
// diagramControl
//
resources.ApplyResources(this.diagramControl, "diagramControl");
this.diagramControl.ChildNodeMargin = 50;
this.diagramControl.ConnectorType = global::Controls.Diagram.DiagramConnectorType.Bezier;
this.diagramControl.DrawArrows = true;
this.diagramControl.LayoutDirection = global::Controls.Diagram.DiagramLayoutDirection.Horizontal;
this.diagramControl.Name = "diagramControl";
this.diagramControl.PeerNodeMargin = 20;
this.diagramControl.RootShape = null;
this.diagramControl.ShowExpanders = false;
//
// pnlInfo
//
this.pnlInfo.BackColor = System.Drawing.Color.Transparent;
this.pnlInfo.BorderSize = 1F;
this.pnlInfo.Controls.Add(this.lblInfoMessage);
this.pnlInfo.Controls.Add(this.pictureBox1);
this.pnlInfo.CornerRadius = 5;
this.pnlInfo.DisplayShadow = false;
resources.ApplyResources(this.pnlInfo, "pnlInfo");
this.pnlInfo.ForeColor = System.Drawing.Color.Silver;
this.pnlInfo.Name = "pnlInfo";
this.pnlInfo.PanelColor = System.Drawing.Color.Beige;
this.pnlInfo.ShadowColor = System.Drawing.Color.Gray;
this.pnlInfo.ShadowOffset = 5;
//
// lblInfoMessage
//
resources.ApplyResources(this.lblInfoMessage, "lblInfoMessage");
this.lblInfoMessage.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(83)))), ((int)(((byte)(83)))), ((int)(((byte)(83)))));
this.lblInfoMessage.Name = "lblInfoMessage";
//
// pictureBox1
//
this.pictureBox1.BackColor = System.Drawing.Color.Transparent;
resources.ApplyResources(this.pictureBox1, "pictureBox1");
this.pictureBox1.Image = global::CallButler.Manager.Properties.Resources.information;
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.TabStop = false;
//
// toolStrip
//
this.toolStrip.BackColor = System.Drawing.Color.WhiteSmoke;
this.toolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.btnOrientation,
this.btnSaveImage,
this.toolStripSeparator1,
this.btnMultilingual,
this.cboLanguage});
resources.ApplyResources(this.toolStrip, "toolStrip");
this.toolStrip.Name = "toolStrip";
//
// btnSaveImage
//
this.btnSaveImage.Image = global::CallButler.Manager.Properties.Resources.photo_scenery_16;
resources.ApplyResources(this.btnSaveImage, "btnSaveImage");
this.btnSaveImage.Name = "btnSaveImage";
this.btnSaveImage.Click += new System.EventHandler(this.btnSaveImage_Click);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
resources.ApplyResources(this.toolStripSeparator1, "toolStripSeparator1");
//
// btnMultilingual
//
this.btnMultilingual.CheckOnClick = true;
this.btnMultilingual.Image = global::CallButler.Manager.Properties.Resources.earth2_16;
resources.ApplyResources(this.btnMultilingual, "btnMultilingual");
this.btnMultilingual.Name = "btnMultilingual";
this.btnMultilingual.CheckedChanged += new System.EventHandler(this.btnMultilingual_CheckedChanged);
//
// cboLanguage
//
this.cboLanguage.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cboLanguage.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(83)))), ((int)(((byte)(83)))), ((int)(((byte)(83)))));
this.cboLanguage.Name = "cboLanguage";
resources.ApplyResources(this.cboLanguage, "cboLanguage");
this.cboLanguage.SelectedIndexChanged += new System.EventHandler(this.cboLanguage_SelectedIndexChanged);
//
// saveFileDialog
//
this.saveFileDialog.DefaultExt = "GIF";
this.saveFileDialog.FileName = "CallButler CallFlow";
resources.ApplyResources(this.saveFileDialog, "saveFileDialog");
this.saveFileDialog.InitialDirectory = "My Documents";
//
// btnOrientation
//
this.btnOrientation.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.mnuHorizontal,
this.mnuVertical});
this.btnOrientation.Image = global::CallButler.Manager.Properties.Resources.refresh_16;
resources.ApplyResources(this.btnOrientation, "btnOrientation");
this.btnOrientation.Name = "btnOrientation";
this.btnOrientation.ButtonClick += new System.EventHandler(this.btnOrientation_ButtonClick);
//
// mnuHorizontal
//
this.mnuHorizontal.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(83)))), ((int)(((byte)(83)))), ((int)(((byte)(83)))));
this.mnuHorizontal.Name = "mnuHorizontal";
resources.ApplyResources(this.mnuHorizontal, "mnuHorizontal");
this.mnuHorizontal.Click += new System.EventHandler(this.mnuHorizontal_Click);
//
// mnuVertical
//
this.mnuVertical.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(83)))), ((int)(((byte)(83)))), ((int)(((byte)(83)))));
this.mnuVertical.Name = "mnuVertical";
resources.ApplyResources(this.mnuVertical, "mnuVertical");
this.mnuVertical.Click += new System.EventHandler(this.mnuVertical_Click);
//
// CallFlowView
//
resources.ApplyResources(this, "$this");
this.Controls.Add(this.pnlOuter);
this.HeaderIcon = global::CallButler.Manager.Properties.Resources.branch_48_shadow;
this.Name = "CallFlowView";
this.Controls.SetChildIndex(this.pnlOuter, 0);
this.pnlOuter.ResumeLayout(false);
this.pnlOuter.PerformLayout();
this.pnlInfo.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.toolStrip.ResumeLayout(false);
this.toolStrip.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Panel pnlOuter;
private System.Windows.Forms.ToolStrip toolStrip;
private System.Windows.Forms.ToolStripComboBox cboLanguage;
private System.Windows.Forms.ToolStripButton btnMultilingual;
private global::Controls.Diagram.DiagramControl diagramControl;
private global::Controls.RoundedCornerPanel pnlInfo;
private System.Windows.Forms.Label lblInfoMessage;
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.SaveFileDialog saveFileDialog;
private System.Windows.Forms.ToolStripButton btnSaveImage;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripSplitButton btnOrientation;
private System.Windows.Forms.ToolStripMenuItem mnuHorizontal;
private System.Windows.Forms.ToolStripMenuItem mnuVertical;
}
}
| |
// Copyright 2009 Auxilium B.V. - http://www.auxilium.nl/
//
// 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 JelloScrum.Services
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Configuration;
using System.Text;
using System.Threading;
using FileHelpers.DataLink;
using Model.Entities;
using Model.Enumerations;
using Model.Services;
using Model.Helpers;
public class ExcelExportService : IExcelExportService
{
private CultureInfo currentCulture;
/// <summary>
/// Maakt excel file met alle stories van de projectbacklog en geeft filename terug
/// </summary>
/// <param name="project">Project</param>
public string ExportProjectBacklog(Project project)
{
SetCultureInfo();
string fileName = String.Format("ProductBacklog_{0}_{1}.xls", DateTime.Now.ToString("yyyy-MM-dd") ,project.Name);
ExcelStorage provider = new ExcelStorage(typeof(ProductBackLog));
provider.StartRow = 2;
provider.StartColumn = 1;
provider.FileName = ConfigurationManager.AppSettings["exportLocation"] + fileName;
provider.TemplateFile = ConfigurationManager.AppSettings["productBackLogTemplate"];
List<ProductBackLog> res = new List<ProductBackLog>();
foreach (Story story in project.Stories)
{
ProductBackLog row = new ProductBackLog();
row.Id = story.Id.ToString();
row.Title = story.Title;
row.Priority = Enum.GetName(typeof(Priority), story.ProductBacklogPriority);
row.Type = Enum.GetName(typeof(StoryType), story.StoryType);
row.Description = story.Description;
row.Points = Enum.GetName(typeof(StoryPoint), story.StoryPoints);
row.Estimation = TimeSpanInMinuten(story.Estimation).ToString();
row.Tasks = story.Tasks.Count.ToString();
res.Add(row);
}
provider.InsertRecords(res.ToArray());
RestoreCultureInfo();
return fileName;
}
/// <summary>
/// Maakt excel file met alle stories van de sprintbacklog en geeft filename terug
/// </summary>
/// <param name="sprint">Sprint</param>
public string ExportSprintBacklog(Sprint sprint)
{
SetCultureInfo();
string fileName = String.Format("SprintBacklog_{0}_{1}.xls", DateTime.Now.ToString("yyyy-MM-dd"), sprint.Goal);
ExcelStorage provider = new ExcelStorage(typeof(SprintBackLog));
provider.StartRow = 2;
provider.StartColumn = 1;
provider.FileName = ConfigurationManager.AppSettings["exportLocation"] + fileName;
provider.TemplateFile = ConfigurationManager.AppSettings["sprintBackLogTemplate"];
List<SprintBackLog> res = new List<SprintBackLog>();
foreach (SprintStory sprintStory in sprint.SprintStories)
{
SprintBackLog row = new SprintBackLog();
row.Id = sprintStory.Id.ToString();
row.Title = sprintStory.Story.Title;
row.SprintPriority = Enum.GetName(typeof(Priority), sprintStory.SprintBacklogPriority);
row.ProjectPriority = Enum.GetName(typeof(Priority), sprintStory.Story.ProductBacklogPriority);
row.Type = Enum.GetName(typeof(StoryType), sprintStory.Story.StoryType);
row.Description = sprintStory.Story.Description;
row.Points = Enum.GetName(typeof(StoryPoint), sprintStory.Story.StoryPoints);
row.Estimation = TimeSpanInMinuten(sprintStory.Story.Estimation).ToString();
row.Tasks = sprintStory.Story.Tasks.Count.ToString();
res.Add(row);
}
provider.InsertRecords(res.ToArray());
RestoreCultureInfo();
return fileName;
}
/// <summary>
/// Maakt excel file met alle stories en taken van de sprint cardwall en geeft filename terug
/// </summary>
/// <param name="sprint">Sprint</param>
public string ExportSprintCardwall(Sprint sprint)
{
SetCultureInfo();
string fileName = String.Format("SprintCardwall_{0}_{1}.xls", DateTime.Now.ToString("yyyy-MM-dd"), sprint.Goal);
ExcelStorage provider = new ExcelStorage(typeof(Cardwall));
provider.StartRow = 3;
provider.StartColumn = 1;
provider.FileName = ConfigurationManager.AppSettings["exportLocation"] + fileName;
provider.TemplateFile = ConfigurationManager.AppSettings["sprintCardwallTemplate"];
List<Cardwall> res = new List<Cardwall>();
foreach (SprintStory sprintStory in sprint.SprintStories)
{
Cardwall storyRow = new Cardwall();
storyRow.StoryId = sprintStory.Id.ToString();
storyRow.StoryTitle = sprintStory.Story.Title;
storyRow.StoryPriority = Enum.GetName(typeof(Priority), sprintStory.Story.ProductBacklogPriority);
storyRow.StoryEstimatedHours = TimeSpanInMinuten(sprintStory.Story.Estimation).ToString();
res.Add(storyRow);
foreach (Task task in sprintStory.Story.Tasks)
{
Cardwall taskRow = new Cardwall();
switch(task.State)
{
case State.Open:
taskRow.TaskOpenId = task.Id.ToString();
taskRow.TaskOpenTitle = task.Title;
taskRow.TaskOpenAssignee = task.AssignedUserName;
taskRow.TaskOpenTimeSpent = TimeSpanInMinuten(task.TotalTimeSpent()).ToString();
break;
case State.Taken:
taskRow.TaskInProgressId = task.Id.ToString();
taskRow.TaskInProgressTitle = task.Title;
taskRow.TaskInProgressAssignee = task.AssignedUserName;
taskRow.TaskInProgressTimeSpent = TimeSpanInMinuten(task.TotalTimeSpent()).ToString();
break;
case State.Closed:
taskRow.TaskDoneId = task.Id.ToString();
taskRow.TaskDoneTitle = task.Title;
taskRow.TaskDoneAssignee = task.AssignedUserName;
taskRow.TaskDoneTimeSpent = TimeSpanInMinuten(task.TotalTimeSpent()).ToString();
break;
}
res.Add(taskRow);
}
}
provider.InsertRecords(res.ToArray());
RestoreCultureInfo();
return fileName;
}
/// <summary>
/// for the excel export to work, the currentculture MUST be en-US
/// </summary>
private void SetCultureInfo()
{
currentCulture = Thread.CurrentThread.CurrentCulture;
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
}
/// <summary>
/// Restore CulturInfo
/// </summary>
private void RestoreCultureInfo()
{
Thread.CurrentThread.CurrentCulture = currentCulture;
}
/// <summary>
/// Geeft de timespan geformatteerd als double HH,MM.
/// </summary>
/// <param name="timeSpan">De timespan.</param>
/// <returns>"HH,MM"</returns>
public static double TimeSpanInMinuten(TimeSpan timeSpan)
{
return Math.Round(timeSpan.TotalMinutes / 60, 2);
}
}
}
| |
/*
* MindTouch Core - open source enterprise collaborative networking
* Copyright (c) 2006-2010 MindTouch Inc.
* www.mindtouch.com oss@mindtouch.com
*
* For community documentation and downloads visit www.opengarden.org;
* please review the licensing section.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
* http://www.gnu.org/copyleft/gpl.html
*/
using System;
using System.IO;
using System.Diagnostics;
using log4net;
using MindTouch.Deki.Data;
using MindTouch.Dream;
using MindTouch.Tasking;
namespace MindTouch.Deki.Logic {
public static class AttachmentPreviewBL {
//--- Constants ---
private const string BADPREVIEWFILENAME = "badpreview.png";
private const string HEADERSTAT_CONVERT = "imconvert-ms";
private const string HEADERSTAT_IDENTIFY = "imidentify-ms";
//--- Class Fields ---
private static byte[] _badPreviewImageContent;
private new static readonly ILog _log = LogUtils.CreateLog();
//--- Class Methods ---
public static StreamInfo RetrievePreview(AttachmentBE attachment, uint height, uint width, RatioType ratio, SizeType size, FormatType format) {
string filename;
return RetrievePreview(attachment, height, width, ratio, size, format, out filename);
}
public static StreamInfo RetrievePreview(AttachmentBE attachment, uint height, uint width, RatioType ratio, SizeType size, FormatType format, out string filename) {
if (!AttachmentBL.Instance.IsAllowedForImageMagickPreview(attachment)) {
throw new DreamAbortException(DreamMessage.NotImplemented(string.Format(DekiResources.FAILED_WITH_MIME_TYPE, attachment.MimeType)));
}
if(format != FormatType.UNDEFINED && size != SizeType.UNDEFINED && size != SizeType.ORIGINAL && size != SizeType.CUSTOM) {
throw new DreamAbortException(DreamMessage.NotImplemented(DekiResources.FORMAT_CONVERSION_WITH_SIZE_UNSUPPORTED));
}
// check that attachment has a width and height defined
AttachmentBL.Instance.IdentifyUnknownImages(new AttachmentBE[] { attachment });
#region check validity of size, width, and height parameters
// NOTE (steveb): following table describes the possible state-transitions; note that the resulting graph must acyclic to avoid infinite loops.
// BESTFIT
// -> THUMB
// -> WEBVIEW
// -> ORIGINAL
// UNDEFINED
// -> CUSTOM
// -> ORIGINAL
// THUMB
// -> ORIGINAL
// WEBVIEW
// -> ORIGINAL
// CUSTOM
// -> ORIGINAL
// ORIGINAL
again:
switch(size) {
case SizeType.BESTFIT:
if(width == 0 && height == 0) {
// no dimensions specified, use original
size = SizeType.ORIGINAL;
goto again;
}
if(width <= DekiContext.Current.Instance.ImageThumbPixels && height <= DekiContext.Current.Instance.ImageThumbPixels) {
// thumbnail is big enough
size = SizeType.THUMB;
goto again;
} else if(width <= DekiContext.Current.Instance.ImageWebviewPixels && height <= DekiContext.Current.Instance.ImageWebviewPixels) {
// webview is big enough
size = SizeType.WEBVIEW;
goto again;
} else {
// use original
size = SizeType.ORIGINAL;
goto again;
}
case SizeType.CUSTOM:
if(height == 0 && width == 0) {
// no dimensions specified, use original
size = SizeType.ORIGINAL;
goto again;
}
if((attachment.ImageWidth <= width && attachment.ImageHeight <= height) && (attachment.ImageWidth >= 0 && attachment.ImageHeight >= 0)) {
// requested dimensions are larger than original, use original (we don't scale up!)
size = SizeType.ORIGINAL;
goto again;
}
break;
case SizeType.ORIGINAL:
width = 0;
height = 0;
break;
case SizeType.UNDEFINED:
if(height != 0 || width != 0) {
size = SizeType.CUSTOM;
goto again;
} else {
size = SizeType.ORIGINAL;
goto again;
}
case SizeType.THUMB:
width = DekiContext.Current.Instance.ImageThumbPixels;
height = DekiContext.Current.Instance.ImageThumbPixels;
if((attachment.ImageWidth <= width && attachment.ImageHeight <= height) && (attachment.ImageWidth >= 0 && attachment.ImageHeight >= 0)) {
size = SizeType.ORIGINAL;
goto again;
}
break;
case SizeType.WEBVIEW:
width = DekiContext.Current.Instance.ImageWebviewPixels;
height = DekiContext.Current.Instance.ImageWebviewPixels;
if((attachment.ImageWidth <= width && attachment.ImageHeight <= height) && (attachment.ImageWidth >= 0 && attachment.ImageHeight >= 0)) {
size = SizeType.ORIGINAL;
goto again;
}
break;
}
#endregion
// Asking to convert to the same format as original
if(format != FormatType.UNDEFINED && format == ResolvePreviewFormat(attachment.MimeType)) {
format = FormatType.UNDEFINED;
}
//Determine if the result is capable of being cached
bool cachable = (
format == FormatType.UNDEFINED //No format conversion
&& ratio != RatioType.VARIABLE //must be a fixed aspect ratio or not provided
&& (size == SizeType.THUMB || size == SizeType.WEBVIEW) //must be one of the known cached thumb sizes.
);
// load image
StreamInfo result = null;
try {
if(size == SizeType.ORIGINAL && format == FormatType.UNDEFINED) {
result = DekiContext.Current.Instance.Storage.GetFile(attachment, SizeType.ORIGINAL, false);
} else {
bool cached = false;
//The type of image is based on uploaded file's mimetype
if(format == FormatType.UNDEFINED) {
format = ResolvePreviewFormat(attachment.MimeType);
}
// check if image can be taken from the cache
if(cachable) {
result = GetCachedThumb(attachment, size);
cached = (result != null);
}
// load image if we haven't yet
if(result == null) {
result = DekiContext.Current.Instance.Storage.GetFile(attachment, SizeType.ORIGINAL, false);
if(result != null) {
result = BuildThumb(attachment, result, format, ratio, width, height);
}
}
// store result if possible and needed
if(cachable && !cached && (result != null)) {
SaveCachedThumb(attachment, size, result);
result = GetCachedThumb(attachment, size);
}
}
if(result == null) {
throw new DreamAbortException(BadPreviewImageMsg());
}
// full filename for response content-disposition header
switch(size) {
case SizeType.CUSTOM:
filename = string.Format("{0}_({1}x{2}){3}", attachment.Name, width == 0 ? "" : width.ToString(), height == 0 ? "" : height.ToString(), attachment.Extension == string.Empty ? string.Empty : "." + attachment.Extension);
break;
case SizeType.ORIGINAL:
filename = attachment.Name;
break;
case SizeType.BESTFIT:
case SizeType.THUMB:
case SizeType.UNDEFINED:
case SizeType.WEBVIEW:
default:
filename = string.Format("{0}_({1}){2}", attachment.Name, size.ToString().ToLowerInvariant(), attachment.Extension == string.Empty ? string.Empty : "." + attachment.Extension);
break;
}
if(format != FormatType.UNDEFINED) {
filename = Path.ChangeExtension(filename, format.ToString().ToLowerInvariant());
}
return result;
} catch {
if(result != null) {
result.Close();
}
throw;
}
}
public static void PreSaveAllPreviews(AttachmentBE attachment) {
if (AttachmentBL.Instance.IsAllowedForImageMagickPreview(attachment)) {
//The type of preview based on uploaded mimetype
FormatType previewFormat = ResolvePreviewFormat(attachment.MimeType);
// generate thumbnail
StreamInfo file = DekiContext.Current.Instance.Storage.GetFile(attachment, SizeType.ORIGINAL, false);
if(file != null) {
SaveCachedThumb(attachment, SizeType.THUMB, BuildThumb(attachment, file, previewFormat, RatioType.UNDEFINED, DekiContext.Current.Instance.ImageThumbPixels, DekiContext.Current.Instance.ImageThumbPixels));
}
// generate webview
file = DekiContext.Current.Instance.Storage.GetFile(attachment, SizeType.ORIGINAL, false);
if(file != null) {
SaveCachedThumb(attachment, SizeType.WEBVIEW, BuildThumb(attachment, file, previewFormat, RatioType.UNDEFINED, DekiContext.Current.Instance.ImageWebviewPixels, DekiContext.Current.Instance.ImageWebviewPixels));
}
}
}
private static StreamInfo GetCachedThumb(AttachmentBE attachment, SizeType size) {
StreamInfo result = null;
if(size == SizeType.THUMB || size == SizeType.WEBVIEW) {
result = DekiContext.Current.Instance.Storage.GetFile(attachment, size, false);
}
return result;
}
private static void SaveCachedThumb(AttachmentBE attachment, SizeType size, StreamInfo file) {
if(file != null) {
DekiContext.Current.Instance.Storage.PutFile(attachment, size, file);
}
}
private static StreamInfo BuildThumb(AttachmentBE attachment, StreamInfo file, FormatType format, RatioType ratio, uint width, uint height) {
if (!AttachmentBL.Instance.IsAllowedForImageMagickPreview(attachment)) {
return file;
}
return BuildThumb(file, format, ratio, width, height);
}
public static StreamInfo BuildThumb(StreamInfo file, FormatType format, RatioType ratio, uint width, uint height) {
using(file) {
//The mimetype of the thumb is based on the formattype. The
MimeType mime = ResolvePreviewMime(ref format);
//Some basic DoS protection.
if(!IsPreviewSizeAllowed(width, height)) {
throw new Exceptions.ImagePreviewOversizedException();
}
string thumbnailArgs = string.Empty;
if(width > 0 || height > 0) {
thumbnailArgs = string.Format("-colorspace RGB -thumbnail {0}{1}{2}{3}", width == 0 ? "" : width.ToString(), height > 0 ? "x" : "", height == 0 ? string.Empty : height.ToString(), ratio == RatioType.FIXED || ratio == RatioType.UNDEFINED ? "" : "!");
}
// NOTE (steveb): the '-[0]' option means that we only want to convert the first frame if there are multiple frames
string args = string.Format("{0} -[0] {1}-", thumbnailArgs, (format == FormatType.UNDEFINED) ? string.Empty : format.ToString() + ":");
Stopwatch sw = Stopwatch.StartNew();
// run ImageMagick application
Tuplet<int, Stream, Stream> exitValues = Async.ExecuteProcess(DekiContext.Current.Deki.ImageMagickConvertPath, args, file.Stream, new Result<Tuplet<int, Stream, Stream>>(TimeSpan.FromMilliseconds(DekiContext.Current.Deki.ImageMagickTimeout))).Wait();
// record stats about this imagemagick execution
sw.Stop();
AddToStats(HEADERSTAT_CONVERT, sw.ElapsedMilliseconds);
int status = exitValues.Item1;
Stream outputStream = exitValues.Item2;
Stream errorStream = exitValues.Item3;
if(outputStream.Length == 0) {
using(StreamReader error = new StreamReader(errorStream)) {
_log.WarnMethodCall("Imagemagick convert failed", args, status, error.ReadToEnd());
}
return null;
}
_log.InfoFormat("Imagemagick convert finished in {0}ms. Args:{1}", sw.ElapsedMilliseconds, args);
return new StreamInfo(outputStream, outputStream.Length, mime);
}
}
/// <summary>
/// Given the mimetype of an original file, return the mimetype of the preview images
/// </summary>
/// <param name="mime"></param>
/// <returns></returns>
public static MimeType ResolvePreviewMime(MimeType mime) {
FormatType f = ResolvePreviewFormat(mime);
MimeType m = ResolvePreviewMime(ref f);
return m;
}
/// <summary>
/// Given a formattype, return the associated mimetype. Used for user-defined conversions
/// </summary>
/// <param name="format"></param>
/// <returns></returns>
private static MimeType ResolvePreviewMime(ref FormatType format) {
MimeType mime;
switch (format) {
case FormatType.BMP:
mime = MimeType.BMP;
break;
case FormatType.GIF:
mime = MimeType.GIF;
break;
case FormatType.JPG:
mime = MimeType.JPEG;
break;
case FormatType.PNG:
mime = MimeType.PNG;
break;
default:
mime = MimeType.JPEG;
format = FormatType.JPG;
break;
}
return mime;
}
/// <summary>
/// Given the mimetype of an original file, return the formattype for the preview images to be used by imagemagick
/// </summary>
/// <param name="mime"></param>
/// <returns></returns>
private static FormatType ResolvePreviewFormat(MimeType mime) {
if(mime.Match(MimeType.JPEG) || mime.Match(new MimeType("image/x-jpeg"))) {
return FormatType.JPG;
}
if(mime.Match(MimeType.PNG) || mime.Match(new MimeType("image/x-png"))) {
return FormatType.PNG;
}
if(mime.Match(MimeType.BMP) || mime.Match(new MimeType("image/x-bmp"))) {
return FormatType.BMP;
}
if(mime.Match(MimeType.GIF) || mime.Match(new MimeType("image/x-gif"))) {
return FormatType.GIF;
}
return FormatType.JPG;
}
/// <summary>
/// Retrieves image dimensions.
/// </summary>
/// <param name="file"></param>
/// <param name="width"></param>
/// <param name="height"></param>
/// <returns>True if image too large to be identified or identifying succeeded. False if identification attempted but failed</returns>
public static bool RetrieveImageDimensions(StreamInfo file, out int width, out int height, out int frames) {
width = 0;
height = 0;
frames = 0;
if(file == null) {
return false;
}
using(file) {
// prevent manipulation of large images
if (DekiContext.Current.Instance.MaxImageSize < (ulong) file.Length) {
return true;
}
Stopwatch sw = Stopwatch.StartNew();
// execute imagemagick-identify
Tuplet<int, Stream, Stream> exitValues = Async.ExecuteProcess(DekiContext.Current.Deki.ImageMagickIdentifyPath, "-format \"%wx%h \" -", file.Stream, new Result<Tuplet<int,Stream,Stream>>(TimeSpan.FromMilliseconds(DekiContext.Current.Deki.ImageMagickTimeout))).Wait();
// record stats about this imagemagick execution
sw.Stop();
AddToStats(HEADERSTAT_IDENTIFY, sw.ElapsedMilliseconds);
int status = exitValues.Item1;
Stream outputStream = exitValues.Item2;
Stream errorStream = exitValues.Item3;
// parse output
string output = new StreamReader(outputStream).ReadToEnd();
string[] dimensions = output.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
foreach(string dimension in dimensions) {
int tmpWidth;
int tmpHeight;
string[] parts = dimension.Split(new char[] { 'x' }, 2);
if(parts.Length == 2) {
int.TryParse(parts[0], out tmpWidth);
int.TryParse(parts[1], out tmpHeight);
if((tmpWidth > 0) && (tmpHeight > 0)) {
++frames;
width = Math.Max(width, tmpWidth);
height = Math.Max(height, tmpHeight);
}
}
}
_log.InfoFormat("Imagemagick identify finished in {0}ms", sw.ElapsedMilliseconds);
}
return frames > 0;
}
private static DreamMessage BadPreviewImageMsg() {
DreamMessage errorMsg = null;
string filepath = Utils.PathCombine(DekiContext.Current.Deki.ResourcesPath, "images", BADPREVIEWFILENAME);
try {
lock (BADPREVIEWFILENAME) {
if (_badPreviewImageContent == null || _badPreviewImageContent.Length == 0) {
_badPreviewImageContent = System.IO.File.ReadAllBytes(filepath);
}
}
}
catch (Exception) { }
if (_badPreviewImageContent != null && _badPreviewImageContent.Length > 0) {
errorMsg = new DreamMessage(DreamStatus.InternalError, null, MimeType.FromFileExtension(BADPREVIEWFILENAME), _badPreviewImageContent);
}
else {
errorMsg = new DreamMessage(DreamStatus.InternalError, null, MimeType.TEXT, DekiResources.CANNOT_CREATE_THUMBNAIL);
}
return errorMsg;
}
private static bool IsPreviewSizeAllowed(uint width, uint height) {
uint maxWidth = Math.Max(1024, Math.Max(DekiContext.Current.Instance.ImageThumbPixels, DekiContext.Current.Instance.ImageWebviewPixels));
uint maxHeight = Math.Max(768, Math.Max(DekiContext.Current.Instance.ImageThumbPixels, DekiContext.Current.Instance.ImageWebviewPixels));
if(height * width > maxWidth * maxHeight) {
return false;
}
return true;
}
private static void AddToStats(string statName, long value) {
string current;
if(DekiContext.Current.Stats.TryGetValue(statName, out current)) {
long currentLong;
if(long.TryParse(current, out currentLong)) {
currentLong += value;
current = currentLong.ToString();
}
}
if(string.IsNullOrEmpty(current)) {
current = value.ToString();
}
DekiContext.Current.Stats[statName] = current;
}
}
}
| |
using System;
using System.Collections.Generic;
using MLAPI.Transports.Tasks;
namespace MLAPI.Transports.Multiplex
{
/// <summary>
/// Multiplex transport adapter.
/// </summary>
public class MultiplexTransportAdapter : NetworkTransport
{
/// <summary>
/// The method to use to distribute the transport connectionIds in a fixed size 64 bit integer.
/// </summary>
public enum ConnectionIdSpreadMethod
{
/// <summary>
/// Drops the first few bits (left side) by shifting the transport clientId to the left and inserting the transportId in the first bits.
/// Ensure that ALL transports dont use the last bits in their produced clientId.
/// For incremental clientIds, this is the most space efficient assuming that every transport get used an equal amount.
/// </summary>
MakeRoomLastBits,
/// <summary>
/// Drops the first few bits (left side) and replaces them with the transport index.
/// Ensure that ALL transports dont use the first few bits in the produced clientId.
/// </summary>
ReplaceFirstBits,
/// <summary>
/// Drops the last few bits (right side) and replaces them with the transport index.
/// Ensure that ALL transports dont use the last bits in their produced clientId.
/// This option is for advanced users and will not work with the official MLAPI transports as they use the last bits.
/// </summary>
ReplaceLastBits,
/// <summary>
/// Drops the last few bits (right side) by shifting the transport clientId to the right and inserting the transportId in the first bits.
/// Ensure that ALL transports dont use the first bits in their produced clientId.
/// </summary>
MakeRoomFirstBits,
/// <summary>
/// Spreads the clientIds evenly among the transports.
/// </summary>
Spread
}
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
public ConnectionIdSpreadMethod SpreadMethod = ConnectionIdSpreadMethod.MakeRoomLastBits;
public NetworkTransport[] Transports = new NetworkTransport[0];
public override ulong ServerClientId => 0;
private byte m_LastProcessedTransportIndex;
public override bool IsSupported => true;
public override void DisconnectLocalClient()
{
Transports[GetFirstSupportedTransportIndex()].DisconnectLocalClient();
}
public override void DisconnectRemoteClient(ulong clientId)
{
GetMultiplexTransportDetails(clientId, out byte transportId, out ulong connectionId);
Transports[transportId].DisconnectRemoteClient(connectionId);
}
public override ulong GetCurrentRtt(ulong clientId)
{
GetMultiplexTransportDetails(clientId, out byte transportId, out ulong connectionId);
return Transports[transportId].GetCurrentRtt(connectionId);
}
public override void Init()
{
for (int i = 0; i < Transports.Length; i++)
{
if (Transports[i].IsSupported)
{
Transports[i].Init();
}
}
}
public override NetworkEvent PollEvent(out ulong clientId, out NetworkChannel networkChannel, out ArraySegment<byte> payload, out float receiveTime)
{
if (m_LastProcessedTransportIndex >= Transports.Length - 1)
{
m_LastProcessedTransportIndex = 0;
}
for (byte i = m_LastProcessedTransportIndex; i < Transports.Length; i++)
{
m_LastProcessedTransportIndex = i;
if (Transports[i].IsSupported)
{
var networkEvent = Transports[i].PollEvent(out ulong connectionId, out networkChannel, out payload, out receiveTime);
if (networkEvent != NetworkEvent.Nothing)
{
clientId = GetMLAPIClientId(i, connectionId, false);
return networkEvent;
}
}
}
clientId = 0;
networkChannel = 0;
payload = new ArraySegment<byte>();
receiveTime = 0;
return NetworkEvent.Nothing;
}
public override void Send(ulong clientId, ArraySegment<byte> data, NetworkChannel networkChannel)
{
GetMultiplexTransportDetails(clientId, out byte transportId, out ulong connectionId);
Transports[transportId].Send(connectionId, data, networkChannel);
}
public override void Shutdown()
{
for (int i = 0; i < Transports.Length; i++)
{
if (Transports[i].IsSupported)
{
Transports[i].Shutdown();
}
}
}
public override SocketTasks StartClient()
{
var socketTasks = new List<SocketTask>();
for (int i = 0; i < Transports.Length; i++)
{
if (Transports[i].IsSupported)
{
socketTasks.AddRange(Transports[i].StartClient().Tasks);
}
}
return new SocketTasks { Tasks = socketTasks.ToArray() };
}
public override SocketTasks StartServer()
{
var socketTasks = new List<SocketTask>();
for (int i = 0; i < Transports.Length; i++)
{
if (Transports[i].IsSupported)
{
socketTasks.AddRange(Transports[i].StartServer().Tasks);
}
}
return new SocketTasks { Tasks = socketTasks.ToArray() };
}
public ulong GetMLAPIClientId(byte transportId, ulong connectionId, bool isServer)
{
if (isServer)
{
return ServerClientId;
}
switch (SpreadMethod)
{
case ConnectionIdSpreadMethod.ReplaceFirstBits:
{
// Calculate bits to store transportId
byte bits = (byte)UnityEngine.Mathf.CeilToInt(UnityEngine.Mathf.Log(Transports.Length, 2));
// Drop first bits of connectionId
ulong clientId = ((connectionId << bits) >> bits);
// Place transportId there
ulong shiftedTransportId = (ulong)transportId << ((sizeof(ulong) * 8) - bits);
return (clientId | shiftedTransportId) + 1;
}
case ConnectionIdSpreadMethod.MakeRoomFirstBits:
{
// Calculate bits to store transportId
byte bits = (byte)UnityEngine.Mathf.CeilToInt(UnityEngine.Mathf.Log(Transports.Length, 2));
// Drop first bits of connectionId
ulong clientId = (connectionId >> bits);
// Place transportId there
ulong shiftedTransportId = (ulong)transportId << ((sizeof(ulong) * 8) - bits);
return (clientId | shiftedTransportId) + 1;
}
case ConnectionIdSpreadMethod.ReplaceLastBits:
{
// Calculate bits to store transportId
byte bits = (byte)UnityEngine.Mathf.CeilToInt(UnityEngine.Mathf.Log(Transports.Length, 2));
// Drop the last bits of connectionId
ulong clientId = ((connectionId >> bits) << bits);
// Return the transport inserted at the end
return (clientId | transportId) + 1;
}
case ConnectionIdSpreadMethod.MakeRoomLastBits:
{
// Calculate bits to store transportId
byte bits = (byte)UnityEngine.Mathf.CeilToInt(UnityEngine.Mathf.Log(Transports.Length, 2));
// Drop the last bits of connectionId
ulong clientId = (connectionId << bits);
// Return the transport inserted at the end
return (clientId | transportId) + 1;
}
case ConnectionIdSpreadMethod.Spread:
{
return (connectionId * (ulong)Transports.Length + (ulong)transportId) + 1;
}
default:
{
return ServerClientId;
}
}
}
public void GetMultiplexTransportDetails(ulong clientId, out byte transportId, out ulong connectionId)
{
if (clientId == ServerClientId)
{
transportId = GetFirstSupportedTransportIndex();
connectionId = Transports[transportId].ServerClientId;
}
else
{
switch (SpreadMethod)
{
case ConnectionIdSpreadMethod.ReplaceFirstBits:
{
// The first clientId is reserved. Thus every clientId is always offset by 1
clientId--;
// Calculate bits to store transportId
byte bits = (byte)UnityEngine.Mathf.CeilToInt(UnityEngine.Mathf.Log(Transports.Length, 2));
transportId = (byte)(clientId >> ((sizeof(ulong) * 8) - bits));
connectionId = ((clientId << bits) >> bits);
break;
}
case ConnectionIdSpreadMethod.MakeRoomFirstBits:
{
// The first clientId is reserved. Thus every clientId is always offset by 1
clientId--;
// Calculate bits to store transportId
byte bits = (byte)UnityEngine.Mathf.CeilToInt(UnityEngine.Mathf.Log(Transports.Length, 2));
transportId = (byte)(clientId >> ((sizeof(ulong) * 8) - bits));
connectionId = (clientId << bits);
break;
}
case ConnectionIdSpreadMethod.ReplaceLastBits:
{
// The first clientId is reserved. Thus every clientId is always offset by 1
clientId--;
// Calculate bits to store transportId
byte bits = (byte)UnityEngine.Mathf.CeilToInt(UnityEngine.Mathf.Log(Transports.Length, 2));
transportId = (byte)((clientId << ((sizeof(ulong) * 8) - bits)) >> ((sizeof(ulong) * 8) - bits));
connectionId = ((clientId >> bits) << bits);
break;
}
case ConnectionIdSpreadMethod.MakeRoomLastBits:
{
// The first clientId is reserved. Thus every clientId is always offset by 1
clientId--;
// Calculate bits to store transportId
byte bits = (byte)UnityEngine.Mathf.CeilToInt(UnityEngine.Mathf.Log(Transports.Length, 2));
transportId = (byte)((clientId << ((sizeof(ulong) * 8) - bits)) >> ((sizeof(ulong) * 8) - bits));
connectionId = (clientId >> bits);
break;
}
case ConnectionIdSpreadMethod.Spread:
{
// The first clientId is reserved. Thus every clientId is always offset by 1
clientId--;
transportId = (byte)(clientId % (ulong)Transports.Length);
connectionId = (clientId / (ulong)Transports.Length);
break;
}
default:
{
transportId = GetFirstSupportedTransportIndex();
connectionId = Transports[transportId].ServerClientId;
break;
}
}
}
}
public byte GetFirstSupportedTransportIndex()
{
for (byte i = 0; i < Transports.Length; i++)
{
if (Transports[i].IsSupported)
{
return i;
}
}
return 0;
}
#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member
}
}
| |
// ***********************************************************************
// Copyright (c) 2007-2014 Charlie Poole
//
// 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 !PORTABLE
using System;
using System.Collections;
namespace NUnit.Framework.Internal
{
/// <summary>
/// Summary description for PlatformHelperTests.
/// </summary>
[TestFixture]
public class PlatformDetectionTests
{
private static readonly PlatformHelper win95Helper = new PlatformHelper(
new OSPlatform( PlatformID.Win32Windows , new Version( 4, 0 ) ),
new RuntimeFramework( RuntimeType.Net, new Version( 1, 1, 4322, 0 ) ) );
private static readonly PlatformHelper winXPHelper = new PlatformHelper(
new OSPlatform( PlatformID.Win32NT , new Version( 5,1 ) ),
new RuntimeFramework( RuntimeType.Net, new Version( 1, 1, 4322, 0 ) ) );
private void CheckOSPlatforms( OSPlatform os,
string expectedPlatforms )
{
Assert.That(expectedPlatforms, Is.SubsetOf(PlatformHelper.OSPlatforms).IgnoreCase,
"Error in test: one or more expected platforms is not a valid OSPlatform.");
CheckPlatforms(
new PlatformHelper( os, RuntimeFramework.CurrentFramework ),
expectedPlatforms,
PlatformHelper.OSPlatforms );
}
private void CheckRuntimePlatforms( RuntimeFramework runtimeFramework,
string expectedPlatforms )
{
CheckPlatforms(
new PlatformHelper( OSPlatform.CurrentPlatform, runtimeFramework ),
expectedPlatforms,
PlatformHelper.RuntimePlatforms + ",NET-1.0,NET-1.1,NET-2.0,NET-3.0,NET-3.5,NET-4.0,NET-4.5,MONO-1.0,MONO-2.0,MONO-3.0,MONO-3.5,MONO-4.0,MONOTOUCH,NETCF-2.0,NETCF-3.5,SL-3.0,SL-4.0,SL-5.0" );
}
private void CheckPlatforms( PlatformHelper helper,
string expectedPlatforms, string checkPlatforms )
{
string[] expected = expectedPlatforms.Split( new char[] { ',' } );
string[] check = checkPlatforms.Split( new char[] { ',' } );
foreach( string testPlatform in check )
{
bool shouldPass = false;
foreach( string platform in expected )
if ( shouldPass = platform.ToLower() == testPlatform.ToLower() )
break;
bool didPass = helper.IsPlatformSupported( testPlatform );
if ( shouldPass && !didPass )
Assert.Fail( "Failed to detect {0}", testPlatform );
else if ( didPass && !shouldPass )
Assert.Fail( "False positive on {0}", testPlatform );
else if ( !shouldPass && !didPass )
Assert.AreEqual( "Only supported on " + testPlatform, helper.Reason );
}
}
[Test]
public void DetectWin95()
{
CheckOSPlatforms(
new OSPlatform( PlatformID.Win32Windows, new Version( 4, 0 ) ),
"Win95,Win32Windows,Win32,Win" );
}
[Test]
public void DetectWin98()
{
CheckOSPlatforms(
new OSPlatform( PlatformID.Win32Windows, new Version( 4, 10 ) ),
"Win98,Win32Windows,Win32,Win" );
}
[Test]
public void DetectWinMe()
{
CheckOSPlatforms(
new OSPlatform( PlatformID.Win32Windows, new Version( 4, 90 ) ),
"WinMe,Win32Windows,Win32,Win" );
}
// WinCE isn't defined in .NET 1.0.
[Test, Platform(Exclude="Net-1.0")]
public void DetectWinCE()
{
PlatformID winCE = (PlatformID)Enum.Parse(typeof(PlatformID), "WinCE", false);
CheckOSPlatforms(
new OSPlatform(winCE, new Version(1, 0)),
"WinCE,Win32,Win" );
}
[Test]
public void DetectNT3()
{
CheckOSPlatforms(
new OSPlatform( PlatformID.Win32NT, new Version( 3, 51 ) ),
"NT3,Win32NT,Win32,Win" );
}
[Test]
public void DetectNT4()
{
CheckOSPlatforms(
new OSPlatform( PlatformID.Win32NT, new Version( 4, 0 ) ),
"NT4,Win32NT,Win32,Win" );
}
[Test]
public void DetectWin2K()
{
CheckOSPlatforms(
new OSPlatform( PlatformID.Win32NT, new Version( 5, 0 ) ),
"Win2K,NT5,Win32NT,Win32,Win" );
}
[Test]
public void DetectWinXP()
{
CheckOSPlatforms(
new OSPlatform( PlatformID.Win32NT, new Version( 5, 1 ) ),
"WinXP,NT5,Win32NT,Win32,Win" );
}
[Test]
public void DetectWinXPProfessionalX64()
{
CheckOSPlatforms(
new OSPlatform( PlatformID.Win32NT, new Version( 5, 2 ), OSPlatform.ProductType.WorkStation ),
"WinXP,NT5,Win32NT,Win32,Win" );
}
[Test]
public void DetectWin2003Server()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.Win32NT, new Version(5, 2), OSPlatform.ProductType.Server),
"Win2003Server,NT5,Win32NT,Win32,Win");
}
[Test]
public void DetectVista()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.Win32NT, new Version(6, 0), OSPlatform.ProductType.WorkStation),
"Vista,NT6,Win32NT,Win32,Win");
}
[Test]
public void DetectWin2008ServerOriginal()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.Win32NT, new Version(6, 0), OSPlatform.ProductType.Server),
"Win2008Server,NT6,Win32NT,Win32,Win");
}
[Test]
public void DetectWin2008ServerR2()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.Win32NT, new Version(6, 1), OSPlatform.ProductType.Server),
"Win2008Server,Win2008ServerR2,NT6,Win32NT,Win32,Win");
}
[Test]
public void DetectWindows7()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.Win32NT, new Version(6, 1), OSPlatform.ProductType.WorkStation),
"Win7,Windows7,NT6,Win32NT,Win32,Win");
}
[Test]
public void DetectWindows2012ServerOriginal()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.Win32NT, new Version(6, 2), OSPlatform.ProductType.Server),
"Win2012Server,Win2012ServerR1,NT6,Win32NT,Win32,Win");
}
[Test]
public void DetectWindows2012ServerR2()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.Win32NT, new Version(6, 3), OSPlatform.ProductType.Server),
"Win2012Server,Win2012ServerR2,NT6,Win32NT,Win32,Win");
}
[Test]
public void DetectWindows8()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.Win32NT, new Version(6, 2), OSPlatform.ProductType.WorkStation),
"Win8,Windows8,NT6,Win32NT,Win32,Win");
}
[Test]
public void DetectWindows81()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.Win32NT, new Version(6, 3), OSPlatform.ProductType.WorkStation),
"Win8.1,Windows8.1,NT6,Win32NT,Win32,Win");
}
[Test]
public void DetectWindows10()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.Win32NT, new Version(10, 0), OSPlatform.ProductType.WorkStation),
"Win10,Windows10,Win32NT,Win32,Win");
}
[Test]
public void DetectWindowsServer()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.Win32NT, new Version(10, 0), OSPlatform.ProductType.Server),
"WindowsServer10,Win32NT,Win32,Win");
}
[Test]
public void DetectUnixUnderMicrosoftDotNet()
{
CheckOSPlatforms(
new OSPlatform(OSPlatform.UnixPlatformID_Microsoft, new Version(0,0)),
"UNIX,Linux");
}
// This throws under Microsoft .Net due to the invalid enumeration value of 128
[Test, Platform(Exclude="Net")]
public void DetectUnixUnderMono()
{
CheckOSPlatforms(
new OSPlatform(OSPlatform.UnixPlatformID_Mono, new Version(0,0)),
"UNIX,Linux");
}
#if !NETCF
[Test]
public void DetectXbox()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.Xbox, new Version(0, 0)),
"Xbox");
}
[Test]
public void DetectMacOSX()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.MacOSX, new Version(0, 0)),
"MacOSX");
}
#endif
[Test]
public void DetectNet10()
{
CheckRuntimePlatforms(
new RuntimeFramework( RuntimeType.Net, new Version( 1, 0, 3705, 0 ) ),
"NET,NET-1.0" );
}
[Test]
public void DetectNet11()
{
CheckRuntimePlatforms(
new RuntimeFramework( RuntimeType.Net, new Version( 1, 1, 4322, 0 ) ),
"NET,NET-1.1" );
}
[Test]
public void DetectNet20()
{
CheckRuntimePlatforms(
new RuntimeFramework( RuntimeType.Net, new Version( 2, 0, 50727, 0 ) ),
"Net,Net-2.0" );
}
[Test]
public void DetectNet30()
{
CheckRuntimePlatforms(
new RuntimeFramework(RuntimeType.Net, new Version(3, 0)),
"Net,Net-2.0,Net-3.0");
}
[Test]
public void DetectNet35()
{
CheckRuntimePlatforms(
new RuntimeFramework(RuntimeType.Net, new Version(3, 5)),
"Net,Net-2.0,Net-3.0,Net-3.5");
}
[Test]
public void DetectNet40()
{
CheckRuntimePlatforms(
new RuntimeFramework(RuntimeType.Net, new Version(4, 0, 30319, 0)),
"Net,Net-4.0");
}
[Test]
public void DetectNetCF()
{
CheckRuntimePlatforms(
new RuntimeFramework( RuntimeType.NetCF, new Version( 1, 1, 4322, 0 ) ),
"NetCF" );
}
[Test]
public void DetectSSCLI()
{
CheckRuntimePlatforms(
new RuntimeFramework( RuntimeType.SSCLI, new Version( 1, 0, 3, 0 ) ),
"SSCLI,Rotor" );
}
[Test]
public void DetectMono10()
{
CheckRuntimePlatforms(
new RuntimeFramework( RuntimeType.Mono, new Version( 1, 1, 4322, 0 ) ),
"Mono,Mono-1.0" );
}
[Test]
public void DetectMono20()
{
CheckRuntimePlatforms(
new RuntimeFramework( RuntimeType.Mono, new Version( 2, 0, 50727, 0 ) ),
"Mono,Mono-2.0" );
}
[Test]
public void DetectMono30()
{
CheckRuntimePlatforms(
new RuntimeFramework(RuntimeType.Mono, new Version(3, 0)),
"Mono,Mono-2.0,Mono-3.0");
}
[Test]
public void DetectMono35()
{
CheckRuntimePlatforms(
new RuntimeFramework(RuntimeType.Mono, new Version(3, 5)),
"Mono,Mono-2.0,Mono-3.0,Mono-3.5");
}
[Test]
public void DetectMono40()
{
CheckRuntimePlatforms(
new RuntimeFramework(RuntimeType.Mono, new Version(4, 0, 30319)),
"Mono,Mono-4.0");
}
[Test]
public void DetectMonoTouch()
{
CheckRuntimePlatforms(
new RuntimeFramework(RuntimeType.MonoTouch, new Version(4, 0, 30319)),
"MonoTouch");
}
[Test]
public void DetectSilverlight30()
{
CheckRuntimePlatforms(
new RuntimeFramework(RuntimeType.Silverlight, new Version(3, 0)),
"Silverlight,SL-3.0");
}
[Test]
public void DetectSilverlight40()
{
CheckRuntimePlatforms(
new RuntimeFramework(RuntimeType.Silverlight, new Version(4, 0)),
"Silverlight,SL-4.0");
}
[Test]
public void DetectSilverlight50()
{
CheckRuntimePlatforms(
new RuntimeFramework(RuntimeType.Silverlight, new Version(5, 0)),
"Silverlight,SL-5.0");
}
[Test]
public void DetectExactVersion()
{
Assert.IsTrue( winXPHelper.IsPlatformSupported( "net-1.1.4322" ) );
Assert.IsTrue( winXPHelper.IsPlatformSupported( "net-1.1.4322.0" ) );
Assert.IsFalse( winXPHelper.IsPlatformSupported( "net-1.1.4323.0" ) );
Assert.IsFalse( winXPHelper.IsPlatformSupported( "net-1.1.4322.1" ) );
}
[Test]
public void ArrayOfPlatforms()
{
string[] platforms = new string[] { "NT4", "Win2K", "WinXP" };
Assert.IsTrue( winXPHelper.IsPlatformSupported( platforms ) );
Assert.IsFalse( win95Helper.IsPlatformSupported( platforms ) );
}
[Test]
public void PlatformAttribute_Include()
{
PlatformAttribute attr = new PlatformAttribute( "Win2K,WinXP,NT4" );
Assert.IsTrue( winXPHelper.IsPlatformSupported( attr ) );
Assert.IsFalse( win95Helper.IsPlatformSupported( attr ) );
Assert.AreEqual("Only supported on Win2K,WinXP,NT4", win95Helper.Reason);
}
[Test]
public void PlatformAttribute_Exclude()
{
PlatformAttribute attr = new PlatformAttribute();
attr.Exclude = "Win2K,WinXP,NT4";
Assert.IsFalse( winXPHelper.IsPlatformSupported( attr ) );
Assert.AreEqual( "Not supported on Win2K,WinXP,NT4", winXPHelper.Reason );
Assert.IsTrue( win95Helper.IsPlatformSupported( attr ) );
}
[Test]
public void PlatformAttribute_IncludeAndExclude()
{
PlatformAttribute attr = new PlatformAttribute( "Win2K,WinXP,NT4" );
attr.Exclude = "Mono";
Assert.IsFalse( win95Helper.IsPlatformSupported( attr ) );
Assert.AreEqual( "Only supported on Win2K,WinXP,NT4", win95Helper.Reason );
Assert.IsTrue( winXPHelper.IsPlatformSupported( attr ) );
attr.Exclude = "Net";
Assert.IsFalse( win95Helper.IsPlatformSupported( attr ) );
Assert.AreEqual( "Only supported on Win2K,WinXP,NT4", win95Helper.Reason );
Assert.IsFalse( winXPHelper.IsPlatformSupported( attr ) );
Assert.AreEqual( "Not supported on Net", winXPHelper.Reason );
}
[Test]
public void PlatformAttribute_InvalidPlatform()
{
PlatformAttribute attr = new PlatformAttribute( "Net-1.0,Net11,Mono" );
Assert.IsFalse( winXPHelper.IsPlatformSupported( attr ) );
Assert.That( winXPHelper.Reason, Does.StartWith("Invalid platform name"));
Assert.That( winXPHelper.Reason, Does.Contain("Net11"));
}
[Test]
public void PlatformAttribute_ProcessBitNess()
{
PlatformAttribute attr32 = new PlatformAttribute("32-Bit");
PlatformAttribute attr64 = new PlatformAttribute("64-Bit");
PlatformHelper helper = new PlatformHelper();
// This test verifies that the two labels are known,
// do not cause an error and return consistent results.
bool is32BitProcess = helper.IsPlatformSupported(attr32);
bool is64BitProcess = helper.IsPlatformSupported(attr64);
Assert.False(is32BitProcess & is64BitProcess, "Process cannot be both 32 and 64 bit");
#if NET_4_0 || NET_4_5 || PORTABLE
// For .NET 4.0 and 4.5, we can check further
Assert.That(is64BitProcess, Is.EqualTo(Environment.Is64BitProcess));
#endif
}
#if NET_4_0 || NET_4_5 || PORTABLE
[Test]
public void PlatformAttribute_OperatingSystemBitNess()
{
PlatformAttribute attr32 = new PlatformAttribute("32-Bit-OS");
PlatformAttribute attr64 = new PlatformAttribute("64-Bit-OS");
PlatformHelper helper = new PlatformHelper();
bool is64BitOS = Environment.Is64BitOperatingSystem;
Assert.That(helper.IsPlatformSupported(attr32), Is.Not.EqualTo(is64BitOS));
Assert.That(helper.IsPlatformSupported(attr64), Is.EqualTo(is64BitOS));
}
#endif
}
}
#endif
| |
//! \file Audio.cs
//! \date Tue Nov 04 17:35:54 2014
//! \brief audio format class.
//
// Copyright (C) 2014 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.IO;
using System.Linq;
namespace GameRes
{
public struct WaveFormat
{
public ushort FormatTag;
public ushort Channels;
public uint SamplesPerSecond;
public uint AverageBytesPerSecond;
public ushort BlockAlign;
public ushort BitsPerSample;
public ushort ExtraSize;
public void SetBPS ()
{
AverageBytesPerSecond = (uint)(SamplesPerSecond * Channels * BitsPerSample / 8);
}
}
public abstract class SoundInput : Stream
{
public abstract int SourceBitrate { get; }
public abstract string SourceFormat { get; }
public WaveFormat Format { get; protected set; }
public Stream Source { get; protected set; }
public long PcmSize { get; protected set; }
protected SoundInput (Stream input)
{
Source = input;
}
public virtual void Reset ()
{
Position = 0;
}
#region System.IO.Stream methods
public override bool CanRead { get { return Source.CanRead; } }
public override bool CanWrite { get { return false; } }
public override long Length { get { return PcmSize; } }
public override void Flush()
{
Source.Flush();
}
public override long Seek(long offset, SeekOrigin origin)
{
if (origin == SeekOrigin.Begin)
Position = offset;
else if (origin == SeekOrigin.Current)
Position += offset;
else
Position = Length + offset;
return Position;
}
public override void SetLength (long length)
{
throw new System.NotSupportedException ("SoundInput.SetLength method is not supported");
}
public override void Write (byte[] buffer, int offset, int count)
{
throw new System.NotSupportedException ("SoundInput.Write method is not supported");
}
public override void WriteByte (byte value)
{
throw new System.NotSupportedException ("SoundInput.WriteByte method is not supported");
}
#endregion
#region IDisposable Members
bool disposed = false;
protected override void Dispose (bool disposing)
{
if (!disposed)
{
if (disposing)
{
Source.Dispose();
}
disposed = true;
base.Dispose (disposing);
}
}
#endregion
}
/// <summary>
/// Class representing raw PCM sound input.
/// </summary>
public class RawPcmInput : SoundInput
{
public override string SourceFormat { get { return "raw"; } }
public override int SourceBitrate
{
get { return (int)Format.AverageBytesPerSecond * 8; }
}
public RawPcmInput (Stream file, WaveFormat format) : base (file)
{
this.Format = format;
this.PcmSize = file.Length;
}
#region IO.Stream methods
public override long Position
{
get { return Source.Position; }
set { Source.Position = value; }
}
public override bool CanSeek { get { return Source.CanSeek; } }
public override long Seek (long offset, SeekOrigin origin)
{
return Source.Seek (offset, origin);
}
public override int Read (byte[] buffer, int offset, int count)
{
return Source.Read (buffer, offset, count);
}
public override int ReadByte ()
{
return Source.ReadByte();
}
#endregion
}
public abstract class AudioFormat : IResource
{
public override string Type { get { return "audio"; } }
public abstract SoundInput TryOpen (IBinaryStream file);
public virtual void Write (SoundInput source, Stream output)
{
throw new System.NotImplementedException ("AudioFormat.Write not implemenented");
}
public static SoundInput Read (IBinaryStream file)
{
foreach (var impl in FormatCatalog.Instance.FindFormats<AudioFormat> (file.Name, file.Signature))
{
try
{
file.Position = 0;
SoundInput sound = impl.TryOpen (file);
if (null != sound)
return sound;
}
catch (OperationCanceledException)
{
throw;
}
catch (System.Exception X)
{
FormatCatalog.Instance.LastError = X;
}
}
return null;
}
public static AudioFormat Wav { get { return s_WavFormat.Value; } }
static readonly Lazy<AudioFormat> s_WavFormat = new Lazy<AudioFormat> (() => FormatCatalog.Instance.AudioFormats.FirstOrDefault (x => x.Tag == "WAV"));
}
}
| |
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using DereTore.Common;
namespace DereTore.Exchange.Audio.HCA {
internal sealed unsafe class ChannelArray : DisposableBase {
static ChannelArray() {
}
public ChannelArray(int channelCount) {
ChannelCount = channelCount;
var totalSize = channelCount * ChannelSize;
_basePtr = Marshal.AllocHGlobal(totalSize);
ZeroMemory(_basePtr.ToPointer(), totalSize);
}
public int ChannelCount { get; }
public void Decode1(int channelIndex, DataBits data, uint a, int b, byte[] ath) {
var v = data.GetBit(3);
var pCount = GetPtrOfCount(channelIndex);
var pValue = GetPtrOfValue(channelIndex);
if (v >= 6) {
for (var i = 0; i < *pCount; ++i) {
pValue[i] = (sbyte)data.GetBit(6);
}
} else if (v != 0) {
var v1 = data.GetBit(6);
var v2 = (1 << v) - 1;
var v3 = v2 >> 1;
pValue[0] = (sbyte)v1;
for (var i = 1; i < *pCount; ++i) {
var v4 = data.GetBit(v);
if (v4 != v2) {
v1 += v4 - v3;
} else {
v1 = data.GetBit(6);
}
pValue[i] = (sbyte)v1;
}
} else {
ZeroMemory(pValue, 0x80);
}
var pType = GetPtrOfType(channelIndex);
var pValue2 = GetPtrOfValue2(channelIndex);
var ppValue3 = GetPtrOfValue3(channelIndex);
if (*pType == 2) {
v = data.CheckBit(4);
pValue2[0] = (sbyte)v;
if (v < 15) {
for (var i = 0; i < 8; ++i) {
pValue2[i] = (sbyte)data.GetBit(4);
}
}
} else {
for (var i = 0; i < a; ++i) {
(*ppValue3)[i] = (sbyte)data.GetBit(6);
}
}
var pScale = GetPtrOfScale(channelIndex);
for (var i = 0; i < *pCount; ++i) {
v = pValue[i];
if (v != 0) {
v = ath[i] + ((b + i) >> 8) - ((v * 5) >> 1) + 1;
if (v < 0) {
v = 15;
} else if (v >= 0x39) {
v = 1;
} else {
v = ChannelTables.Decode1ScaleList[v];
}
}
pScale[i] = (sbyte)v;
}
ZeroMemory(&pScale[*pCount], (int)(0x80 - *pCount));
var pBase = GetPtrOfBase(channelIndex);
for (var i = 0; i < *pCount; ++i) {
pBase[i] = ChannelTables.Decode1ValueSingle[pValue[i]] * ChannelTables.Decode1ScaleSingle[pScale[i]];
}
}
public void Decode2(int channelIndex, DataBits data) {
var pCount = GetPtrOfCount(channelIndex);
var pScale = GetPtrOfScale(channelIndex);
var pBlock = GetPtrOfBlock(channelIndex);
var pBase = GetPtrOfBase(channelIndex);
for (var i = 0; i < *pCount; ++i) {
int s = pScale[i];
int bitSize = ChannelTables.Decode2List1[s];
var v = data.GetBit(bitSize);
float f;
if (s < 8) {
v += s << 4;
data.AddBit(ChannelTables.Decode2List2[v] - bitSize);
f = ChannelTables.Decode2List3[v];
} else {
v = (1 - ((v & 1) << 1)) * (v >> 1);
if (v == 0) {
data.AddBit(-1);
}
f = v;
}
pBlock[i] = pBase[i] * f;
}
ZeroMemory(&pBlock[*pCount], sizeof(float) * (int)(0x80 - *pCount));
}
public void Decode3(int channelIndex, uint a, uint b, uint c, uint d) {
var pType = GetPtrOfType(channelIndex);
if (*pType != 2 && b != 0) {
fixed (float* listFloatBase = ChannelTables.Decode3ListSingle) {
var pBlock = GetPtrOfBlock(channelIndex);
var ppValue3 = GetPtrOfValue3(channelIndex);
var pValue = GetPtrOfValue(channelIndex);
var listFloat = listFloatBase + 0x40;
var k = c;
var l = c - 1;
for (var i = 0; i < a; ++i) {
for (var j = 0; j < b && k < d; ++j, --l) {
pBlock[k++] = listFloat[(*ppValue3)[i] - pValue[l]] * pBlock[l];
}
}
pBlock[0x80 - 1] = 0;
}
}
}
public void Decode4(int channelIndex1, int channelIndex2, int index, uint a, uint b, uint c) {
var pTypeA = GetPtrOfType(channelIndex1);
if (*pTypeA == 1 && c != 0) {
var pValue2B = GetPtrOfValue2(channelIndex2);
var pBlockA = GetPtrOfBlock(channelIndex1);
var pBlockB = GetPtrOfBlock(channelIndex2);
var f1 = ChannelTables.Decode4ListSingle[pValue2B[index]];
var f2 = f1 - 2.0f;
var s = &pBlockA[b];
var d = &pBlockB[b];
for (var i = 0; i < a; ++i) {
*(d++) = *s * f2;
*(s++) = *s * f1;
}
}
}
public void Decode5(int channelIndex, int index) {
float* s, d;
s = GetPtrOfBlock(channelIndex);
d = GetPtrOfWav1(channelIndex);
var count1 = 1;
var count2 = 0x40;
for (var i = 0; i < 7; ++i, count1 <<= 1, count2 >>= 1) {
var d1 = d;
var d2 = &d[count2];
for (var j = 0; j < count1; ++j) {
for (var k = 0; k < count2; ++k) {
var a = *(s++);
var b = *(s++);
*(d1++) = b + a;
*(d2++) = a - b;
}
d1 += count2;
d2 += count2;
}
var w = &s[-0x80];
s = d;
d = w;
}
s = GetPtrOfWav1(channelIndex);
d = GetPtrOfBlock(channelIndex);
fixed (float* list1FloatBase = ChannelTables.Decode5List1Single) {
fixed (float* list2FloatBase = ChannelTables.Decode5List2Single) {
count1 = 0x40;
count2 = 1;
for (var i = 0; i < 7; ++i, count1 >>= 1, count2 <<= 1) {
var list1Float = &list1FloatBase[i * 0x40];
var list2Float = &list2FloatBase[i * 0x40];
var s1 = s;
var s2 = &s1[count2];
var d1 = d;
var d2 = &d1[count2 * 2 - 1];
for (var j = 0; j < count1; ++j) {
for (var k = 0; k < count2; ++k) {
var fa = *(s1++);
var fb = *(s2++);
var fc = *(list1Float++);
var fd = *(list2Float++);
*(d1++) = fa * fc - fb * fd;
*(d2--) = fa * fd + fb * fc;
}
s1 += count2;
s2 += count2;
d1 += count2;
d2 += count2 * 3;
}
var w = s;
s = d;
d = w;
}
}
}
d = GetPtrOfWav2(channelIndex);
for (var i = 0; i < 0x80; ++i) {
*(d++) = *(s++);
}
fixed (float* list3FloatBase = ChannelTables.Decode5List3Single) {
s = list3FloatBase;
d = GetPtrOfWave(channelIndex) + index * 0x80;
var s1 = &GetPtrOfWav2(channelIndex)[0x40];
var s2 = GetPtrOfWav3(channelIndex);
for (var i = 0; i < 0x40; ++i) {
*(d++) = *(s1++) * *(s++) + *(s2++);
}
for (var i = 0; i < 0x40; ++i) {
*(d++) = *(s++) * *(--s1) - *(s2++);
}
s1 = &GetPtrOfWav2(channelIndex)[0x40 - 1];
s2 = GetPtrOfWav3(channelIndex);
for (var i = 0; i < 0x40; ++i) {
*(s2++) = *(s1--) * *(--s);
}
for (var i = 0; i < 0x40; ++i) {
*(s2++) = *(--s) * *(++s1);
}
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void* GetBasePtr(int channelIndex) {
return (void*)(_basePtr + ChannelSize * channelIndex);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public float* GetPtrOfBlock(int channelIndex) {
return (float*)GetPtrOf(channelIndex, OffsetOfBlock);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public float* GetPtrOfBase(int channelIndex) {
return (float*)GetPtrOf(channelIndex, OffsetOfBase);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public sbyte* GetPtrOfValue(int channelIndex) {
return (sbyte*)GetPtrOf(channelIndex, OffsetOfValue);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public sbyte* GetPtrOfScale(int channelIndex) {
return (sbyte*)GetPtrOf(channelIndex, OffsetOfScale);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public sbyte* GetPtrOfValue2(int channelIndex) {
return (sbyte*)GetPtrOf(channelIndex, OffsetOfValue2);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int* GetPtrOfType(int channelIndex) {
return (int*)GetPtrOf(channelIndex, OffsetOfType);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public sbyte** GetPtrOfValue3(int channelIndex) {
return (sbyte**)GetPtrOf(channelIndex, OffsetOfValue3);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public uint* GetPtrOfCount(int channelIndex) {
return (uint*)GetPtrOf(channelIndex, OffsetOfCount);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public float* GetPtrOfWav1(int channelIndex) {
return (float*)GetPtrOf(channelIndex, OffsetOfWav1);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public float* GetPtrOfWav2(int channelIndex) {
return (float*)GetPtrOf(channelIndex, OffsetOfWav2);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public float* GetPtrOfWav3(int channelIndex) {
return (float*)GetPtrOf(channelIndex, OffsetOfWav3);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public float* GetPtrOfWave(int channelIndex) {
return (float*)GetPtrOf(channelIndex, OffsetOfWave);
}
protected override void Dispose(bool disposing) {
if (_basePtr != IntPtr.Zero) {
Marshal.FreeHGlobal(_basePtr);
}
_basePtr = IntPtr.Zero;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private IntPtr GetPtrOf(int channelIndex, IntPtr fieldOffset) {
return _basePtr + ChannelSize * channelIndex + fieldOffset.ToInt32();
}
private static void ZeroMemory(void* ptr, int byteCount) {
if (ptr == null || byteCount <= 0) {
return;
}
var p = (byte*)ptr;
for (var i = 0; i < byteCount; ++i) {
p[i] = 0;
}
}
private static readonly int ChannelSize = Marshal.SizeOf(typeof(Channel));
private static readonly IntPtr OffsetOfBlock = Marshal.OffsetOf(typeof(Channel), nameof(Channel.Block));
private static readonly IntPtr OffsetOfBase = Marshal.OffsetOf(typeof(Channel), nameof(Channel.Base));
private static readonly IntPtr OffsetOfValue = Marshal.OffsetOf(typeof(Channel), nameof(Channel.Value));
private static readonly IntPtr OffsetOfScale = Marshal.OffsetOf(typeof(Channel), nameof(Channel.Scale));
private static readonly IntPtr OffsetOfValue2 = Marshal.OffsetOf(typeof(Channel), nameof(Channel.Value2));
private static readonly IntPtr OffsetOfType = Marshal.OffsetOf(typeof(Channel), nameof(Channel.Type));
private static readonly IntPtr OffsetOfValue3 = Marshal.OffsetOf(typeof(Channel), nameof(Channel.Value3));
private static readonly IntPtr OffsetOfCount = Marshal.OffsetOf(typeof(Channel), nameof(Channel.Count));
private static readonly IntPtr OffsetOfWav1 = Marshal.OffsetOf(typeof(Channel), nameof(Channel.Wav1));
private static readonly IntPtr OffsetOfWav2 = Marshal.OffsetOf(typeof(Channel), nameof(Channel.Wav2));
private static readonly IntPtr OffsetOfWav3 = Marshal.OffsetOf(typeof(Channel), nameof(Channel.Wav3));
private static readonly IntPtr OffsetOfWave = Marshal.OffsetOf(typeof(Channel), nameof(Channel.Wave));
private IntPtr _basePtr;
}
}
| |
// 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.Diagnostics;
using System.IO;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Principal;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpSys.Internal;
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNetCore.Server.HttpSys
{
internal partial class RequestContext : NativeRequestContext, IThreadPoolWorkItem
{
private static readonly Action<object?> AbortDelegate = Abort;
private CancellationTokenSource? _requestAbortSource;
private CancellationToken? _disconnectToken;
private bool _disposed;
private bool _initialized;
public RequestContext(HttpSysListener server, uint? bufferSize, ulong requestId)
: base(server.MemoryPool, bufferSize, requestId, server.Options.UseLatin1RequestHeaders)
{
Server = server;
AllowSynchronousIO = server.Options.AllowSynchronousIO;
}
internal HttpSysListener Server { get; }
internal ILogger Logger => Server.Logger;
public Request Request { get; private set; } = default!;
public Response Response { get; private set; } = default!;
public WindowsPrincipal User => Request.User;
public CancellationToken DisconnectToken
{
get
{
// Create a new token per request, but link it to a single connection token.
// We need to be able to dispose of the registrations each request to prevent leaks.
if (!_disconnectToken.HasValue)
{
if (_disposed || Response.BodyIsFinished)
{
// We cannot register for disconnect notifications after the response has finished sending.
_disconnectToken = CancellationToken.None;
}
else
{
var connectionDisconnectToken = Server.DisconnectListener.GetTokenForConnection(Request.UConnectionId);
if (connectionDisconnectToken.CanBeCanceled)
{
_requestAbortSource = CancellationTokenSource.CreateLinkedTokenSource(connectionDisconnectToken);
_disconnectToken = _requestAbortSource.Token;
}
else
{
_disconnectToken = CancellationToken.None;
}
}
}
return _disconnectToken.Value;
}
}
public unsafe Guid TraceIdentifier
{
get
{
// This is the base GUID used by HTTP.SYS for generating the activity ID.
// HTTP.SYS overwrites the first 8 bytes of the base GUID with RequestId to generate ETW activity ID.
var guid = new Guid(0xffcb4c93, 0xa57f, 0x453c, 0xb6, 0x3f, 0x84, 0x71, 0xc, 0x79, 0x67, 0xbb);
*((ulong*)&guid) = Request.RequestId;
return guid;
}
}
public bool IsUpgradableRequest => Request.IsUpgradable;
internal bool AllowSynchronousIO { get; set; }
public Task<Stream> UpgradeAsync()
{
if (!IsUpgradableRequest)
{
throw new InvalidOperationException("This request cannot be upgraded, it is incompatible.");
}
if (Response.HasStarted)
{
throw new InvalidOperationException("This request cannot be upgraded, the response has already started.");
}
// Set the status code and reason phrase
Response.StatusCode = StatusCodes.Status101SwitchingProtocols;
Response.ReasonPhrase = HttpReasonPhrase.Get(StatusCodes.Status101SwitchingProtocols);
Response.SendOpaqueUpgrade(); // TODO: Async
Request.SwitchToOpaqueMode();
Response.SwitchToOpaqueMode();
var opaqueStream = new OpaqueStream(Request.Body, Response.Body);
return Task.FromResult<Stream>(opaqueStream);
}
// TODO: Public when needed
internal bool TryGetChannelBinding(ref ChannelBinding? value)
{
if (!Request.IsHttps)
{
Log.ChannelBindingNeedsHttps(Logger);
return false;
}
value = ClientCertLoader.GetChannelBindingFromTls(Server.RequestQueue, Request.UConnectionId, Logger);
Debug.Assert(value != null, "GetChannelBindingFromTls returned null even though OS supposedly supports Extended Protection");
Log.ChannelBindingRetrieved(Logger);
return value != null;
}
/// <summary>
/// Flushes and completes the response.
/// </summary>
public override void Dispose()
{
if (_disposed)
{
return;
}
_disposed = true;
if (_initialized)
{
// TODO: Verbose log
try
{
_requestAbortSource?.Dispose();
Response.Dispose();
}
catch
{
Abort();
}
finally
{
Request.Dispose();
}
}
base.Dispose();
}
/// <summary>
/// Forcibly terminate and dispose the request, closing the connection if necessary.
/// </summary>
public void Abort()
{
// May be called from Dispose() code path, don't check _disposed.
// TODO: Verbose log
_disposed = true;
if (_requestAbortSource != null)
{
try
{
_requestAbortSource.Cancel();
}
catch (ObjectDisposedException)
{
}
catch (Exception ex)
{
Log.AbortError(Logger, ex);
}
_requestAbortSource.Dispose();
}
else
{
_disconnectToken = new CancellationToken(canceled: true);
}
ForceCancelRequest();
Request.Dispose();
// Only Abort, Response.Dispose() tries a graceful flush
Response.Abort();
}
private static void Abort(object? state)
{
var context = (RequestContext)state!;
context.Abort();
}
internal CancellationTokenRegistration RegisterForCancellation(CancellationToken cancellationToken)
{
return cancellationToken.Register(AbortDelegate, this);
}
// The request is being aborted, but large writes may be in progress. Cancel them.
internal void ForceCancelRequest()
{
try
{
var statusCode = HttpApi.HttpCancelHttpRequest(Server.RequestQueue.Handle,
Request.RequestId, IntPtr.Zero);
// Either the connection has already dropped, or the last write is in progress.
// The requestId becomes invalid as soon as the last Content-Length write starts.
// The only way to cancel now is with CancelIoEx.
if (statusCode == UnsafeNclNativeMethods.ErrorCodes.ERROR_CONNECTION_INVALID)
{
Response.CancelLastWrite();
}
}
catch (ObjectDisposedException)
{
// RequestQueueHandle may have been closed
}
}
// You must still call ForceCancelRequest after this.
internal unsafe void SetResetCode(int errorCode)
{
if (!HttpApi.SupportsReset)
{
return;
}
try
{
var streamError = new HttpApiTypes.HTTP_REQUEST_PROPERTY_STREAM_ERROR() { ErrorCode = (uint)errorCode };
var statusCode = HttpApi.HttpSetRequestProperty(Server.RequestQueue.Handle, Request.RequestId, HttpApiTypes.HTTP_REQUEST_PROPERTY.HttpRequestPropertyStreamError, (void*)&streamError,
(uint)sizeof(HttpApiTypes.HTTP_REQUEST_PROPERTY_STREAM_ERROR), IntPtr.Zero);
}
catch (ObjectDisposedException)
{
// RequestQueueHandle may have been closed
}
}
public virtual Task ExecuteAsync()
{
return Task.CompletedTask;
}
public void Execute()
{
_ = ExecuteAsync();
}
protected void SetFatalResponse(int status)
{
Response.StatusCode = status;
Response.ContentLength = 0;
Dispose();
}
internal unsafe void Delegate(DelegationRule destination)
{
if (destination == null)
{
throw new ArgumentNullException(nameof(destination));
}
if (Request.HasRequestBodyStarted)
{
throw new InvalidOperationException("This request cannot be delegated, the request body has already started.");
}
if (Response.HasStarted)
{
throw new InvalidOperationException("This request cannot be delegated, the response has already started.");
}
var source = Server.RequestQueue;
uint statusCode;
fixed (char* uriPointer = destination.UrlPrefix)
{
var property = new HttpApiTypes.HTTP_DELEGATE_REQUEST_PROPERTY_INFO()
{
PropertyId = HttpApiTypes.HTTP_DELEGATE_REQUEST_PROPERTY_ID.DelegateRequestDelegateUrlProperty,
PropertyInfo = (IntPtr)uriPointer,
PropertyInfoLength = (uint)System.Text.Encoding.Unicode.GetByteCount(destination.UrlPrefix)
};
statusCode = HttpApi.HttpDelegateRequestEx(source.Handle,
destination.Queue.Handle,
Request.RequestId,
destination.Queue.UrlGroup.Id,
propertyInfoSetSize: 1,
&property);
}
if (statusCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS)
{
throw new HttpSysException((int)statusCode);
}
Response.MarkDelegated();
}
}
}
| |
// 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.Threading;
interface IGen<T>
{
void Target<U>(object p);
T Dummy(T t);
}
class GenInt : IGen<int>
{
public int Dummy(int t) { return t; }
public void Target<U>(object p)
{
//dummy line to avoid warnings
Test.Eval(typeof(U)!=p.GetType());
ManualResetEvent evt = (ManualResetEvent) p;
Interlocked.Increment(ref Test.Xcounter);
evt.Set();
}
public static void ThreadPoolTest<U>()
{
ManualResetEvent[] evts = new ManualResetEvent[Test.nThreads];
WaitHandle[] hdls = new WaitHandle[Test.nThreads];
for (int i=0; i<Test.nThreads; i++)
{
evts[i] = new ManualResetEvent(false);
hdls[i] = (WaitHandle) evts[i];
}
IGen<int> obj = new GenInt();
for (int i = 0; i <Test.nThreads; i++)
{
WaitCallback cb = new WaitCallback(obj.Target<U>);
ThreadPool.QueueUserWorkItem(cb,evts[i]);
}
WaitHandle.WaitAll(hdls);
Test.Eval(Test.Xcounter==Test.nThreads);
Test.Xcounter = 0;
}
}
class GenDouble : IGen<double>
{
public double Dummy(double t) { return t; }
public void Target<U>(object p)
{
//dummy line to avoid warnings
Test.Eval(typeof(U)!=p.GetType());
ManualResetEvent evt = (ManualResetEvent) p;
Interlocked.Increment(ref Test.Xcounter);
evt.Set();
}
public static void ThreadPoolTest<U>()
{
ManualResetEvent[] evts = new ManualResetEvent[Test.nThreads];
WaitHandle[] hdls = new WaitHandle[Test.nThreads];
for (int i=0; i<Test.nThreads; i++)
{
evts[i] = new ManualResetEvent(false);
hdls[i] = (WaitHandle) evts[i];
}
IGen<double> obj = new GenDouble();
for (int i = 0; i <Test.nThreads; i++)
{
WaitCallback cb = new WaitCallback(obj.Target<U>);
ThreadPool.QueueUserWorkItem(cb,evts[i]);
}
WaitHandle.WaitAll(hdls);
Test.Eval(Test.Xcounter==Test.nThreads);
Test.Xcounter = 0;
}
}
class GenString : IGen<string>
{
public string Dummy(string t) { return t; }
public void Target<U>(object p)
{
//dummy line to avoid warnings
Test.Eval(typeof(U)!=p.GetType());
ManualResetEvent evt = (ManualResetEvent) p;
Interlocked.Increment(ref Test.Xcounter);
evt.Set();
}
public static void ThreadPoolTest<U>()
{
ManualResetEvent[] evts = new ManualResetEvent[Test.nThreads];
WaitHandle[] hdls = new WaitHandle[Test.nThreads];
for (int i=0; i<Test.nThreads; i++)
{
evts[i] = new ManualResetEvent(false);
hdls[i] = (WaitHandle) evts[i];
}
IGen<string> obj = new GenString();
for (int i = 0; i <Test.nThreads; i++)
{
WaitCallback cb = new WaitCallback(obj.Target<U>);
ThreadPool.QueueUserWorkItem(cb,evts[i]);
}
WaitHandle.WaitAll(hdls);
Test.Eval(Test.Xcounter==Test.nThreads);
Test.Xcounter = 0;
}
}
class GenObject : IGen<object>
{
public object Dummy(object t) { return t; }
public void Target<U>(object p)
{
//dummy line to avoid warnings
Test.Eval(typeof(U)!=p.GetType());
ManualResetEvent evt = (ManualResetEvent) p;
Interlocked.Increment(ref Test.Xcounter);
evt.Set();
}
public static void ThreadPoolTest<U>()
{
ManualResetEvent[] evts = new ManualResetEvent[Test.nThreads];
WaitHandle[] hdls = new WaitHandle[Test.nThreads];
for (int i=0; i<Test.nThreads; i++)
{
evts[i] = new ManualResetEvent(false);
hdls[i] = (WaitHandle) evts[i];
}
IGen<object> obj = new GenObject();
for (int i = 0; i <Test.nThreads; i++)
{
WaitCallback cb = new WaitCallback(obj.Target<U>);
ThreadPool.QueueUserWorkItem(cb,evts[i]);
}
WaitHandle.WaitAll(hdls);
Test.Eval(Test.Xcounter==Test.nThreads);
Test.Xcounter = 0;
}
}
class GenGuid : IGen<Guid>
{
public Guid Dummy(Guid t) { return t; }
public void Target<U>(object p)
{
//dummy line to avoid warnings
Test.Eval(typeof(U)!=p.GetType());
ManualResetEvent evt = (ManualResetEvent) p;
Interlocked.Increment(ref Test.Xcounter);
evt.Set();
}
public static void ThreadPoolTest<U>()
{
ManualResetEvent[] evts = new ManualResetEvent[Test.nThreads];
WaitHandle[] hdls = new WaitHandle[Test.nThreads];
for (int i=0; i<Test.nThreads; i++)
{
evts[i] = new ManualResetEvent(false);
hdls[i] = (WaitHandle) evts[i];
}
IGen<Guid> obj = new GenGuid();
for (int i = 0; i <Test.nThreads; i++)
{
WaitCallback cb = new WaitCallback(obj.Target<U>);
ThreadPool.QueueUserWorkItem(cb,evts[i]);
}
WaitHandle.WaitAll(hdls);
Test.Eval(Test.Xcounter==Test.nThreads);
Test.Xcounter = 0;
}
}
public class Test
{
public static int nThreads =50;
public static int counter = 0;
public static int Xcounter = 0;
public static bool result = true;
public static void Eval(bool exp)
{
counter++;
if (!exp)
{
result = exp;
Console.WriteLine("Test Failed at location: " + counter);
}
}
public static int Main()
{
GenInt.ThreadPoolTest<int>();
GenDouble.ThreadPoolTest<int>();
GenString.ThreadPoolTest<int>();
GenObject.ThreadPoolTest<int>();
GenGuid.ThreadPoolTest<int>();
GenInt.ThreadPoolTest<double>();
GenDouble.ThreadPoolTest<double>();
GenString.ThreadPoolTest<double>();
GenObject.ThreadPoolTest<double>();
GenGuid.ThreadPoolTest<double>();
GenInt.ThreadPoolTest<string>();
GenDouble.ThreadPoolTest<string>();
GenString.ThreadPoolTest<string>();
GenObject.ThreadPoolTest<string>();
GenGuid.ThreadPoolTest<string>();
GenInt.ThreadPoolTest<object>();
GenDouble.ThreadPoolTest<object>();
GenString.ThreadPoolTest<object>();
GenObject.ThreadPoolTest<object>();
GenGuid.ThreadPoolTest<object>();
GenInt.ThreadPoolTest<Guid>();
GenDouble.ThreadPoolTest<Guid>();
GenString.ThreadPoolTest<Guid>();
GenObject.ThreadPoolTest<Guid>();
GenGuid.ThreadPoolTest<Guid>();
if (result)
{
Console.WriteLine("Test Passed");
return 100;
}
else
{
Console.WriteLine("Test Failed");
return 1;
}
}
}
| |
// 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;
using System.Runtime.InteropServices;
namespace System.Management
{
//CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC//
/// <summary>
/// <para> Represents a collection of <see cref='System.Management.QualifierData'/> objects.</para>
/// </summary>
/// <example>
/// <code lang='C#'>using System;
/// using System.Management;
///
/// // This sample demonstrates how to list all qualifiers including amended
/// // qualifiers of a ManagementClass object.
/// class Sample_QualifierDataCollection
/// {
/// public static int Main(string[] args) {
/// ManagementClass diskClass = new ManagementClass("Win32_LogicalDisk");
/// diskClass.Options.UseAmendedQualifiers = true;
/// QualifierDataCollection qualifierCollection = diskClass.Qualifiers;
/// foreach (QualifierData q in qualifierCollection) {
/// Console.WriteLine(q.Name + " = " + q.Value);
/// }
/// return 0;
/// }
/// }
/// </code>
/// <code lang='VB'>Imports System
/// Imports System.Management
/// ' This sample demonstrates how to list all qualifiers including amended
/// ' qualifiers of a ManagementClass object.
/// Class Sample_QualifierDataCollection
/// Overloads Public Shared Function Main(args() As String) As Integer
/// Dim diskClass As New ManagementClass("Win32_LogicalDisk")
/// diskClass.Options.UseAmendedQualifiers = true
/// Dim qualifierCollection As QualifierDataCollection = diskClass.Qualifiers
/// Dim q As QualifierData
/// For Each q In qualifierCollection
/// Console.WriteLine(q.Name & " = " & q.Value)
/// Next q
/// Return 0
/// End Function
/// End Class
/// </code>
/// </example>
//CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC//
public class QualifierDataCollection : ICollection, IEnumerable
{
private ManagementBaseObject parent;
private string propertyOrMethodName;
private QualifierType qualifierSetType;
internal QualifierDataCollection(ManagementBaseObject parent) : base()
{
this.parent = parent;
this.qualifierSetType = QualifierType.ObjectQualifier;
this.propertyOrMethodName = null;
}
internal QualifierDataCollection(ManagementBaseObject parent, string propertyOrMethodName, QualifierType type) : base()
{
this.parent = parent;
this.propertyOrMethodName = propertyOrMethodName;
this.qualifierSetType = type;
}
/// <summary>
/// Return the qualifier set associated with its type
/// Overload with use of private data member, qualifierType
/// </summary>
private IWbemQualifierSetFreeThreaded GetTypeQualifierSet()
{
return GetTypeQualifierSet(qualifierSetType);
}
/// <summary>
/// Return the qualifier set associated with its type
/// </summary>
private IWbemQualifierSetFreeThreaded GetTypeQualifierSet(QualifierType qualifierSetType)
{
IWbemQualifierSetFreeThreaded qualifierSet = null;
int status = (int)ManagementStatus.NoError;
switch (qualifierSetType)
{
case QualifierType.ObjectQualifier :
status = parent.wbemObject.GetQualifierSet_(out qualifierSet);
break;
case QualifierType.PropertyQualifier :
status = parent.wbemObject.GetPropertyQualifierSet_(propertyOrMethodName, out qualifierSet);
break;
case QualifierType.MethodQualifier :
status = parent.wbemObject.GetMethodQualifierSet_(propertyOrMethodName, out qualifierSet);
break;
default :
throw new ManagementException(ManagementStatus.Unexpected, null, null); // Is this the best fit error ??
}
if (status < 0)
{
if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
return qualifierSet;
}
//
//ICollection
//
/// <summary>
/// <para>Gets or sets the number of <see cref='System.Management.QualifierData'/> objects in the <see cref='System.Management.QualifierDataCollection'/>.</para>
/// </summary>
/// <value>
/// <para>The number of objects in the collection.</para>
/// </value>
public int Count
{
get {
string[] qualifierNames = null;
IWbemQualifierSetFreeThreaded quals;
try
{
quals = GetTypeQualifierSet();
}
catch(ManagementException e)
{
// If we ask for the number of qualifiers on a system property, we return '0'
if(qualifierSetType == QualifierType.PropertyQualifier && e.ErrorCode == ManagementStatus.SystemProperty)
return 0;
else
throw;
}
int status = quals.GetNames_(0, out qualifierNames);
if (status < 0)
{
if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
return qualifierNames.Length;
}
}
/// <summary>
/// <para>Gets or sets a value indicating whether the object is synchronized.</para>
/// </summary>
/// <value>
/// <para><see langword='true'/> if the object is synchronized;
/// otherwise, <see langword='false'/>.</para>
/// </value>
public bool IsSynchronized { get { return false; }
}
/// <summary>
/// <para>Gets or sets the object to be used for synchronization.</para>
/// </summary>
/// <value>
/// <para>The object to be used for synchronization.</para>
/// </value>
public object SyncRoot { get { return this; }
}
/// <overload>
/// <para>Copies the <see cref='System.Management.QualifierDataCollection'/> into an array.</para>
/// </overload>
/// <summary>
/// <para> Copies the <see cref='System.Management.QualifierDataCollection'/> into an array.</para>
/// </summary>
/// <param name='array'>The array to which to copy the <see cref='System.Management.QualifierDataCollection'/>. </param>
/// <param name='index'>The index from which to start copying. </param>
public void CopyTo(Array array, int index)
{
if (null == array)
throw new ArgumentNullException(nameof(array));
if ((index < array.GetLowerBound(0)) || (index > array.GetUpperBound(0)))
throw new ArgumentOutOfRangeException(nameof(index));
// Get the names of the qualifiers
string[] qualifierNames = null;
IWbemQualifierSetFreeThreaded quals;
try
{
quals = GetTypeQualifierSet();
}
catch(ManagementException e)
{
// There are NO qualifiers on system properties, so we just return
if(qualifierSetType == QualifierType.PropertyQualifier && e.ErrorCode == ManagementStatus.SystemProperty)
return;
else
throw;
}
int status = quals.GetNames_(0, out qualifierNames);
if (status < 0)
{
if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
if ((index + qualifierNames.Length) > array.Length)
throw new ArgumentException(null, nameof(index));
foreach (string qualifierName in qualifierNames)
array.SetValue(new QualifierData(parent, propertyOrMethodName, qualifierName, qualifierSetType), index++);
return;
}
/// <summary>
/// <para>Copies the <see cref='System.Management.QualifierDataCollection'/> into a specialized
/// <see cref='System.Management.QualifierData'/>
/// array.</para>
/// </summary>
/// <param name='qualifierArray'><para>The specialized array of <see cref='System.Management.QualifierData'/> objects
/// to which to copy the <see cref='System.Management.QualifierDataCollection'/>.</para></param>
/// <param name=' index'>The index from which to start copying.</param>
public void CopyTo(QualifierData[] qualifierArray, int index)
{
CopyTo((Array)qualifierArray, index);
}
//
// IEnumerable
//
IEnumerator IEnumerable.GetEnumerator()
{
return (IEnumerator)(new QualifierDataEnumerator(parent, propertyOrMethodName, qualifierSetType));
}
/// <summary>
/// <para>Returns an enumerator for the <see cref='System.Management.QualifierDataCollection'/>. This method is strongly typed.</para>
/// </summary>
/// <returns>
/// <para>An <see cref='System.Collections.IEnumerator'/> that can be used to iterate through the
/// collection.</para>
/// </returns>
public QualifierDataEnumerator GetEnumerator()
{
return new QualifierDataEnumerator(parent, propertyOrMethodName, qualifierSetType);
}
/// <summary>
/// <para>Represents the enumerator for <see cref='System.Management.QualifierData'/>
/// objects in the <see cref='System.Management.QualifierDataCollection'/>.</para>
/// </summary>
/// <example>
/// <code lang='C#'>using System;
/// using System.Management;
///
/// // This sample demonstrates how to enumerate qualifiers of a ManagementClass
/// // using QualifierDataEnumerator object.
/// class Sample_QualifierDataEnumerator
/// {
/// public static int Main(string[] args) {
/// ManagementClass diskClass = new ManagementClass("Win32_LogicalDisk");
/// diskClass.Options.UseAmendedQualifiers = true;
/// QualifierDataCollection diskQualifier = diskClass.Qualifiers;
/// QualifierDataCollection.QualifierDataEnumerator
/// qualifierEnumerator = diskQualifier.GetEnumerator();
/// while(qualifierEnumerator.MoveNext()) {
/// Console.WriteLine(qualifierEnumerator.Current.Name + " = " +
/// qualifierEnumerator.Current.Value);
/// }
/// return 0;
/// }
/// }
/// </code>
/// <code lang='VB'>Imports System
/// Imports System.Management
///
/// ' This sample demonstrates how to enumerate qualifiers of a ManagementClass
/// ' using QualifierDataEnumerator object.
/// Class Sample_QualifierDataEnumerator
/// Overloads Public Shared Function Main(args() As String) As Integer
/// Dim diskClass As New ManagementClass("win32_logicaldisk")
/// diskClass.Options.UseAmendedQualifiers = True
/// Dim diskQualifier As QualifierDataCollection = diskClass.Qualifiers
/// Dim qualifierEnumerator As _
/// QualifierDataCollection.QualifierDataEnumerator = _
/// diskQualifier.GetEnumerator()
/// While qualifierEnumerator.MoveNext()
/// Console.WriteLine(qualifierEnumerator.Current.Name & _
/// " = " & qualifierEnumerator.Current.Value)
/// End While
/// Return 0
/// End Function
/// End Class
/// </code>
/// </example>
public class QualifierDataEnumerator : IEnumerator
{
private ManagementBaseObject parent;
private string propertyOrMethodName;
private QualifierType qualifierType;
private string[] qualifierNames;
private int index = -1;
//Internal constructor
internal QualifierDataEnumerator(ManagementBaseObject parent, string propertyOrMethodName,
QualifierType qualifierType)
{
this.parent = parent;
this.propertyOrMethodName = propertyOrMethodName;
this.qualifierType = qualifierType;
this.qualifierNames = null;
IWbemQualifierSetFreeThreaded qualifierSet = null;
int status = (int)ManagementStatus.NoError;
switch (qualifierType)
{
case QualifierType.ObjectQualifier :
status = parent.wbemObject.GetQualifierSet_(out qualifierSet);
break;
case QualifierType.PropertyQualifier :
status = parent.wbemObject.GetPropertyQualifierSet_(propertyOrMethodName, out qualifierSet);
break;
case QualifierType.MethodQualifier :
status = parent.wbemObject.GetMethodQualifierSet_(propertyOrMethodName, out qualifierSet);
break;
default :
throw new ManagementException(ManagementStatus.Unexpected, null, null); // Is this the best fit error ??
}
// If we got an error code back, assume there are NO qualifiers for this object/property/method
if(status < 0)
{
qualifierNames = Array.Empty<String>();
}
else
{
status = qualifierSet.GetNames_(0, out qualifierNames);
if (status < 0)
{
if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
}
}
//Standard "Current" variant
/// <internalonly/>
object IEnumerator.Current { get { return (object)this.Current; } }
/// <summary>
/// <para>Gets or sets the current <see cref='System.Management.QualifierData'/> in the <see cref='System.Management.QualifierDataCollection'/> enumeration.</para>
/// </summary>
/// <value>
/// <para>The current <see cref='System.Management.QualifierData'/> element in the collection.</para>
/// </value>
public QualifierData Current
{
get {
if ((index == -1) || (index == qualifierNames.Length))
throw new InvalidOperationException();
else
return new QualifierData(parent, propertyOrMethodName,
qualifierNames[index], qualifierType);
}
}
/// <summary>
/// <para> Moves to the next element in the <see cref='System.Management.QualifierDataCollection'/> enumeration.</para>
/// </summary>
/// <returns>
/// <para><see langword='true'/> if the enumerator was successfully advanced to the next
/// element; <see langword='false'/> if the enumerator has passed the end of the
/// collection.</para>
/// </returns>
public bool MoveNext()
{
if (index == qualifierNames.Length) //passed the end of the array
return false; //don't advance the index any more
index++;
return (index == qualifierNames.Length) ? false : true;
}
/// <summary>
/// <para>Resets the enumerator to the beginning of the <see cref='System.Management.QualifierDataCollection'/> enumeration.</para>
/// </summary>
public void Reset()
{
index = -1;
}
}//QualifierDataEnumerator
//
//Methods
//
/// <summary>
/// <para> Gets the specified <see cref='System.Management.QualifierData'/> from the <see cref='System.Management.QualifierDataCollection'/>.</para>
/// </summary>
/// <param name='qualifierName'>The name of the <see cref='System.Management.QualifierData'/> to access in the <see cref='System.Management.QualifierDataCollection'/>. </param>
/// <value>
/// <para>A <see cref='System.Management.QualifierData'/>, based on the name specified.</para>
/// </value>
public virtual QualifierData this[string qualifierName]
{
get {
if (null == qualifierName)
throw new ArgumentNullException(nameof(qualifierName));
return new QualifierData(parent, propertyOrMethodName, qualifierName, qualifierSetType);
}
}
/// <summary>
/// <para>Removes a <see cref='System.Management.QualifierData'/> from the <see cref='System.Management.QualifierDataCollection'/> by name.</para>
/// </summary>
/// <param name='qualifierName'>The name of the <see cref='System.Management.QualifierData'/> to remove. </param>
public virtual void Remove(string qualifierName)
{
int status = GetTypeQualifierSet().Delete_(qualifierName);
if (status < 0)
{
if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
}
/// <overload>
/// <para>Adds a <see cref='System.Management.QualifierData'/> to the <see cref='System.Management.QualifierDataCollection'/>.</para>
/// </overload>
/// <summary>
/// <para>Adds a <see cref='System.Management.QualifierData'/> to the <see cref='System.Management.QualifierDataCollection'/>. This overload specifies the qualifier name and value.</para>
/// </summary>
/// <param name='qualifierName'>The name of the <see cref='System.Management.QualifierData'/> to be added to the <see cref='System.Management.QualifierDataCollection'/>. </param>
/// <param name='qualifierValue'>The value for the new qualifier. </param>
public virtual void Add(string qualifierName, object qualifierValue)
{
Add(qualifierName, qualifierValue, false, false, false, true);
}
/// <summary>
/// <para>Adds a <see cref='System.Management.QualifierData'/> to the <see cref='System.Management.QualifierDataCollection'/>. This overload
/// specifies all property values for a <see cref='System.Management.QualifierData'/> object.</para>
/// </summary>
/// <param name='qualifierName'>The qualifier name. </param>
/// <param name='qualifierValue'>The qualifier value. </param>
/// <param name='isAmended'><see langword='true'/> to specify that this qualifier is amended (flavor); otherwise, <see langword='false'/>. </param>
/// <param name='propagatesToInstance'><see langword='true'/> to propagate this qualifier to instances; otherwise, <see langword='false'/>. </param>
/// <param name='propagatesToSubclass'><see langword='true'/> to propagate this qualifier to subclasses; otherwise, <see langword='false'/>. </param>
/// <param name='isOverridable'><see langword='true'/> to specify that this qualifier's value is overridable in instances of subclasses; otherwise, <see langword='false'/>. </param>
public virtual void Add(string qualifierName, object qualifierValue, bool isAmended, bool propagatesToInstance, bool propagatesToSubclass, bool isOverridable)
{
//Build the flavors bitmask and call the internal Add that takes a bitmask
int qualFlavor = 0;
if (isAmended) qualFlavor = (qualFlavor | (int)tag_WBEM_FLAVOR_TYPE.WBEM_FLAVOR_AMENDED);
if (propagatesToInstance) qualFlavor = (qualFlavor | (int)tag_WBEM_FLAVOR_TYPE.WBEM_FLAVOR_FLAG_PROPAGATE_TO_INSTANCE);
if (propagatesToSubclass) qualFlavor = (qualFlavor | (int)tag_WBEM_FLAVOR_TYPE.WBEM_FLAVOR_FLAG_PROPAGATE_TO_DERIVED_CLASS);
// Note we use the NOT condition here since WBEM_FLAVOR_OVERRIDABLE == 0
if (!isOverridable) qualFlavor = (qualFlavor | (int)tag_WBEM_FLAVOR_TYPE.WBEM_FLAVOR_NOT_OVERRIDABLE);
//Try to add the qualifier to the WMI object
int status = GetTypeQualifierSet().Put_(qualifierName, ref qualifierValue, qualFlavor);
if (status < 0)
{
if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
}
}//QualifierDataCollection
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Threading;
namespace System.Text
{
// This class overrides Encoding with the things we need for our NLS Encodings
//
// All of the GetBytes/Chars GetByte/CharCount methods are just wrappers for the pointer
// plus decoder/encoder method that is our real workhorse. Note that this is an internal
// class, so our public classes cannot derive from this class. Because of this, all of the
// GetBytes/Chars GetByte/CharCount wrapper methods are duplicated in all of our public
// encodings, which currently include:
//
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, & UnicodeEncoding
//
// So if you change the wrappers in this class, you must change the wrappers in the other classes
// as well because they should have the same behavior.
internal abstract class EncodingNLS : Encoding
{
protected EncodingNLS(int codePage) : base(codePage)
{
}
// Returns the number of bytes required to encode a range of characters in
// a character array.
//
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
// parent method is safe
public override unsafe int GetByteCount(char[] chars, int index, int count)
{
// Validate input parameters
if (chars == null)
throw new ArgumentNullException("chars", SR.ArgumentNull_Array);
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum);
if (chars.Length - index < count)
throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer);
// If no input, return 0, avoid fixed empty array problem
if (count == 0)
return 0;
// Just call the pointer version
fixed (char* pChars = chars)
return GetByteCount(pChars + index, count, null);
}
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
// parent method is safe
public override unsafe int GetByteCount(String s)
{
// Validate input
if (s==null)
throw new ArgumentNullException("s");
fixed (char* pChars = s)
return GetByteCount(pChars, s.Length, null);
}
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
public override unsafe int GetByteCount(char* chars, int count)
{
// Validate Parameters
if (chars == null)
throw new ArgumentNullException("chars", SR.ArgumentNull_Array);
if (count < 0)
throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum);
// Call it with empty encoder
return GetByteCount(chars, count, null);
}
// Parent method is safe.
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
public override unsafe int GetBytes(String s, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
if (s == null || bytes == null)
throw new ArgumentNullException((s == null ? "s" : "bytes"), SR.ArgumentNull_Array);
if (charIndex < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((charIndex < 0 ? "charIndex" : "charCount"), SR.ArgumentOutOfRange_NeedNonNegNum);
if (s.Length - charIndex < charCount)
throw new ArgumentOutOfRangeException("s", SR.ArgumentOutOfRange_IndexCount);
if (byteIndex < 0 || byteIndex > bytes.Length)
throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index);
int byteCount = bytes.Length - byteIndex;
fixed (char* pChars = s) fixed (byte* pBytes = &MemoryMarshal.GetReference((Span<byte>)bytes))
return GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, null);
}
// Encodes a range of characters in a character array into a range of bytes
// in a byte array. An exception occurs if the byte array is not large
// enough to hold the complete encoding of the characters. The
// GetByteCount method can be used to determine the exact number of
// bytes that will be produced for a given range of characters.
// Alternatively, the GetMaxByteCount method can be used to
// determine the maximum number of bytes that will be produced for a given
// number of characters, regardless of the actual character values.
//
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
// parent method is safe
public override unsafe int GetBytes(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
// Validate parameters
if (chars == null || bytes == null)
throw new ArgumentNullException((chars == null ? "chars" : "bytes"), SR.ArgumentNull_Array);
if (charIndex < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((charIndex < 0 ? "charIndex" : "charCount"), SR.ArgumentOutOfRange_NeedNonNegNum);
if (chars.Length - charIndex < charCount)
throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer);
if (byteIndex < 0 || byteIndex > bytes.Length)
throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index);
// If nothing to encode return 0, avoid fixed problem
if (charCount == 0)
return 0;
// Just call pointer version
int byteCount = bytes.Length - byteIndex;
fixed (char* pChars = chars) fixed (byte* pBytes = &MemoryMarshal.GetReference((Span<byte>)bytes))
// Remember that byteCount is # to decode, not size of array.
return GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, null);
}
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount)
{
// Validate Parameters
if (bytes == null || chars == null)
throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array);
if (charCount < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum);
return GetBytes(chars, charCount, bytes, byteCount, null);
}
// Returns the number of characters produced by decoding a range of bytes
// in a byte array.
//
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
// parent method is safe
public override unsafe int GetCharCount(byte[] bytes, int index, int count)
{
// Validate Parameters
if (bytes == null)
throw new ArgumentNullException("bytes", SR.ArgumentNull_Array);
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum);
if (bytes.Length - index < count)
throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer);
// If no input just return 0, fixed doesn't like 0 length arrays
if (count == 0)
return 0;
// Just call pointer version
fixed (byte* pBytes = bytes)
return GetCharCount(pBytes + index, count, null);
}
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
public override unsafe int GetCharCount(byte* bytes, int count)
{
// Validate Parameters
if (bytes == null)
throw new ArgumentNullException("bytes", SR.ArgumentNull_Array);
if (count < 0)
throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum);
return GetCharCount(bytes, count, null);
}
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
// parent method is safe
public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount,
char[] chars, int charIndex)
{
// Validate Parameters
if (bytes == null || chars == null)
throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array);
if (byteIndex < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((byteIndex < 0 ? "byteIndex" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum);
if ( bytes.Length - byteIndex < byteCount)
throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer);
if (charIndex < 0 || charIndex > chars.Length)
throw new ArgumentOutOfRangeException("charIndex", SR.ArgumentOutOfRange_Index);
// If no input, return 0 & avoid fixed problem
if (byteCount == 0)
return 0;
// Just call pointer version
int charCount = chars.Length - charIndex;
fixed (byte* pBytes = bytes) fixed (char* pChars = &MemoryMarshal.GetReference((Span<char>)chars))
// Remember that charCount is # to decode, not size of array
return GetChars(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, null);
}
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount)
{
// Validate Parameters
if (bytes == null || chars == null)
throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array);
if (charCount < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum);
return GetChars(bytes, byteCount, chars, charCount, null);
}
// Returns a string containing the decoded representation of a range of
// bytes in a byte array.
//
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
// parent method is safe
public override unsafe String GetString(byte[] bytes, int index, int count)
{
// Validate Parameters
if (bytes == null)
throw new ArgumentNullException("bytes", SR.ArgumentNull_Array);
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum);
if (bytes.Length - index < count)
throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer);
// Avoid problems with empty input buffer
if (count == 0) return String.Empty;
fixed (byte* pBytes = bytes)
return String.CreateStringFromEncoding(
pBytes + index, count, this);
}
public override Decoder GetDecoder()
{
return new DecoderNLS(this);
}
public override Encoder GetEncoder()
{
return new EncoderNLS(this);
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Data.dll
// Description: The data access libraries for the DotSpatial project.
// ********************************************************************************************************
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 2/18/2010 3:12:48 PM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.Linq;
namespace DotSpatial.Data
{
/// <summary>
/// CRC32
/// </summary>
public static class Crc32
{
private static UInt32[] _createdTable;
private static readonly UInt32[] CrcTable =
{
0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419,
0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4,
0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07,
0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de,
0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856,
0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4,
0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,
0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3,
0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a,
0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599,
0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190,
0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f,
0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e,
0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,
0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed,
0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3,
0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2,
0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a,
0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5,
0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010,
0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17,
0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6,
0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615,
0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8,
0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344,
0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a,
0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,
0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1,
0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c,
0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef,
0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe,
0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31,
0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c,
0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,
0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b,
0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1,
0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c,
0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278,
0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7,
0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66,
0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605,
0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8,
0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b,
0x2d02ef8d
};
/// <summary>
/// A table of values
/// </summary>
static long[] _table;
/// <summary>
/// Calculates the CRC-32-IEEE 802.3 Checkzum for png according to:
/// x^32 + x^26 + x^23 + x^22 + x^16 + + x^12 + x^11 + x^10 + x^8 + x^7 + x^5 + x^4 + x^2 + x + 1
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static byte[] GetCrcOld(byte[] value)
{
UInt32 crcVal = value.Aggregate(0xffffffff, (current, t) => (current >> 8) ^ CrcTable[(current & 0xff) ^ t]);
crcVal ^= 0xffffffff; // Toggle operation
byte[] result = new byte[4];
result[0] = (byte)(crcVal >> 24);
result[1] = (byte)(crcVal >> 16);
result[2] = (byte)(crcVal >> 8);
result[3] = (byte)(crcVal);
return result;
}
/// <summary>
/// Computes the Checksum
/// </summary>
/// <param name="bytes"></param>
/// <returns></returns>
public static long ComputeChecksum(byte[] bytes)
{
if (_table == null) _table = CreateTable2();
uint crc = 0xffffffff;
for (int i = 0; i < bytes.Length; ++i)
{
byte index = (byte)(((crc) & 0xff) ^ bytes[i]);
crc = (crc >> 8) ^ (uint)_table[index];
}
return ~crc;
}
/// <summary>
/// Computes the checksum bytes
/// </summary>
/// <param name="bytes"></param>
/// <returns></returns>
public static byte[] ComputeChecksumBytes(byte[] bytes)
{
return BitConverter.GetBytes(ComputeChecksum(bytes));
}
/// <summary>
/// Creates a table of checksum values
/// </summary>
/// <returns></returns>
public static long[] CreateTable2()
{
const uint poly = 0xedb88320;
_table = new long[256];
for (uint i = 0; i < _table.Length; ++i)
{
uint temp = i;
for (int j = 8; j > 0; --j)
{
if ((temp & 1) == 1)
{
temp = (temp >> 1) ^ poly;
}
else
{
temp >>= 1;
}
}
_table[i] = temp;
}
return _table;
}
/// <summary>
/// Calculates the CRC-32-IEEE 802.3 Checkzum for png according to:
/// x^32 + x^26 + x^23 + x^22 + x^16 + + x^12 + x^11 + x^10 + x^8 + x^7 + x^5 + x^4 + x^2 + x + 1
/// </summary>
/// <param name="value"></param>
/// <returns>A UInt32 value stored in a long because UINT32 is not CLS compliant</returns>
public static long GetCrc2(byte[] value)
{
uint val = UpdateCrc(0xffffffff, value, value.Length) ^ 0xffffffff;
byte[] vals = BitConverter.GetBytes(val);
for (int i = 0; i < 4; i++)
{
vals[i] = (byte)~vals[i];
}
return BitConverter.ToUInt32(vals, 0);
}
/// <summary>
/// Updates the running CRC
/// </summary>
private static uint UpdateCrc(uint crc, byte[] buff, int len)
{
uint c = crc;
int n;
if (_createdTable == null) _createdTable = CreateTable();
for (n = 0; n < len; n++)
{
c = _createdTable[(c ^ buff[n]) & 0xff] ^ (c >> 8);
}
return c;
}
/// <summary>
/// Creates the table according to the png specification
/// </summary>
/// <returns></returns>
private static uint[] CreateTable()
{
_createdTable = new uint[256];
for (int n = 0; n < 256; n++)
{
uint c = (uint)n;
int k;
for (k = 0; k < 8; k++)
{
if ((c & 1) > 0)
{
c = 0xedb88320 ^ (c >> 1);
}
else
{
c = c >> 1;
}
}
_createdTable[n] = c;
}
return _createdTable;
}
}
}
| |
// Copyright 2013, Catlike Coding, http://catlikecoding.com
using UnityEngine;
namespace CatlikeCoding.NumberFlow.Functions.Floats {
public sealed class Add : Function {
protected override void Configure () {
name = "+";
menuName = "Floats/+ Add";
propertyNames = new string[] { "A", "B" };
}
public override void Compute (Value output, Value[] arguments) {
output.Float = arguments[0].Float + arguments[1].Float;
}
}
public sealed class AddAdd : Function {
protected override void Configure () {
name = "+ +";
menuName = "Floats/+ + Add Add";
propertyNames = new string[] { "A", "B", "C" };
}
public override void Compute (Value output, Value[] arguments) {
output.Float = arguments[0].Float + arguments[1].Float + arguments[2].Float;
}
}
public sealed class Subtract : Function {
protected override void Configure () {
name = "-";
menuName = "Floats/- Subtract";
propertyNames = new string[] { "A", "B" };
}
public override void Compute (Value output, Value[] arguments) {
output.Float = arguments[0].Float - arguments[1].Float;
}
}
public sealed class Multiply : Function {
protected override void Configure () {
name = "\u00d7";
menuName = "Floats/\u00d7 Multiply";
propertyNames = new string[] { "A", "B" };
}
public override void Compute (Value output, Value[] arguments) {
output.Float = arguments[0].Float * arguments[1].Float;
}
}
public sealed class MultiplyAdd : Function {
protected override void Configure () {
name = "\u00d7 +";
menuName = "Floats/\u00d7 + Multiply Add";
propertyNames = new string[] { "A", "B", "C" };
}
public override void Compute (Value output, Value[] arguments) {
output.Float = arguments[0].Float * arguments[1].Float + arguments[2].Float;
}
}
public sealed class Divide : Function {
protected override void Configure () {
name = "\u00f7";
menuName = "Floats/\u00f7 Divide";
propertyNames = new string[] { "A", "B" };
}
public override void Compute (Value output, Value[] arguments) {
output.Float = arguments[0].Float / arguments[1].Float;
}
}
public sealed class Modulo : Function {
protected override void Configure () {
name = "%";
menuName = "Floats/% Modulo";
propertyNames = new string[] { "A", "B" };
}
public override void Compute (Value output, Value[] arguments) {
output.Float = arguments[0].Float % arguments[1].Float;
}
}
#region With 1
public sealed class PlusOne : Function {
protected override void Configure () {
name = "+ 1";
menuName = "Floats/With 1/+ 1";
propertyNames = new string[] { "Value" };
}
public override void Compute (Value output, Value[] arguments) {
output.Float = arguments[0].Float + 1f;
}
}
public sealed class MinusOne : Function {
protected override void Configure () {
name = "- 1";
menuName = "Floats/With 1/- 1";
propertyNames = new string[] { "Value" };
}
public override void Compute (Value output, Value[] arguments) {
output.Float = arguments[0].Float - 1f;
}
}
public sealed class OneMinus : Function {
protected override void Configure () {
name = "1 -";
menuName = "Floats/With 1/1 -";
propertyNames = new string[] { "Value" };
}
public override void Compute (Value output, Value[] arguments) {
output.Float = 1f - arguments[0].Float;
}
}
public sealed class DivideOne : Function {
protected override void Configure () {
name = "1 \u00f7";
menuName = "Floats/With 1/1 \u00f7";
propertyNames = new string[] { "Value" };
}
public override void Compute (Value output, Value[] arguments) {
output.Float = 1f / arguments[0].Float;
}
}
#endregion
#region Relative
public sealed class Highest : Function {
protected override void Configure () {
name = "Highest";
menuName = "Floats/Relative/Highest";
propertyNames = new string[] { "A", "B" };
}
public override void Compute (Value output, Value[] arguments) {
float
a = arguments[0].Float,
b = arguments[1].Float;
output.Float = a >= b ? a : b;
}
}
public sealed class Lowest : Function {
protected override void Configure () {
name = "Lowest";
menuName = "Floats/Relative/Lowest";
propertyNames = new string[] { "A", "B" };
}
public override void Compute (Value output, Value[] arguments) {
float
a = arguments[0].Float,
b = arguments[1].Float;
output.Float = a <= b ? a : b;
}
}
public sealed class Average : Function {
protected override void Configure () {
name = "Average";
menuName = "Floats/Relative/Average";
propertyNames = new string[] { "A", "B" };
}
public override void Compute (Value output, Value[] arguments) {
output.Float = (arguments[0].Float + arguments[1].Float) * 0.5f;
}
}
#endregion
public sealed class Absolute : Function {
protected override void Configure () {
name = "Abs";
menuName = "Floats/Absolute";
propertyNames = new string[] { "Value" };
}
public override void Compute (Value output, Value[] arguments) {
float v = arguments[0].Float;
output.Float = v >= 0f ? v : -v;
}
}
public sealed class Square : Function {
protected override void Configure () {
name = "x\u00b2";
menuName = "Floats/x\u00b2 Square";
propertyNames = new string[] { "Value" };
}
public override void Compute (Value output, Value[] arguments) {
float v = arguments[0].Float;
output.Float = v * v;
}
}
public sealed class Cube : Function {
protected override void Configure () {
name = "x\u00b3";
menuName = "Floats/x\u00b3 Cube";
propertyNames = new string[] { "Value" };
}
public override void Compute (Value output, Value[] arguments) {
float v = arguments[0].Float;
output.Float = v * v * v;
}
}
public sealed class SquareRoot : Function {
protected override void Configure () {
name = "\u221a";
menuName = "Floats/\u221a Square Root";
propertyNames = new string[] { "Value" };
}
public override void Compute (Value output, Value[] arguments) {
output.Float = Mathf.Sqrt(arguments[0].Float);
}
}
public sealed class FromInt : Function {
protected override void Configure () {
name = "Float";
menuName = "Floats/From Int";
returnType = ValueType.Float;
propertyNames = new string[] { "Int" };
propertyTypes = new ValueType[] { ValueType.Int };
}
public override void Compute (Value output, Value[] arguments) {
output.Float = arguments[0].Int;
}
}
public sealed class Curve : Function {
protected override void Configure () {
name = "Curve";
menuName = "Floats/Curve";
propertyNames = new string[] { "Curve", "T" };
propertyTypes = new ValueType[] { ValueType.AnimationCurve, ValueType.Float };
}
public override void Compute (Value output, Value[] arguments) {
output.Float = arguments[0].AnimationCurve.Evaluate(arguments[1].Float);
}
}
public sealed class Lerp : Function {
protected override void Configure () {
name = "Lerp";
menuName = "Floats/Lerp";
propertyNames = new string[] { "A", "B", "T" };
}
public override void Compute (Value output, Value[] arguments) {
float
a = arguments[0].Float,
t = arguments[2].Float;
if (t <= 0f) {
output.Float = a;
}
else if (t >= 1f) {
output.Float = arguments[1].Float;
}
else {
output.Float = a + (arguments[1].Float - a) * t;
}
}
}
#region Trigonometry
public sealed class Cosine : Function {
protected override void Configure () {
name = "Cosine";
menuName = "Floats/Trigonometry/Cosine";
propertyNames = new string[] { "Value" };
}
public override void Compute (Value output, Value[] arguments) {
output.Float = Mathf.Cos(arguments[0].Float);
}
}
public sealed class Sine : Function {
protected override void Configure () {
name = "Sine";
menuName = "Floats/Trigonometry/Sine";
propertyNames = new string[] { "Value" };
}
public override void Compute (Value output, Value[] arguments) {
output.Float = Mathf.Sin(arguments[0].Float);
}
}
public sealed class Sinusoid : Function {
protected override void Configure () {
name = "Sinusoid";
menuName = "Floats/Trigonometry/Sinusoid";
propertyNames = new string[] { "Value", "Frequency", "Offset" };
}
public override void Compute (Value output, Value[] arguments) {
output.Float = Mathf.Sin((arguments[0].Float * arguments[1].Float + arguments[2].Float) * (Mathf.PI * 2f));
}
}
#endregion
#region Range
public sealed class Clamp01 : Function {
protected override void Configure () {
name = "Clamp 01";
menuName = "Floats/Range/Clamp 01";
propertyNames = new string[] { "Value" };
}
public override void Compute (Value output, Value[] arguments) {
float v = arguments[0].Float;
if (v < 0f) {
output.Float = 0f;
}
else if (v > 1f) {
output.Float = 1f;
}
else {
output.Float = v;
}
}
}
public sealed class Loop01 : Function {
protected override void Configure () {
name = "Loop 01";
menuName = "Floats/Range/Loop 01";
propertyNames = new string[] { "Value" };
}
public override void Compute (Value output, Value[] arguments) {
float v = arguments[0].Float;
if (v < 0f ) {
v += 1 - (int)v;
}
output.Float = v - (int)v;
}
}
public sealed class PingPong01 : Function {
protected override void Configure () {
name = "Pingpong 01";
menuName = "Floats/Range/Pingpong 01";
propertyNames = new string[] { "Value" };
}
public override void Compute (Value output, Value[] arguments) {
float v = arguments[0].Float;
if (v < 0f) {
v = -v;
}
int i = (int)v;
output.Float = (i & 1) == 1 ? 1f - v + i : (v - i);
}
}
#endregion
#region Perlin
public sealed class PerlinNoise : Function {
protected override void Configure () {
name = "Perlin";
menuName = "Noise 3D/Perlin/Regular";
propertyNames = new string[] { "Point", "Frequency", "Octaves", "Lacunarity", "Persistence" };
propertyTypes = new ValueType[] {
ValueType.Vector3,
ValueType.Float,
ValueType.Int,
ValueType.Float,
ValueType.Float
};
}
public override void Compute (Value output, Value[] arguments) {
output.Float = CatlikeCoding.Noise.PerlinNoise.Sample3D(
arguments[0].Vector3, arguments[1].Float, arguments[2].Int, arguments[3].Float, arguments[4].Float);
}
}
public sealed class PerlinNoiseTiledX : Function {
protected override void Configure () {
name = "Perlin tX";
menuName = "Noise 3D/Perlin/Tiled X";
propertyNames = new string[] { "Point", "Offset", "Frequency", "Octaves", "Lacunarity", "Persistence" };
propertyTypes = new ValueType[] {
ValueType.Vector3,
ValueType.Vector3,
ValueType.Int,
ValueType.Int,
ValueType.Int,
ValueType.Float
};
}
public override void Compute (Value output, Value[] arguments) {
output.Float = CatlikeCoding.Noise.PerlinNoise.Sample3DTiledX(
arguments[0].Vector3, arguments[1].Vector3, arguments[2].Int, arguments[3].Int, arguments[4].Int, arguments[5].Float);
}
}
public sealed class PerlinNoiseTiledXY : Function {
protected override void Configure () {
name = "Perlin tXY";
menuName = "Noise 3D/Perlin/Tiled XY";
propertyNames = new string[] { "Point", "Offset", "Frequency", "Octaves", "Lacunarity", "Persistence" };
propertyTypes = new ValueType[] {
ValueType.Vector3,
ValueType.Vector3,
ValueType.Int,
ValueType.Int,
ValueType.Int,
ValueType.Float
};
}
public override void Compute (Value output, Value[] arguments) {
output.Float = CatlikeCoding.Noise.PerlinNoise.Sample3DTiledXY(
arguments[0].Vector3, arguments[1].Vector3, arguments[2].Int, arguments[3].Int, arguments[4].Int, arguments[5].Float);
}
}
public sealed class PerlinNoiseTiledXYZ : Function {
protected override void Configure () {
name = "Perlin tXYZ";
menuName = "Noise 3D/Perlin/Tiled XYZ";
propertyNames = new string[] { "Point", "Offset", "Frequency", "Octaves", "Lacunarity", "Persistence" };
propertyTypes = new ValueType[] {
ValueType.Vector3,
ValueType.Vector3,
ValueType.Int,
ValueType.Int,
ValueType.Int,
ValueType.Float
};
}
public override void Compute (Value output, Value[] arguments) {
output.Float = CatlikeCoding.Noise.PerlinNoise.Sample3DTiledXYZ(
arguments[0].Vector3, arguments[1].Vector3, arguments[2].Int, arguments[3].Int, arguments[4].Int, arguments[5].Float);
}
}
public sealed class PerlinNoise2D : Function {
protected override void Configure () {
name = "Perlin";
menuName = "Noise 2D/Perlin/Regular";
propertyNames = new string[] { "Point", "Frequency", "Octaves", "Lacunarity", "Persistence" };
propertyTypes = new ValueType[] {
ValueType.Vector2,
ValueType.Float,
ValueType.Int,
ValueType.Float,
ValueType.Float
};
}
public override void Compute (Value output, Value[] arguments) {
output.Float = CatlikeCoding.Noise.PerlinNoise.Sample2D(
arguments[0].Vector2, arguments[1].Float, arguments[2].Int, arguments[3].Float, arguments[4].Float);
}
}
public sealed class PerlinNoise2DTiledX : Function {
protected override void Configure () {
name = "Perlin tX";
menuName = "Noise 2D/Perlin/Tiled X";
propertyNames = new string[] { "Point", "Offset", "Frequency", "Octaves", "Lacunarity", "Persistence" };
propertyTypes = new ValueType[] {
ValueType.Vector2,
ValueType.Vector2,
ValueType.Int,
ValueType.Int,
ValueType.Int,
ValueType.Float
};
}
public override void Compute (Value output, Value[] arguments) {
output.Float = CatlikeCoding.Noise.PerlinNoise.Sample2DTiledX(
arguments[0].Vector2, arguments[1].Vector2, arguments[2].Int, arguments[3].Int, arguments[4].Int, arguments[5].Float);
}
}
public sealed class PerlinNoise2DTiledXY : Function {
protected override void Configure () {
name = "Perlin tXY";
menuName = "Noise 2D/Perlin/Tiled XY";
propertyNames = new string[] { "Point", "Offset", "Frequency", "Octaves", "Lacunarity", "Persistence" };
propertyTypes = new ValueType[] {
ValueType.Vector2,
ValueType.Vector2,
ValueType.Int,
ValueType.Int,
ValueType.Int,
ValueType.Float
};
}
public override void Compute (Value output, Value[] arguments) {
output.Float = CatlikeCoding.Noise.PerlinNoise.Sample2DTiledXY(
arguments[0].Vector2, arguments[1].Vector2, arguments[2].Int, arguments[3].Int, arguments[4].Int, arguments[5].Float);
}
}
public sealed class PerlinTurbulence : Function {
protected override void Configure () {
name = "Turbulence";
menuName = "Noise 3D/Turbulence/Regular";
propertyNames = new string[] { "Point", "Frequency", "Octaves", "Lacunarity", "Persistence" };
propertyTypes = new ValueType[] {
ValueType.Vector3,
ValueType.Float,
ValueType.Int,
ValueType.Float,
ValueType.Float
};
}
public override void Compute (Value output, Value[] arguments) {
output.Float = CatlikeCoding.Noise.PerlinNoise.SampleTurbulence3D(
arguments[0].Vector3, arguments[1].Float, arguments[2].Int, arguments[3].Float, arguments[4].Float);
}
}
public sealed class PerlinTurbulenceTiledX : Function {
protected override void Configure () {
name = "Turbulence tX";
menuName = "Noise 3D/Turbulence/Tiled X";
propertyNames = new string[] { "Point", "Offset", "Frequency", "Octaves", "Lacunarity", "Persistence" };
propertyTypes = new ValueType[] {
ValueType.Vector3,
ValueType.Vector3,
ValueType.Int,
ValueType.Int,
ValueType.Int,
ValueType.Float
};
}
public override void Compute (Value output, Value[] arguments) {
output.Float = CatlikeCoding.Noise.PerlinNoise.SampleTurbulence3DTiledX(
arguments[0].Vector3, arguments[1].Vector3, arguments[2].Int, arguments[3].Int, arguments[4].Int, arguments[5].Float);
}
}
public sealed class PerlinTurbulenceTiledXY : Function {
protected override void Configure () {
name = "Turbulence tXY";
menuName = "Noise 3D/Turbulence/Tiled XY";
propertyNames = new string[] { "Point", "Offset", "Frequency", "Octaves", "Lacunarity", "Persistence" };
propertyTypes = new ValueType[] {
ValueType.Vector3,
ValueType.Vector3,
ValueType.Int,
ValueType.Int,
ValueType.Int,
ValueType.Float
};
}
public override void Compute (Value output, Value[] arguments) {
output.Float = CatlikeCoding.Noise.PerlinNoise.SampleTurbulence3DTiledXY(
arguments[0].Vector3, arguments[1].Vector3, arguments[2].Int, arguments[3].Int, arguments[4].Int, arguments[5].Float);
}
}
public sealed class PerlinTurbulenceTiledXYZ : Function {
protected override void Configure () {
name = "Turbulence tXYZ";
menuName = "Noise 3D/Turbulence/Tiled XYZ";
propertyNames = new string[] { "Point", "Offset", "Frequency", "Octaves", "Lacunarity", "Persistence" };
propertyTypes = new ValueType[] {
ValueType.Vector3,
ValueType.Vector3,
ValueType.Int,
ValueType.Int,
ValueType.Int,
ValueType.Float
};
}
public override void Compute (Value output, Value[] arguments) {
output.Float = CatlikeCoding.Noise.PerlinNoise.SampleTurbulence3DTiledXYZ(
arguments[0].Vector3, arguments[1].Vector3, arguments[2].Int, arguments[3].Int, arguments[4].Int, arguments[5].Float);
}
}
public sealed class PerlinTurbulence2D : Function {
protected override void Configure () {
name = "Turbulence";
menuName = "Noise 2D/Turbulence/Regular";
propertyNames = new string[] { "Point", "Frequency", "Octaves", "Lacunarity", "Persistence" };
propertyTypes = new ValueType[] {
ValueType.Vector2,
ValueType.Float,
ValueType.Int,
ValueType.Float,
ValueType.Float
};
}
public override void Compute (Value output, Value[] arguments) {
output.Float = CatlikeCoding.Noise.PerlinNoise.SampleTurbulence2D(
arguments[0].Vector2, arguments[1].Float, arguments[2].Int, arguments[3].Float, arguments[4].Float);
}
}
public sealed class PerlinTurbulence2DTiledX : Function {
protected override void Configure () {
name = "Turbulence tX";
menuName = "Noise 2D/Turbulence/Tiled X";
propertyNames = new string[] { "Point", "Offset", "Frequency", "Octaves", "Lacunarity", "Persistence" };
propertyTypes = new ValueType[] {
ValueType.Vector2,
ValueType.Vector2,
ValueType.Int,
ValueType.Int,
ValueType.Int,
ValueType.Float
};
}
public override void Compute (Value output, Value[] arguments) {
output.Float = CatlikeCoding.Noise.PerlinNoise.SampleTurbulence2DTiledX(
arguments[0].Vector2, arguments[1].Vector2, arguments[2].Int, arguments[3].Int, arguments[4].Int, arguments[5].Float);
}
}
public sealed class PerlinTurbulence2DTiledXY : Function {
protected override void Configure () {
name = "Turbulence tXY";
menuName = "Noise 2D/Turbulence/Tiled XY";
propertyNames = new string[] { "Point", "Offset", "Frequency", "Octaves", "Lacunarity", "Persistence" };
propertyTypes = new ValueType[] {
ValueType.Vector2,
ValueType.Vector2,
ValueType.Int,
ValueType.Int,
ValueType.Int,
ValueType.Float
};
}
public override void Compute (Value output, Value[] arguments) {
output.Float = CatlikeCoding.Noise.PerlinNoise.SampleTurbulence2DTiledXY(
arguments[0].Vector2, arguments[1].Vector2, arguments[2].Int, arguments[3].Int, arguments[4].Int, arguments[5].Float);
}
}
#endregion
#region Value
public sealed class ValueNoise : Function {
protected override void Configure () {
name = "Value";
menuName = "Noise 3D/Value/Regular";
propertyNames = new string[] { "Point", "Frequency", "Octaves", "Lacunarity", "Persistence" };
propertyTypes = new ValueType[] {
ValueType.Vector3,
ValueType.Float,
ValueType.Int,
ValueType.Float,
ValueType.Float
};
}
public override void Compute (Value output, Value[] arguments) {
output.Float = CatlikeCoding.Noise.ValueNoise.Sample3D(
arguments[0].Vector3, arguments[1].Float, arguments[2].Int, arguments[3].Float, arguments[4].Float);
}
}
public sealed class ValueNoiseTiledX : Function {
protected override void Configure () {
name = "Value tX";
menuName = "Noise 3D/Value/Tiled X";
propertyNames = new string[] { "Point", "Offset", "Frequency", "Octaves", "Lacunarity", "Persistence" };
propertyTypes = new ValueType[] {
ValueType.Vector3,
ValueType.Vector3,
ValueType.Int,
ValueType.Int,
ValueType.Int,
ValueType.Float
};
}
public override void Compute (Value output, Value[] arguments) {
output.Float = CatlikeCoding.Noise.ValueNoise.Sample3DTiledX(
arguments[0].Vector3, arguments[1].Vector3, arguments[2].Int, arguments[3].Int, arguments[4].Int, arguments[5].Float);
}
}
public sealed class ValueNoiseTiledXY : Function {
protected override void Configure () {
name = "Value tXY";
menuName = "Noise 3D/Value/Tiled XY";
propertyNames = new string[] { "Point", "Offset", "Frequency", "Octaves", "Lacunarity", "Persistence" };
propertyTypes = new ValueType[] {
ValueType.Vector3,
ValueType.Vector3,
ValueType.Int,
ValueType.Int,
ValueType.Int,
ValueType.Float
};
}
public override void Compute (Value output, Value[] arguments) {
output.Float = CatlikeCoding.Noise.ValueNoise.Sample3DTiledXY(
arguments[0].Vector3, arguments[1].Vector3, arguments[2].Int, arguments[3].Int, arguments[4].Int, arguments[5].Float);
}
}
public sealed class ValueNoiseTiledXYZ : Function {
protected override void Configure () {
name = "Noise tXYZ";
menuName = "Noise 3D/Value/Tiled XYZ";
propertyNames = new string[] { "Point", "Offset", "Frequency", "Octaves", "Lacunarity", "Persistence" };
propertyTypes = new ValueType[] {
ValueType.Vector3,
ValueType.Vector3,
ValueType.Int,
ValueType.Int,
ValueType.Int,
ValueType.Float
};
}
public override void Compute (Value output, Value[] arguments) {
output.Float = CatlikeCoding.Noise.ValueNoise.Sample3DTiledXYZ(
arguments[0].Vector3, arguments[1].Vector3, arguments[2].Int, arguments[3].Int, arguments[4].Int, arguments[5].Float);
}
}
public sealed class ValueNoise2D : Function {
protected override void Configure () {
name = "Value";
menuName = "Noise 2D/Value/Regular";
propertyNames = new string[] { "Point", "Frequency", "Octaves", "Lacunarity", "Persistence" };
propertyTypes = new ValueType[] {
ValueType.Vector2,
ValueType.Float,
ValueType.Int,
ValueType.Float,
ValueType.Float
};
}
public override void Compute (Value output, Value[] arguments) {
output.Float = CatlikeCoding.Noise.ValueNoise.Sample2D(
arguments[0].Vector2, arguments[1].Float, arguments[2].Int, arguments[3].Float, arguments[4].Float);
}
}
public sealed class ValueNoise2DTiledX : Function {
protected override void Configure () {
name = "Value tX";
menuName = "Noise 2D/Value/Tiled X";
propertyNames = new string[] { "Point", "Offset", "Frequency", "Octaves", "Lacunarity", "Persistence" };
propertyTypes = new ValueType[] {
ValueType.Vector2,
ValueType.Vector2,
ValueType.Int,
ValueType.Int,
ValueType.Int,
ValueType.Float
};
}
public override void Compute (Value output, Value[] arguments) {
output.Float = CatlikeCoding.Noise.ValueNoise.Sample2DTiledX(
arguments[0].Vector2, arguments[1].Vector2, arguments[2].Int, arguments[3].Int, arguments[4].Int, arguments[5].Float);
}
}
public sealed class ValueNoise2DTiledXY : Function {
protected override void Configure () {
name = "Value tXY";
menuName = "Noise 2D/Value/Tiled XY";
propertyNames = new string[] { "Point", "Offset", "Frequency", "Octaves", "Lacunarity", "Persistence" };
propertyTypes = new ValueType[] {
ValueType.Vector2,
ValueType.Vector2,
ValueType.Int,
ValueType.Int,
ValueType.Int,
ValueType.Float
};
}
public override void Compute (Value output, Value[] arguments) {
output.Float = CatlikeCoding.Noise.ValueNoise.Sample2DTiledXY(
arguments[0].Vector2, arguments[1].Vector2, arguments[2].Int, arguments[3].Int, arguments[4].Int, arguments[5].Float);
}
}
#endregion
}
| |
using System;
using System.Xml;
using System.Reflection;
using System.Collections.Generic;
namespace Platform.Xml.Serialization
{
public class ListTypeSerializer
: ComplexTypeTypeSerializer
{
public override bool MemberBound => true;
public override Type SupportedType => this.listType;
private Type listType;
private readonly IDictionary<Type, ListItem> typeToItemMap;
private readonly IDictionary<string, ListItem> aliasToItemMap;
private class ListItem
{
private string alias;
public string Alias
{
get
{
if (this.Attribute == null)
{
return this.alias;
}
if (this.Attribute.MakeNameLowercase)
{
return this.alias.ToLower();
}
return this.alias;
}
set { this.alias = value; }
}
public XmlListElementAttribute Attribute;
public TypeSerializer Serializer;
}
private readonly TypeSerializerCache cache;
private readonly IXmlListElementDynamicTypeProvider dynamicTypeResolver;
public ListTypeSerializer(SerializationMemberInfo memberInfo, TypeSerializerCache cache, SerializerOptions options)
: base(memberInfo, memberInfo.ReturnType, cache, options)
{
typeToItemMap = new Dictionary<Type, ListItem>();
aliasToItemMap = new Dictionary<string, ListItem>();
var attribute = (XmlListElementDynamicTypeProviderAttribute)memberInfo.GetFirstApplicableAttribute(typeof(XmlListElementDynamicTypeProviderAttribute));
if (attribute != null)
{
if (dynamicTypeResolver == null)
{
try
{
dynamicTypeResolver = (IXmlListElementDynamicTypeProvider)Activator.CreateInstance(attribute.ProviderType, new object[0]);
}
catch (Exception)
{
}
}
if (dynamicTypeResolver == null)
{
dynamicTypeResolver = (IXmlListElementDynamicTypeProvider)Activator.CreateInstance(attribute.ProviderType, new object[] {memberInfo, cache, options});
}
}
serializationMemberInfo = memberInfo;
this.cache = cache;
Scan(memberInfo, cache, options);
}
private readonly SerializationMemberInfo serializationMemberInfo;
protected virtual void Scan(SerializationMemberInfo memberInfo, TypeSerializerCache cache, SerializerOptions options)
{
XmlSerializationAttribute[] attribs;
var attributes = new List<Attribute>();
// Get the ElementType attributes specified on the type itself as long
// as we're not the type itself!
if (memberInfo.MemberInfo != memberInfo.ReturnType)
{
var smi = new SerializationMemberInfo(memberInfo.ReturnType, options, cache);
attribs = smi.GetApplicableAttributes(typeof(XmlListElementAttribute));
foreach (var a in attribs)
{
attributes.Add(a);
}
}
// Get the ElementType attributes specified on the member.
attribs = memberInfo.GetApplicableAttributes(typeof(XmlListElementAttribute));
foreach (var a in attribs)
{
attributes.Add(a);
}
foreach (var attribute1 in attributes)
{
var attribute = (XmlListElementAttribute)attribute1;
var listItem = new ListItem();
if (attribute.Type == null)
{
if (serializationMemberInfo.ReturnType.IsArray)
{
attribute.Type = serializationMemberInfo.ReturnType.GetElementType();
}
else if (serializationMemberInfo.ReturnType.IsGenericType)
{
attribute.Type = serializationMemberInfo.ReturnType.GetGenericArguments()[0];
}
}
var smi2 = new SerializationMemberInfo(attribute.ItemType, options, cache);
if (attribute.Alias == null)
{
attribute.Alias = smi2.SerializedName;
}
listItem.Attribute = attribute;
listItem.Alias = attribute.Alias;
// Check if a specific type of serializer is specified.
if (attribute.SerializerType == null)
{
// Figure out the serializer based on the type of the element.
listItem.Serializer = cache.GetTypeSerializerBySupportedType(attribute.ItemType, smi2);
}
else
{
// Get the type of serializer they specify.
listItem.Serializer = cache.GetTypeSerializerBySerializerType(attribute.SerializerType, smi2);
}
typeToItemMap[attribute.ItemType] = listItem;
aliasToItemMap[attribute.Alias] = listItem;
}
if (typeToItemMap.Count == 0)
{
if (memberInfo.ReturnType.IsArray)
{
var listItem = new ListItem();
var elementType = memberInfo.ReturnType.GetElementType();
var sm = new SerializationMemberInfo(elementType, options, cache);
listItem.Alias = sm.SerializedName;
listItem.Serializer = cache.GetTypeSerializerBySupportedType(elementType, new SerializationMemberInfo(elementType, options, cache));
typeToItemMap[elementType] = listItem;
aliasToItemMap[listItem.Alias] = listItem;
}
}
if (memberInfo.ReturnType.IsGenericType)
{
var elementType = memberInfo.ReturnType.GetGenericArguments()[0];
if (!typeToItemMap.ContainsKey(elementType) && dynamicTypeResolver == null && !(elementType.IsAbstract || elementType.IsInterface))
{
var listItem = new ListItem();
var sm = new SerializationMemberInfo(elementType, options, cache);
listItem.Alias = sm.SerializedName;
listItem.Serializer = cache.GetTypeSerializerBySupportedType(elementType, new SerializationMemberInfo(elementType, options, cache));
typeToItemMap[elementType] = listItem;
aliasToItemMap[listItem.Alias] = listItem;
}
}
if (typeToItemMap.Count == 0 && this.dynamicTypeResolver == null)
{
throw new InvalidOperationException(
$"Must specify at least one XmlListElemenType or an XmlListElementTypeSerializerProvider for field {((Type)memberInfo.MemberInfo).FullName}");
}
listType = memberInfo.ReturnType;
}
protected override void SerializeElements(object obj, XmlWriter writer, SerializationContext state)
{
base.SerializeElements (obj, writer, state);
foreach (var item in (System.Collections.IEnumerable)obj)
{
if (state.ShouldSerialize(item, this.serializationMemberInfo))
{
ListItem listItem;
if (typeToItemMap.TryGetValue(item.GetType(), out listItem))
{
writer.WriteStartElement(listItem.Alias);
if (listItem.Attribute != null
&& listItem.Attribute.SerializeAsValueNode
&& listItem.Attribute.ValueNodeAttributeName != null
&& listItem.Serializer is TypeSerializerWithSimpleTextSupport)
{
writer.WriteAttributeString(listItem.Attribute.ValueNodeAttributeName,
((TypeSerializerWithSimpleTextSupport)listItem.Serializer).Serialize(item, state));
}
else
{
listItem.Serializer.Serialize(item, writer, state);
}
}
else
{
if (this.dynamicTypeResolver == null)
{
throw new XmlSerializerException();
}
else
{
var type = this.dynamicTypeResolver.GetType(item);
if (type == null)
{
throw new XmlSerializerException();
}
var serializer = cache.GetTypeSerializerBySupportedType(type);
writer.WriteStartElement(this.dynamicTypeResolver.GetName(item));
serializer.Serialize(item, writer, state);
}
}
writer.WriteEndElement();
}
}
}
protected override object CreateInstance(XmlReader reader, SerializationContext state)
{
if (listType.IsArray)
{
return new List<object>();
}
else
{
return Activator.CreateInstance(serializationMemberInfo.GetReturnType(reader));
}
}
protected override bool CanDeserializeElement(object obj, XmlReader reader, SerializationContext state)
{
if (aliasToItemMap[reader.Name] != null)
{
return true;
}
return base.CanDeserializeElement (obj, reader, state);
}
protected override void DeserializeElement(object obj, XmlReader reader, SerializationContext state)
{
ListItem listItem;
bool isGenericList;
MethodInfo methodInfo;
System.Collections.IList list;
if (obj is System.Collections.IList)
{
methodInfo = null;
isGenericList = false;
list = (System.Collections.IList)obj;
}
else
{
list = null;
isGenericList = true;
methodInfo = obj.GetType().GetMethod("Add");
}
if (base.CanDeserializeElement(obj, reader, state))
{
base.DeserializeElement (obj, reader, state);
return;
}
if (aliasToItemMap.TryGetValue(reader.Name, out listItem))
{
if (listItem.Attribute != null
&& listItem.Attribute.SerializeAsValueNode
&& listItem.Attribute.ValueNodeAttributeName != null
&& listItem.Serializer is TypeSerializerWithSimpleTextSupport)
{
var s = reader.GetAttribute(listItem.Attribute.ValueNodeAttributeName);
if (isGenericList)
{
methodInfo.Invoke(obj, new object[] { ((TypeSerializerWithSimpleTextSupport)listItem.Serializer).Deserialize(s, state) });
}
else
{
list.Add(((TypeSerializerWithSimpleTextSupport)listItem.Serializer).Deserialize(s, state));
}
XmlReaderHelper.ReadAndConsumeMatchingEndElement(reader);
}
else
{
if (isGenericList)
{
methodInfo.Invoke(obj, new object[] { listItem.Serializer.Deserialize(reader, state) });
}
else
{
list.Add(listItem.Serializer.Deserialize(reader, state));
}
}
}
else
{
TypeSerializer serializer = null;
if (this.dynamicTypeResolver != null)
{
var type = dynamicTypeResolver.GetType(reader);
if (type != null)
{
serializer = cache.GetTypeSerializerBySupportedType(type);
}
}
if (serializer == null)
{
base.DeserializeElement (obj, reader, state);
}
else
{
if (isGenericList)
{
methodInfo.Invoke(obj, new object[] { serializer.Deserialize(reader, state) });
}
else
{
list.Add(serializer.Deserialize(reader, state));
}
}
}
}
public override object Deserialize(XmlReader reader, SerializationContext state)
{
var retval = base.Deserialize(reader, state);
if (listType.IsArray)
{
int count;
if (retval is System.Collections.IList)
{
count = ((System.Collections.IList)retval).Count;
}
else
{
count = (int)retval.GetType().GetProperty("Count", BindingFlags.Instance | BindingFlags.Public).GetValue(retval, new object[0]);
}
var array = Array.CreateInstance(listType.GetElementType(), count);
state.DeserializationStart(retval);
if (retval is System.Collections.IList)
{
((System.Collections.IList)retval).CopyTo(array, 0);
}
else
{
retval.GetType().GetMethod
(
"CopyTo",
BindingFlags.Instance | BindingFlags.Public
).Invoke(retval, new object[] { array, 0 });
}
retval = array;
}
state.DeserializationEnd(retval);
return retval;
}
}
}
| |
// 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.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Batch.Protocol.Models
{
using System;
using System.Linq;
using System.Collections.Generic;
using Newtonsoft.Json;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Microsoft.Rest.Azure;
/// <summary>
/// A job schedule that allows recurring jobs by specifying when to run
/// jobs and a specification used to create each job.
/// </summary>
public partial class CloudJobSchedule
{
/// <summary>
/// Initializes a new instance of the CloudJobSchedule class.
/// </summary>
public CloudJobSchedule() { }
/// <summary>
/// Initializes a new instance of the CloudJobSchedule class.
/// </summary>
/// <param name="id">A string that uniquely identifies the schedule within the account.</param>
/// <param name="displayName">The display name for the schedule.</param>
/// <param name="url">The URL of the job schedule.</param>
/// <param name="eTag">The ETag of the job schedule.</param>
/// <param name="lastModified">The last modified time of the job schedule.</param>
/// <param name="creationTime">The creation time of the job schedule.</param>
/// <param name="state">The current state of the job schedule.</param>
/// <param name="stateTransitionTime">The time at which the job schedule entered the current state.</param>
/// <param name="previousState">The previous state of the job schedule.</param>
/// <param name="previousStateTransitionTime">The time at which the job schedule entered its previous state.</param>
/// <param name="schedule">The schedule according to which jobs will be created.</param>
/// <param name="jobSpecification">The details of the jobs to be created on this schedule.</param>
/// <param name="executionInfo">Information about jobs that have been and will be run under this schedule.</param>
/// <param name="metadata">A list of name-value pairs associated with the schedule as metadata.</param>
/// <param name="stats">The lifetime resource usage statistics for the job schedule.</param>
public CloudJobSchedule(string id = default(string), string displayName = default(string), string url = default(string), string eTag = default(string), DateTime? lastModified = default(DateTime?), DateTime? creationTime = default(DateTime?), JobScheduleState? state = default(JobScheduleState?), DateTime? stateTransitionTime = default(DateTime?), JobScheduleState? previousState = default(JobScheduleState?), DateTime? previousStateTransitionTime = default(DateTime?), Schedule schedule = default(Schedule), JobSpecification jobSpecification = default(JobSpecification), JobScheduleExecutionInformation executionInfo = default(JobScheduleExecutionInformation), IList<MetadataItem> metadata = default(IList<MetadataItem>), JobScheduleStatistics stats = default(JobScheduleStatistics))
{
Id = id;
DisplayName = displayName;
Url = url;
ETag = eTag;
LastModified = lastModified;
CreationTime = creationTime;
State = state;
StateTransitionTime = stateTransitionTime;
PreviousState = previousState;
PreviousStateTransitionTime = previousStateTransitionTime;
Schedule = schedule;
JobSpecification = jobSpecification;
ExecutionInfo = executionInfo;
Metadata = metadata;
Stats = stats;
}
/// <summary>
/// Gets or sets a string that uniquely identifies the schedule within
/// the account.
/// </summary>
/// <remarks>
/// It is common to use a GUID for the id.
/// </remarks>
[JsonProperty(PropertyName = "id")]
public string Id { get; set; }
/// <summary>
/// Gets or sets the display name for the schedule.
/// </summary>
[JsonProperty(PropertyName = "displayName")]
public string DisplayName { get; set; }
/// <summary>
/// Gets or sets the URL of the job schedule.
/// </summary>
[JsonProperty(PropertyName = "url")]
public string Url { get; set; }
/// <summary>
/// Gets or sets the ETag of the job schedule.
/// </summary>
[JsonProperty(PropertyName = "eTag")]
public string ETag { get; set; }
/// <summary>
/// Gets or sets the last modified time of the job schedule.
/// </summary>
[JsonProperty(PropertyName = "lastModified")]
public DateTime? LastModified { get; set; }
/// <summary>
/// Gets or sets the creation time of the job schedule.
/// </summary>
[JsonProperty(PropertyName = "creationTime")]
public DateTime? CreationTime { get; set; }
/// <summary>
/// Gets or sets the current state of the job schedule.
/// </summary>
/// <remarks>
/// Possible values include: 'active', 'completed', 'disabled',
/// 'terminating', 'deleting'
/// </remarks>
[JsonProperty(PropertyName = "state")]
public JobScheduleState? State { get; set; }
/// <summary>
/// Gets or sets the time at which the job schedule entered the
/// current state.
/// </summary>
[JsonProperty(PropertyName = "stateTransitionTime")]
public DateTime? StateTransitionTime { get; set; }
/// <summary>
/// Gets or sets the previous state of the job schedule.
/// </summary>
/// <remarks>
/// Possible values include: 'active', 'completed', 'disabled',
/// 'terminating', 'deleting'
/// </remarks>
[JsonProperty(PropertyName = "previousState")]
public JobScheduleState? PreviousState { get; set; }
/// <summary>
/// Gets or sets the time at which the job schedule entered its
/// previous state.
/// </summary>
[JsonProperty(PropertyName = "previousStateTransitionTime")]
public DateTime? PreviousStateTransitionTime { get; set; }
/// <summary>
/// Gets or sets the schedule according to which jobs will be created.
/// </summary>
[JsonProperty(PropertyName = "schedule")]
public Schedule Schedule { get; set; }
/// <summary>
/// Gets or sets the details of the jobs to be created on this
/// schedule.
/// </summary>
[JsonProperty(PropertyName = "jobSpecification")]
public JobSpecification JobSpecification { get; set; }
/// <summary>
/// Gets or sets information about jobs that have been and will be run
/// under this schedule.
/// </summary>
[JsonProperty(PropertyName = "executionInfo")]
public JobScheduleExecutionInformation ExecutionInfo { get; set; }
/// <summary>
/// Gets or sets a list of name-value pairs associated with the
/// schedule as metadata.
/// </summary>
[JsonProperty(PropertyName = "metadata")]
public IList<MetadataItem> Metadata { get; set; }
/// <summary>
/// Gets or sets the lifetime resource usage statistics for the job
/// schedule.
/// </summary>
[JsonProperty(PropertyName = "stats")]
public JobScheduleStatistics Stats { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (this.JobSpecification != null)
{
this.JobSpecification.Validate();
}
if (this.Metadata != null)
{
foreach (var element in this.Metadata)
{
if (element != null)
{
element.Validate();
}
}
}
if (this.Stats != null)
{
this.Stats.Validate();
}
}
}
}
| |
///////////////////////////////////////////////////////////////////////////////////////////////
//
// This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler
//
// Copyright (c) 2005-2008, Jim Heising
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// * Neither the name of Jim Heising nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using Microsoft.Office.Interop.Outlook;
namespace Utilities.ContactManagement
{
public class OutlookContactItem : IContactItem
{
public OutlookContactItem(Microsoft.Office.Interop.Outlook.ContactItem baseItem)
{
_baseContact = baseItem;
SyncValuesFromBase();
}
private Microsoft.Office.Interop.Outlook.ContactItem _baseContact;
[OutlookSync]
public string FirstName
{
get
{
return _baseContact.FirstName;
}
set
{
_baseContact.FirstName = value;
}
}
[OutlookSync]
public string LastName
{
get
{
return _baseContact.LastName;// _lastName;
}
set
{
_baseContact.LastName = value;
}
}
[OutlookSync]
public string PrimaryTelephoneNumber
{
get
{
return _baseContact.PrimaryTelephoneNumber;
}
set
{
_baseContact.PrimaryTelephoneNumber = value;
}
}
[OutlookSync]
public string Email1Address
{
get
{
return _baseContact.Email1Address;
}
set
{
_baseContact.Email1Address = value;
}
}
[OutlookSync]
public string FullName
{
get
{
return _baseContact.FullName;
}
set
{
_baseContact.FullName = value;
}
}
[OutlookSync]
public string BusinessTelephoneNumber
{
get
{
return _baseContact.BusinessTelephoneNumber;
}
set
{
_baseContact.BusinessTelephoneNumber = value;
}
}
public object BaseContact
{
get
{
return _baseContact;
}
//set
//{
// _baseContact = (Outlook.ContactItem) value;
// if (_baseContact != null)
// {
// SyncValuesFromBase();
// }
//}
}
public void SyncValuesFromContact()
{
Microsoft.Office.Interop.Outlook.ContactItem item = BaseContact as Microsoft.Office.Interop.Outlook.ContactItem;
PropertyInfo[] props = this.GetType().GetProperties();
foreach (PropertyInfo pi in props)
{
string name = pi.Name.Replace("set_", "");
object[] attribs = pi.GetCustomAttributes(typeof(OutlookSync), false);
if (attribs.Length > 0)
{
SyncValue(pi.Name, pi.GetValue(this, null));
}
}
}
public void SyncValuesFromBase()
{
Microsoft.Office.Interop.Outlook.ContactItem item = BaseContact as Microsoft.Office.Interop.Outlook.ContactItem;
PropertyInfo[] props = this.GetType().GetProperties();
foreach (PropertyInfo pi in props)
{
string name = pi.Name.Replace("set_", "");
object[] attribs = pi.GetCustomAttributes(typeof(OutlookSync), false);
if (attribs.Length > 0)
{
Microsoft.Office.Interop.Outlook.ItemProperty oProp = item.ItemProperties[name];
if (oProp != null)
{
pi.SetValue(this, oProp.Value, null);
}
}
}
}
private void SyncValue(string methodName, object value)
{
methodName = methodName.Replace("set_", "");
Microsoft.Office.Interop.Outlook.ContactItem item = BaseContact as Microsoft.Office.Interop.Outlook.ContactItem;
if (item != null)
{
Microsoft.Office.Interop.Outlook.ItemProperty prop = item.ItemProperties[methodName];
if (prop != null)
{
prop.Value = value;
}
}
}
}
public class OutlookSync : Attribute
{
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Security.Principal;
namespace System.Security.Claims
{
/// <summary>
/// Concrete IPrincipal supporting multiple claims-based identities
/// </summary>
public class ClaimsPrincipal : IPrincipal
{
private enum SerializationMask
{
None = 0,
HasIdentities = 1,
UserData = 2
}
private readonly List<ClaimsIdentity> _identities = new List<ClaimsIdentity>();
private readonly byte[] _userSerializationData;
private static Func<IEnumerable<ClaimsIdentity>, ClaimsIdentity> s_identitySelector = SelectPrimaryIdentity;
private static Func<ClaimsPrincipal> s_principalSelector = ClaimsPrincipalSelector;
protected ClaimsPrincipal(SerializationInfo info, StreamingContext context)
{
throw new PlatformNotSupportedException();
}
/// <summary>
/// This method iterates through the collection of ClaimsIdentities and chooses an identity as the primary.
/// </summary>
private static ClaimsIdentity SelectPrimaryIdentity(IEnumerable<ClaimsIdentity> identities)
{
if (identities == null)
{
throw new ArgumentNullException(nameof(identities));
}
foreach (ClaimsIdentity identity in identities)
{
if (identity != null)
{
return identity;
}
}
return null;
}
public static Func<IEnumerable<ClaimsIdentity>, ClaimsIdentity> PrimaryIdentitySelector
{
get
{
return s_identitySelector;
}
set
{
s_identitySelector = value;
}
}
public static Func<ClaimsPrincipal> ClaimsPrincipalSelector
{
get
{
return s_principalSelector;
}
set
{
s_principalSelector = value;
}
}
/// <summary>
/// Initializes an instance of <see cref="ClaimsPrincipal"/>.
/// </summary>
public ClaimsPrincipal()
{
}
/// <summary>
/// Initializes an instance of <see cref="ClaimsPrincipal"/>.
/// </summary>
/// <param name="identities"> <see cref="IEnumerable{ClaimsIdentity}"/> the subjects in the principal.</param>
/// <exception cref="ArgumentNullException">if 'identities' is null.</exception>
public ClaimsPrincipal(IEnumerable<ClaimsIdentity> identities)
{
if (identities == null)
{
throw new ArgumentNullException(nameof(identities));
}
_identities.AddRange(identities);
}
/// <summary>
/// Initializes an instance of <see cref="ClaimsPrincipal"/>
/// </summary>
/// <param name="identity"> <see cref="IIdentity"/> representing the subject in the principal. </param>
/// <exception cref="ArgumentNullException">if 'identity' is null.</exception>
public ClaimsPrincipal(IIdentity identity)
{
if (identity == null)
{
throw new ArgumentNullException(nameof(identity));
}
ClaimsIdentity ci = identity as ClaimsIdentity;
if (ci != null)
{
_identities.Add(ci);
}
else
{
_identities.Add(new ClaimsIdentity(identity));
}
}
/// <summary>
/// Initializes an instance of <see cref="ClaimsPrincipal"/>
/// </summary>
/// <param name="principal"><see cref="IPrincipal"/> used to form this instance.</param>
/// <exception cref="ArgumentNullException">if 'principal' is null.</exception>
public ClaimsPrincipal(IPrincipal principal)
{
if (null == principal)
{
throw new ArgumentNullException(nameof(principal));
}
//
// If IPrincipal is a ClaimsPrincipal add all of the identities
// If IPrincipal is not a ClaimsPrincipal, create a new identity from IPrincipal.Identity
//
ClaimsPrincipal cp = principal as ClaimsPrincipal;
if (null == cp)
{
_identities.Add(new ClaimsIdentity(principal.Identity));
}
else
{
if (null != cp.Identities)
{
_identities.AddRange(cp.Identities);
}
}
}
/// <summary>
/// Initializes an instance of <see cref="ClaimsPrincipal"/> using a <see cref="BinaryReader"/>.
/// Normally the <see cref="BinaryReader"/> is constructed using the bytes from <see cref="WriteTo(BinaryWriter)"/> and initialized in the same way as the <see cref="BinaryWriter"/>.
/// </summary>
/// <param name="reader">a <see cref="BinaryReader"/> pointing to a <see cref="ClaimsPrincipal"/>.</param>
/// <exception cref="ArgumentNullException">if 'reader' is null.</exception>
public ClaimsPrincipal(BinaryReader reader)
{
if (reader == null)
{
throw new ArgumentNullException(nameof(reader));
}
SerializationMask mask = (SerializationMask)reader.ReadInt32();
int numPropertiesToRead = reader.ReadInt32();
int numPropertiesRead = 0;
if ((mask & SerializationMask.HasIdentities) == SerializationMask.HasIdentities)
{
numPropertiesRead++;
int numberOfIdentities = reader.ReadInt32();
for (int index = 0; index < numberOfIdentities; ++index)
{
// directly add to _identities as that is what we serialized from
_identities.Add(CreateClaimsIdentity(reader));
}
}
if ((mask & SerializationMask.UserData) == SerializationMask.UserData)
{
int cb = reader.ReadInt32();
_userSerializationData = reader.ReadBytes(cb);
numPropertiesRead++;
}
for (int i = numPropertiesRead; i < numPropertiesToRead; i++)
{
reader.ReadString();
}
}
/// <summary>
/// Adds a single <see cref="ClaimsIdentity"/> to an internal list.
/// </summary>
/// <param name="identity">the <see cref="ClaimsIdentity"/>add.</param>
/// <exception cref="ArgumentNullException">if 'identity' is null.</exception>
public virtual void AddIdentity(ClaimsIdentity identity)
{
if (identity == null)
{
throw new ArgumentNullException(nameof(identity));
}
_identities.Add(identity);
}
/// <summary>
/// Adds a <see cref="IEnumerable{ClaimsIdentity}"/> to the internal list.
/// </summary>
/// <param name="identities">Enumeration of ClaimsIdentities to add.</param>
/// <exception cref="ArgumentNullException">if 'identities' is null.</exception>
public virtual void AddIdentities(IEnumerable<ClaimsIdentity> identities)
{
if (identities == null)
{
throw new ArgumentNullException(nameof(identities));
}
_identities.AddRange(identities);
}
/// <summary>
/// Gets the claims as <see cref="IEnumerable{Claim}"/>, associated with this <see cref="ClaimsPrincipal"/> by enumerating all <see cref="Identities"/>.
/// </summary>
public virtual IEnumerable<Claim> Claims
{
get
{
foreach (ClaimsIdentity identity in Identities)
{
foreach (Claim claim in identity.Claims)
{
yield return claim;
}
}
}
}
/// <summary>
/// Contains any additional data provided by derived type, typically set when calling <see cref="WriteTo(BinaryWriter, byte[])"/>.
/// </summary>
protected virtual byte[] CustomSerializationData
{
get
{
return _userSerializationData;
}
}
/// <summary>
/// Creates a new instance of <see cref="ClaimsPrincipal"/> with values copied from this object.
/// </summary>
public virtual ClaimsPrincipal Clone()
{
return new ClaimsPrincipal(this);
}
/// <summary>
/// Provides an extensibility point for derived types to create a custom <see cref="ClaimsIdentity"/>.
/// </summary>
/// <param name="reader">the <see cref="BinaryReader"/>that points at the claim.</param>
/// <exception cref="ArgumentNullException">if 'reader' is null.</exception>
/// <returns>a new <see cref="ClaimsIdentity"/>.</returns>
protected virtual ClaimsIdentity CreateClaimsIdentity(BinaryReader reader)
{
if (reader == null)
{
throw new ArgumentNullException(nameof(reader));
}
return new ClaimsIdentity(reader);
}
/// <summary>
/// Returns the Current Principal by calling a delegate. Users may specify the delegate.
/// </summary>
public static ClaimsPrincipal Current
{
// just accesses the current selected principal selector, doesn't set
get
{
if (s_principalSelector != null)
{
return s_principalSelector();
}
return null;
}
}
/// <summary>
/// Retrieves a <see cref="IEnumerable{Claim}"/> where each claim is matched by <paramref name="match"/>.
/// </summary>
/// <param name="match">The predicate that performs the matching logic.</param>
/// <returns>A <see cref="IEnumerable{Claim}"/> of matched claims.</returns>
/// <remarks>Each <see cref="ClaimsIdentity"/> is called. <seealso cref="ClaimsIdentity.FindAll(string)"/>.</remarks>
/// <exception cref="ArgumentNullException">if 'match' is null.</exception>
public virtual IEnumerable<Claim> FindAll(Predicate<Claim> match)
{
if (match == null)
{
throw new ArgumentNullException(nameof(match));
}
foreach (ClaimsIdentity identity in Identities)
{
if (identity != null)
{
foreach (Claim claim in identity.FindAll(match))
{
yield return claim;
}
}
}
}
/// <summary>
/// Retrieves a <see cref="IEnumerable{Claim}"/> where each Claim.Type equals <paramref name="type"/>.
/// </summary>
/// <param name="type">The type of the claim to match.</param>
/// <returns>A <see cref="IEnumerable{Claim}"/> of matched claims.</returns>
/// <remarks>Each <see cref="ClaimsIdentity"/> is called. <seealso cref="ClaimsIdentity.FindAll(Predicate{Claim})"/>.</remarks>
/// <exception cref="ArgumentNullException">if 'type' is null.</exception>
public virtual IEnumerable<Claim> FindAll(string type)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
foreach (ClaimsIdentity identity in Identities)
{
if (identity != null)
{
foreach (Claim claim in identity.FindAll(type))
{
yield return claim;
}
}
}
}
/// <summary>
/// Retrieves the first <see cref="Claim"/> that is matched by <paramref name="match"/>.
/// </summary>
/// <param name="match">The predicate that performs the matching logic.</param>
/// <returns>A <see cref="Claim"/>, null if nothing matches.</returns>
/// <remarks>Each <see cref="ClaimsIdentity"/> is called. <seealso cref="ClaimsIdentity.FindFirst(string)"/>.</remarks>
/// <exception cref="ArgumentNullException">if 'match' is null.</exception>
public virtual Claim FindFirst(Predicate<Claim> match)
{
if (match == null)
{
throw new ArgumentNullException(nameof(match));
}
Claim claim = null;
foreach (ClaimsIdentity identity in Identities)
{
if (identity != null)
{
claim = identity.FindFirst(match);
if (claim != null)
{
return claim;
}
}
}
return claim;
}
/// <summary>
/// Retrieves the first <see cref="Claim"/> where the Claim.Type equals <paramref name="type"/>.
/// </summary>
/// <param name="type">The type of the claim to match.</param>
/// <returns>A <see cref="Claim"/>, null if nothing matches.</returns>
/// <remarks>Each <see cref="ClaimsIdentity"/> is called. <seealso cref="ClaimsIdentity.FindFirst(Predicate{Claim})"/>.</remarks>
/// <exception cref="ArgumentNullException">if 'type' is null.</exception>
public virtual Claim FindFirst(string type)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
Claim claim = null;
for (int i = 0; i < _identities.Count; i++)
{
if (_identities[i] != null)
{
claim = _identities[i].FindFirst(type);
if (claim != null)
{
return claim;
}
}
}
return claim;
}
/// <summary>
/// Determines if a claim is contained within all the ClaimsIdentities in this ClaimPrincipal.
/// </summary>
/// <param name="match">The predicate that performs the matching logic.</param>
/// <returns>true if a claim is found, false otherwise.</returns>
/// <remarks>Each <see cref="ClaimsIdentity"/> is called. <seealso cref="ClaimsIdentity.HasClaim(string, string)"/>.</remarks>
/// <exception cref="ArgumentNullException">if 'match' is null.</exception>
public virtual bool HasClaim(Predicate<Claim> match)
{
if (match == null)
{
throw new ArgumentNullException(nameof(match));
}
for (int i = 0; i < _identities.Count; i++)
{
if (_identities[i] != null)
{
if (_identities[i].HasClaim(match))
{
return true;
}
}
}
return false;
}
/// <summary>
/// Determines if a claim of claimType AND claimValue exists in any of the identities.
/// </summary>
/// <param name="type"> the type of the claim to match.</param>
/// <param name="value"> the value of the claim to match.</param>
/// <returns>true if a claim is matched, false otherwise.</returns>
/// <remarks>Each <see cref="ClaimsIdentity"/> is called. <seealso cref="ClaimsIdentity.HasClaim(Predicate{Claim})"/>.</remarks>
/// <exception cref="ArgumentNullException">if 'type' is null.</exception>
/// <exception cref="ArgumentNullException">if 'value' is null.</exception>
public virtual bool HasClaim(string type, string value)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
for (int i = 0; i < _identities.Count; i++)
{
if (_identities[i] != null)
{
if (_identities[i].HasClaim(type, value))
{
return true;
}
}
}
return false;
}
/// <summary>
/// Collection of <see cref="ClaimsIdentity" />
/// </summary>
public virtual IEnumerable<ClaimsIdentity> Identities
{
get
{
return _identities;
}
}
/// <summary>
/// Gets the identity of the current principal.
/// </summary>
public virtual System.Security.Principal.IIdentity Identity
{
get
{
if (s_identitySelector != null)
{
return s_identitySelector(_identities);
}
else
{
return SelectPrimaryIdentity(_identities);
}
}
}
/// <summary>
/// IsInRole answers the question: does an identity this principal possesses
/// contain a claim of type RoleClaimType where the value is '==' to the role.
/// </summary>
/// <param name="role">The role to check for.</param>
/// <returns>'True' if a claim is found. Otherwise 'False'.</returns>
/// <remarks>Each Identity has its own definition of the ClaimType that represents a role.</remarks>
public virtual bool IsInRole(string role)
{
for (int i = 0; i < _identities.Count; i++)
{
if (_identities[i] != null)
{
if (_identities[i].HasClaim(_identities[i].RoleClaimType, role))
{
return true;
}
}
}
return false;
}
/// <summary>
/// Serializes using a <see cref="BinaryWriter"/>
/// </summary>
/// <exception cref="ArgumentNullException">if 'writer' is null.</exception>
public virtual void WriteTo(BinaryWriter writer)
{
WriteTo(writer, null);
}
/// <summary>
/// Serializes using a <see cref="BinaryWriter"/>
/// </summary>
/// <param name="writer">the <see cref="BinaryWriter"/> to use for data storage.</param>
/// <param name="userData">additional data provided by derived type.</param>
/// <exception cref="ArgumentNullException">if 'writer' is null.</exception>
protected virtual void WriteTo(BinaryWriter writer, byte[] userData)
{
if (writer == null)
{
throw new ArgumentNullException(nameof(writer));
}
int numberOfPropertiesWritten = 0;
var mask = SerializationMask.None;
if (_identities.Count > 0)
{
mask |= SerializationMask.HasIdentities;
numberOfPropertiesWritten++;
}
if (userData != null && userData.Length > 0)
{
numberOfPropertiesWritten++;
mask |= SerializationMask.UserData;
}
writer.Write((int)mask);
writer.Write(numberOfPropertiesWritten);
if ((mask & SerializationMask.HasIdentities) == SerializationMask.HasIdentities)
{
writer.Write(_identities.Count);
foreach (var identity in _identities)
{
identity.WriteTo(writer);
}
}
if ((mask & SerializationMask.UserData) == SerializationMask.UserData)
{
writer.Write(userData.Length);
writer.Write(userData);
}
writer.Flush();
}
[OnSerializing]
private void OnSerializingMethod(StreamingContext context)
{
if (this is ISerializable)
{
return;
}
if (_identities.Count > 0)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_Serialization); // BinaryFormatter and WindowsIdentity would be needed
}
}
protected virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new PlatformNotSupportedException();
}
}
}
| |
using System;
using UnityEngine;
using ws.winx.input;
using System.Collections.Generic;
using System.IO;
using System.Collections;
using ws.winx.devices;
namespace ws.winx.input.components
{
public class UserInterfaceWindow : MonoBehaviour
{
protected Rect _buttonRect = new Rect (0, 0, 100, 15);
protected Rect _layerLabelRect = new Rect (0, 0, 100, 15);
protected Dictionary<int, InputState> _stateInputCombinations;
// public Dictionary<int, InputState> StateInputCombinations
// {
// get { return _stateInputCombinations; }
// set { _stateInputCombinations = value; }
// }
protected static bool _settingsLoaded = false;
protected static bool _submitButton = false;
protected static bool _deviceListShow = false;
protected int _selectedStateHash = 0;
protected string _combinationSeparator = InputAction.SPACE_DESIGNATOR.ToString ();
protected int _isPrimary = 0;
protected string _currentInputString;
protected string _defaultProfile = "default";
protected GUILayoutOption[] _inputLabelStyle = new GUILayoutOption[] { GUILayout.Width (200) };
protected GUILayoutOption[] _stateNameLabelStyle = new GUILayoutOption[] { GUILayout.Width (250) };
#if UNITY_ANDROID || UNITY_IPHONE
protected GUILayoutOption[] _inputButtonStyle = new GUILayoutOption[] { GUILayout.Height(200) };
protected GUILayoutOption[] _submitButtonStyle = new GUILayoutOption[] {GUILayout.Height(200), GUILayout.Width(80) };
#else
protected GUILayoutOption[] _inputButtonStyle = new GUILayoutOption[] { GUILayout.Height (30) };
#endif
protected InputAction _action;
protected Vector2 _scrollPosition = Vector2.zero;
protected InputCombination _previousStateInput = null;
//Players
int _playerIndexSelected;
int _playerIndexSelectedPrev;
string[] _playerDisplayOptions;
// int[] _playerIndices;
InputPlayer _playerSelected;
//Device
int _deviceDisplayIndex;
string[] _deviceDisplayOptions;
// int[] _deviceIndices;
int _deviceDisplayIndexPrev;
/// <summary>
/// Path very InputSettings would be saved
/// </summary>
///
public string saveURL;
public InputManager.InputSettings settings;
public int maxCombosNum = 3;
public GUISkin guiSkin;
public bool isComplexActionTypesAllowed;
public Rect windowRect = new Rect (0, 0, 600, 430);
//public bool allowDuplicates=false;
void Start ()
{
}
/// <summary>
/// Update this instance.
/// </summary>
void Update ()
{
if (_selectedStateHash != 0) {
// UnityEngine.Debug.Log("Edit mode true");
//Use is mapping states so no quering keys during gameplay
InputManager.EditMode = true;
_action = InputManager.GetAction (_playerSelected.Device);
if (_action != null && (_action.getCode (_playerSelected.Device) ^ (int)KeyCode.Escape) != 0 && (_action.getCode (_playerSelected.Device) ^ (int)KeyCode.Return) != 0) {
if ((_action.getCode (_playerSelected.Device) ^ (int)KeyCode.Backspace) == 0) {
_stateInputCombinations [_selectedStateHash].combinations [_isPrimary].Clear ();
_stateInputCombinations [_selectedStateHash].combinations [_isPrimary].Add (new InputAction (KeyCode.None));
} else {
if (!isComplexActionTypesAllowed)
_action.type = InputActionType.SINGLE;
//remove ord
_action.setCode(InputCode.toCodeAnyDevice(_action.getCode(_playerSelected.Device)), _playerSelected.Device);
toInputCombination (_stateInputCombinations [_selectedStateHash].combinations [_isPrimary], _action);
}
// Debug.Log("Action:" + _action + " " + _action.getCode(_playerSelected.Device));
}
//Debug.Log ("Action:"+action);
} else {
// UnityEngine.Debug.Log("Edit mode false");
//Continue gameplay
InputManager.EditMode = false;
}
}
/// <summary>
/// Saves the input settings.
/// </summary>
void saveInputSettings ()
{
#if UNITY_WEBPLAYER && !UNITY_EDITOR
if (saveURL == null) throw new Exception("Save path should point to some web service resposable for saving");
InputManager.saveSettings(saveURL);
#endif
#if UNITY_WEBPLAYER && UNITY_EDITOR
InputManager.saveSettings(Path.Combine(Application.streamingAssetsPath, "InputSettings.xml"));
InputManager.saveSettings(Path.Combine(Application.streamingAssetsPath,this.GetComponent<InputComponent>().settingsFileName));
#endif
#if UNITY_ANDROID
//Try to save to /storage/sdcard0/Android/data/ws.winx.InputManager/files
//InputManager.saveSettings(Application.persistentDataPath+"/InputSettings.xml");
InputManager.saveSettings(Path.Combine(Application.persistentDataPath,this.GetComponent<InputComponent>().settingsFileName));
Debug.Log("UI>> Try to save to " + Application.persistentDataPath);
#endif
#if UNITY_STANDALONE
InputManager.saveSettings(Path.Combine(Application.streamingAssetsPath,this.GetComponent<InputComponent>().settingsFileName));
#endif
}
/// <summary>
/// Tos the input combination.
/// </summary>
/// <param name="combos">Combos.</param>
/// <param name="input">Input.</param>
void toInputCombination (InputCombination combos, InputAction input)
{
if (combos.numActions + 1 > maxCombosNum || (combos.numActions == 1 && combos.GetActionAt (0).getCode (_playerSelected.Device) == 0))
combos.Clear ();
combos.Add (input);
}
/// <summary>
/// Raises the GU event.
/// </summary>
private void OnGUI ()
{
GUI.skin = guiSkin;
GUI.Window (1, windowRect, CreateWindow, new GUIContent ());
//GUI.Window(1, new Rect(0, 0, Screen.width, Screen.height), CreateWindow,new GUIContent());
//if event is of key or mouse
if (Event.current.isKey) {
if (Event.current.keyCode == KeyCode.Return) {
_selectedStateHash = 0;
_previousStateInput = null;
//this.Repaint ();
} else if (Event.current.keyCode == KeyCode.Escape) {
if (_selectedStateHash != 0) {
_stateInputCombinations [_selectedStateHash].combinations [_isPrimary] = _previousStateInput;
_previousStateInput = null;
_selectedStateHash = 0;
}
}
}
//Approach dependent of GUI so not applicable if you have 3D GUI
//if (_selectedStateHash != 0)
// InputEx.processGUIEvent (Event.current);//process input from keyboard & mouses
}
/// <summary>
/// Creates the window.
/// </summary>
/// <param name="windowID">Window I.</param>
private void CreateWindow (int windowID)
{
GUILayout.Label ("http://unity3de.blogspot.com/");
GUILayout.Label ("InputEx");
int i = 0;
if (settings != null) {
///////// PLAYERS //////////
if (_playerDisplayOptions == null) {
int numPlayers = settings.Players.Length;
_playerDisplayOptions = new string[numPlayers];
for (i=0; i<numPlayers; i++) {
_playerDisplayOptions [i] = "Player" + i;
}
}
_playerIndexSelected = GUILayout.SelectionGrid (_playerIndexSelected, _playerDisplayOptions, _playerDisplayOptions.Length);
_playerSelected = settings.Players [_playerIndexSelected];
// close/hide device list when player index changed
if (_playerIndexSelectedPrev != _playerIndexSelected) {
_deviceListShow = false;
_deviceDisplayIndexPrev = 0;
}
_playerIndexSelectedPrev = _playerIndexSelected;
///////////// DEVICES ////////////
List<IDevice> devicesList = InputManager.GetDevices<IDevice> ();
if (devicesList.Count > 0) {
//remove devices already assigned except of currentPlayer's Device
for (i=0; i<settings.Players.Length; i++) {
IDevice device = settings.Players [i].Device;
if (device != null && !device.Equals (_playerSelected.Device))
devicesList.Remove (device);
}
//Fill Device List (first option NoDevice)
_deviceDisplayOptions = new string[devicesList.Count + 1];
_deviceDisplayOptions [0] = "No Device";
for (i=1; i<_deviceDisplayOptions.Length;) {
//if(currentPlayer.Device!=devices [i - 1]){
_deviceDisplayOptions [i] = "(" + (i - 1) + ")" + devicesList [i - 1].Name;
i++;
//}
}
string deviceButtonLabel = _playerSelected.Device != null ? _playerSelected.Device.Name : "No Device";
int deviceIndex = -1;
if (_playerSelected.Device != null) {
deviceIndex = devicesList.IndexOf (_playerSelected.Device);
_deviceDisplayIndex = deviceIndex + 1;
} else {
_deviceDisplayIndex = 0;
}
//toggle DeviceList
if (GUILayout.Button (deviceButtonLabel)) {
_deviceListShow = !_deviceListShow;
}
//show Device List
if (_deviceListShow) {
//get selection
_deviceDisplayIndex = GUILayout.SelectionGrid (_deviceDisplayIndex, _deviceDisplayOptions, 1);
if (_deviceDisplayIndexPrev != _deviceDisplayIndex)
_deviceListShow = false;
_deviceDisplayIndexPrev = _deviceDisplayIndex;
}
//assign/remove device to player
if (_deviceDisplayIndex == 0)
_playerSelected.Device = null;
else if (deviceIndex + 1 != _deviceDisplayIndex)
_playerSelected.Device = devicesList [_deviceDisplayIndex - 1];
}
///PROFILE
//if device is assigned to player and device have profile and there are input settings for that profile
if (_playerSelected.Device != null && _playerSelected.Device.profile != null && _playerSelected.DeviceProfileStateInputs.ContainsKey (_playerSelected.Device.profile.Name)) {
_stateInputCombinations = _playerSelected.DeviceProfileStateInputs [_playerSelected.Device.profile.Name];
} else {
_stateInputCombinations = _playerSelected.DeviceProfileStateInputs [_defaultProfile];
}
}
//////////// INPUT STATES /////////////
_scrollPosition = GUILayout.BeginScrollView (_scrollPosition, false, true);
if (_stateInputCombinations != null)
foreach (var keyValuPair in _stateInputCombinations) {
//primary,secondary...
createInputStateGUI (keyValuPair.Key, keyValuPair.Value.name, keyValuPair.Value.combinations);
}
GUILayout.EndScrollView ();
//////////////////////////////////////
GUILayout.Space (20);
if (_selectedStateHash == 0 && GUILayout.Button ("Save")) {
saveInputSettings ();
}
}
/// <summary>
/// Creates the Input State GUI.
/// </summary>
/// <param name="hash">State Hash.</param>
/// <param name="stateName">State name.</param>
/// <param name="combinations">State Combinations.</param>
void createInputStateGUI (int hash, string stateName, InputCombination[] combinations)
{
string currentCombinationString;
GUILayout.BeginHorizontal ();
//string stateName=((CharacterInputControllerClass.States)hash).ToString();
//(AnimatorEnum)hash
//GUILayout.Label(stateName.Remove(0,stateName.IndexOf("Layer")+6).Replace("_"," "),_stateNameLabelStyle);
GUILayout.Label (stateName, _stateNameLabelStyle);
if (_selectedStateHash != hash) {
//!!! USE HERE YOUR CUSTOM METHOD TO SHOW DISPLAY
if (GUILayout.Button (InputCode.beautify (combinations [0].combinationString), _inputButtonStyle)) {
_selectedStateHash = hash;
_previousStateInput = null;
_isPrimary = 0;
}
if (combinations.Length > 1 && combinations [1] != null)
//!!! USE HERE YOUR CUSTOM METHOD TO SHOW DISPLAY
if (GUILayout.Button (InputCode.beautify (combinations [1].combinationString), _inputButtonStyle)) {
_selectedStateHash = hash;
_previousStateInput = null;
_isPrimary = 1;
}
} else {
currentCombinationString = combinations [_isPrimary].combinationString;
if (_previousStateInput == null) {
_previousStateInput = combinations [_isPrimary].Clone ();
}
//!!! USE HERE YOUR CUSTOM METHOD TO SHOW DISPLAY
currentCombinationString = InputCode.beautify (currentCombinationString);
GUILayout.Label (currentCombinationString);
#if UNITY_ANDROID || UNITY_IPHONE
if (GUILayout.Button("Submit",_submitButtonStyle))
{
_selectedStateHash = 0;
_previousStateInput = null;
return;
}
#endif
//this.Repaint ();
}
//Debug.Log ("_selectedStateHash after" + _selectedStateHash);
GUILayout.EndHorizontal ();
GUILayout.Space (20);
}
/// <summary>
/// DONT FORGET TO CLEAN AFTER YOURSELF
/// </summary>
void OnDestroy ()
{
Debug.Log ("onDestroy UserInterfaceWindow");
_selectedStateHash = 0;
Debug.Log ("onDestroy End UserInterfaceWindow");
}
}
}
| |
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;
namespace IO.Swagger.Model
{
/// <summary>
///
/// </summary>
[DataContract]
public class PrivateIndividualName : IEquatable<PrivateIndividualName>
{
/// <summary>
/// Initializes a new instance of the <see cref="PrivateIndividualName" /> class.
/// </summary>
public PrivateIndividualName()
{
}
/// <summary>
/// Gets or Sets Forename
/// </summary>
[DataMember(Name="forename", EmitDefaultValue=false)]
public string Forename { get; set; }
/// <summary>
/// Gets or Sets MiddleName
/// </summary>
[DataMember(Name="middle_name", EmitDefaultValue=false)]
public string MiddleName { get; set; }
/// <summary>
/// Gets or Sets Surname
/// </summary>
[DataMember(Name="surname", EmitDefaultValue=false)]
public string Surname { get; set; }
/// <summary>
/// Gets or Sets Dob
/// </summary>
[DataMember(Name="dob", EmitDefaultValue=false)]
public string Dob { get; set; }
/// <summary>
/// Gets or Sets Gender
/// </summary>
[DataMember(Name="gender", EmitDefaultValue=false)]
public string Gender { get; set; }
/// <summary>
/// Gets or Sets PhoneNumber
/// </summary>
[DataMember(Name="phone_number", EmitDefaultValue=false)]
public string PhoneNumber { get; set; }
/// <summary>
/// Gets or Sets Address
/// </summary>
[DataMember(Name="address", EmitDefaultValue=false)]
public string Address { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class PrivateIndividualName {\n");
sb.Append(" Forename: ").Append(Forename).Append("\n");
sb.Append(" MiddleName: ").Append(MiddleName).Append("\n");
sb.Append(" Surname: ").Append(Surname).Append("\n");
sb.Append(" Dob: ").Append(Dob).Append("\n");
sb.Append(" Gender: ").Append(Gender).Append("\n");
sb.Append(" PhoneNumber: ").Append(PhoneNumber).Append("\n");
sb.Append(" Address: ").Append(Address).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as PrivateIndividualName);
}
/// <summary>
/// Returns true if PrivateIndividualName instances are equal
/// </summary>
/// <param name="other">Instance of PrivateIndividualName to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(PrivateIndividualName other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Forename == other.Forename ||
this.Forename != null &&
this.Forename.Equals(other.Forename)
) &&
(
this.MiddleName == other.MiddleName ||
this.MiddleName != null &&
this.MiddleName.Equals(other.MiddleName)
) &&
(
this.Surname == other.Surname ||
this.Surname != null &&
this.Surname.Equals(other.Surname)
) &&
(
this.Dob == other.Dob ||
this.Dob != null &&
this.Dob.Equals(other.Dob)
) &&
(
this.Gender == other.Gender ||
this.Gender != null &&
this.Gender.Equals(other.Gender)
) &&
(
this.PhoneNumber == other.PhoneNumber ||
this.PhoneNumber != null &&
this.PhoneNumber.Equals(other.PhoneNumber)
) &&
(
this.Address == other.Address ||
this.Address != null &&
this.Address.Equals(other.Address)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Forename != null)
hash = hash * 57 + this.Forename.GetHashCode();
if (this.MiddleName != null)
hash = hash * 57 + this.MiddleName.GetHashCode();
if (this.Surname != null)
hash = hash * 57 + this.Surname.GetHashCode();
if (this.Dob != null)
hash = hash * 57 + this.Dob.GetHashCode();
if (this.Gender != null)
hash = hash * 57 + this.Gender.GetHashCode();
if (this.PhoneNumber != null)
hash = hash * 57 + this.PhoneNumber.GetHashCode();
if (this.Address != null)
hash = hash * 57 + this.Address.GetHashCode();
return hash;
}
}
}
}
| |
using System;
using System.IO;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using RestSharp;
using IO.Swagger.Client;
using IO.Swagger.Model;
namespace IO.Swagger.Api
{
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public interface IComplaintsApi
{
#region Synchronous Operations
/// <summary>
/// Complaints: Free service (with registration), providing community and government complaint lookup by phone number for up to 2,000 queries per month. Details include number complaint rates from (FTC, FCC, IRS, Indiana Attorney General) and key entity tag extractions from complaints.
/// </summary>
/// <remarks>
/// This is the main funciton to get data out of the call control reporting system<br />\r\n Try with api_key 'demo' and phone numbers 18008472911, 13157244022, 17275567300, 18008276655, and 12061231234 (last one not spam)
/// </remarks>
/// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="phoneNumber">phone number to search</param>
/// <returns>Complaints</returns>
Complaints ComplaintsComplaints (string phoneNumber);
/// <summary>
/// Complaints: Free service (with registration), providing community and government complaint lookup by phone number for up to 2,000 queries per month. Details include number complaint rates from (FTC, FCC, IRS, Indiana Attorney General) and key entity tag extractions from complaints.
/// </summary>
/// <remarks>
/// This is the main funciton to get data out of the call control reporting system<br />\r\n Try with api_key 'demo' and phone numbers 18008472911, 13157244022, 17275567300, 18008276655, and 12061231234 (last one not spam)
/// </remarks>
/// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="phoneNumber">phone number to search</param>
/// <returns>ApiResponse of Complaints</returns>
ApiResponse<Complaints> ComplaintsComplaintsWithHttpInfo (string phoneNumber);
#endregion Synchronous Operations
#region Asynchronous Operations
/// <summary>
/// Complaints: Free service (with registration), providing community and government complaint lookup by phone number for up to 2,000 queries per month. Details include number complaint rates from (FTC, FCC, IRS, Indiana Attorney General) and key entity tag extractions from complaints.
/// </summary>
/// <remarks>
/// This is the main funciton to get data out of the call control reporting system<br />\r\n Try with api_key 'demo' and phone numbers 18008472911, 13157244022, 17275567300, 18008276655, and 12061231234 (last one not spam)
/// </remarks>
/// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="phoneNumber">phone number to search</param>
/// <returns>Task of Complaints</returns>
System.Threading.Tasks.Task<Complaints> ComplaintsComplaintsAsync (string phoneNumber);
/// <summary>
/// Complaints: Free service (with registration), providing community and government complaint lookup by phone number for up to 2,000 queries per month. Details include number complaint rates from (FTC, FCC, IRS, Indiana Attorney General) and key entity tag extractions from complaints.
/// </summary>
/// <remarks>
/// This is the main funciton to get data out of the call control reporting system<br />\r\n Try with api_key 'demo' and phone numbers 18008472911, 13157244022, 17275567300, 18008276655, and 12061231234 (last one not spam)
/// </remarks>
/// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="phoneNumber">phone number to search</param>
/// <returns>Task of ApiResponse (Complaints)</returns>
System.Threading.Tasks.Task<ApiResponse<Complaints>> ComplaintsComplaintsAsyncWithHttpInfo (string phoneNumber);
#endregion Asynchronous Operations
}
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public class ComplaintsApi : IComplaintsApi
{
/// <summary>
/// Initializes a new instance of the <see cref="ComplaintsApi"/> class.
/// </summary>
/// <returns></returns>
public ComplaintsApi(String basePath)
{
this.Configuration = new Configuration(new ApiClient(basePath));
// ensure API client has configuration ready
if (Configuration.ApiClient.Configuration == null)
{
this.Configuration.ApiClient.Configuration = this.Configuration;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="ComplaintsApi"/> class
/// using Configuration object
/// </summary>
/// <param name="configuration">An instance of Configuration</param>
/// <returns></returns>
public ComplaintsApi(Configuration configuration = null)
{
if (configuration == null) // use the default one in Configuration
this.Configuration = Configuration.Default;
else
this.Configuration = configuration;
// ensure API client has configuration ready
if (Configuration.ApiClient.Configuration == null)
{
this.Configuration.ApiClient.Configuration = this.Configuration;
}
}
/// <summary>
/// Gets the base path of the API client.
/// </summary>
/// <value>The base path</value>
public String GetBasePath()
{
return this.Configuration.ApiClient.RestClient.BaseUrl.ToString();
}
/// <summary>
/// Sets the base path of the API client.
/// </summary>
/// <value>The base path</value>
[Obsolete("SetBasePath is deprecated, please do 'Configuraiton.ApiClient = new ApiClient(\"http://new-path\")' instead.")]
public void SetBasePath(String basePath)
{
// do nothing
}
/// <summary>
/// Gets or sets the configuration object
/// </summary>
/// <value>An instance of the Configuration</value>
public Configuration Configuration {get; set;}
/// <summary>
/// Gets the default header.
/// </summary>
/// <returns>Dictionary of HTTP header</returns>
[Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")]
public Dictionary<String, String> DefaultHeader()
{
return this.Configuration.DefaultHeader;
}
/// <summary>
/// Add default header.
/// </summary>
/// <param name="key">Header field name.</param>
/// <param name="value">Header field value.</param>
/// <returns></returns>
[Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")]
public void AddDefaultHeader(string key, string value)
{
this.Configuration.AddDefaultHeader(key, value);
}
/// <summary>
/// Complaints: Free service (with registration), providing community and government complaint lookup by phone number for up to 2,000 queries per month. Details include number complaint rates from (FTC, FCC, IRS, Indiana Attorney General) and key entity tag extractions from complaints. This is the main funciton to get data out of the call control reporting system<br />\r\n Try with api_key 'demo' and phone numbers 18008472911, 13157244022, 17275567300, 18008276655, and 12061231234 (last one not spam)
/// </summary>
/// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="phoneNumber">phone number to search</param>
/// <returns>Complaints</returns>
public Complaints ComplaintsComplaints (string phoneNumber)
{
ApiResponse<Complaints> localVarResponse = ComplaintsComplaintsWithHttpInfo(phoneNumber);
return localVarResponse.Data;
}
/// <summary>
/// Complaints: Free service (with registration), providing community and government complaint lookup by phone number for up to 2,000 queries per month. Details include number complaint rates from (FTC, FCC, IRS, Indiana Attorney General) and key entity tag extractions from complaints. This is the main funciton to get data out of the call control reporting system<br />\r\n Try with api_key 'demo' and phone numbers 18008472911, 13157244022, 17275567300, 18008276655, and 12061231234 (last one not spam)
/// </summary>
/// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="phoneNumber">phone number to search</param>
/// <returns>ApiResponse of Complaints</returns>
public ApiResponse< Complaints > ComplaintsComplaintsWithHttpInfo (string phoneNumber)
{
// verify the required parameter 'phoneNumber' is set
if (phoneNumber == null)
throw new ApiException(400, "Missing required parameter 'phoneNumber' when calling ComplaintsApi->ComplaintsComplaints");
var localVarPath = "/api/2015-11-01/Complaints/{phoneNumber}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json", "text/json", "application/xml", "text/xml"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (phoneNumber != null) localVarPathParams.Add("phoneNumber", Configuration.ApiClient.ParameterToString(phoneNumber)); // path parameter
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (localVarStatusCode >= 400)
throw new ApiException (localVarStatusCode, "Error calling ComplaintsComplaints: " + localVarResponse.Content, localVarResponse.Content);
else if (localVarStatusCode == 0)
throw new ApiException (localVarStatusCode, "Error calling ComplaintsComplaints: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage);
return new ApiResponse<Complaints>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(Complaints) Configuration.ApiClient.Deserialize(localVarResponse, typeof(Complaints)));
}
/// <summary>
/// Complaints: Free service (with registration), providing community and government complaint lookup by phone number for up to 2,000 queries per month. Details include number complaint rates from (FTC, FCC, IRS, Indiana Attorney General) and key entity tag extractions from complaints. This is the main funciton to get data out of the call control reporting system<br />\r\n Try with api_key 'demo' and phone numbers 18008472911, 13157244022, 17275567300, 18008276655, and 12061231234 (last one not spam)
/// </summary>
/// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="phoneNumber">phone number to search</param>
/// <returns>Task of Complaints</returns>
public async System.Threading.Tasks.Task<Complaints> ComplaintsComplaintsAsync (string phoneNumber)
{
ApiResponse<Complaints> localVarResponse = await ComplaintsComplaintsAsyncWithHttpInfo(phoneNumber);
return localVarResponse.Data;
}
/// <summary>
/// Complaints: Free service (with registration), providing community and government complaint lookup by phone number for up to 2,000 queries per month. Details include number complaint rates from (FTC, FCC, IRS, Indiana Attorney General) and key entity tag extractions from complaints. This is the main funciton to get data out of the call control reporting system<br />\r\n Try with api_key 'demo' and phone numbers 18008472911, 13157244022, 17275567300, 18008276655, and 12061231234 (last one not spam)
/// </summary>
/// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="phoneNumber">phone number to search</param>
/// <returns>Task of ApiResponse (Complaints)</returns>
public async System.Threading.Tasks.Task<ApiResponse<Complaints>> ComplaintsComplaintsAsyncWithHttpInfo (string phoneNumber)
{
// verify the required parameter 'phoneNumber' is set
if (phoneNumber == null) throw new ApiException(400, "Missing required parameter 'phoneNumber' when calling ComplaintsComplaints");
var localVarPath = "/api/2015-11-01/Complaints/{phoneNumber}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json", "text/json", "application/xml", "text/xml"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (phoneNumber != null) localVarPathParams.Add("phoneNumber", Configuration.ApiClient.ParameterToString(phoneNumber)); // path parameter
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (localVarStatusCode >= 400)
throw new ApiException (localVarStatusCode, "Error calling ComplaintsComplaints: " + localVarResponse.Content, localVarResponse.Content);
else if (localVarStatusCode == 0)
throw new ApiException (localVarStatusCode, "Error calling ComplaintsComplaints: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage);
return new ApiResponse<Complaints>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(Complaints) Configuration.ApiClient.Deserialize(localVarResponse, typeof(Complaints)));
}
}
}
| |
// Copyright 2014, Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Author: api.anash@gmail.com (Anash P. Oommen)
using Google.Api.Ads.Dfp.Lib;
using Google.Api.Ads.Dfp.Util.v201408;
using Google.Api.Ads.Dfp.v201408;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Threading;
namespace Google.Api.Ads.Dfp.Tests.v201408 {
/// <summary>
/// UnitTests for <see cref="LineItemService"/> class.
/// </summary>
[TestFixture]
public class LineItemServiceTests : BaseTests {
/// <summary>
/// UnitTests for <see cref="LineItemService"/> class.
/// </summary>
private LineItemService lineItemService;
/// <summary>
/// Advertiser company id for running tests.
/// </summary>
private long advertiserId;
/// <summary>
/// Salesperson user id for running tests.
/// </summary>
private long salespersonId;
/// <summary>
/// Trafficker user id for running tests.
/// </summary>
private long traffickerId;
/// <summary>
/// Ad unit id for running tests.
/// </summary>
private string adUnitId;
/// <summary>
/// Placement id for running tests.
/// </summary>
private long placementId;
/// <summary>
/// Order id for running tests.
/// </summary>
private long orderId;
/// <summary>
/// Line item 1 for running tests.
/// </summary>
private LineItem lineItem1;
/// <summary>
/// Line item 2 for running tests.
/// </summary>
private LineItem lineItem2;
/// <summary>
/// Default public constructor.
/// </summary>
public LineItemServiceTests() : base() {
}
/// <summary>
/// Initialize the test case.
/// </summary>
[SetUp]
public void Init() {
TestUtils utils = new TestUtils();
lineItemService = (LineItemService)user.GetService(DfpService.v201408.LineItemService);
advertiserId = utils.CreateCompany(user, CompanyType.ADVERTISER).id;
salespersonId = utils.GetSalesperson(user).id;
traffickerId = utils.GetTrafficker(user).id;
orderId = utils.CreateOrder(user, advertiserId, salespersonId, traffickerId).id;
adUnitId = utils.CreateAdUnit(user).id;
placementId = utils.CreatePlacement(user, new string[] {adUnitId}).id;
lineItem1 = utils.CreateLineItem(user, orderId, adUnitId);
lineItem2 = utils.CreateLineItem(user, orderId, adUnitId);
}
/// <summary>
/// Test whether we can create a list of line items.
/// </summary>
[Test]
public void TestCreateLineItems() {
// Create inventory targeting.
InventoryTargeting inventoryTargeting = new InventoryTargeting();
inventoryTargeting.targetedPlacementIds = new long[] {placementId};
// Create geographical targeting.
GeoTargeting geoTargeting = new GeoTargeting();
// Include the US and Quebec, Canada.
Location countryLocation = new Location();
countryLocation.id = 2840L;
Location regionLocation = new Location();
regionLocation.id = 20123L;
geoTargeting.targetedLocations = new Location[] {countryLocation, regionLocation};
// Exclude Chicago and the New York metro area.
Location cityLocation = new Location();
cityLocation.id = 1016367L;
Location metroLocation = new Location();
metroLocation.id = 200501L;
geoTargeting.excludedLocations = new Location[] {cityLocation, metroLocation};
// Exclude domains that are not under the network's control.
UserDomainTargeting userDomainTargeting = new UserDomainTargeting();
userDomainTargeting.domains = new String[] {"usa.gov"};
userDomainTargeting.targeted = false;
// Create day-part targeting.
DayPartTargeting dayPartTargeting = new DayPartTargeting();
dayPartTargeting.timeZone = DeliveryTimeZone.BROWSER;
// Target only the weekend in the browser's timezone.
DayPart saturdayDayPart = new DayPart();
saturdayDayPart.dayOfWeek = Google.Api.Ads.Dfp.v201408.DayOfWeek.SATURDAY;
saturdayDayPart.startTime = new TimeOfDay();
saturdayDayPart.startTime.hour = 0;
saturdayDayPart.startTime.minute = MinuteOfHour.ZERO;
saturdayDayPart.endTime = new TimeOfDay();
saturdayDayPart.endTime.hour = 24;
saturdayDayPart.endTime.minute = MinuteOfHour.ZERO;
DayPart sundayDayPart = new DayPart();
sundayDayPart.dayOfWeek = Google.Api.Ads.Dfp.v201408.DayOfWeek.SUNDAY;
sundayDayPart.startTime = new TimeOfDay();
sundayDayPart.startTime.hour = 0;
sundayDayPart.startTime.minute = MinuteOfHour.ZERO;
sundayDayPart.endTime = new TimeOfDay();
sundayDayPart.endTime.hour = 24;
sundayDayPart.endTime.minute = MinuteOfHour.ZERO;
dayPartTargeting.dayParts = new DayPart[] {saturdayDayPart, sundayDayPart};
// Create technology targeting.
TechnologyTargeting technologyTargeting = new TechnologyTargeting();
// Create browser targeting.
BrowserTargeting browserTargeting = new BrowserTargeting();
browserTargeting.isTargeted = true;
// Target just the Chrome browser.
Technology browserTechnology = new Technology();
browserTechnology.id = 500072L;
browserTargeting.browsers = new Technology[] {browserTechnology};
technologyTargeting.browserTargeting = browserTargeting;
// Create an array to store local line item objects.
LineItem[] lineItems = new LineItem[2];
for (int i = 0; i < lineItems.Length; i++) {
LineItem lineItem = new LineItem();
lineItem.name = "Line item #" + new TestUtils().GetTimeStamp();
lineItem.orderId = orderId;
lineItem.targeting = new Targeting();
lineItem.targeting.inventoryTargeting = inventoryTargeting;
lineItem.targeting.geoTargeting = geoTargeting;
lineItem.targeting.userDomainTargeting = userDomainTargeting;
lineItem.targeting.dayPartTargeting = dayPartTargeting;
lineItem.targeting.technologyTargeting = technologyTargeting;
lineItem.lineItemType = LineItemType.STANDARD;
lineItem.allowOverbook = true;
// Set the creative rotation type to even.
lineItem.creativeRotationType = CreativeRotationType.EVEN;
// Set the size of creatives that can be associated with this line item.
Size size = new Size();
size.width = 300;
size.height = 250;
size.isAspectRatio = false;
// Create the creative placeholder.
CreativePlaceholder creativePlaceholder = new CreativePlaceholder();
creativePlaceholder.size = size;
lineItem.creativePlaceholders = new CreativePlaceholder[] {creativePlaceholder};
// Set the length of the line item to run.
//lineItem.startDateTimeType = StartDateTimeType.IMMEDIATELY;
lineItem.startDateTimeType = StartDateTimeType.IMMEDIATELY;
lineItem.endDateTime = DateTimeUtilities.FromDateTime(System.DateTime.Today.AddMonths(1));
// Set the cost per unit to $2.
lineItem.costType = CostType.CPM;
lineItem.costPerUnit = new Money();
lineItem.costPerUnit.currencyCode = "USD";
lineItem.costPerUnit.microAmount = 2000000L;
// Set the number of units bought to 500,000 so that the budget is
// $1,000.
Goal goal = new Goal();
goal.units = 500000L;
goal.unitType = UnitType.IMPRESSIONS;
lineItem.primaryGoal = goal;
lineItems[i] = lineItem;
}
LineItem[] localLineItems = null;
Assert.DoesNotThrow(delegate() {
localLineItems = lineItemService.createLineItems(lineItems);
});
Assert.NotNull(localLineItems);
Assert.AreEqual(localLineItems.Length, 2);
Assert.AreEqual(localLineItems[0].name, lineItems[0].name);
Assert.AreEqual(localLineItems[0].orderId, lineItems[0].orderId);
Assert.AreEqual(localLineItems[1].name, lineItems[1].name);
Assert.AreEqual(localLineItems[1].orderId, lineItems[1].orderId);
}
/// <summary>
/// Test whether we can fetch a list of existing line items that match given
/// statement.
/// </summary>
[Test]
public void TestGetLineItemsByStatement() {
Statement statement = new Statement();
statement.query = string.Format("WHERE id = '{0}' LIMIT 1", lineItem1.id);
LineItemPage page = null;
Assert.DoesNotThrow(delegate() {
page = lineItemService.getLineItemsByStatement(statement);
});
Assert.NotNull(page);
Assert.AreEqual(page.totalResultSetSize, 1);
Assert.NotNull(page.results);
Assert.AreEqual(page.results[0].id, lineItem1.id);
Assert.AreEqual(page.results[0].name, lineItem1.name);
Assert.AreEqual(page.results[0].orderId, lineItem1.orderId);
}
/// <summary>
/// Test whether we can activate a line item.
/// </summary>
[Test]
public void TestPerformLineItemAction() {
Statement statement = new Statement();
statement.query = string.Format("WHERE orderId = '{0}' and status = '{1}'",
orderId, ComputedStatus.NEEDS_CREATIVES);
ActivateLineItems action = new ActivateLineItems();
UpdateResult result = null;
Assert.DoesNotThrow(delegate() {
result = lineItemService.performLineItemAction(action, statement);
});
Assert.NotNull(result);
}
/// <summary>
/// Test whether we can update a list of line items.
/// </summary>
[Test]
public void TestUpdateLineItems() {
lineItem1.costPerUnit.microAmount = 3500000;
lineItem2.costPerUnit.microAmount = 3500000;
LineItem[] localLineItems = null;
Assert.DoesNotThrow(delegate() {
localLineItems = lineItemService.updateLineItems(new LineItem[] {lineItem1, lineItem2});
});
Assert.NotNull(localLineItems);
Assert.AreEqual(localLineItems.Length, 2);
Assert.AreEqual(localLineItems[0].id, lineItem1.id);
Assert.AreEqual(localLineItems[0].name, lineItem1.name);
Assert.AreEqual(localLineItems[0].orderId, lineItem1.orderId);
Assert.AreEqual(localLineItems[0].costPerUnit.microAmount, lineItem1.costPerUnit.microAmount);
Assert.AreEqual(localLineItems[1].id, lineItem2.id);
Assert.AreEqual(localLineItems[1].name, lineItem2.name);
Assert.AreEqual(localLineItems[1].orderId, lineItem2.orderId);
Assert.AreEqual(localLineItems[1].costPerUnit.microAmount, lineItem2.costPerUnit.microAmount);
}
}
}
| |
namespace Epi.Windows.Analysis.Dialogs
{
partial class LinearRegressionDialog
{
/// <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 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(LinearRegressionDialog));
this.cmbWeight = new System.Windows.Forms.ComboBox();
this.lblWeight = new System.Windows.Forms.Label();
this.lblOutput = new System.Windows.Forms.Label();
this.txtOutput = new System.Windows.Forms.TextBox();
this.cmbOutcome = new System.Windows.Forms.ComboBox();
this.lblOutcomeVar = new System.Windows.Forms.Label();
this.lbxOther = new System.Windows.Forms.ListBox();
this.btnHelp = new System.Windows.Forms.Button();
this.btnClear = new System.Windows.Forms.Button();
this.btnOK = new System.Windows.Forms.Button();
this.btnSaveOnly = new System.Windows.Forms.Button();
this.cmbOther = new System.Windows.Forms.ComboBox();
this.lblOther = new System.Windows.Forms.Label();
this.cmbConfLimits = new System.Windows.Forms.ComboBox();
this.lblConfLimits = new System.Windows.Forms.Label();
this.btnModifyTerm = new System.Windows.Forms.Button();
this.lblDummyVar = new System.Windows.Forms.Label();
this.lblInteractionTerms = new System.Windows.Forms.Label();
this.lbxInteractionTerms = new System.Windows.Forms.ListBox();
this.checkboxNoIntercept = new System.Windows.Forms.CheckBox();
this.btnCancel = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// baseImageList
//
this.baseImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("baseImageList.ImageStream")));
this.baseImageList.Images.SetKeyName(0, "");
this.baseImageList.Images.SetKeyName(1, "");
this.baseImageList.Images.SetKeyName(2, "");
this.baseImageList.Images.SetKeyName(3, "");
this.baseImageList.Images.SetKeyName(4, "");
this.baseImageList.Images.SetKeyName(5, "");
this.baseImageList.Images.SetKeyName(6, "");
this.baseImageList.Images.SetKeyName(7, "");
this.baseImageList.Images.SetKeyName(8, "");
this.baseImageList.Images.SetKeyName(9, "");
this.baseImageList.Images.SetKeyName(10, "");
this.baseImageList.Images.SetKeyName(11, "");
this.baseImageList.Images.SetKeyName(12, "");
this.baseImageList.Images.SetKeyName(13, "");
this.baseImageList.Images.SetKeyName(14, "");
this.baseImageList.Images.SetKeyName(15, "");
this.baseImageList.Images.SetKeyName(16, "");
this.baseImageList.Images.SetKeyName(17, "");
this.baseImageList.Images.SetKeyName(18, "");
this.baseImageList.Images.SetKeyName(19, "");
this.baseImageList.Images.SetKeyName(20, "");
this.baseImageList.Images.SetKeyName(21, "");
this.baseImageList.Images.SetKeyName(22, "");
this.baseImageList.Images.SetKeyName(23, "");
this.baseImageList.Images.SetKeyName(24, "");
this.baseImageList.Images.SetKeyName(25, "");
this.baseImageList.Images.SetKeyName(26, "");
this.baseImageList.Images.SetKeyName(27, "");
this.baseImageList.Images.SetKeyName(28, "");
this.baseImageList.Images.SetKeyName(29, "");
this.baseImageList.Images.SetKeyName(30, "");
this.baseImageList.Images.SetKeyName(31, "");
this.baseImageList.Images.SetKeyName(32, "");
this.baseImageList.Images.SetKeyName(33, "");
this.baseImageList.Images.SetKeyName(34, "");
this.baseImageList.Images.SetKeyName(35, "");
this.baseImageList.Images.SetKeyName(36, "");
this.baseImageList.Images.SetKeyName(37, "");
this.baseImageList.Images.SetKeyName(38, "");
this.baseImageList.Images.SetKeyName(39, "");
this.baseImageList.Images.SetKeyName(40, "");
this.baseImageList.Images.SetKeyName(41, "");
this.baseImageList.Images.SetKeyName(42, "");
this.baseImageList.Images.SetKeyName(43, "");
this.baseImageList.Images.SetKeyName(44, "");
this.baseImageList.Images.SetKeyName(45, "");
this.baseImageList.Images.SetKeyName(46, "");
this.baseImageList.Images.SetKeyName(47, "");
this.baseImageList.Images.SetKeyName(48, "");
this.baseImageList.Images.SetKeyName(49, "");
this.baseImageList.Images.SetKeyName(50, "");
this.baseImageList.Images.SetKeyName(51, "");
this.baseImageList.Images.SetKeyName(52, "");
this.baseImageList.Images.SetKeyName(53, "");
this.baseImageList.Images.SetKeyName(54, "");
this.baseImageList.Images.SetKeyName(55, "");
this.baseImageList.Images.SetKeyName(56, "");
this.baseImageList.Images.SetKeyName(57, "");
this.baseImageList.Images.SetKeyName(58, "");
this.baseImageList.Images.SetKeyName(59, "");
this.baseImageList.Images.SetKeyName(60, "");
this.baseImageList.Images.SetKeyName(61, "");
this.baseImageList.Images.SetKeyName(62, "");
this.baseImageList.Images.SetKeyName(63, "");
this.baseImageList.Images.SetKeyName(64, "");
this.baseImageList.Images.SetKeyName(65, "");
this.baseImageList.Images.SetKeyName(66, "");
this.baseImageList.Images.SetKeyName(67, "");
this.baseImageList.Images.SetKeyName(68, "");
this.baseImageList.Images.SetKeyName(69, "");
this.baseImageList.Images.SetKeyName(70, "");
this.baseImageList.Images.SetKeyName(71, "");
this.baseImageList.Images.SetKeyName(72, "");
this.baseImageList.Images.SetKeyName(73, "");
this.baseImageList.Images.SetKeyName(74, "");
this.baseImageList.Images.SetKeyName(75, "");
//
// cmbWeight
//
this.cmbWeight.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
resources.ApplyResources(this.cmbWeight, "cmbWeight");
this.cmbWeight.Name = "cmbWeight";
this.cmbWeight.SelectedIndexChanged += new System.EventHandler(this.cmbWeight_SelectedIndexChanged);
this.cmbWeight.KeyDown += new System.Windows.Forms.KeyEventHandler(this.cmbWeight_KeyDown);
//
// lblWeight
//
this.lblWeight.FlatStyle = System.Windows.Forms.FlatStyle.System;
resources.ApplyResources(this.lblWeight, "lblWeight");
this.lblWeight.Name = "lblWeight";
//
// lblOutput
//
this.lblOutput.FlatStyle = System.Windows.Forms.FlatStyle.System;
resources.ApplyResources(this.lblOutput, "lblOutput");
this.lblOutput.Name = "lblOutput";
//
// txtOutput
//
resources.ApplyResources(this.txtOutput, "txtOutput");
this.txtOutput.Name = "txtOutput";
//
// cmbOutcome
//
this.cmbOutcome.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
resources.ApplyResources(this.cmbOutcome, "cmbOutcome");
this.cmbOutcome.Name = "cmbOutcome";
this.cmbOutcome.SelectedIndexChanged += new System.EventHandler(this.cmbOutcome_SelectedIndexChanged);
//
// lblOutcomeVar
//
this.lblOutcomeVar.FlatStyle = System.Windows.Forms.FlatStyle.System;
resources.ApplyResources(this.lblOutcomeVar, "lblOutcomeVar");
this.lblOutcomeVar.Name = "lblOutcomeVar";
//
// lbxOther
//
resources.ApplyResources(this.lbxOther, "lbxOther");
this.lbxOther.Name = "lbxOther";
this.lbxOther.SelectionMode = System.Windows.Forms.SelectionMode.MultiSimple;
this.lbxOther.SelectedIndexChanged += new System.EventHandler(this.lbxOther_SelectedIndexChanged);
this.lbxOther.KeyDown += new System.Windows.Forms.KeyEventHandler(this.lbxOther_KeyDown);
//
// btnHelp
//
resources.ApplyResources(this.btnHelp, "btnHelp");
this.btnHelp.Name = "btnHelp";
this.btnHelp.Click += new System.EventHandler(this.btnHelp_Click);
//
// btnClear
//
resources.ApplyResources(this.btnClear, "btnClear");
this.btnClear.Name = "btnClear";
this.btnClear.Click += new System.EventHandler(this.btnClear_Click);
//
// btnOK
//
resources.ApplyResources(this.btnOK, "btnOK");
this.btnOK.Name = "btnOK";
//
// btnSaveOnly
//
resources.ApplyResources(this.btnSaveOnly, "btnSaveOnly");
this.btnSaveOnly.Name = "btnSaveOnly";
//
// cmbOther
//
resources.ApplyResources(this.cmbOther, "cmbOther");
this.cmbOther.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbOther.Name = "cmbOther";
this.cmbOther.SelectedIndexChanged += new System.EventHandler(this.cmbOther_SelectedIndexChanged);
//
// lblOther
//
resources.ApplyResources(this.lblOther, "lblOther");
this.lblOther.BackColor = System.Drawing.Color.Transparent;
this.lblOther.Name = "lblOther";
//
// cmbConfLimits
//
this.cmbConfLimits.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
resources.ApplyResources(this.cmbConfLimits, "cmbConfLimits");
this.cmbConfLimits.Name = "cmbConfLimits";
//
// lblConfLimits
//
this.lblConfLimits.FlatStyle = System.Windows.Forms.FlatStyle.System;
resources.ApplyResources(this.lblConfLimits, "lblConfLimits");
this.lblConfLimits.Name = "lblConfLimits";
//
// btnModifyTerm
//
resources.ApplyResources(this.btnModifyTerm, "btnModifyTerm");
this.btnModifyTerm.Name = "btnModifyTerm";
this.btnModifyTerm.Click += new System.EventHandler(this.btnModifyTerm_Click);
//
// lblDummyVar
//
resources.ApplyResources(this.lblDummyVar, "lblDummyVar");
this.lblDummyVar.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.lblDummyVar.Name = "lblDummyVar";
//
// lblInteractionTerms
//
resources.ApplyResources(this.lblInteractionTerms, "lblInteractionTerms");
this.lblInteractionTerms.Name = "lblInteractionTerms";
//
// lbxInteractionTerms
//
resources.ApplyResources(this.lbxInteractionTerms, "lbxInteractionTerms");
this.lbxInteractionTerms.Name = "lbxInteractionTerms";
this.lbxInteractionTerms.KeyDown += new System.Windows.Forms.KeyEventHandler(this.lbxInteractionTerms_KeyDown);
//
// checkboxNoIntercept
//
resources.ApplyResources(this.checkboxNoIntercept, "checkboxNoIntercept");
this.checkboxNoIntercept.Name = "checkboxNoIntercept";
this.checkboxNoIntercept.UseVisualStyleBackColor = true;
//
// btnCancel
//
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
resources.ApplyResources(this.btnCancel, "btnCancel");
this.btnCancel.Name = "btnCancel";
//
// LinearRegressionDialog
//
this.AcceptButton = this.btnOK;
resources.ApplyResources(this, "$this");
this.CancelButton = this.btnCancel;
this.Controls.Add(this.checkboxNoIntercept);
this.Controls.Add(this.lbxInteractionTerms);
this.Controls.Add(this.lblInteractionTerms);
this.Controls.Add(this.lblDummyVar);
this.Controls.Add(this.btnModifyTerm);
this.Controls.Add(this.cmbConfLimits);
this.Controls.Add(this.lblConfLimits);
this.Controls.Add(this.cmbOther);
this.Controls.Add(this.btnSaveOnly);
this.Controls.Add(this.btnHelp);
this.Controls.Add(this.btnClear);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.btnOK);
this.Controls.Add(this.lbxOther);
this.Controls.Add(this.cmbOutcome);
this.Controls.Add(this.lblOutcomeVar);
this.Controls.Add(this.lblOutput);
this.Controls.Add(this.txtOutput);
this.Controls.Add(this.cmbWeight);
this.Controls.Add(this.lblWeight);
this.Controls.Add(this.lblOther);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "LinearRegressionDialog";
this.Load += new System.EventHandler(this.LinearRegressionDialog_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ComboBox cmbWeight;
private System.Windows.Forms.Label lblWeight;
private System.Windows.Forms.Label lblOutput;
private System.Windows.Forms.TextBox txtOutput;
private System.Windows.Forms.ComboBox cmbOutcome;
private System.Windows.Forms.Label lblOutcomeVar;
private System.Windows.Forms.ListBox lbxOther;
private System.Windows.Forms.Button btnHelp;
private System.Windows.Forms.Button btnClear;
private System.Windows.Forms.Button btnOK;
private System.Windows.Forms.Button btnSaveOnly;
private System.Windows.Forms.ComboBox cmbOther;
private System.Windows.Forms.Label lblOther;
private System.Windows.Forms.ComboBox cmbConfLimits;
private System.Windows.Forms.Label lblConfLimits;
private System.Windows.Forms.Button btnModifyTerm;
private System.Windows.Forms.Label lblDummyVar;
private System.Windows.Forms.Label lblInteractionTerms;
private System.Windows.Forms.ListBox lbxInteractionTerms;
private System.Windows.Forms.CheckBox checkboxNoIntercept;
private System.Windows.Forms.Button btnCancel;
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
namespace ServiceStack.ServiceHost
{
/// <summary>
/// Decorate on Request DTO's to alter the accessibility of a service and its visibility on /metadata pages
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public class RestrictAttribute
: Attribute
{
/// <summary>
/// Allow access but hide from metadata to requests from Localhost only
/// </summary>
public bool VisibleInternalOnly
{
get { return CanShowTo(EndpointAttributes.InternalNetworkAccess); }
set
{
if (value == false)
throw new Exception("Only true allowed");
VisibilityTo = EndpointAttributes.InternalNetworkAccess.ToAllowedFlagsSet();
}
}
/// <summary>
/// Allow access but hide from metadata to requests from Localhost and Local Intranet only
/// </summary>
public bool VisibleLocalhostOnly
{
get { return CanShowTo(EndpointAttributes.Localhost); }
set
{
if (value == false)
throw new Exception("Only true allowed");
VisibilityTo = EndpointAttributes.Localhost.ToAllowedFlagsSet();
}
}
/// <summary>
/// Restrict access and hide from metadata to requests from Localhost and Local Intranet only
/// </summary>
public bool InternalOnly
{
get { return HasAccessTo(EndpointAttributes.InternalNetworkAccess) && CanShowTo(EndpointAttributes.InternalNetworkAccess); }
set
{
if (value == false)
throw new Exception("Only true allowed");
AccessTo = EndpointAttributes.InternalNetworkAccess.ToAllowedFlagsSet();
VisibilityTo = EndpointAttributes.InternalNetworkAccess.ToAllowedFlagsSet();
}
}
/// <summary>
/// Restrict access and hide from metadata to requests from Localhost only
/// </summary>
public bool LocalhostOnly
{
get { return HasAccessTo(EndpointAttributes.Localhost) && CanShowTo(EndpointAttributes.Localhost); }
set
{
if (value == false)
throw new Exception("Only true allowed");
AccessTo = EndpointAttributes.Localhost.ToAllowedFlagsSet();
VisibilityTo = EndpointAttributes.Localhost.ToAllowedFlagsSet();
}
}
/// <summary>
/// Sets a single access restriction
/// </summary>
/// <value>Restrict Access to.</value>
public EndpointAttributes AccessTo
{
get
{
return this.AccessibleToAny.Length == 0
? EndpointAttributes.Any
: this.AccessibleToAny[0];
}
set
{
this.AccessibleToAny = new[] { value };
}
}
/// <summary>
/// Restrict access to any of the specified access scenarios
/// </summary>
/// <value>Access restrictions</value>
public EndpointAttributes[] AccessibleToAny { get; private set; }
/// <summary>
/// Sets a single metadata Visibility restriction
/// </summary>
/// <value>Restrict metadata Visibility to.</value>
public EndpointAttributes VisibilityTo
{
get
{
return this.VisibleToAny.Length == 0
? EndpointAttributes.Any
: this.VisibleToAny[0];
}
set
{
this.VisibleToAny = new[] { value };
}
}
/// <summary>
/// Restrict metadata visibility to any of the specified access scenarios
/// </summary>
/// <value>Visibility restrictions</value>
public EndpointAttributes[] VisibleToAny { get; private set; }
public RestrictAttribute()
{
this.AccessTo = EndpointAttributes.Any;
this.VisibilityTo = EndpointAttributes.Any;
}
/// <summary>
/// Restrict access and metadata visibility to any of the specified access scenarios
/// </summary>
/// <value>The restrict access to scenarios.</value>
public RestrictAttribute(params EndpointAttributes[] restrictAccessAndVisibilityToScenarios)
{
this.AccessibleToAny = ToAllowedFlagsSet(restrictAccessAndVisibilityToScenarios);
this.VisibleToAny = ToAllowedFlagsSet(restrictAccessAndVisibilityToScenarios);
}
/// <summary>
/// Restrict access and metadata visibility to any of the specified access scenarios
/// </summary>
/// <value>The restrict access to scenarios.</value>
public RestrictAttribute(EndpointAttributes[] allowedAccessScenarios, EndpointAttributes[] visibleToScenarios)
: this()
{
this.AccessibleToAny = ToAllowedFlagsSet(allowedAccessScenarios);
this.VisibleToAny = ToAllowedFlagsSet(visibleToScenarios);
}
/// <summary>
/// Returns the allowed set of scenarios based on the user-specified restrictions
/// </summary>
/// <param name="restrictToAny"></param>
/// <returns></returns>
private static EndpointAttributes[] ToAllowedFlagsSet(EndpointAttributes[] restrictToAny)
{
if (restrictToAny.Length == 0)
return new[] { EndpointAttributes.Any };
var scenarios = new List<EndpointAttributes>();
foreach (var restrictToScenario in restrictToAny)
{
var restrictTo = restrictToScenario.ToAllowedFlagsSet();
scenarios.Add(restrictTo);
}
return scenarios.ToArray();
}
public bool CanShowTo(EndpointAttributes restrictions)
{
return this.VisibleToAny.Any(scenario => (restrictions & scenario) == restrictions);
}
public bool HasAccessTo(EndpointAttributes restrictions)
{
return this.AccessibleToAny.Any(scenario => (restrictions & scenario) == restrictions);
}
public bool HasNoAccessRestrictions
{
get
{
return this.AccessTo == EndpointAttributes.Any;
}
}
public bool HasNoVisibilityRestrictions
{
get
{
return this.VisibilityTo == EndpointAttributes.Any;
}
}
}
public static class RestrictExtensions
{
/// <summary>
/// Converts from a User intended restriction to a flag with all the allowed attribute flags set, e.g:
///
/// If No Network restrictions were specified all Network access types are allowed, e.g:
/// restrict EndpointAttributes.None => ... 111
///
/// If a Network restriction was specified, only it will be allowed, e.g:
/// restrict EndpointAttributes.LocalSubnet => ... 010
///
/// The returned Enum will have a flag with all the allowed attributes set
/// </summary>
/// <param name="restrictTo"></param>
/// <returns></returns>
public static EndpointAttributes ToAllowedFlagsSet(this EndpointAttributes restrictTo)
{
if (restrictTo == EndpointAttributes.Any)
return EndpointAttributes.Any;
var allowedAttrs = EndpointAttributes.None;
//Network access
if (!HasAnyRestrictionsOf(restrictTo, EndpointAttributes.AnyNetworkAccessType))
allowedAttrs |= EndpointAttributes.AnyNetworkAccessType;
else
allowedAttrs |= (restrictTo & EndpointAttributes.AnyNetworkAccessType);
//Security
if (!HasAnyRestrictionsOf(restrictTo, EndpointAttributes.AnySecurityMode))
allowedAttrs |= EndpointAttributes.AnySecurityMode;
else
allowedAttrs |= (restrictTo & EndpointAttributes.AnySecurityMode);
//Http Method
if (!HasAnyRestrictionsOf(restrictTo, EndpointAttributes.AnyHttpMethod))
allowedAttrs |= EndpointAttributes.AnyHttpMethod;
else
allowedAttrs |= (restrictTo & EndpointAttributes.AnyHttpMethod);
//Call Style
if (!HasAnyRestrictionsOf(restrictTo, EndpointAttributes.AnyCallStyle))
allowedAttrs |= EndpointAttributes.AnyCallStyle;
else
allowedAttrs |= (restrictTo & EndpointAttributes.AnyCallStyle);
//Format
if (!HasAnyRestrictionsOf(restrictTo, EndpointAttributes.AnyFormat))
allowedAttrs |= EndpointAttributes.AnyFormat;
else
allowedAttrs |= (restrictTo & EndpointAttributes.AnyFormat);
//Endpoint
if (!HasAnyRestrictionsOf(restrictTo, EndpointAttributes.AnyEndpoint))
allowedAttrs |= EndpointAttributes.AnyEndpoint;
else
allowedAttrs |= (restrictTo & EndpointAttributes.AnyEndpoint);
return allowedAttrs;
}
public static bool HasAnyRestrictionsOf(EndpointAttributes allRestrictions, EndpointAttributes restrictions)
{
return (allRestrictions & restrictions) != 0;
}
}
}
| |
namespace PeregrineDb.Tests.Dialects
{
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Data;
using System.Diagnostics.CodeAnalysis;
using FluentAssertions;
using Pagination;
using PeregrineDb;
using PeregrineDb.Dialects;
using PeregrineDb.Schema;
using PeregrineDb.Tests.ExampleEntities;
using PeregrineDb.Tests.Utils;
using Xunit;
[SuppressMessage("ReSharper", "ConvertToConstant.Local")]
public class PostgreSqlDialectTests
{
private PeregrineConfig config = PeregrineConfig.Postgres;
private IDialect Sut => this.config.Dialect;
private TableSchema GetTableSchema<T>()
{
return this.GetTableSchema(typeof(T));
}
private TableSchema GetTableSchema(Type type)
{
return this.config.SchemaFactory.GetTableSchema(type);
}
private ImmutableArray<ConditionColumnSchema> GetConditionsSchema<T>(object conditions)
{
var entityType = typeof(T);
var tableSchema = this.GetTableSchema(entityType);
return this.config.SchemaFactory.GetConditionsSchema(entityType, tableSchema, conditions.GetType());
}
public class MakeCountStatement
: PostgreSqlDialectTests
{
[Fact]
public void Selects_from_given_table()
{
// Act
var command = this.Sut.MakeCountCommand(null, null, this.GetTableSchema<Dog>());
// Assert
var expected = new SqlCommand(@"
SELECT COUNT(*)
FROM dog");
command.Should().Be(expected);
}
[Fact]
public void Adds_conditions()
{
// Act
var command = this.Sut.MakeCountCommand("WHERE Foo IS NOT NULL", null, this.GetTableSchema<Dog>());
// Assert
var expected = new SqlCommand(@"
SELECT COUNT(*)
FROM dog
WHERE Foo IS NOT NULL");
command.Should().Be(expected);
}
}
public class MakeFindStatement
: PostgreSqlDialectTests
{
[Fact]
public void Errors_when_id_is_null()
{
// Act
Action act = () => this.Sut.MakeFindCommand(null, this.GetTableSchema<Dog>());
// Assert
act.Should().Throw<ArgumentNullException>();
}
[Fact]
public void Selects_from_given_table()
{
// Act
var command = this.Sut.MakeFindCommand(5, this.GetTableSchema<Dog>());
// Assert
var expected = new SqlCommand(@"
SELECT id, name, age
FROM dog
WHERE id = @Id",
new Dictionary<string, object>
{
["Id"] = 5
});
command.Should().Be(expected);
}
[Fact]
public void Uses_non_default_primary_key_name()
{
// Act
var command = this.Sut.MakeFindCommand(5, this.GetTableSchema<KeyExplicit>());
// Assert
var expected = new SqlCommand(@"
SELECT key, name
FROM KeyExplicit
WHERE key = @Key",
new Dictionary<string, object>
{
["Key"] = 5
});
command.Should().Be(expected);
}
[Fact]
public void Uses_each_key_in_composite_key()
{
// Act
var command = this.Sut.MakeFindCommand(new { key1 = 2, key2 = 3 }, this.GetTableSchema<CompositeKeys>());
// Assert
var expected = new SqlCommand(@"
SELECT key1, key2, name
FROM CompositeKeys
WHERE key1 = @Key1 AND key2 = @Key2",
new { key1 = 2, key2 = 3 });
command.Should().Be(expected);
}
[Fact]
public void Adds_alias_when_primary_key_is_aliased()
{
// Act
var command = this.Sut.MakeFindCommand(5, this.GetTableSchema<KeyAlias>());
// Assert
var expected = new SqlCommand(@"
SELECT Key AS Id, name
FROM KeyAlias
WHERE Key = @Id",
new Dictionary<string, object>
{
["Id"] = 5
});
command.Should().Be(expected);
}
[Fact]
public void Adds_alias_when_column_name_is_aliased()
{
// Act
var command = this.Sut.MakeFindCommand(5, this.GetTableSchema<PropertyAlias>());
// Assert
var expected = new SqlCommand(@"
SELECT id, YearsOld AS Age
FROM PropertyAlias
WHERE id = @Id",
new Dictionary<string, object>
{
["Id"] = 5
});
command.Should().Be(expected);
}
}
public class MakeGetRangeStatement
: PostgreSqlDialectTests
{
[Fact]
public void Selects_from_given_table()
{
// Act
var command = this.Sut.MakeGetRangeCommand(null, null, this.GetTableSchema<Dog>());
// Assert
var expected = new SqlCommand(@"
SELECT id, name, age
FROM dog");
command.Should().Be(expected);
}
[Fact]
public void Adds_conditions_clause()
{
// Act
var command = this.Sut.MakeGetRangeCommand("WHERE Age > @Age", new { Age = 10 }, this.GetTableSchema<Dog>());
// Assert
var expected = new SqlCommand(@"
SELECT id, name, age
FROM dog
WHERE Age > @Age",
new { Age = 10 });
command.Should().Be(expected);
}
[Fact]
public void Uses_explicit_primary_key_name()
{
// Act
var command = this.Sut.MakeGetRangeCommand(null, null, this.GetTableSchema<KeyExplicit>());
// Assert
var expected = new SqlCommand(@"
SELECT key, name
FROM KeyExplicit");
command.Should().Be(expected);
}
[Fact]
public void Adds_alias_when_primary_key_is_aliased()
{
// Act
var command = this.Sut.MakeGetRangeCommand(null, null, this.GetTableSchema<KeyAlias>());
// Assert
var expected = new SqlCommand(@"
SELECT Key AS Id, name
FROM KeyAlias");
command.Should().Be(expected);
}
[Fact]
public void Adds_alias_when_column_name_is_aliased()
{
// Act
var command = this.Sut.MakeGetRangeCommand(null, null, this.GetTableSchema<PropertyAlias>());
// Assert
var expected = new SqlCommand(@"
SELECT id, YearsOld AS Age
FROM PropertyAlias");
command.Should().Be(expected);
}
}
public class MakeGetFirstNCommand
: PostgreSqlDialectTests
{
[Fact]
public void Adds_conditions_clause()
{
// Act
var command = this.Sut.MakeGetFirstNCommand(1, "WHERE Name LIKE @Name", new { Name = "Foo%" }, "Name", this.GetTableSchema<Dog>());
// Assert
var expected = new SqlCommand(@"
SELECT id, name, age
FROM dog
WHERE Name LIKE @Name
ORDER BY Name
LIMIT 1",
new { Name = "Foo%" });
command.Should().Be(expected);
}
[Fact]
public void Adds_alias_when_column_name_is_aliased()
{
// Act
var command = this.Sut.MakeGetFirstNCommand(1, "WHERE Name LIKE @Name", new { Name = "Foo%" }, "Name", this.GetTableSchema<PropertyAlias>());
// Assert
var expected = new SqlCommand(@"
SELECT id, YearsOld AS Age
FROM PropertyAlias
WHERE Name LIKE @Name
ORDER BY Name
LIMIT 1",
new { Name = "Foo%" });
command.Should().Be(expected);
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData(" ")]
public void Does_not_order_when_no_orderby_given(string orderBy)
{
// Act
var command = this.Sut.MakeGetFirstNCommand(1, "WHERE Name LIKE @Name", new { Name = "Foo%" }, orderBy, this.GetTableSchema<Dog>());
// Assert
var expected = new SqlCommand(@"
SELECT id, name, age
FROM dog
WHERE Name LIKE @Name
LIMIT 1",
new { Name = "Foo%" });
command.Should().Be(expected);
}
}
public class MakeGetPageStatement
: PostgreSqlDialectTests
{
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData(" ")]
public void Throws_exception_when_order_by_is_empty(string orderBy)
{
// Act / Assert
Assert.Throws<ArgumentException>(() => this.Sut.MakeGetPageCommand(new Page(1, 10, true, 0, 9), null, null, orderBy, this.GetTableSchema<Dog>()));
}
[Fact]
public void Selects_from_given_table()
{
// Act
var command = this.Sut.MakeGetPageCommand(new Page(1, 10, true, 0, 9), null, null, "Name", this.GetTableSchema<Dog>());
// Assert
var expected = new SqlCommand(@"
SELECT id, name, age
FROM dog
ORDER BY Name
LIMIT 10 OFFSET 0");
command.Should().Be(expected);
}
[Fact]
public void Adds_conditions_clause()
{
// Act
var command = this.Sut.MakeGetPageCommand(new Page(1, 10, true, 0, 9), "WHERE Name LIKE @Name", new { Name = "Foo%" }, "Name", this.GetTableSchema<Dog>());
// Assert
var expected = new SqlCommand(@"
SELECT id, name, age
FROM dog
WHERE Name LIKE @Name
ORDER BY Name
LIMIT 10 OFFSET 0",
new { Name = "Foo%" });
command.Should().Be(expected);
}
[Fact]
public void Adds_alias_when_column_name_is_aliased()
{
// Act
var command = this.Sut.MakeGetPageCommand(new Page(1, 10, true, 0, 9), null, null, "Name", this.GetTableSchema<PropertyAlias>());
// Assert
var expected = new SqlCommand(@"
SELECT id, YearsOld AS Age
FROM PropertyAlias
ORDER BY Name
LIMIT 10 OFFSET 0");
command.Should().Be(expected);
}
[Fact]
public void Selects_second_page()
{
// Act
var command = this.Sut.MakeGetPageCommand(new Page(2, 10, true, 10, 19), null, null, "Name", this.GetTableSchema<Dog>());
// Assert
var expected = new SqlCommand(@"
SELECT id, name, age
FROM dog
ORDER BY Name
LIMIT 10 OFFSET 10");
command.Should().Be(expected);
}
[Fact]
public void Selects_appropriate_number_of_rows()
{
// Act
var command = this.Sut.MakeGetPageCommand(new Page(2, 5, true, 5, 9), null, null, "Name", this.GetTableSchema<Dog>());
// Assert
var expected = new SqlCommand(@"
SELECT id, name, age
FROM dog
ORDER BY Name
LIMIT 5 OFFSET 5");
command.Should().Be(expected);
}
}
public class MakeInsertStatement
: PostgreSqlDialectTests
{
[Fact]
public void Inserts_into_given_table()
{
// Act
object entity = new Dog { Name = "Foo", Age = 10 };
var command = this.Sut.MakeInsertCommand(entity, this.GetTableSchema<Dog>());
// Assert
var expected = new SqlCommand(@"
INSERT INTO dog (name, age)
VALUES (@Name, @Age);",
new Dog { Name = "Foo", Age = 10 });
command.Should().Be(expected);
}
[Fact]
public void Adds_primary_key_if_its_not_generated_by_database()
{
// Act
object entity = new KeyNotGenerated { Id = 6, Name = "Foo" };
var command = this.Sut.MakeInsertCommand(entity, this.GetTableSchema<KeyNotGenerated>());
// Assert
var expected = new SqlCommand(@"
INSERT INTO KeyNotGenerated (id, name)
VALUES (@Id, @Name);",
new KeyNotGenerated { Id = 6, Name = "Foo" });
command.Should().Be(expected);
}
[Fact]
public void Does_not_include_computed_columns()
{
// Act
object entity = new PropertyComputed { Name = "Foo" };
var command = this.Sut.MakeInsertCommand(entity, this.GetTableSchema<PropertyComputed>());
// Assert
var expected = new SqlCommand(@"
INSERT INTO PropertyComputed (name)
VALUES (@Name);",
new PropertyComputed { Name = "Foo" });
command.Should().Be(expected);
}
[Fact]
public void Does_not_include_generated_columns()
{
// Act
object entity = new PropertyGenerated { Name = "Foo" };
var command = this.Sut.MakeInsertCommand(entity, this.GetTableSchema<PropertyGenerated>());
// Assert
var expected = new SqlCommand(@"
INSERT INTO PropertyGenerated (name)
VALUES (@Name);",
new PropertyGenerated { Name = "Foo" });
command.Should().Be(expected);
}
}
public class MakeInsertReturningIdentityStatement
: PostgreSqlDialectTests
{
[Fact]
public void Inserts_into_given_table()
{
// Act
var command = this.Sut.MakeInsertReturningPrimaryKeyCommand(new Dog { Name = "Foo", Age = 10 }, this.GetTableSchema<Dog>());
// Assert
var expected = new SqlCommand(@"
INSERT INTO dog (name, age)
VALUES (@Name, @Age)
RETURNING id",
new Dog { Name = "Foo", Age = 10 });
command.Should().Be(expected);
}
[Fact]
public void Adds_primary_key_if_its_not_generated_by_database()
{
// Act
var command = this.Sut.MakeInsertReturningPrimaryKeyCommand(new KeyNotGenerated { Id = 10, Name = "Foo" }, this.GetTableSchema<KeyNotGenerated>());
// Assert
var expected = new SqlCommand(@"
INSERT INTO KeyNotGenerated (id, name)
VALUES (@Id, @Name)
RETURNING id",
new KeyNotGenerated { Id = 10, Name = "Foo" });
command.Should().Be(expected);
}
[Fact]
public void Does_not_include_computed_columns()
{
// Act
var command = this.Sut.MakeInsertReturningPrimaryKeyCommand(new PropertyComputed { Name = "Foo" }, this.GetTableSchema<PropertyComputed>());
// Assert
var expected = new SqlCommand(@"
INSERT INTO PropertyComputed (name)
VALUES (@Name)
RETURNING id",
new PropertyComputed { Name = "Foo" });
command.Should().Be(expected);
}
[Fact]
public void Does_not_include_generated_columns()
{
// Act
var command = this.Sut.MakeInsertReturningPrimaryKeyCommand(new PropertyGenerated { Name = "Foo" }, this.GetTableSchema<PropertyGenerated>());
// Assert
var expected = new SqlCommand(@"
INSERT INTO PropertyGenerated (name)
VALUES (@Name)
RETURNING id",
new PropertyGenerated { Name = "Foo" });
command.Should().Be(expected);
}
}
public class MakeUpdateStatement
: PostgreSqlDialectTests
{
[Fact]
public void Updates_given_table()
{
// Act
var command = this.Sut.MakeUpdateCommand(new Dog { Id = 5, Name = "Foo", Age = 10 }, this.GetTableSchema<Dog>());
// Assert
var expected = new SqlCommand(@"
UPDATE dog
SET name = @Name, age = @Age
WHERE id = @Id",
new Dog { Id = 5, Name = "Foo", Age = 10 });
command.Should().Be(expected);
}
[Fact]
public void Uses_each_key_in_composite_key()
{
// Act
var command = this.Sut.MakeUpdateCommand(new CompositeKeys { Key1 = 7, Key2 = 8, Name = "Foo" }, this.GetTableSchema<CompositeKeys>());
// Assert
var expected = new SqlCommand(@"
UPDATE CompositeKeys
SET name = @Name
WHERE key1 = @Key1 AND key2 = @Key2",
new CompositeKeys { Key1 = 7, Key2 = 8, Name = "Foo" });
command.Should().Be(expected);
}
[Fact]
public void Does_not_update_primary_key_even_if_its_not_auto_generated()
{
// Act
var command = this.Sut.MakeUpdateCommand(new KeyNotGenerated { Id = 7, Name = "Foo" }, this.GetTableSchema<KeyNotGenerated>());
// Assert
var expected = new SqlCommand(@"
UPDATE KeyNotGenerated
SET name = @Name
WHERE id = @Id",
new KeyNotGenerated { Id = 7, Name = "Foo" });
command.Should().Be(expected);
}
[Fact]
public void Uses_aliased_property_names()
{
// Act
var command = this.Sut.MakeUpdateCommand(new PropertyAlias { Id = 5, Age = 10 }, this.GetTableSchema<PropertyAlias>());
// Assert
var expected = new SqlCommand(@"
UPDATE PropertyAlias
SET YearsOld = @Age
WHERE id = @Id",
new PropertyAlias { Id = 5, Age = 10 });
command.Should().Be(expected);
}
[Fact]
public void Uses_aliased_key_name()
{
// Act
var command = this.Sut.MakeUpdateCommand(new KeyAlias { Name = "Foo", Id = 10 }, this.GetTableSchema<KeyAlias>());
// Assert
var expected = new SqlCommand(@"
UPDATE KeyAlias
SET name = @Name
WHERE Key = @Id",
new KeyAlias { Name = "Foo", Id = 10 });
command.Should().Be(expected);
}
[Fact]
public void Uses_explicit_key_name()
{
// Act
var command = this.Sut.MakeUpdateCommand(new KeyExplicit { Name = "Foo", Key = 10 }, this.GetTableSchema<KeyExplicit>());
// Assert
var expected = new SqlCommand(@"
UPDATE KeyExplicit
SET name = @Name
WHERE key = @Key",
new KeyExplicit { Name = "Foo", Key = 10 });
command.Should().Be(expected);
}
[Fact]
public void Does_not_include_computed_columns()
{
// Act
var command = this.Sut.MakeUpdateCommand(new PropertyComputed { Name = "Foo", Id = 10 }, this.GetTableSchema<PropertyComputed>());
// Assert
var expected = new SqlCommand(@"
UPDATE PropertyComputed
SET name = @Name
WHERE id = @Id",
new PropertyComputed { Name = "Foo", Id = 10 });
command.Should().Be(expected);
}
[Fact]
public void Includes_generated_columns()
{
// Act
var command = this.Sut.MakeUpdateCommand(new PropertyGenerated { Id = 5, Name = "Foo", Created = new DateTime(2018, 4, 1) }, this.GetTableSchema<PropertyGenerated>());
// Assert
var expected = new SqlCommand(@"
UPDATE PropertyGenerated
SET name = @Name, created = @Created
WHERE id = @Id",
new PropertyGenerated { Id = 5, Name = "Foo", Created = new DateTime(2018, 4, 1) });
command.Should().Be(expected);
}
}
public class MakeDeleteByPrimaryKeyStatement
: PostgreSqlDialectTests
{
[Fact]
public void Deletes_from_given_table()
{
// Act
var command = this.Sut.MakeDeleteByPrimaryKeyCommand(5, this.GetTableSchema<Dog>());
// Assert
var expected = new SqlCommand(@"
DELETE FROM dog
WHERE id = @Id",
new Dictionary<string, object>
{
["Id"] = 5
});
command.Should().Be(expected);
}
[Fact]
public void Uses_each_key_in_composite_key()
{
// Act
var command = this.Sut.MakeDeleteByPrimaryKeyCommand(new { Key1 = 1, Key2 = 2 }, this.GetTableSchema<CompositeKeys>());
// Assert
var expected = new SqlCommand(@"
DELETE FROM CompositeKeys
WHERE key1 = @Key1 AND key2 = @Key2",
new { Key1 = 1, Key2 = 2 });
command.Should().Be(expected);
}
[Fact]
public void Uses_primary_key_even_if_its_not_auto_generated()
{
// Act
var command = this.Sut.MakeDeleteByPrimaryKeyCommand(5, this.GetTableSchema<KeyNotGenerated>());
// Assert
var expected = new SqlCommand(@"
DELETE FROM KeyNotGenerated
WHERE id = @Id",
new Dictionary<string, object>
{
["Id"] = 5
});
command.Should().Be(expected);
}
[Fact]
public void Uses_aliased_key_name()
{
// Act
var command = this.Sut.MakeDeleteByPrimaryKeyCommand(5, this.GetTableSchema<KeyAlias>());
// Assert
var expected = new SqlCommand(@"
DELETE FROM KeyAlias
WHERE Key = @Id",
new Dictionary<string, object>
{
["Id"] = 5
});
command.Should().Be(expected);
}
[Fact]
public void Uses_explicit_key_name()
{
// Act
var command = this.Sut.MakeDeleteByPrimaryKeyCommand(5, this.GetTableSchema<KeyExplicit>());
// Assert
var expected = new SqlCommand(@"
DELETE FROM KeyExplicit
WHERE key = @Key",
new Dictionary<string, object>
{
["Key"] = 5
});
command.Should().Be(expected);
}
}
public class MakeDeleteRangeStatement
: PostgreSqlDialectTests
{
[Fact]
public void Deletes_from_given_table()
{
// Act
var command = this.Sut.MakeDeleteRangeCommand("WHERE [Age] > @Age", new { Age = 10 }, this.GetTableSchema<Dog>());
// Assert
var expected = new SqlCommand(@"
DELETE FROM dog
WHERE [Age] > @Age",
new { Age = 10 });
command.Should().Be(expected);
}
}
public class MakeCreateTempTableStatement
: PostgreSqlDialectTests
{
public MakeCreateTempTableStatement()
{
this.config = this.config.AddSqlTypeMapping(typeof(DateTime), DbType.DateTime2);
}
[Fact]
public void Throws_exception_if_there_are_no_columns()
{
// Act
Assert.Throws<ArgumentException>(() => this.Sut.MakeCreateTempTableCommand(this.GetTableSchema<NoColumns>()));
}
[Fact]
public void Creates_table_with_all_possible_types()
{
// Act
var command = this.Sut.MakeCreateTempTableCommand(this.GetTableSchema<TempAllPossibleTypes>());
// Assert
var expected = new SqlCommand(@"CREATE TEMP TABLE TempAllPossibleTypes
(
id INT NOT NULL,
int16_property SMALLINT NOT NULL,
nullable_int16_property SMALLINT NULL,
int32_property INT NOT NULL,
nullable_int32_property INT NULL,
int64_property BIGINT NOT NULL,
nullable_int64_property BIGINT NULL,
single_property REAL NOT NULL,
nullable_single_property REAL NULL,
double_property DOUBLE PRECISION NOT NULL,
nullable_double_property DOUBLE PRECISION NULL,
decimal_property NUMERIC NOT NULL,
nullable_decimal_property NUMERIC NULL,
bool_property BOOL NOT NULL,
nullable_bool_property BOOL NULL,
string_property TEXT NOT NULL,
nullable_string_property TEXT NULL,
fixed_length_string_property TEXT NULL,
char_property TEXT NOT NULL,
nullable_char_property TEXT NULL,
guid_property UUID NOT NULL,
nullable_guid_property UUID NULL,
date_time_property TIMESTAMP NOT NULL,
nullable_date_time_property TIMESTAMP NULL,
date_time_offset_property TIMESTAMP WITH TIME ZONE NOT NULL,
nullable_date_time_offset_property TIMESTAMP WITH TIME ZONE NULL,
byte_array_property BYTEA NOT NULL,
color INT NOT NULL,
nullable_color INT NULL
)");
command.Should().Be(expected);
}
}
public class MakeDropTempTableStatement
: PostgreSqlDialectTests
{
[Fact]
public void Drops_temporary_tables()
{
// Act
var command = this.Sut.MakeDropTempTableCommand(this.GetTableSchema<Dog>());
// Assert
var expected = new SqlCommand(@"DROP TABLE dog");
command.Should().Be(expected);
}
}
public class MakeWhereClause
: PostgreSqlDialectTests
{
[Fact]
public void Returns_empty_string_when_conditions_is_empty()
{
// Arrange
var conditions = new { };
var conditionsSchema = this.GetConditionsSchema<Dog>(conditions);
// Act
var clause = this.Sut.MakeWhereClause(conditionsSchema, conditions);
// Assert
clause.Should().BeEmpty();
}
[Fact]
public void Selects_from_given_table()
{
// Arrange
var conditions = new { Name = "Fido" };
var conditionsSchema = this.GetConditionsSchema<Dog>(conditions);
// Act
var clause = this.Sut.MakeWhereClause(conditionsSchema, conditions);
// Assert
clause.Should().Be("WHERE name = @Name");
}
[Fact]
public void Adds_alias_when_column_name_is_aliased()
{
// Arrange
var conditions = new { Age = 15 };
var conditionsSchema = this.GetConditionsSchema<PropertyAlias>(conditions);
// Act
var clause = this.Sut.MakeWhereClause(conditionsSchema, conditions);
// Assert
clause.Should().Be("WHERE YearsOld = @Age");
}
[Fact]
public void Checks_multiple_properties()
{
// Arrange
var conditions = new { Name = "Fido", Age = 15 };
var conditionsSchema = this.GetConditionsSchema<Dog>(conditions);
// Act
var clause = this.Sut.MakeWhereClause(conditionsSchema, conditions);
// Assert
clause.Should().Be("WHERE name = @Name AND age = @Age");
}
[Fact]
public void Checks_for_null_properly()
{
// Arrange
var conditions = new { Name = (string)null };
var conditionsSchema = this.GetConditionsSchema<Dog>(conditions);
// Act
var clause = this.Sut.MakeWhereClause(conditionsSchema, conditions);
// Assert
clause.Should().Be("WHERE name IS NULL");
}
[Fact]
public void Checks_for_null_properly_with_multiple_properties()
{
// Arrange
var conditions = new { Name = (string)null, age = (int?)null };
var conditionsSchema = this.GetConditionsSchema<Dog>(conditions);
// Act
var clause = this.Sut.MakeWhereClause(conditionsSchema, conditions);
// Assert
clause.Should().Be("WHERE name IS NULL AND age IS NULL");
}
}
}
}
| |
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Rendering;
using Microsoft.Extensions.DependencyInjection;
using Rc.Models;
namespace Rc.Controllers
{
[Authorize]
public class AccountController : Controller
{
public AccountController(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager
)
{
UserManager = userManager;
SignInManager = signInManager;
}
public UserManager<ApplicationUser> UserManager { get; }
public SignInManager<ApplicationUser> SignInManager { get; }
//
// GET: /Account/Login
[AllowAnonymous]
public IActionResult Login(string returnUrl = null)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
{
if (!ModelState.IsValid)
{
return View(model);
}
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, change to lockoutOnFailure: true
var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
return RedirectToLocal(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
}
if (result.IsLockedOut)
{
return View("Lockout");
}
else
{
ModelState.AddModelError("", "Invalid login attempt.");
return View(model);
}
}
//
// GET: /Account/VerifyCode
[AllowAnonymous]
public async Task<ActionResult> VerifyCode(string provider, bool rememberMe, string returnUrl = null)
{
var user = await SignInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return View("Error");
}
// Remove before production
#if DEMO
if (user != null)
{
ViewBag.Code = await UserManager.GenerateTwoFactorTokenAsync(user, provider);
}
#endif
return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
//
// POST: /Account/VerifyCode
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> VerifyCode(VerifyCodeViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// The following code protects for brute force attacks against the two factor codes.
// If a user enters incorrect codes for a specified amount of time then the user account
// will be locked out for a specified amount of time.
// You can configure the account lockout settings in IdentityConfig
var result = await SignInManager.TwoFactorSignInAsync(model.Provider, model.Code, model.RememberMe, model.RememberBrowser);
if (result.Succeeded)
{
return RedirectToLocal(model.ReturnUrl);
}
if (result.IsLockedOut)
{
return View("Lockout");
}
else
{
ModelState.AddModelError("", "Invalid code.");
return View(model);
}
}
//
// GET: /Account/Register
[AllowAnonymous]
public IActionResult Register()
{
return View();
}
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
//Bug: Remember browser option missing?
//Uncomment this and comment the later part if account verification is not needed.
//await SignInManager.SignInAsync(user, isPersistent: false);
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
// Send an email with this link
string code = await UserManager.GenerateEmailConfirmationTokenAsync(user);
var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
await MessageServices.SendEmailAsync(model.Email, "Confirm your account",
"Please confirm your account by clicking this link: <a href=\"" + callbackUrl + "\">link</a>");
#if !DEMO
return RedirectToAction("Index", "Home");
#else
//To display the email link in a friendly page instead of sending email
ViewBag.Link = callbackUrl;
return View("DemoLinkDisplay");
#endif
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// GET: /Account/ConfirmEmail
[AllowAnonymous]
public async Task<ActionResult> ConfirmEmail(string userId, string code)
{
if (userId == null || code == null)
{
return View("Error");
}
var user = await UserManager.FindByIdAsync(userId);
if (user == null)
{
return View("Error");
}
var result = await UserManager.ConfirmEmailAsync(user, code);
return View(result.Succeeded ? "ConfirmEmail" : "Error");
}
//
// GET: /Account/ForgotPassword
[AllowAnonymous]
public ActionResult ForgotPassword()
{
return View();
}
//
// POST: /Account/ForgotPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
{
if (ModelState.IsValid)
{
var user = await UserManager.FindByNameAsync(model.Email);
if (user == null || !(await UserManager.IsEmailConfirmedAsync(user)))
{
// Don't reveal that the user does not exist or is not confirmed
return View("ForgotPasswordConfirmation");
}
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
// Send an email with this link
string code = await UserManager.GeneratePasswordResetTokenAsync(user);
var callbackUrl = Url.Action("ResetPassword", "Account", new { code = code }, protocol: HttpContext.Request.Scheme);
await MessageServices.SendEmailAsync(model.Email, "Reset Password",
"Please reset your password by clicking here: <a href=\"" + callbackUrl + "\">link</a>");
#if !DEMO
return RedirectToAction("ForgotPasswordConfirmation");
#else
//To display the email link in a friendly page instead of sending email
ViewBag.Link = callbackUrl;
return View("DemoLinkDisplay");
#endif
}
ModelState.AddModelError("", string.Format("We could not locate an account with email : {0}", model.Email));
// If we got this far, something failed, redisplay form
return View(model);
}
//
// GET: /Account/ForgotPasswordConfirmation
[AllowAnonymous]
public ActionResult ForgotPasswordConfirmation()
{
return View();
}
//
// GET: /Account/ResetPassword
[AllowAnonymous]
public ActionResult ResetPassword(string code)
{
//TODO: Fix this?
var resetPasswordViewModel = new ResetPasswordViewModel() { Code = code };
return code == null ? View("Error") : View(resetPasswordViewModel);
}
//
// POST: /Account/ResetPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ResetPassword(ResetPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await UserManager.FindByNameAsync(model.Email);
if (user == null)
{
// Don't reveal that the user does not exist
return RedirectToAction("ResetPasswordConfirmation", "Account");
}
var result = await UserManager.ResetPasswordAsync(user, model.Code, model.Password);
if (result.Succeeded)
{
return RedirectToAction("ResetPasswordConfirmation", "Account");
}
AddErrors(result);
return View();
}
//
// GET: /Account/ResetPasswordConfirmation
[AllowAnonymous]
public ActionResult ResetPasswordConfirmation()
{
return View();
}
//
// POST: /Account/ExternalLogin
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult ExternalLogin(string provider, string returnUrl = null)
{
// Request a redirect to the external login provider
var redirectUrl = Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl });
var properties = SignInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
return new ChallengeResult(provider, properties);
}
//
// GET: /Account/SendCode
[AllowAnonymous]
public async Task<ActionResult> SendCode(bool rememberMe, string returnUrl = null)
{
//TODO : Default rememberMe as well?
var user = await SignInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return View("Error");
}
var userFactors = await UserManager.GetValidTwoFactorProvidersAsync(user);
var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList();
return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
//
// POST: /Account/SendCode
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> SendCode(SendCodeViewModel model)
{
if (!ModelState.IsValid)
{
return View();
}
var user = await SignInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return View("Error");
}
// Generate the token and send it
var code = await UserManager.GenerateTwoFactorTokenAsync(user, model.SelectedProvider);
if (string.IsNullOrWhiteSpace(code))
{
return View("Error");
}
var message = "Your security code is: " + code;
if (model.SelectedProvider == "Email")
{
await MessageServices.SendEmailAsync(await UserManager.GetEmailAsync(user), "Security Code", message);
}
else if (model.SelectedProvider == "Phone")
{
await MessageServices.SendSmsAsync(await UserManager.GetPhoneNumberAsync(user), message);
}
return RedirectToAction("VerifyCode", new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe });
}
//
// GET: /Account/ExternalLoginCallback
[AllowAnonymous]
public async Task<ActionResult> ExternalLoginCallback(string returnUrl = null)
{
var loginInfo = await SignInManager.GetExternalLoginInfoAsync();
if (loginInfo == null)
{
return RedirectToAction("Login");
}
// Sign in the user with this external login provider if the user already has a login
var result = await SignInManager.ExternalLoginSignInAsync(loginInfo.LoginProvider, loginInfo.ProviderKey, isPersistent: false);
if (result.Succeeded)
{
return RedirectToLocal(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false });
}
if (result.IsLockedOut)
{
return View("Lockout");
}
else
{
// If the user does not have an account, then prompt the user to create an account
ViewBag.ReturnUrl = returnUrl;
ViewBag.LoginProvider = loginInfo.LoginProvider;
// REVIEW: handle case where email not in claims?
var email = loginInfo.ExternalPrincipal.FindFirstValue(ClaimTypes.Email);
return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = email });
}
}
//
// POST: /Account/ExternalLoginConfirmation
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl = null)
{
if (User.IsSignedIn())
{
return RedirectToAction("Index", "Manage");
}
if (ModelState.IsValid)
{
// Get the information about the user from the external login provider
var info = await SignInManager.GetExternalLoginInfoAsync();
if (info == null)
{
return View("ExternalLoginFailure");
}
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user);
#if TESTING
//Just for automated testing adding a claim named 'ManageStore' - Not required for production
var manageClaim = info.ExternalPrincipal.Claims.Where(c => c.Type == "ManageStore").FirstOrDefault();
if (manageClaim != null)
{
await UserManager.AddClaimAsync(user, manageClaim);
}
#endif
if (result.Succeeded)
{
result = await UserManager.AddLoginAsync(user, info);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent: false);
return RedirectToLocal(returnUrl);
}
}
AddErrors(result);
}
ViewBag.ReturnUrl = returnUrl;
return View(model);
}
//
// POST: /Account/LogOff
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> LogOff()
{
// clear all items from the cart
HttpContext.Session.Clear();
await SignInManager.SignOutAsync();
// TODO: Currently SignInManager.SignOut does not sign out OpenIdc and does not have a way to pass in a specific
// AuthType to sign out.
var appEnv = HttpContext.RequestServices.GetService<IHostingEnvironment>();
if (appEnv.EnvironmentName.StartsWith("OpenIdConnect"))
{
await HttpContext.Authentication.SignOutAsync("OpenIdConnect");
}
return RedirectToAction("Index", "Home");
}
//
// GET: /Account/ExternalLoginFailure
[AllowAnonymous]
public ActionResult ExternalLoginFailure()
{
return View();
}
#region Helpers
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError("", error.Description);
}
}
private async Task<ApplicationUser> GetCurrentUserAsync()
{
return await UserManager.FindByIdAsync(HttpContext.User.GetUserId());
}
private ActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
#endregion
}
}
| |
// 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.Text;
using Gallio.Common;
using Gallio.Framework;
using Gallio.Framework.Assertions;
namespace MbUnit.Framework
{
public abstract partial class Assert
{
#region AreEqual
/// <summary>
/// Verifies that an actual value equals some expected value.
/// </summary>
/// <typeparam name="T">The type of value.</typeparam>
/// <param name="expectedValue">The expected value.</param>
/// <param name="actualValue">The actual value.</param>
/// <exception cref="AssertionException">Thrown if the verification failed unless the current <see cref="AssertionContext.AssertionFailureBehavior" /> indicates otherwise.</exception>
///
public static void AreEqual<T>(T expectedValue, T actualValue)
{
AreEqual<T>(expectedValue, actualValue, (string)null, null);
}
/// <summary>
/// Verifies that an actual value equals some expected value.
/// </summary>
/// <typeparam name="T">The type of value.</typeparam>
/// <param name="expectedValue">The expected value.</param>
/// <param name="actualValue">The actual value.</param>
/// <param name="messageFormat">The custom assertion message format, or null if none.</param>
/// <param name="messageArgs">The custom assertion message arguments, or null if none.</param>
/// <exception cref="AssertionException">Thrown if the verification failed unless the current <see cref="AssertionContext.AssertionFailureBehavior" /> indicates otherwise.</exception>
public static void AreEqual<T>(T expectedValue, T actualValue, string messageFormat, params object[] messageArgs)
{
AreEqual<T>(expectedValue, actualValue, (EqualityComparison<T>)null, messageFormat, messageArgs);
}
/// <summary>
/// Verifies that an actual value equals some expected value according to a particular comparer.
/// </summary>
/// <typeparam name="T">The type of value.</typeparam>
/// <param name="expectedValue">The expected value.</param>
/// <param name="actualValue">The actual value.</param>
/// <param name="comparer">The comparer to use, or null to use the default one.</param>
/// <exception cref="AssertionException">Thrown if the verification failed unless the current <see cref="AssertionContext.AssertionFailureBehavior" /> indicates otherwise.</exception>
public static void AreEqual<T>(T expectedValue, T actualValue, IEqualityComparer<T> comparer)
{
AreEqual<T>(expectedValue, actualValue, comparer, null, null);
}
/// <summary>
/// Verifies that an actual value equals some expected value according to a particular comparer.
/// </summary>
/// <typeparam name="T">The type of value.</typeparam>
/// <param name="expectedValue">The expected value.</param>
/// <param name="actualValue">The actual value.</param>
/// <param name="comparer">The comparer to use, or null to use the default one.</param>
/// <param name="messageFormat">The custom assertion message format, or null if none.</param>
/// <param name="messageArgs">The custom assertion message arguments, or null if none.</param>
/// <exception cref="AssertionException">Thrown if the verification failed unless the current <see cref="AssertionContext.AssertionFailureBehavior" /> indicates otherwise.</exception>
public static void AreEqual<T>(T expectedValue, T actualValue, IEqualityComparer<T> comparer, string messageFormat, params object[] messageArgs)
{
AreEqual<T>(expectedValue, actualValue, comparer != null ? comparer.Equals : (EqualityComparison<T>)null, messageFormat, messageArgs);
}
/// <summary>
/// Verifies that an actual value equals some expected value according to a particular comparer.
/// </summary>
/// <typeparam name="T">The type of value.</typeparam>
/// <param name="expectedValue">The expected value.</param>
/// <param name="actualValue">The actual value.</param>
/// <param name="comparer">The comparer to use, or null to use the default one.</param>
/// <exception cref="AssertionException">Thrown if the verification failed unless the current <see cref="AssertionContext.AssertionFailureBehavior" /> indicates otherwise.</exception>
public static void AreEqual<T>(T expectedValue, T actualValue, EqualityComparison<T> comparer)
{
AreEqual<T>(expectedValue, actualValue, comparer, null, null);
}
/// <summary>
/// Verifies that an actual value equals some expected value according to a particular comparer.
/// </summary>
/// <typeparam name="T">The type of value.</typeparam>
/// <param name="expectedValue">The expected value.</param>
/// <param name="actualValue">The actual value.</param>
/// <param name="comparer">The comparer to use, or null to use the default one.</param>
/// <param name="messageFormat">The custom assertion message format, or null if none.</param>
/// <param name="messageArgs">The custom assertion message arguments, or null if none.</param>
/// <exception cref="AssertionException">Thrown if the verification failed unless the current <see cref="AssertionContext.AssertionFailureBehavior" /> indicates otherwise.</exception>
public static void AreEqual<T>(T expectedValue, T actualValue, EqualityComparison<T> comparer, string messageFormat, params object[] messageArgs)
{
AssertionHelper.Verify(delegate
{
if (comparer == null)
comparer = ComparisonSemantics.Default.Equals;
if (comparer(expectedValue, actualValue))
return null;
return new AssertionFailureBuilder("Expected values to be equal.")
.SetMessage(messageFormat, messageArgs)
.AddRawExpectedAndActualValuesWithDiffs(expectedValue, actualValue)
.ToAssertionFailure();
});
}
#endregion
#region AreNotEqual
/// <summary>
/// Verifies that an actual value does not equal some unexpected value.
/// </summary>
/// <typeparam name="T">The type of value.</typeparam>
/// <param name="unexpectedValue">The unexpected value.</param>
/// <param name="actualValue">The actual value.</param>
/// <exception cref="AssertionException">Thrown if the verification failed unless the current <see cref="AssertionContext.AssertionFailureBehavior" /> indicates otherwise.</exception>
public static void AreNotEqual<T>(T unexpectedValue, T actualValue)
{
AreNotEqual<T>(unexpectedValue, actualValue, (string)null, null);
}
/// <summary>
/// Verifies that an actual value does not equal some unexpected value.
/// </summary>
/// <typeparam name="T">The type of value.</typeparam>
/// <param name="unexpectedValue">The unexpected value.</param>
/// <param name="actualValue">The actual value.</param>
/// <param name="messageFormat">The custom assertion message format, or null if none.</param>
/// <param name="messageArgs">The custom assertion message arguments, or null if none.</param>
/// <exception cref="AssertionException">Thrown if the verification failed unless the current <see cref="AssertionContext.AssertionFailureBehavior" /> indicates otherwise.</exception>
public static void AreNotEqual<T>(T unexpectedValue, T actualValue, string messageFormat, params object[] messageArgs)
{
AreNotEqual<T>(unexpectedValue, actualValue, (EqualityComparison<T>)null, messageFormat, messageArgs);
}
/// <summary>
/// Verifies that an actual value does not equal some unexpected value according to a particular comparer.
/// </summary>
/// <typeparam name="T">The type of value.</typeparam>
/// <param name="unexpectedValue">The unexpected value.</param>
/// <param name="actualValue">The actual value.</param>
/// <param name="comparer">The comparer to use, or null to use the default one.</param>
/// <exception cref="AssertionException">Thrown if the verification failed unless the current <see cref="AssertionContext.AssertionFailureBehavior" /> indicates otherwise.</exception>
public static void AreNotEqual<T>(T unexpectedValue, T actualValue, IEqualityComparer<T> comparer)
{
AreNotEqual<T>(unexpectedValue, actualValue, comparer, null, null);
}
/// <summary>
/// Verifies that an actual value does not equal some unexpected value according to a particular comparer.
/// </summary>
/// <typeparam name="T">The type of value.</typeparam>
/// <param name="unexpectedValue">The unexpected value.</param>
/// <param name="actualValue">The actual value.</param>
/// <param name="comparer">The comparer to use, or null to use the default one.</param>
/// <param name="messageFormat">The custom assertion message format, or null if none.</param>
/// <param name="messageArgs">The custom assertion message arguments, or null if none.</param>
/// <exception cref="AssertionException">Thrown if the verification failed unless the current <see cref="AssertionContext.AssertionFailureBehavior" /> indicates otherwise.</exception>
public static void AreNotEqual<T>(T unexpectedValue, T actualValue, IEqualityComparer<T> comparer, string messageFormat, params object[] messageArgs)
{
AreNotEqual<T>(unexpectedValue, actualValue, comparer != null ? comparer.Equals : (EqualityComparison<T>)null, messageFormat, messageArgs);
}
/// <summary>
/// Verifies that an actual value does not equal some unexpected value according to a particular comparer.
/// </summary>
/// <typeparam name="T">The type of value.</typeparam>
/// <param name="unexpectedValue">The unexpected value.</param>
/// <param name="actualValue">The actual value.</param>
/// <param name="comparer">The comparer to use, or null to use the default one.</param>
/// <exception cref="AssertionException">Thrown if the verification failed unless the current <see cref="AssertionContext.AssertionFailureBehavior" /> indicates otherwise.</exception>
public static void AreNotEqual<T>(T unexpectedValue, T actualValue, EqualityComparison<T> comparer)
{
AreNotEqual<T>(unexpectedValue, actualValue, comparer, null, null);
}
/// <summary>
/// Verifies that an actual value does not equal some unexpected value according to a particular comparer.
/// </summary>
/// <typeparam name="T">The type of value.</typeparam>
/// <param name="unexpectedValue">The unexpected value.</param>
/// <param name="actualValue">The actual value.</param>
/// <param name="comparer">The comparer to use, or null to use the default one.</param>
/// <param name="messageFormat">The custom assertion message format, or null if none.</param>
/// <param name="messageArgs">The custom assertion message arguments, or null if none.</param>
/// <exception cref="AssertionException">Thrown if the verification failed unless the current <see cref="AssertionContext.AssertionFailureBehavior" /> indicates otherwise.</exception>
public static void AreNotEqual<T>(T unexpectedValue, T actualValue, EqualityComparison<T> comparer, string messageFormat, params object[] messageArgs)
{
AssertionHelper.Verify(delegate
{
if (comparer == null)
comparer = ComparisonSemantics.Default.Equals;
if (!comparer(unexpectedValue, actualValue))
return null;
return new AssertionFailureBuilder("Expected values to be non-equal.")
.SetMessage(messageFormat, messageArgs)
.AddRawLabeledValuesWithDiffs("Unexpected Value", unexpectedValue, "Actual Value", actualValue)
.ToAssertionFailure();
});
}
#endregion
#region AreSame
/// <summary>
/// Verifies that an actual value is referentially identical to some expected value.
/// </summary>
/// <typeparam name="T">The type of value.</typeparam>
/// <param name="expectedValue">The expected value.</param>
/// <param name="actualValue">The actual value.</param>
/// <exception cref="AssertionException">Thrown if the verification failed unless the current <see cref="AssertionContext.AssertionFailureBehavior" /> indicates otherwise.</exception>
public static void AreSame<T>(T expectedValue, T actualValue)
where T : class
{
AreSame<T>(expectedValue, actualValue, (string)null, null);
}
/// <summary>
/// Verifies that an actual value is referentially identical to some expected value.
/// </summary>
/// <typeparam name="T">The type of value.</typeparam>
/// <param name="expectedValue">The expected value.</param>
/// <param name="actualValue">The actual value.</param>
/// <param name="messageFormat">The custom assertion message format, or null if none.</param>
/// <param name="messageArgs">The custom assertion message arguments, or null if none.</param>
/// <exception cref="AssertionException">Thrown if the verification failed unless the current <see cref="AssertionContext.AssertionFailureBehavior" /> indicates otherwise.</exception>
public static void AreSame<T>(T expectedValue, T actualValue, string messageFormat, params object[] messageArgs)
where T : class
{
AssertionHelper.Verify(delegate
{
if (ComparisonSemantics.Default.Same(expectedValue, actualValue))
return null;
return new AssertionFailureBuilder("Expected values to be referentially identical.")
.SetMessage(messageFormat, messageArgs)
.AddRawExpectedAndActualValuesWithDiffs(expectedValue, actualValue)
.ToAssertionFailure();
});
}
#endregion
#region AreNotSame
/// <summary>
/// Verifies that an actual value is not referentially identical to some unexpected value.
/// </summary>
/// <typeparam name="T">The type of value.</typeparam>
/// <param name="unexpectedValue">The unexpected value.</param>
/// <param name="actualValue">The actual value.</param>
/// <exception cref="AssertionException">Thrown if the verification failed unless the current <see cref="AssertionContext.AssertionFailureBehavior" /> indicates otherwise.</exception>
public static void AreNotSame<T>(T unexpectedValue, T actualValue)
where T : class
{
AreNotSame<T>(unexpectedValue, actualValue, (string)null, null);
}
/// <summary>
/// Verifies that an actual value is not referentially identical to some unexpected value.
/// </summary>
/// <typeparam name="T">The type of value.</typeparam>
/// <param name="unexpectedValue">The unexpected value.</param>
/// <param name="actualValue">The actual value.</param>
/// <param name="messageFormat">The custom assertion message format, or null if none.</param>
/// <param name="messageArgs">The custom assertion message arguments, or null if none.</param>
/// <exception cref="AssertionException">Thrown if the verification failed unless the current <see cref="AssertionContext.AssertionFailureBehavior" /> indicates otherwise.</exception>
public static void AreNotSame<T>(T unexpectedValue, T actualValue, string messageFormat, params object[] messageArgs)
where T : class
{
AssertionHelper.Verify(delegate
{
if (!ComparisonSemantics.Default.Same(unexpectedValue, actualValue))
return null;
return new AssertionFailureBuilder("Expected values to be referentially different.")
.SetMessage(messageFormat, messageArgs)
.AddRawLabeledValuesWithDiffs("Unexpected Value", unexpectedValue, "Actual Value", actualValue)
.ToAssertionFailure();
});
}
#endregion
#region IsTrue
/// <summary>
/// Verifies that an actual value is true.
/// </summary>
/// <param name="actualValue">The actual value.</param>
/// <exception cref="AssertionException">Thrown if the verification failed unless the current <see cref="AssertionContext.AssertionFailureBehavior" /> indicates otherwise.</exception>
public static void IsTrue(bool actualValue)
{
IsTrue(actualValue, null, null);
}
/// <summary>
/// Verifies that an actual value is true.
/// </summary>
/// <param name="actualValue">The actual value.</param>
/// <param name="messageFormat">The custom assertion message format, or null if none.</param>
/// <param name="messageArgs">The custom assertion message arguments, or null if none.</param>
/// <exception cref="AssertionException">Thrown if the verification failed unless the current <see cref="AssertionContext.AssertionFailureBehavior" /> indicates otherwise.</exception>
public static void IsTrue(bool actualValue, string messageFormat, params object[] messageArgs)
{
AssertionHelper.Verify(delegate
{
if (actualValue)
return null;
return new AssertionFailureBuilder("Expected value to be true.")
.SetMessage(messageFormat, messageArgs)
.AddRawActualValue(actualValue)
.ToAssertionFailure();
});
}
#endregion
#region IsFalse
/// <summary>
/// Verifies that an actual value is false.
/// </summary>
/// <param name="actualValue">The actual value.</param>
/// <exception cref="AssertionException">Thrown if the verification failed unless the current <see cref="AssertionContext.AssertionFailureBehavior" /> indicates otherwise.</exception>
public static void IsFalse(bool actualValue)
{
IsFalse(actualValue, null, null);
}
/// <summary>
/// Verifies that an actual value is false.
/// </summary>
/// <param name="actualValue">The actual value.</param>
/// <param name="messageFormat">The custom assertion message format, or null if none.</param>
/// <param name="messageArgs">The custom assertion message arguments, or null if none.</param>
/// <exception cref="AssertionException">Thrown if the verification failed unless the current <see cref="AssertionContext.AssertionFailureBehavior" /> indicates otherwise.</exception>
public static void IsFalse(bool actualValue, string messageFormat, params object[] messageArgs)
{
AssertionHelper.Verify(delegate
{
if (!actualValue)
return null;
return new AssertionFailureBuilder("Expected value to be false.")
.SetMessage(messageFormat, messageArgs)
.AddRawActualValue(actualValue)
.ToAssertionFailure();
});
}
#endregion
#region IsNull
/// <summary>
/// Verifies that an actual value is null.
/// </summary>
/// <param name="actualValue">The actual value.</param>
/// <exception cref="AssertionException">Thrown if the verification failed unless the current <see cref="AssertionContext.AssertionFailureBehavior" /> indicates otherwise.</exception>
public static void IsNull(object actualValue)
{
IsNull(actualValue, null, null);
}
/// <summary>
/// Verifies that an actual value is null.
/// </summary>
/// <param name="actualValue">The actual value.</param>
/// <param name="messageFormat">The custom assertion message format, or null if none.</param>
/// <param name="messageArgs">The custom assertion message arguments, or null if none.</param>
/// <exception cref="AssertionException">Thrown if the verification failed unless the current <see cref="AssertionContext.AssertionFailureBehavior" /> indicates otherwise.</exception>
public static void IsNull(object actualValue, string messageFormat, params object[] messageArgs)
{
AssertionHelper.Verify(delegate
{
if (actualValue == null)
return null;
return new AssertionFailureBuilder("Expected value to be null.")
.SetMessage(messageFormat, messageArgs)
.AddRawActualValue(actualValue)
.ToAssertionFailure();
});
}
#endregion
#region IsNotNull
/// <summary>
/// Verifies that an actual value is not null.
/// </summary>
/// <param name="actualValue">The actual value.</param>
/// <exception cref="AssertionException">Thrown if the verification failed unless the current <see cref="AssertionContext.AssertionFailureBehavior" /> indicates otherwise.</exception>
public static void IsNotNull(object actualValue)
{
IsNotNull(actualValue, null, null);
}
/// <summary>
/// Verifies that an actual value is not null.
/// </summary>
/// <param name="actualValue">The actual value.</param>
/// <param name="messageFormat">The custom assertion message format, or null if none.</param>
/// <param name="messageArgs">The custom assertion message arguments, or null if none.</param>
/// <exception cref="AssertionException">Thrown if the verification failed unless the current <see cref="AssertionContext.AssertionFailureBehavior" /> indicates otherwise.</exception>
public static void IsNotNull(object actualValue, string messageFormat, params object[] messageArgs)
{
AssertionHelper.Verify(delegate
{
if (actualValue != null)
return null;
return new AssertionFailureBuilder("Expected value to be non-null.")
.SetMessage(messageFormat, messageArgs)
.AddRawActualValue(actualValue)
.ToAssertionFailure();
});
}
#endregion
#region AreApproximatelyEqual
/// <summary>
/// Verifies that an actual value approximately equals some expected value
/// to within a specified delta.
/// </summary>
/// <remarks>
/// <para>
/// The values are considered approximately equal if the absolute value of their difference
/// is less than or equal to the delta.
/// </para>
/// <para>
/// This method works with any comparable type that also supports a subtraction operator
/// including <see cref="Single" />, <see cref="Double" />, <see cref="Decimal" />,
/// <see cref="Int32" />, <see cref="DateTime" /> (using a <see cref="TimeSpan" /> delta),
/// and many others.
/// </para>
/// </remarks>
/// <typeparam name="TValue">The type of values to be compared.</typeparam>
/// <typeparam name="TDifference">The type of the difference produced when the values are
/// subtracted, for numeric types this is the same as <typeparamref name="TValue"/> but it
/// may differ for other types.</typeparam>
/// <param name="expectedValue">The expected value.</param>
/// <param name="actualValue">The actual value.</param>
/// <param name="delta">The inclusive delta between the values.</param>
/// <exception cref="AssertionException">Thrown if the verification failed unless the current <see cref="AssertionContext.AssertionFailureBehavior" /> indicates otherwise.</exception>
public static void AreApproximatelyEqual<TValue, TDifference>(TValue expectedValue, TValue actualValue, TDifference delta)
{
AreApproximatelyEqual(expectedValue, actualValue, delta, null, null);
}
/// <summary>
/// Verifies that an actual value approximately equals some expected value
/// to within a specified delta.
/// </summary>
/// <remarks>
/// <para>
/// The values are considered approximately equal if the absolute value of their difference
/// is less than or equal to the delta.
/// </para>
/// <para>
/// This method works with any comparable type that also supports a subtraction operator
/// including <see cref="Single" />, <see cref="Double" />, <see cref="Decimal" />,
/// <see cref="Int32" />, <see cref="DateTime" /> (using a <see cref="TimeSpan" /> delta),
/// and many others.
/// </para>
/// </remarks>
/// <typeparam name="TValue">The type of values to be compared.</typeparam>
/// <typeparam name="TDifference">The type of the difference produced when the values are
/// subtracted, for numeric types this is the same as <typeparamref name="TValue"/> but it
/// may differ for other types.</typeparam>
/// <param name="expectedValue">The expected value.</param>
/// <param name="actualValue">The actual value.</param>
/// <param name="delta">The inclusive delta between the values.</param>
/// <param name="messageFormat">The custom assertion message format, or null if none.</param>
/// <param name="messageArgs">The custom assertion message arguments, or null if none.</param>
/// <exception cref="AssertionException">Thrown if the verification failed unless the current <see cref="AssertionContext.AssertionFailureBehavior" /> indicates otherwise.</exception>
public static void AreApproximatelyEqual<TValue, TDifference>(TValue expectedValue, TValue actualValue, TDifference delta,
string messageFormat, params object[] messageArgs)
{
AssertionHelper.Verify(delegate
{
if (ComparisonSemantics.Default.ApproximatelyEqual(expectedValue, actualValue, delta))
return null;
return new AssertionFailureBuilder("Expected values to be approximately equal to within a delta.")
.SetMessage(messageFormat, messageArgs)
.AddRawExpectedValue(expectedValue)
.AddRawActualValue(actualValue)
.AddRawLabeledValue("Delta", delta)
.ToAssertionFailure();
});
}
#endregion
#region AreNotApproximatelyEqual
/// <summary>
/// Verifies that an actual value does not approximately equal some unexpected value
/// to within a specified delta.
/// </summary>
/// <remarks>
/// <para>
/// The values are considered approximately equal if the absolute value of their difference
/// is less than or equal to the delta.
/// </para>
/// <para>
/// This method works with any comparable type that also supports a subtraction operator
/// including <see cref="Single" />, <see cref="Double" />, <see cref="Decimal" />,
/// <see cref="Int32" />, <see cref="DateTime" /> (using a <see cref="TimeSpan" /> delta),
/// and many others.
/// </para>
/// </remarks>
/// <typeparam name="TValue">The type of values to be compared.</typeparam>
/// <typeparam name="TDifference">The type of the difference produced when the values are
/// subtracted, for numeric types this is the same as <typeparamref name="TValue"/> but it
/// may differ for other types.</typeparam>
/// <param name="unexpectedValue">The expected value.</param>
/// <param name="actualValue">The actual value.</param>
/// <param name="delta">The inclusive delta between the values.</param>
/// <exception cref="AssertionException">Thrown if the verification failed unless the current <see cref="AssertionContext.AssertionFailureBehavior" /> indicates otherwise.</exception>
public static void AreNotApproximatelyEqual<TValue, TDifference>(TValue unexpectedValue, TValue actualValue, TDifference delta)
{
AreNotApproximatelyEqual(unexpectedValue, actualValue, delta, null, null);
}
/// <summary>
/// Verifies that an actual value does not approximately equal some unexpected value
/// to within a specified delta.
/// </summary>
/// <remarks>
/// <para>
/// The values are considered approximately equal if the absolute value of their difference
/// is less than or equal to the delta.
/// </para>
/// <para>
/// This method works with any comparable type that also supports a subtraction operator
/// including <see cref="Single" />, <see cref="Double" />, <see cref="Decimal" />,
/// <see cref="Int32" />, <see cref="DateTime" /> (using a <see cref="TimeSpan" /> delta),
/// and many others.
/// </para>
/// </remarks>
/// <typeparam name="TValue">The type of values to be compared.</typeparam>
/// <typeparam name="TDifference">The type of the difference produced when the values are
/// subtracted, for numeric types this is the same as <typeparamref name="TValue"/> but it
/// may differ for other types.</typeparam>
/// <param name="unexpectedValue">The expected value.</param>
/// <param name="actualValue">The actual value.</param>
/// <param name="delta">The inclusive delta between the values.</param>
/// <param name="messageFormat">The custom assertion message format, or null if none.</param>
/// <param name="messageArgs">The custom assertion message arguments, or null if none.</param>
/// <exception cref="AssertionException">Thrown if the verification failed unless the current <see cref="AssertionContext.AssertionFailureBehavior" /> indicates otherwise.</exception>
public static void AreNotApproximatelyEqual<TValue, TDifference>(TValue unexpectedValue, TValue actualValue, TDifference delta,
string messageFormat, params object[] messageArgs)
{
AssertionHelper.Verify(delegate
{
if (!ComparisonSemantics.Default.ApproximatelyEqual(unexpectedValue, actualValue, delta))
return null;
return new AssertionFailureBuilder("Expected values not to be approximately equal to within a delta.")
.SetMessage(messageFormat, messageArgs)
.AddRawLabeledValue("Unexpected Value", unexpectedValue)
.AddRawActualValue(actualValue)
.AddRawLabeledValue("Delta", delta)
.ToAssertionFailure();
});
}
#endregion
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="PrologVariableDictionary.cs" company="Axiom">
//
// Copyright (c) 2006 Ali Hodroj. All rights reserved.
//
// The use and distribution terms for this source code are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
// </copyright>
//------------------------------------------------------------------------------
namespace Axiom.Compiler.Framework
{
using System;
using System.Collections;
using Axiom.Compiler.CodeObjectModel;
// This class implements a simple dictionary using an array of DictionaryEntry objects (key/value pairs).
public class PrologVariableDictionary : IDictionary
{
private ArrayList _items;
private int _temporaryVariableCount = 0;
public int TemporaryVariableCount
{
get { return _temporaryVariableCount; }
}
private PrologRegisterTable _registers = PrologRegisterTable.Instance;
private int _goalCount = 0;
public int GoalCount
{
get { return _goalCount; }
}
private int _currentArgumentIndex = 0;
public int CurrentArgumentIndex
{
get { return _currentArgumentIndex; }
set { _currentArgumentIndex = value; }
}
private int _currentGoalIndex = 0;
public int CurrentGoalIndex
{
get { return _currentGoalIndex; }
set { _currentGoalIndex = value; }
}
public PrologVariableDictionary()
{
_items = new ArrayList();
}
// Construct the SimpleDictionary with the desired number of items.
// The number of items cannot change for the life time of this SimpleDictionary.
public PrologVariableDictionary(int numItems)
{
_items = new ArrayList(numItems);
}
#region IDictionary Members
public bool IsReadOnly
{
get { return false; }
}
public bool Contains(object key)
{
foreach(PrologVariableDictionaryEntry e in _items)
{
if(e.Name == (string)key)
{
return true;
}
}
return false;
}
public bool IsFixedSize
{
get { return false; }
}
public void Remove(object key)
{
if (key == null)
{
throw new ArgumentNullException("key");
}
string name = (string)key;
for(int i = 0; i < _items.Count; i++)
{
PrologVariableDictionaryEntry entry = (PrologVariableDictionaryEntry)_items[i];
if(entry.Name == name)
{
_items.RemoveAt(i);
return;
}
}
}
public void Clear()
{
_items.Clear();
}
public void Add(object key, object val)
{
string name = (string)key;
if(this.Contains(key))
{
PrologVariableDictionaryEntry entry = GetEntry((string)key);
entry.Occurrences += 1;
entry.LastGoal = _currentGoalIndex;
entry.LastGoalArgument = _currentArgumentIndex;
}
else
{
PrologVariableDictionaryEntry variable = new PrologVariableDictionaryEntry(name, -1);
variable.Occurrences = 0;
variable.FirstGoal = _currentGoalIndex;
variable.IsReferenced = false;
variable.IsGlobal = false;
variable.Occurrences += 1;
variable.LastGoal = _currentGoalIndex;
variable.LastGoalArgument = _currentArgumentIndex;
variable.IsReferenced = false;
_items.Add(variable);
}
}
public ICollection Keys
{
get
{
// Return an array where each item is a key.
Object[] keys = new Object[_items.Count];
for (int n = 0; n < _items.Count; n++)
keys[n] = ((PrologVariableDictionaryEntry)_items[n]).Name;
return keys;
}
}
public ICollection Values
{
get
{
return _items.ToArray();
}
}
public object this[object key]
{
get
{
foreach(PrologVariableDictionaryEntry entry in _items)
{
if(entry.Name == (string)key)
{
return entry;
}
}
return null;
}
set
{
// This method is not implemented
}
}
private PrologVariableDictionaryEntry GetEntry(string name)
{
foreach(PrologVariableDictionaryEntry e in _items)
{
if(e.Name == name)
{
return e;
}
}
return null;
}
private class PrologVariableDictionaryEnumerator : IDictionaryEnumerator
{
// A copy of the SimpleDictionary object's key/value pairs.
ArrayList items = new ArrayList();
int index = -1;
public PrologVariableDictionaryEnumerator(PrologVariableDictionary dict)
{
items.AddRange(dict._items);
/************** BUG: This causes a StackOverflow ********************
foreach(PrologVariableDictionaryEntry e in dict)
{
items.Add(e);
}
*******************************************************************/
}
// Return the current item.
public Object Current
{
get { ValidateIndex(); return items[index]; }
}
// Return the current dictionary entry.
public DictionaryEntry Entry
{
get
{
DictionaryEntry e = new DictionaryEntry(null,null);
return e;
}
}
// Return the key of the current item.
public Object Key
{
get
{
ValidateIndex();
return ((PrologVariableDictionaryEntry)items[index]).Name;
}
}
// Return the value of the current item.
public Object Value
{
get
{
ValidateIndex();
return items[index];
}
}
// Advance to the next item.
public bool MoveNext()
{
if (index < items.Count - 1)
{
index++;
return true;
}
return false;
}
// Validate the enumeration index and throw an exception if the index is out of range.
private void ValidateIndex()
{
if (index < 0 || index >= items.Count)
throw new InvalidOperationException("Enumerator is before or after the collection.");
}
// Reset the index to restart the enumeration.
public void Reset()
{
index = -1;
}
}
public IDictionaryEnumerator GetEnumerator()
{
// Construct and return an enumerator.
return new PrologVariableDictionaryEnumerator(this);
}
#endregion
#region ICollection Members
public bool IsSynchronized
{
get { return false; }
}
public object SyncRoot
{
get { throw new NotImplementedException(); }
}
public int Count
{
get { return _items.Count; }
}
public void CopyTo(Array array, int index)
{
throw new NotImplementedException();
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
// Construct and return an enumerator.
return ((IDictionary)this).GetEnumerator();
}
#endregion
#region Prolog Dictionary Operations
public void Build(PrologCodeClause clause)
{
/* reset goal count */
_goalCount = 0;
// reset everything.
this.Reset();
// set current goal index
_currentGoalIndex = 0;
// store head variables
AddGoalVariables(clause.Head);
_currentGoalIndex++;
// build clause body goals
foreach(PrologCodeTerm goal in clause.Goals)
{
AddGoalVariables(goal);
_currentGoalIndex++;
}
// set goal count to where we reached so far
_goalCount = _currentGoalIndex;
// Mark temporary variables
MarkTemporaryVariables();
// Mark permanent variables
MarkPermanentVariables();
}
private void MarkTemporaryVariables()
{
foreach(PrologVariableDictionaryEntry entry in _items)
{
if(entry.LastGoal <= 1 || entry.FirstGoal == entry.LastGoal)
{
entry.IsTemporary = true;
}
if(!entry.IsTemporary && entry.FirstGoal != 0)
{
entry.IsUnsafe = true;
}
if(entry.IsTemporary)
{
_temporaryVariableCount++;
}
}
}
private void MarkPermanentVariables()
{
int nPermVars = 0;
int goalN = 0;
int index = 0;
for(nPermVars = (_items.Count - _temporaryVariableCount), goalN = _goalCount - 1, index = 0;
nPermVars > 0;
goalN--)
{
foreach(PrologVariableDictionaryEntry entry in _items)
{
if(!entry.IsTemporary && entry.LastGoal == goalN)
{
entry.PermanentIndex = index++;
nPermVars--;
}
}
}
}
public void ClearTempIndexOfPermanentVariables()
{
foreach(PrologVariableDictionaryEntry entry in _items)
{
if(!entry.IsTemporary)
{
entry.TemporaryIndex = -1;
}
}
}
private void AddGoalVariables(PrologCodeTerm term)
{
// no variables to add: predicate/0
if(PrologCodeTerm.IsAtom(term) || PrologCodeTerm.IsAtomicPredicate(term))
{
return;
}
// goal is a variable X
else if(PrologCodeTerm.IsVariable(term))
{
_currentArgumentIndex = 0;
this.Add(((PrologCodeVariable)term).Name,null);
return;
}
// goal is a list, [Term|Term]
else if(PrologCodeTerm.IsList(term))
{
_currentArgumentIndex = 0;
if(term is PrologCodeNonEmptyList)
{
PrologCodeNonEmptyList list = (PrologCodeNonEmptyList)term;
AddGoalArgumentVariables(list.Head);
_currentArgumentIndex = 1;
if(list.Tail != null)
{
if(list.Tail is PrologCodeNonEmptyList)
{
AddGoalArgumentVariables(list.Tail);
}
else
{
AddGoalArgumentVariables(list.Tail);
}
}
}
}
// Goal is a predicate, term(term,...)
else if(PrologCodeTerm.IsStruct(term))
{
_currentArgumentIndex = 0;
PrologCodePredicate goal = (PrologCodePredicate)term;
foreach(PrologCodeTerm argument in goal.Arguments)
{
AddGoalArgumentVariables(argument);
_currentArgumentIndex++;
}
}
}
private void AddGoalArgumentVariables(PrologCodeTerm term)
{
// goal(atom).
if(PrologCodeTerm.IsAtom(term))
{
return;
}
// goal(X).
else if(PrologCodeTerm.IsVariable(term))
{
this.Add(((PrologCodeVariable)term).Name, null);
return;
}
// goal([A|B]).
else if(PrologCodeTerm.IsList(term))
{
if(term is PrologCodeNonEmptyList)
{
PrologCodeNonEmptyList list = (PrologCodeNonEmptyList)term;
AddGoalStructArgumentVariables(list.Head);
if (list.Tail is PrologCodeNonEmptyList)
{
AddGoalStructArgumentVariables(list.Tail);
}
else
{
AddGoalStructArgumentVariables(list.Tail);
}
}
}
else if(PrologCodeTerm.IsStruct(term))
{
PrologCodePredicate goal = (PrologCodePredicate)term;
foreach (PrologCodeTerm argument in goal.Arguments)
{
AddGoalStructArgumentVariables(argument);
}
}
}
private void AddGoalStructArgumentVariables(PrologCodeTerm term)
{
if (PrologCodeTerm.IsAtom(term))
{
return;
}
else if (PrologCodeTerm.IsVariable(term))
{
this.Add(((PrologCodeVariable)term).Name, null);
}
else if (PrologCodeTerm.IsList(term))
{
if (term is PrologCodeNonEmptyList)
{
PrologCodeNonEmptyList list = (PrologCodeNonEmptyList)term;
AddGoalStructArgumentVariables(list.Head);
if (list.Tail is PrologCodeNonEmptyList)
{
AddGoalStructArgumentVariables(list.Tail);
}
else
{
AddGoalStructArgumentVariables(list.Tail);
}
}
}
else if (PrologCodeTerm.IsStruct(term))
{
PrologCodePredicate structure = (PrologCodePredicate)term;
foreach (PrologCodeTerm argument in structure.Arguments)
{
AddGoalStructArgumentVariables(argument);
}
}
}
public void Reset()
{
_items.Clear();
ClearTempIndexOfPermanentVariables();
PrologRegisterTable.Instance = null;
_registers = PrologRegisterTable.Instance;
}
public void AllocateTemporaryVariable(PrologVariableDictionaryEntry entry, int reg)
{
_registers.AllocateRegister(reg);
entry.TemporaryIndex = reg;
}
public void AllocatePermanentVariable(PrologVariableDictionaryEntry entry, int reg)
{
entry.PermanentIndex = reg;
}
public PrologVariableDictionaryEntry GetVariable(string name)
{
if (Contains(name))
{
return GetEntry(name);
}
return null;
}
public PrologVariableDictionaryEntry GetVariable(int register)
{
foreach (PrologVariableDictionaryEntry entry in _items)
{
if (entry.TemporaryIndex == register)
{
return entry;
}
}
return null;
}
#endregion
public bool InLastGoal
{
get { return _currentGoalIndex == _goalCount - 1; }
}
}
}
| |
using System;
using System.Globalization;
using System.Collections.Generic;
using Sasoma.Utils;
using Sasoma.Microdata.Interfaces;
using Sasoma.Languages.Core;
using Sasoma.Microdata.Properties;
namespace Sasoma.Microdata.Types
{
/// <summary>
/// A travel agency.
/// </summary>
public class TravelAgency_Core : TypeCore, ILocalBusiness
{
public TravelAgency_Core()
{
this._TypeId = 272;
this._Id = "TravelAgency";
this._Schema_Org_Url = "http://schema.org/TravelAgency";
string label = "";
GetLabel(out label, "TravelAgency", typeof(TravelAgency_Core));
this._Label = label;
this._Ancestors = new int[]{266,193,155};
this._SubTypes = new int[0];
this._SuperTypes = new int[]{155};
this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,47,75,77,94,95,130,137,36,60,152,156,167};
}
/// <summary>
/// Physical address of the item.
/// </summary>
private Address_Core address;
public Address_Core Address
{
get
{
return address;
}
set
{
address = value;
SetPropertyInstance(address);
}
}
/// <summary>
/// The overall rating, based on a collection of reviews or ratings, of the item.
/// </summary>
private Properties.AggregateRating_Core aggregateRating;
public Properties.AggregateRating_Core AggregateRating
{
get
{
return aggregateRating;
}
set
{
aggregateRating = value;
SetPropertyInstance(aggregateRating);
}
}
/// <summary>
/// The larger organization that this local business is a branch of, if any.
/// </summary>
private BranchOf_Core branchOf;
public BranchOf_Core BranchOf
{
get
{
return branchOf;
}
set
{
branchOf = value;
SetPropertyInstance(branchOf);
}
}
/// <summary>
/// A contact point for a person or organization.
/// </summary>
private ContactPoints_Core contactPoints;
public ContactPoints_Core ContactPoints
{
get
{
return contactPoints;
}
set
{
contactPoints = value;
SetPropertyInstance(contactPoints);
}
}
/// <summary>
/// The basic containment relation between places.
/// </summary>
private ContainedIn_Core containedIn;
public ContainedIn_Core ContainedIn
{
get
{
return containedIn;
}
set
{
containedIn = value;
SetPropertyInstance(containedIn);
}
}
/// <summary>
/// The currency accepted (in <a href=\http://en.wikipedia.org/wiki/ISO_4217\ target=\new\>ISO 4217 currency format</a>).
/// </summary>
private CurrenciesAccepted_Core currenciesAccepted;
public CurrenciesAccepted_Core CurrenciesAccepted
{
get
{
return currenciesAccepted;
}
set
{
currenciesAccepted = value;
SetPropertyInstance(currenciesAccepted);
}
}
/// <summary>
/// A short description of the item.
/// </summary>
private Description_Core description;
public Description_Core Description
{
get
{
return description;
}
set
{
description = value;
SetPropertyInstance(description);
}
}
/// <summary>
/// Email address.
/// </summary>
private Email_Core email;
public Email_Core Email
{
get
{
return email;
}
set
{
email = value;
SetPropertyInstance(email);
}
}
/// <summary>
/// People working for this organization.
/// </summary>
private Employees_Core employees;
public Employees_Core Employees
{
get
{
return employees;
}
set
{
employees = value;
SetPropertyInstance(employees);
}
}
/// <summary>
/// Upcoming or past events associated with this place or organization.
/// </summary>
private Events_Core events;
public Events_Core Events
{
get
{
return events;
}
set
{
events = value;
SetPropertyInstance(events);
}
}
/// <summary>
/// The fax number.
/// </summary>
private FaxNumber_Core faxNumber;
public FaxNumber_Core FaxNumber
{
get
{
return faxNumber;
}
set
{
faxNumber = value;
SetPropertyInstance(faxNumber);
}
}
/// <summary>
/// A person who founded this organization.
/// </summary>
private Founders_Core founders;
public Founders_Core Founders
{
get
{
return founders;
}
set
{
founders = value;
SetPropertyInstance(founders);
}
}
/// <summary>
/// The date that this organization was founded.
/// </summary>
private FoundingDate_Core foundingDate;
public FoundingDate_Core FoundingDate
{
get
{
return foundingDate;
}
set
{
foundingDate = value;
SetPropertyInstance(foundingDate);
}
}
/// <summary>
/// The geo coordinates of the place.
/// </summary>
private Geo_Core geo;
public Geo_Core Geo
{
get
{
return geo;
}
set
{
geo = value;
SetPropertyInstance(geo);
}
}
/// <summary>
/// URL of an image of the item.
/// </summary>
private Image_Core image;
public Image_Core Image
{
get
{
return image;
}
set
{
image = value;
SetPropertyInstance(image);
}
}
/// <summary>
/// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>.
/// </summary>
private InteractionCount_Core interactionCount;
public InteractionCount_Core InteractionCount
{
get
{
return interactionCount;
}
set
{
interactionCount = value;
SetPropertyInstance(interactionCount);
}
}
/// <summary>
/// The location of the event or organization.
/// </summary>
private Location_Core location;
public Location_Core Location
{
get
{
return location;
}
set
{
location = value;
SetPropertyInstance(location);
}
}
/// <summary>
/// A URL to a map of the place.
/// </summary>
private Maps_Core maps;
public Maps_Core Maps
{
get
{
return maps;
}
set
{
maps = value;
SetPropertyInstance(maps);
}
}
/// <summary>
/// A member of this organization.
/// </summary>
private Members_Core members;
public Members_Core Members
{
get
{
return members;
}
set
{
members = value;
SetPropertyInstance(members);
}
}
/// <summary>
/// The name of the item.
/// </summary>
private Name_Core name;
public Name_Core Name
{
get
{
return name;
}
set
{
name = value;
SetPropertyInstance(name);
}
}
/// <summary>
/// The opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas ',' separating each day. Day or time ranges are specified using a hyphen '-'.<br/>- Days are specified using the following two-letter combinations: <code>Mo</code>, <code>Tu</code>, <code>We</code>, <code>Th</code>, <code>Fr</code>, <code>Sa</code>, <code>Su</code>.<br/>- Times are specified using 24:00 time. For example, 3pm is specified as <code>15:00</code>. <br/>- Here is an example: <code><time itemprop=\openingHours\ datetime=\Tu,Th 16:00-20:00\>Tuesdays and Thursdays 4-8pm</time></code>. <br/>- If a business is open 7 days a week, then it can be specified as <code><time itemprop=\openingHours\ datetime=\Mo-Su\>Monday through Sunday, all day</time></code>.
/// </summary>
private OpeningHours_Core openingHours;
public OpeningHours_Core OpeningHours
{
get
{
return openingHours;
}
set
{
openingHours = value;
SetPropertyInstance(openingHours);
}
}
/// <summary>
/// Cash, credit card, etc.
/// </summary>
private PaymentAccepted_Core paymentAccepted;
public PaymentAccepted_Core PaymentAccepted
{
get
{
return paymentAccepted;
}
set
{
paymentAccepted = value;
SetPropertyInstance(paymentAccepted);
}
}
/// <summary>
/// Photographs of this place.
/// </summary>
private Photos_Core photos;
public Photos_Core Photos
{
get
{
return photos;
}
set
{
photos = value;
SetPropertyInstance(photos);
}
}
/// <summary>
/// The price range of the business, for example <code>$$$</code>.
/// </summary>
private PriceRange_Core priceRange;
public PriceRange_Core PriceRange
{
get
{
return priceRange;
}
set
{
priceRange = value;
SetPropertyInstance(priceRange);
}
}
/// <summary>
/// Review of the item.
/// </summary>
private Reviews_Core reviews;
public Reviews_Core Reviews
{
get
{
return reviews;
}
set
{
reviews = value;
SetPropertyInstance(reviews);
}
}
/// <summary>
/// The telephone number.
/// </summary>
private Telephone_Core telephone;
public Telephone_Core Telephone
{
get
{
return telephone;
}
set
{
telephone = value;
SetPropertyInstance(telephone);
}
}
/// <summary>
/// URL of the item.
/// </summary>
private Properties.URL_Core uRL;
public Properties.URL_Core URL
{
get
{
return uRL;
}
set
{
uRL = value;
SetPropertyInstance(uRL);
}
}
}
}
| |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
namespace DiscUtils.Common
{
public abstract class ProgramBase
{
private CommandLineParser _parser;
private CommandLineSwitch _outFormatSwitch;
private CommandLineEnumSwitch<GenericDiskAdapterType> _adapterTypeSwitch;
private CommandLineSwitch _userNameSwitch;
private CommandLineSwitch _passwordSwitch;
private CommandLineSwitch _partitionSwitch;
private CommandLineSwitch _volumeIdSwitch;
private CommandLineSwitch _diskSizeSwitch;
private CommandLineSwitch _filenameEncodingSwitch;
private CommandLineSwitch _helpSwitch;
private CommandLineSwitch _quietSwitch;
private CommandLineSwitch _verboseSwitch;
private CommandLineSwitch _timeSwitch;
private string _userName;
private string _password;
private string _outputDiskType;
private string _outputDiskVariant;
private GenericDiskAdapterType _adapterType;
private int _partition = -1;
private string _volumeId;
private long _diskSize;
protected ProgramBase()
{
}
protected string UserName
{
get { return _userName; }
}
protected string Password
{
get { return _password; }
}
protected string OutputDiskType
{
get { return _outputDiskType; }
}
protected string OutputDiskVariant
{
get { return _outputDiskVariant; }
}
protected GenericDiskAdapterType AdapterType
{
get { return _adapterType; }
}
protected bool Quiet
{
get { return _quietSwitch.IsPresent; }
}
protected bool Verbose
{
get { return _verboseSwitch.IsPresent; }
}
protected int Partition
{
get { return _partition; }
}
protected string VolumeId
{
get { return _volumeId; }
}
protected long DiskSize
{
get { return _diskSize; }
}
protected VirtualDiskParameters DiskParameters
{
get
{
return new VirtualDiskParameters()
{
AdapterType = AdapterType,
Capacity = DiskSize,
};
}
}
protected FileSystemParameters FileSystemParameters
{
get
{
return new FileSystemParameters()
{
FileNameEncoding = (_filenameEncodingSwitch != null && _filenameEncodingSwitch.IsPresent) ? Encoding.GetEncoding(_filenameEncodingSwitch.Value) : null,
};
}
}
protected abstract StandardSwitches DefineCommandLine(CommandLineParser parser);
protected virtual string[] HelpRemarks { get { return new string[] { }; } }
protected abstract void DoRun();
protected void Run(string[] args)
{
_parser = new CommandLineParser(ExeName);
StandardSwitches stdSwitches = DefineCommandLine(_parser);
if ((stdSwitches & StandardSwitches.OutputFormatAndAdapterType) != 0)
{
_outFormatSwitch = OutputFormatSwitch();
_adapterTypeSwitch = new CommandLineEnumSwitch<GenericDiskAdapterType>("a", "adaptortype", "type", GenericDiskAdapterType.Ide, "Some disk formats encode the disk type (IDE or SCSI) into the disk image, this parameter specifies the type of adaptor to encode.");
_parser.AddSwitch(_outFormatSwitch);
_parser.AddSwitch(_adapterTypeSwitch);
}
if ((stdSwitches & StandardSwitches.DiskSize) != 0)
{
_diskSizeSwitch = new CommandLineSwitch("sz", "size", "size", "The size of the output disk. Use B, KB, MB, GB to specify units (units default to bytes if not specified).");
_parser.AddSwitch(_diskSizeSwitch);
}
if ((stdSwitches & StandardSwitches.FileNameEncoding) != 0)
{
_filenameEncodingSwitch = new CommandLineSwitch(new string[]{"ne"}, "nameencoding", "encoding", "The encoding used for filenames in the file system (aka the codepage), e.g. UTF-8 or IBM437. This is ignored for file systems have fixed/defined encodings.");
_parser.AddSwitch(_filenameEncodingSwitch);
}
if ((stdSwitches & StandardSwitches.PartitionOrVolume) != 0)
{
_partitionSwitch = new CommandLineSwitch("p", "partition", "num", "The number of the partition to inspect, in the range 0-n. If not specified, 0 (the first partition) is the default.");
_volumeIdSwitch = new CommandLineSwitch("v", "volume", "id", "The volume id of the volume to access, use the VolInfo tool to discover this id. If specified, the partition parameter is ignored.");
_parser.AddSwitch(_partitionSwitch);
_parser.AddSwitch(_volumeIdSwitch);
}
if ((stdSwitches & StandardSwitches.UserAndPassword) != 0)
{
_userNameSwitch = new CommandLineSwitch("u", "user", "user_name", "If using an iSCSI source or target, optionally use this parameter to specify the user name to authenticate with. If this parameter is specified without a password, you will be prompted to supply the password.");
_parser.AddSwitch(_userNameSwitch);
_passwordSwitch = new CommandLineSwitch("pw", "password", "secret", "If using an iSCSI source or target, optionally use this parameter to specify the password to authenticate with.");
_parser.AddSwitch(_passwordSwitch);
}
if ((stdSwitches & StandardSwitches.Verbose) != 0)
{
_verboseSwitch = new CommandLineSwitch("v", "verbose", null, "Show detailed information.");
_parser.AddSwitch(_verboseSwitch);
}
_helpSwitch = new CommandLineSwitch(new string[] { "h", "?" }, "help", null, "Show this help.");
_parser.AddSwitch(_helpSwitch);
_quietSwitch = new CommandLineSwitch("q", "quiet", null, "Run quietly.");
_parser.AddSwitch(_quietSwitch);
_timeSwitch = new CommandLineSwitch("time", null, "Times how long this program takes to execute.");
_parser.AddSwitch(_timeSwitch);
bool parseResult = _parser.Parse(args);
if (!_quietSwitch.IsPresent)
{
DisplayHeader();
}
if (_helpSwitch.IsPresent || !parseResult)
{
DisplayHelp();
return;
}
if ((stdSwitches & StandardSwitches.OutputFormatAndAdapterType) != 0)
{
if (_outFormatSwitch.IsPresent)
{
string[] typeAndVariant = _outFormatSwitch.Value.Split(new char[] { '-' }, 2);
_outputDiskType = typeAndVariant[0];
_outputDiskVariant = (typeAndVariant.Length > 1) ? typeAndVariant[1] : "";
}
else
{
DisplayHelp();
return;
}
if (_adapterTypeSwitch.IsPresent)
{
_adapterType = _adapterTypeSwitch.EnumValue;
}
else
{
_adapterType = GenericDiskAdapterType.Ide;
}
}
if ((stdSwitches & StandardSwitches.DiskSize) != 0)
{
if (_diskSizeSwitch.IsPresent && !Utilities.TryParseDiskSize(_diskSizeSwitch.Value, out _diskSize))
{
DisplayHelp();
return;
}
}
if ((stdSwitches & StandardSwitches.PartitionOrVolume) != 0)
{
_partition = -1;
if (_partitionSwitch.IsPresent && !int.TryParse(_partitionSwitch.Value, out _partition))
{
DisplayHelp();
return;
}
_volumeId = _volumeIdSwitch.IsPresent ? _volumeIdSwitch.Value : null;
}
if ((stdSwitches & StandardSwitches.UserAndPassword) != 0)
{
_userName = null;
if (_userNameSwitch.IsPresent)
{
_userName = _userNameSwitch.Value;
if (_passwordSwitch.IsPresent)
{
_password = _passwordSwitch.Value;
}
else
{
_password = Utilities.PromptForPassword();
}
}
}
if (_timeSwitch.IsPresent)
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
DoRun();
stopWatch.Stop();
Console.WriteLine();
Console.WriteLine("Time taken: {0}", stopWatch.Elapsed);
}
else
{
DoRun();
}
}
protected void DisplayHelp()
{
_parser.DisplayHelp(HelpRemarks);
}
protected virtual void DisplayHeader()
{
Console.WriteLine("{0} v{1}, available from http://discutils.codeplex.com", ExeName, Version);
Console.WriteLine("Copyright (c) Kenneth Bell, 2008-2011");
Console.WriteLine("Free software issued under the MIT License, see LICENSE.TXT for details.");
Console.WriteLine();
}
protected CommandLineParameter FileOrUriParameter(string paramName, string intro, bool optional)
{
return new CommandLineParameter(
paramName,
intro + " " +
"This can be a file path or an iSCSI, NFS or ODS URL. " +
"URLs for iSCSI LUNs are of the form: iscsi://192.168.1.2/iqn.2002-2004.example.com:port1?LUN=2. " +
"Use the iSCSIBrowse utility to discover iSCSI URLs. " +
"NFS URLs are of the form: nfs://host/a/path.vhd. " +
"ODS URLs are of the form: ods://domain/host/volumename.",
optional);
}
protected CommandLineMultiParameter FileOrUriMultiParameter(string paramName, string intro, bool optional)
{
return new CommandLineMultiParameter(
paramName,
intro + " " +
"This can be a file path or an iSCSI, NFS or ODS URL. " +
"URLs for iSCSI LUNs are of the form: iscsi://192.168.1.2/iqn.2002-2004.example.com:port1?LUN=2. " +
"Use the iSCSIBrowse utility to discover iSCSI URLs. " +
"NFS URLs are of the form: nfs://host/a/path.vhd. " +
"ODS URLs are of the form: ods://domain/host/volumename.",
optional);
}
protected static void ShowProgress(string label, long totalBytes, DateTime startTime, object sourceObject, PumpProgressEventArgs e)
{
int progressLen = 55 - label.Length;
int numProgressChars = (int)((e.BytesRead * progressLen) / totalBytes);
string progressBar = new string('=', numProgressChars) + new string(' ', progressLen - numProgressChars);
DateTime now = DateTime.Now;
TimeSpan timeSoFar = now - startTime;
TimeSpan remaining = TimeSpan.FromMilliseconds((timeSoFar.TotalMilliseconds / (double)e.BytesRead) * (totalBytes - e.BytesRead));
Console.Write("\r{0} ({1,3}%) |{2}| {3:hh\\:mm\\:ss\\.f}", label, (e.BytesRead * 100) / totalBytes, progressBar, remaining, remaining.TotalHours, remaining.Minutes, remaining.Seconds, remaining.Milliseconds);
}
private CommandLineSwitch OutputFormatSwitch()
{
List<string> outputTypes = new List<string>();
foreach (var type in VirtualDisk.SupportedDiskTypes)
{
List<string> variants = new List<string>(VirtualDisk.GetSupportedDiskVariants(type));
if (variants.Count == 0)
{
outputTypes.Add(type.ToUpperInvariant());
}
else
{
foreach (var variant in variants)
{
outputTypes.Add(type.ToUpperInvariant() + "-" + variant.ToLowerInvariant());
}
}
}
string[] ots = outputTypes.ToArray();
Array.Sort(ots);
return new CommandLineSwitch(
"of",
"outputFormat",
"format",
"Mandatory - the type of disk to output, one of " + string.Join(", ", ots, 0, ots.Length - 1) + " or " + ots[ots.Length - 1] + ".");
}
private string ExeName
{
get { return GetType().Assembly.GetName().Name; }
}
private string Version
{
get { return GetType().Assembly.GetName().Version.ToString(3); }
}
[Flags]
protected internal enum StandardSwitches
{
Default = 0,
UserAndPassword = 1,
OutputFormatAndAdapterType = 2,
Verbose = 4,
PartitionOrVolume = 8,
DiskSize = 16,
FileNameEncoding = 32
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.VisualStudio.Debugger.Interop;
using System.Diagnostics;
using System.Collections.ObjectModel;
using System.Threading;
using MICore;
using Microsoft.DebugEngineHost;
namespace Microsoft.MIDebugEngine
{
internal class EngineCallback : ISampleEngineCallback, MICore.IDeviceAppLauncherEventCallback
{
private readonly IDebugEventCallback2 _eventCallback;
private readonly AD7Engine _engine;
private int _sentProgramDestroy;
public EngineCallback(AD7Engine engine, IDebugEventCallback2 ad7Callback)
{
_engine = engine;
_eventCallback = HostMarshal.GetThreadSafeEventCallback(ad7Callback);
}
public void Send(IDebugEvent2 eventObject, string iidEvent, IDebugProgram2 program, IDebugThread2 thread)
{
uint attributes;
Guid riidEvent = new Guid(iidEvent);
EngineUtils.RequireOk(eventObject.GetAttributes(out attributes));
EngineUtils.RequireOk(_eventCallback.Event(_engine, null, program, thread, eventObject, ref riidEvent, attributes));
}
public void Send(IDebugEvent2 eventObject, string iidEvent, IDebugThread2 thread)
{
IDebugProgram2 program = _engine;
if (!_engine.ProgramCreateEventSent)
{
// Any events before programe create shouldn't include the program
program = null;
}
Send(eventObject, iidEvent, program, thread);
}
public void OnError(string message)
{
SendMessage(message, OutputMessage.Severity.Error, isAsync: true);
}
/// <summary>
/// Sends an error to the user, blocking until the user dismisses the error
/// </summary>
/// <param name="message">string to display to the user</param>
public void OnErrorImmediate(string message)
{
SendMessage(message, OutputMessage.Severity.Error, isAsync: false);
}
public void OnWarning(string message)
{
SendMessage(message, OutputMessage.Severity.Warning, isAsync: true);
}
public void OnModuleLoad(DebuggedModule debuggedModule)
{
// This will get called when the entrypoint breakpoint is fired because the engine sends a mod-load event
// for the exe.
if (_engine.DebuggedProcess != null)
{
Debug.Assert(_engine.DebuggedProcess.WorkerThread.IsPollThread());
}
AD7Module ad7Module = new AD7Module(debuggedModule, _engine.DebuggedProcess);
AD7ModuleLoadEvent eventObject = new AD7ModuleLoadEvent(ad7Module, true /* this is a module load */);
debuggedModule.Client = ad7Module;
// The sample engine does not support binding breakpoints as modules load since the primary exe is the only module
// symbols are loaded for. A production debugger will need to bind breakpoints when a new module is loaded.
Send(eventObject, AD7ModuleLoadEvent.IID, null);
}
public void OnModuleUnload(DebuggedModule debuggedModule)
{
Debug.Assert(_engine.DebuggedProcess.WorkerThread.IsPollThread());
AD7Module ad7Module = (AD7Module)debuggedModule.Client;
Debug.Assert(ad7Module != null);
AD7ModuleLoadEvent eventObject = new AD7ModuleLoadEvent(ad7Module, false /* this is a module unload */);
Send(eventObject, AD7ModuleLoadEvent.IID, null);
}
public void OnOutputString(string outputString)
{
AD7OutputDebugStringEvent eventObject = new AD7OutputDebugStringEvent(outputString);
Send(eventObject, AD7OutputDebugStringEvent.IID, null);
}
public void OnOutputMessage(OutputMessage outputMessage)
{
try
{
if (outputMessage.ErrorCode == 0)
{
var eventObject = new AD7MessageEvent(outputMessage, isAsync: true);
Send(eventObject, AD7MessageEvent.IID, null);
}
else
{
var eventObject = new AD7ErrorEvent(outputMessage, isAsync: true);
Send(eventObject, AD7ErrorEvent.IID, null);
}
}
catch
{
// Since we are often trying to report an exception, if something goes wrong we don't want to take down the process,
// so ignore the failure.
}
}
public void OnProcessExit(uint exitCode)
{
if (Interlocked.Exchange(ref _sentProgramDestroy, 1) == 0)
{
AD7ProgramDestroyEvent eventObject = new AD7ProgramDestroyEvent(exitCode);
try
{
Send(eventObject, AD7ProgramDestroyEvent.IID, null);
}
catch (InvalidOperationException)
{
// If debugging has already stopped, this can throw
}
}
}
public void OnEntryPoint(DebuggedThread thread)
{
AD7EntryPointEvent eventObject = new AD7EntryPointEvent();
Send(eventObject, AD7EntryPointEvent.IID, (AD7Thread)thread.Client);
}
public void OnThreadExit(DebuggedThread debuggedThread, uint exitCode)
{
Debug.Assert(_engine.DebuggedProcess.WorkerThread.IsPollThread());
AD7Thread ad7Thread = (AD7Thread)debuggedThread.Client;
Debug.Assert(ad7Thread != null);
AD7ThreadDestroyEvent eventObject = new AD7ThreadDestroyEvent(exitCode);
Send(eventObject, AD7ThreadDestroyEvent.IID, ad7Thread);
}
public void OnThreadStart(DebuggedThread debuggedThread)
{
// This will get called when the entrypoint breakpoint is fired because the engine sends a thread start event
// for the main thread of the application.
if (_engine.DebuggedProcess != null)
{
Debug.Assert(_engine.DebuggedProcess.WorkerThread.IsPollThread());
}
AD7ThreadCreateEvent eventObject = new AD7ThreadCreateEvent();
Send(eventObject, AD7ThreadCreateEvent.IID, (IDebugThread2)debuggedThread.Client);
}
public void OnBreakpoint(DebuggedThread thread, ReadOnlyCollection<object> clients)
{
IDebugBoundBreakpoint2[] boundBreakpoints = new IDebugBoundBreakpoint2[clients.Count];
int i = 0;
foreach (object objCurrentBreakpoint in clients)
{
boundBreakpoints[i] = (IDebugBoundBreakpoint2)objCurrentBreakpoint;
i++;
}
// An engine that supports more advanced breakpoint features such as hit counts, conditions and filters
// should notify each bound breakpoint that it has been hit and evaluate conditions here.
// The sample engine does not support these features.
AD7BoundBreakpointsEnum boundBreakpointsEnum = new AD7BoundBreakpointsEnum(boundBreakpoints);
AD7BreakpointEvent eventObject = new AD7BreakpointEvent(boundBreakpointsEnum);
AD7Thread ad7Thread = (AD7Thread)thread.Client;
Send(eventObject, AD7BreakpointEvent.IID, ad7Thread);
}
// Exception events are sent when an exception occurs in the debuggee that the debugger was not expecting.
public void OnException(DebuggedThread thread, string name, string description, uint code, Guid? exceptionCategory = null, ExceptionBreakpointState state = ExceptionBreakpointState.None)
{
AD7ExceptionEvent eventObject = new AD7ExceptionEvent(name, description, code, exceptionCategory, state);
AD7Thread ad7Thread = (AD7Thread)thread.Client;
Send(eventObject, AD7ExceptionEvent.IID, ad7Thread);
}
public void OnExpressionEvaluationComplete(IVariableInformation var, IDebugProperty2 prop = null)
{
AD7ExpressionCompleteEvent eventObject = new AD7ExpressionCompleteEvent(_engine, var, prop);
Send(eventObject, AD7ExpressionCompleteEvent.IID, var.Client);
}
public void OnStepComplete(DebuggedThread thread)
{
// Step complete is sent when a step has finished
AD7StepCompleteEvent eventObject = new AD7StepCompleteEvent();
AD7Thread ad7Thread = (AD7Thread)thread.Client;
Send(eventObject, AD7StepCompleteEvent.IID, ad7Thread);
}
public void OnAsyncBreakComplete(DebuggedThread thread)
{
// This will get called when the engine receives the breakpoint event that is created when the user
// hits the pause button in vs.
Debug.Assert(_engine.DebuggedProcess.WorkerThread.IsPollThread());
AD7Thread ad7Thread = (AD7Thread)thread.Client;
AD7AsyncBreakCompleteEvent eventObject = new AD7AsyncBreakCompleteEvent();
Send(eventObject, AD7AsyncBreakCompleteEvent.IID, ad7Thread);
}
public void OnLoadComplete(DebuggedThread thread)
{
AD7Thread ad7Thread = (AD7Thread)thread.Client;
AD7LoadCompleteEvent eventObject = new AD7LoadCompleteEvent();
Send(eventObject, AD7LoadCompleteEvent.IID, ad7Thread);
}
public void OnProgramDestroy(uint exitCode)
{
AD7ProgramDestroyEvent eventObject = new AD7ProgramDestroyEvent(exitCode);
Send(eventObject, AD7ProgramDestroyEvent.IID, null);
}
// Engines notify the debugger about the results of a symbol serach by sending an instance
// of IDebugSymbolSearchEvent2
public void OnSymbolSearch(DebuggedModule module, string status, uint dwStatusFlags)
{
enum_MODULE_INFO_FLAGS statusFlags = (enum_MODULE_INFO_FLAGS)dwStatusFlags;
string statusString = ((statusFlags & enum_MODULE_INFO_FLAGS.MIF_SYMBOLS_LOADED) != 0 ? "Symbols Loaded - " : "No symbols loaded") + status;
AD7Module ad7Module = new AD7Module(module, _engine.DebuggedProcess);
AD7SymbolSearchEvent eventObject = new AD7SymbolSearchEvent(ad7Module, statusString, statusFlags);
Send(eventObject, AD7SymbolSearchEvent.IID, null);
}
// Engines notify the debugger that a breakpoint has bound through the breakpoint bound event.
public void OnBreakpointBound(object objBoundBreakpoint)
{
AD7BoundBreakpoint boundBreakpoint = (AD7BoundBreakpoint)objBoundBreakpoint;
IDebugPendingBreakpoint2 pendingBreakpoint;
((IDebugBoundBreakpoint2)boundBreakpoint).GetPendingBreakpoint(out pendingBreakpoint);
AD7BreakpointBoundEvent eventObject = new AD7BreakpointBoundEvent((AD7PendingBreakpoint)pendingBreakpoint, boundBreakpoint);
Send(eventObject, AD7BreakpointBoundEvent.IID, null);
}
// Engines notify the SDM that a pending breakpoint failed to bind through the breakpoint error event
public void OnBreakpointError(AD7ErrorBreakpoint bperr)
{
AD7BreakpointErrorEvent eventObject = new AD7BreakpointErrorEvent(bperr);
Send(eventObject, AD7BreakpointErrorEvent.IID, null);
}
// Engines notify the SDM that a bound breakpoint change resulted in an error
public void OnBreakpointUnbound(AD7BoundBreakpoint bp, enum_BP_UNBOUND_REASON reason)
{
AD7BreakpointUnboundEvent eventObject = new AD7BreakpointUnboundEvent(bp, reason);
Send(eventObject, AD7BreakpointUnboundEvent.IID, null);
}
public void OnCustomDebugEvent(Guid guidVSService, Guid sourceId, int messageCode, object parameter1, object parameter2)
{
var eventObject = new AD7CustomDebugEvent(guidVSService, sourceId, messageCode, parameter1, parameter2);
Send(eventObject, AD7CustomDebugEvent.IID, null);
}
public void OnStopComplete(DebuggedThread thread)
{
var eventObject = new AD7StopCompleteEvent();
Send(eventObject, AD7StopCompleteEvent.IID, (AD7Thread)thread.Client);
}
private void SendMessage(string message, OutputMessage.Severity severity, bool isAsync)
{
try
{
// IDebugErrorEvent2 is used to report error messages to the user when something goes wrong in the debug engine.
// The sample engine doesn't take advantage of this.
AD7MessageEvent eventObject = new AD7MessageEvent(new OutputMessage(message, enum_MESSAGETYPE.MT_MESSAGEBOX, severity), isAsync);
Send(eventObject, AD7MessageEvent.IID, null);
}
catch
{
// Since we are often trying to report an exception, if something goes wrong we don't want to take down the process,
// so ignore the failure.
}
}
}
}
| |
#if UNITY_EDITOR
namespace InControl
{
using System.Collections.Generic;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;
[InitializeOnLoad]
internal class InputManagerAssetGenerator
{
const string productName = "InControl";
static List<AxisPreset> axisPresets = new List<AxisPreset>();
static InputManagerAssetGenerator()
{
if (!CheckAxisPresets())
{
Debug.LogError( productName + " has detected invalid InputManager settings. To fix, execute 'Edit > Project Settings > " + productName + " > Setup InputManager Settings'." );
}
}
[MenuItem( "Edit/Project Settings/" + productName + "/Setup InputManager Settings" )]
static void GenerateInputManagerAsset()
{
ApplyAxisPresets();
Debug.Log( productName + " has successfully generated new InputManager settings." );
}
[MenuItem( "Edit/Project Settings/" + productName + "/Check InputManager Settings" )]
static void CheckInputManagerAsset()
{
if (CheckAxisPresets())
{
Debug.Log( "InputManager settings are fine." );
}
else
{
Debug.LogError( productName + " has detected invalid InputManager settings. To fix, execute 'Edit > Project Settings > " + productName + " > Setup InputManager Settings'." );
}
}
static bool CheckAxisPresets()
{
SetupAxisPresets();
var axisArray = GetInputManagerAxisArray();
if (axisArray.arraySize != axisPresets.Count)
{
return false;
}
for (int i = 0; i < axisPresets.Count; i++)
{
var axisEntry = axisArray.GetArrayElementAtIndex( i );
if (!axisPresets[i].EqualTo( axisEntry ))
{
return false;
}
}
return true;
}
static void ApplyAxisPresets()
{
SetupAxisPresets();
var inputManagerAsset = AssetDatabase.LoadAllAssetsAtPath( "ProjectSettings/InputManager.asset" )[0];
var serializedObject = new SerializedObject( inputManagerAsset );
var axisArray = serializedObject.FindProperty( "m_Axes" );
axisArray.arraySize = axisPresets.Count;
serializedObject.ApplyModifiedProperties();
for (int i = 0; i < axisPresets.Count; i++)
{
var axisEntry = axisArray.GetArrayElementAtIndex( i );
axisPresets[i].ApplyTo( ref axisEntry );
}
serializedObject.ApplyModifiedProperties();
AssetDatabase.Refresh();
}
static void SetupAxisPresets()
{
axisPresets.Clear();
CreateRequiredAxisPresets();
ImportExistingAxisPresets();
CreateCompatibilityAxisPresets();
}
static void CreateRequiredAxisPresets()
{
for (int device = 1; device <= UnityInputDevice.MaxDevices; device++)
{
for (int analog = 0; analog < UnityInputDevice.MaxAnalogs; analog++)
{
axisPresets.Add( new AxisPreset( device, analog ) );
}
}
axisPresets.Add( new AxisPreset( "mouse x", 1, 0, 1.0f ) );
axisPresets.Add( new AxisPreset( "mouse y", 1, 1, 1.0f ) );
axisPresets.Add( new AxisPreset( "mouse z", 1, 2, 1.0f ) );
}
static void ImportExistingAxisPresets()
{
var axisArray = GetInputManagerAxisArray();
for (int i = 0; i < axisArray.arraySize; i++)
{
var axisEntry = axisArray.GetArrayElementAtIndex( i );
var axisPreset = new AxisPreset( axisEntry );
if (!axisPreset.ReservedName)
{
axisPresets.Add( axisPreset );
}
}
}
static void CreateCompatibilityAxisPresets()
{
if (!HasAxisPreset( "Mouse ScrollWheel" ))
{
axisPresets.Add( new AxisPreset( "Mouse ScrollWheel", 1, 2, 0.1f ) );
}
if (!HasAxisPreset( "Horizontal" ))
{
axisPresets.Add( new AxisPreset() {
name = "Horizontal",
negativeButton = "left",
positiveButton = "right",
altNegativeButton = "a",
altPositiveButton = "d",
gravity = 3.0f,
deadZone = 0.001f,
sensitivity = 3.0f,
snap = true,
type = 0,
axis = 0,
joyNum = 0
} );
axisPresets.Add( new AxisPreset() {
name = "Horizontal",
gravity = 0.0f,
deadZone = 0.19f,
sensitivity = 1.0f,
type = 2,
axis = 0,
joyNum = 0
} );
}
if (!HasAxisPreset( "Vertical" ))
{
axisPresets.Add( new AxisPreset() {
name = "Vertical",
negativeButton = "down",
positiveButton = "up",
altNegativeButton = "s",
altPositiveButton = "w",
gravity = 3.0f,
deadZone = 0.001f,
sensitivity = 3.0f,
snap = true,
type = 0,
axis = 0,
joyNum = 0
} );
axisPresets.Add( new AxisPreset() {
name = "Vertical",
gravity = 0.0f,
deadZone = 0.19f,
sensitivity = 1.0f,
type = 2,
axis = 0,
invert = true,
joyNum = 0
} );
}
if (!HasAxisPreset( "Submit" ))
{
axisPresets.Add( new AxisPreset() {
name = "Submit",
positiveButton = "return",
altPositiveButton = "joystick button 0",
gravity = 1000.0f,
deadZone = 0.001f,
sensitivity = 1000.0f,
type = 0,
axis = 0,
joyNum = 0
} );
axisPresets.Add( new AxisPreset() {
name = "Submit",
positiveButton = "enter",
altPositiveButton = "space",
gravity = 1000.0f,
deadZone = 0.001f,
sensitivity = 1000.0f,
type = 0,
axis = 0,
joyNum = 0
} );
}
if (!HasAxisPreset( "Cancel" ))
{
axisPresets.Add( new AxisPreset() {
name = "Cancel",
positiveButton = "escape",
altPositiveButton = "joystick button 1",
gravity = 1000.0f,
deadZone = 0.001f,
sensitivity = 1000.0f,
type = 0,
axis = 0,
joyNum = 0
} );
}
}
static bool HasAxisPreset( string name )
{
for (int i = 0; i < axisPresets.Count; i++)
{
if (axisPresets[i].name == name)
{
return true;
}
}
return false;
}
static SerializedProperty GetInputManagerAxisArray()
{
var inputManagerAsset = AssetDatabase.LoadAllAssetsAtPath( "ProjectSettings/InputManager.asset" )[0];
var serializedObject = new SerializedObject( inputManagerAsset );
return serializedObject.FindProperty( "m_Axes" );
}
static SerializedProperty GetChildProperty( SerializedProperty parent, string name )
{
SerializedProperty child = parent.Copy();
child.Next( true );
do
{
if (child.name == name)
{
return child;
}
} while (child.Next( false ));
return null;
}
internal class AxisPreset
{
public string name;
public string descriptiveName;
public string descriptiveNegativeName;
public string negativeButton;
public string positiveButton;
public string altNegativeButton;
public string altPositiveButton;
public float gravity;
public float deadZone = 0.001f;
public float sensitivity = 1.0f;
public bool snap;
public bool invert;
public int type;
public int axis;
public int joyNum;
public AxisPreset()
{
}
public AxisPreset( SerializedProperty axisPreset )
{
this.name = GetChildProperty( axisPreset, "m_Name" ).stringValue;
this.descriptiveName = GetChildProperty( axisPreset, "descriptiveName" ).stringValue;
this.descriptiveNegativeName = GetChildProperty( axisPreset, "descriptiveNegativeName" ).stringValue;
this.negativeButton = GetChildProperty( axisPreset, "negativeButton" ).stringValue;
this.positiveButton = GetChildProperty( axisPreset, "positiveButton" ).stringValue;
this.altNegativeButton = GetChildProperty( axisPreset, "altNegativeButton" ).stringValue;
this.altPositiveButton = GetChildProperty( axisPreset, "altPositiveButton" ).stringValue;
this.gravity = GetChildProperty( axisPreset, "gravity" ).floatValue;
this.deadZone = GetChildProperty( axisPreset, "dead" ).floatValue;
this.sensitivity = GetChildProperty( axisPreset, "sensitivity" ).floatValue;
this.snap = GetChildProperty( axisPreset, "snap" ).boolValue;
this.invert = GetChildProperty( axisPreset, "invert" ).boolValue;
this.type = GetChildProperty( axisPreset, "type" ).intValue;
this.axis = GetChildProperty( axisPreset, "axis" ).intValue;
this.joyNum = GetChildProperty( axisPreset, "joyNum" ).intValue;
}
public AxisPreset( string name, int type, int axis, float sensitivity )
{
this.name = name;
this.descriptiveName = "";
this.descriptiveNegativeName = "";
this.negativeButton = "";
this.positiveButton = "";
this.altNegativeButton = "";
this.altPositiveButton = "";
this.gravity = 0.0f;
this.deadZone = 0.001f;
this.sensitivity = sensitivity;
this.snap = false;
this.invert = false;
this.type = type;
this.axis = axis;
this.joyNum = 0;
}
public AxisPreset( int device, int analog )
{
this.name = string.Format( "joystick {0} analog {1}", device, analog );
this.descriptiveName = "";
this.descriptiveNegativeName = "";
this.negativeButton = "";
this.positiveButton = "";
this.altNegativeButton = "";
this.altPositiveButton = "";
this.gravity = 0.0f;
this.deadZone = 0.001f;
this.sensitivity = 1.0f;
this.snap = false;
this.invert = false;
this.type = 2;
this.axis = analog;
this.joyNum = device;
}
public bool ReservedName
{
get
{
if (Regex.Match( name, @"^joystick \d+ analog \d+$" ).Success ||
Regex.Match( name, @"^mouse (x|y|z)$" ).Success)
{
return true;
}
return false;
}
}
public void ApplyTo( ref SerializedProperty axisPreset )
{
GetChildProperty( axisPreset, "m_Name" ).stringValue = name;
GetChildProperty( axisPreset, "descriptiveName" ).stringValue = descriptiveName;
GetChildProperty( axisPreset, "descriptiveNegativeName" ).stringValue = descriptiveNegativeName;
GetChildProperty( axisPreset, "negativeButton" ).stringValue = negativeButton;
GetChildProperty( axisPreset, "positiveButton" ).stringValue = positiveButton;
GetChildProperty( axisPreset, "altNegativeButton" ).stringValue = altNegativeButton;
GetChildProperty( axisPreset, "altPositiveButton" ).stringValue = altPositiveButton;
GetChildProperty( axisPreset, "gravity" ).floatValue = gravity;
GetChildProperty( axisPreset, "dead" ).floatValue = deadZone;
GetChildProperty( axisPreset, "sensitivity" ).floatValue = sensitivity;
GetChildProperty( axisPreset, "snap" ).boolValue = snap;
GetChildProperty( axisPreset, "invert" ).boolValue = invert;
GetChildProperty( axisPreset, "type" ).intValue = type;
GetChildProperty( axisPreset, "axis" ).intValue = axis;
GetChildProperty( axisPreset, "joyNum" ).intValue = joyNum;
}
public bool EqualTo( SerializedProperty axisPreset )
{
if (GetChildProperty( axisPreset, "m_Name" ).stringValue != name)
return false;
if (GetChildProperty( axisPreset, "descriptiveName" ).stringValue != descriptiveName)
return false;
if (GetChildProperty( axisPreset, "descriptiveNegativeName" ).stringValue != descriptiveNegativeName)
return false;
if (GetChildProperty( axisPreset, "negativeButton" ).stringValue != negativeButton)
return false;
if (GetChildProperty( axisPreset, "positiveButton" ).stringValue != positiveButton)
return false;
if (GetChildProperty( axisPreset, "altNegativeButton" ).stringValue != altNegativeButton)
return false;
if (GetChildProperty( axisPreset, "altPositiveButton" ).stringValue != altPositiveButton)
return false;
if (!Utility.Approximately( GetChildProperty( axisPreset, "gravity" ).floatValue, gravity ))
return false;
if (!Utility.Approximately( GetChildProperty( axisPreset, "dead" ).floatValue, deadZone ))
return false;
if (!Utility.Approximately( GetChildProperty( axisPreset, "sensitivity" ).floatValue, this.sensitivity ))
return false;
if (GetChildProperty( axisPreset, "snap" ).boolValue != snap)
return false;
if (GetChildProperty( axisPreset, "invert" ).boolValue != invert)
return false;
if (GetChildProperty( axisPreset, "type" ).intValue != type)
return false;
if (GetChildProperty( axisPreset, "axis" ).intValue != axis)
return false;
if (GetChildProperty( axisPreset, "joyNum" ).intValue != joyNum)
return false;
return true;
}
}
}
}
#endif
| |
using System;
using UnityEngine;
[AddComponentMenu("NGUI/UI/NGUI Unity2D Sprite"), ExecuteInEditMode]
public class UI2DSprite : UIWidget
{
[HideInInspector, SerializeField]
private Sprite mSprite;
[HideInInspector, SerializeField]
private Material mMat;
[HideInInspector, SerializeField]
private Shader mShader;
public Sprite nextSprite;
private int mPMA = -1;
public Sprite sprite2D
{
get
{
return this.mSprite;
}
set
{
if (this.mSprite != value)
{
base.RemoveFromPanel();
this.mSprite = value;
this.nextSprite = null;
this.MarkAsChanged();
}
}
}
public override Material material
{
get
{
return this.mMat;
}
set
{
if (this.mMat != value)
{
base.RemoveFromPanel();
this.mMat = value;
this.mPMA = -1;
this.MarkAsChanged();
}
}
}
public override Shader shader
{
get
{
if (this.mMat != null)
{
return this.mMat.shader;
}
if (this.mShader == null)
{
this.mShader = Shader.Find("Unlit/Transparent Colored");
}
return this.mShader;
}
set
{
if (this.mShader != value)
{
base.RemoveFromPanel();
this.mShader = value;
if (this.mMat == null)
{
this.mPMA = -1;
this.MarkAsChanged();
}
}
}
}
public override Texture mainTexture
{
get
{
if (this.mSprite != null)
{
return this.mSprite.texture;
}
if (this.mMat != null)
{
return this.mMat.mainTexture;
}
return null;
}
}
public bool premultipliedAlpha
{
get
{
if (this.mPMA == -1)
{
Shader shader = this.shader;
this.mPMA = ((!(shader != null) || !shader.name.Contains("Premultiplied")) ? 0 : 1);
}
return this.mPMA == 1;
}
}
public override Vector4 drawingDimensions
{
get
{
Vector2 pivotOffset = base.pivotOffset;
float num = -pivotOffset.x * (float)this.mWidth;
float num2 = -pivotOffset.y * (float)this.mHeight;
float num3 = num + (float)this.mWidth;
float num4 = num2 + (float)this.mHeight;
int num5 = (!(this.mSprite != null)) ? this.mWidth : Mathf.RoundToInt(this.mSprite.textureRect.width);
int num6 = (!(this.mSprite != null)) ? this.mHeight : Mathf.RoundToInt(this.mSprite.textureRect.height);
if ((num5 & 1) != 0)
{
num3 -= 1f / (float)num5 * (float)this.mWidth;
}
if ((num6 & 1) != 0)
{
num4 -= 1f / (float)num6 * (float)this.mHeight;
}
return new Vector4((this.mDrawRegion.x != 0f) ? Mathf.Lerp(num, num3, this.mDrawRegion.x) : num, (this.mDrawRegion.y != 0f) ? Mathf.Lerp(num2, num4, this.mDrawRegion.y) : num2, (this.mDrawRegion.z != 1f) ? Mathf.Lerp(num, num3, this.mDrawRegion.z) : num3, (this.mDrawRegion.w != 1f) ? Mathf.Lerp(num2, num4, this.mDrawRegion.w) : num4);
}
}
public Rect uvRect
{
get
{
Texture mainTexture = this.mainTexture;
if (mainTexture != null)
{
Rect textureRect = this.mSprite.textureRect;
textureRect.xMin /= (float)mainTexture.width;
textureRect.xMax /= (float)mainTexture.width;
textureRect.yMin /= (float)mainTexture.height;
textureRect.yMax /= (float)mainTexture.height;
return textureRect;
}
return new Rect(0f, 0f, 1f, 1f);
}
}
protected override void OnUpdate()
{
if (this.nextSprite != null)
{
if (this.nextSprite != this.mSprite)
{
this.sprite2D = this.nextSprite;
}
this.nextSprite = null;
}
base.OnUpdate();
}
public override void MakePixelPerfect()
{
if (this.mSprite != null)
{
Rect textureRect = this.mSprite.textureRect;
int num = Mathf.RoundToInt(textureRect.width);
int num2 = Mathf.RoundToInt(textureRect.height);
if ((num & 1) == 1)
{
num++;
}
if ((num2 & 1) == 1)
{
num2++;
}
base.width = num;
base.height = num2;
}
base.MakePixelPerfect();
}
public override void OnFill(BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols)
{
Color color = base.color;
color.a = this.finalAlpha;
Color32 item = (!this.premultipliedAlpha) ? color : NGUITools.ApplyPMA(color);
Vector4 drawingDimensions = this.drawingDimensions;
Rect uvRect = this.uvRect;
Vector3 zero = Vector3.zero;
zero.x = drawingDimensions.x;
zero.y = drawingDimensions.y;
verts.Add(zero);
zero.x = drawingDimensions.x;
zero.y = drawingDimensions.w;
verts.Add(zero);
zero.x = drawingDimensions.z;
zero.y = drawingDimensions.w;
verts.Add(zero);
zero.x = drawingDimensions.z;
zero.y = drawingDimensions.y;
verts.Add(zero);
Vector2 zero2 = Vector2.zero;
zero2.x = uvRect.xMin;
zero2.y = uvRect.yMin;
uvs.Add(zero2);
zero2.x = uvRect.xMin;
zero2.y = uvRect.yMax;
uvs.Add(zero2);
zero2.x = uvRect.xMax;
zero2.y = uvRect.yMax;
uvs.Add(zero2);
zero2.x = uvRect.xMax;
zero2.y = uvRect.yMin;
uvs.Add(zero2);
cols.Add(item);
cols.Add(item);
cols.Add(item);
cols.Add(item);
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.Cci.Filters;
using Microsoft.Cci.Writers.CSharp;
using Microsoft.Cci.Writers.Syntax;
namespace Microsoft.Cci.Extensions.CSharp
{
public static class CSharpCciExtensions
{
public static string GetCSharpDeclaration(this IDefinition definition, bool includeAttributes = false)
{
using (var stringWriter = new StringWriter())
{
using (var syntaxWriter = new TextSyntaxWriter(stringWriter))
{
var writer = new CSDeclarationWriter(syntaxWriter, new AttributesFilter(includeAttributes), false, true);
var nsp = definition as INamespaceDefinition;
var typeDefinition = definition as ITypeDefinition;
var member = definition as ITypeDefinitionMember;
if (nsp != null)
writer.WriteNamespaceDeclaration(nsp);
else if (typeDefinition != null)
writer.WriteTypeDeclaration(typeDefinition);
else if (member != null)
{
var method = member as IMethodDefinition;
if (method != null && method.IsPropertyOrEventAccessor())
WriteAccessor(syntaxWriter, method);
else
writer.WriteMemberDeclaration(member);
}
}
return stringWriter.ToString();
}
}
private static void WriteAccessor(ISyntaxWriter syntaxWriter, IMethodDefinition method)
{
var accessorKeyword = GetAccessorKeyword(method);
syntaxWriter.WriteKeyword(accessorKeyword);
syntaxWriter.WriteSymbol(";");
}
private static string GetAccessorKeyword(IMethodDefinition method)
{
switch (method.GetAccessorType())
{
case AccessorType.EventAdder:
return "add";
case AccessorType.EventRemover:
return "remove";
case AccessorType.PropertySetter:
return "set";
case AccessorType.PropertyGetter:
return "get";
default:
throw new ArgumentOutOfRangeException();
}
}
public static bool IsDefaultCSharpBaseType(this ITypeReference baseType, ITypeDefinition type)
{
Contract.Requires(baseType != null);
Contract.Requires(type != null);
if (baseType.AreEquivalent("System.Object"))
return true;
if (type.IsValueType && baseType.AreEquivalent("System.ValueType"))
return true;
if (type.IsEnum && baseType.AreEquivalent("System.Enum"))
return true;
return false;
}
public static IMethodDefinition GetInvokeMethod(this ITypeDefinition type)
{
if (!type.IsDelegate)
return null;
foreach (var method in type.Methods)
if (method.Name.Value == "Invoke")
return method;
throw new InvalidOperationException(String.Format("All delegates should have an Invoke method, but {0} doesn't have one.", type.FullName()));
}
public static ITypeReference GetEnumType(this ITypeDefinition type)
{
if (!type.IsEnum)
return null;
foreach (var field in type.Fields)
if (field.Name.Value == "value__")
return field.Type;
throw new InvalidOperationException("All enums should have a value__ field!");
}
public static bool IsConversionOperator(this IMethodDefinition method)
{
return (method.IsSpecialName &&
(method.Name.Value == "op_Explicit" || method.Name.Value == "op_Implicit"));
}
public static bool IsExplicitInterfaceMember(this ITypeDefinitionMember member)
{
var method = member as IMethodDefinition;
if (method != null)
{
return method.IsExplicitInterfaceMethod();
}
var property = member as IPropertyDefinition;
if (property != null)
{
return property.IsExplicitInterfaceProperty();
}
return false;
}
public static bool IsExplicitInterfaceMethod(this IMethodDefinition method)
{
return MemberHelper.GetExplicitlyOverriddenMethods(method).Any();
}
public static bool IsExplicitInterfaceProperty(this IPropertyDefinition property)
{
if (property.Getter != null && property.Getter.ResolvedMethod != null)
{
return property.Getter.ResolvedMethod.IsExplicitInterfaceMethod();
}
if (property.Setter != null && property.Setter.ResolvedMethod != null)
{
return property.Setter.ResolvedMethod.IsExplicitInterfaceMethod();
}
return false;
}
public static bool IsInterfaceImplementation(this ITypeDefinitionMember member)
{
IMethodDefinition method = member as IMethodDefinition;
if (method != null)
return method.IsInterfaceImplementation();
IPropertyDefinition property = member as IPropertyDefinition;
if (property != null)
return property.Accessors.Any(m => m.ResolvedMethod.IsInterfaceImplementation());
IEventDefinition evnt = member as IEventDefinition;
if (evnt != null)
return evnt.Accessors.Any(m => m.ResolvedMethod.IsInterfaceImplementation());
return false;
}
public static bool IsInterfaceImplementation(this IMethodDefinition method)
{
return MemberHelper.GetImplicitlyImplementedInterfaceMethods(method).Any()
|| MemberHelper.GetExplicitlyOverriddenMethods(method).Any();
}
public static bool IsAbstract(this ITypeDefinitionMember member)
{
IMethodDefinition method = member as IMethodDefinition;
if (method != null)
return method.IsAbstract;
IPropertyDefinition property = member as IPropertyDefinition;
if (property != null)
return property.Accessors.Any(m => m.ResolvedMethod.IsAbstract);
IEventDefinition evnt = member as IEventDefinition;
if (evnt != null)
return evnt.Accessors.Any(m => m.ResolvedMethod.IsAbstract);
return false;
}
public static bool IsVirtual(this ITypeDefinitionMember member)
{
IMethodDefinition method = member as IMethodDefinition;
if (method != null)
return method.IsVirtual;
IPropertyDefinition property = member as IPropertyDefinition;
if (property != null)
return property.Accessors.Any(m => m.ResolvedMethod.IsVirtual);
IEventDefinition evnt = member as IEventDefinition;
if (evnt != null)
return evnt.Accessors.Any(m => m.ResolvedMethod.IsVirtual);
return false;
}
public static bool IsNewSlot(this ITypeDefinitionMember member)
{
IMethodDefinition method = member as IMethodDefinition;
if (method != null)
return method.IsNewSlot;
IPropertyDefinition property = member as IPropertyDefinition;
if (property != null)
return property.Accessors.Any(m => m.ResolvedMethod.IsNewSlot);
IEventDefinition evnt = member as IEventDefinition;
if (evnt != null)
return evnt.Accessors.Any(m => m.ResolvedMethod.IsNewSlot);
return false;
}
public static bool IsSealed(this ITypeDefinitionMember member)
{
IMethodDefinition method = member as IMethodDefinition;
if (method != null)
return method.IsSealed;
IPropertyDefinition property = member as IPropertyDefinition;
if (property != null)
return property.Accessors.Any(m => m.ResolvedMethod.IsSealed);
IEventDefinition evnt = member as IEventDefinition;
if (evnt != null)
return evnt.Accessors.Any(m => m.ResolvedMethod.IsSealed);
return false;
}
public static bool IsOverride(this ITypeDefinitionMember member)
{
IMethodDefinition method = member as IMethodDefinition;
if (method != null)
return method.IsOverride();
IPropertyDefinition property = member as IPropertyDefinition;
if (property != null)
return property.Accessors.Any(m => m.ResolvedMethod.IsOverride());
IEventDefinition evnt = member as IEventDefinition;
if (evnt != null)
return evnt.Accessors.Any(m => m.ResolvedMethod.IsOverride());
return false;
}
public static bool IsOverride(this IMethodDefinition method)
{
return method.IsVirtual && !method.IsNewSlot;
}
public static bool IsUnsafeType(this ITypeReference type)
{
return type.TypeCode == PrimitiveTypeCode.Pointer;
}
public static bool IsMethodUnsafe(this IMethodDefinition method)
{
foreach (var p in method.Parameters)
{
if (p.Type.IsUnsafeType())
return true;
}
if (method.Type.IsUnsafeType())
return true;
return false;
}
public static bool IsDestructor(this IMethodDefinition methodDefinition)
{
if (methodDefinition.ContainingTypeDefinition.IsValueType) return false; //only classes can have destructors
if (methodDefinition.ParameterCount == 0 && methodDefinition.IsVirtual &&
methodDefinition.Visibility == TypeMemberVisibility.Family && methodDefinition.Name.Value == "Finalize")
{
// Should we make sure that this Finalize method overrides the protected System.Object.Finalize?
return true;
}
return false;
}
public static bool IsAssembly(this ITypeDefinitionMember member)
{
return member.Visibility == TypeMemberVisibility.FamilyAndAssembly ||
member.Visibility == TypeMemberVisibility.Assembly;
}
public static bool InSameUnit(ITypeDefinitionMember member1, ITypeDefinitionMember member2)
{
IUnit unit1 = TypeHelper.GetDefiningUnit(member1.ContainingTypeDefinition);
IUnit unit2 = TypeHelper.GetDefiningUnit(member2.ContainingTypeDefinition);
return UnitHelper.UnitsAreEquivalent(unit1, unit2);
}
public static ITypeReference GetReturnType(this ITypeDefinitionMember member)
{
IMethodDefinition method = member as IMethodDefinition;
if (method != null)
return method.Type;
IPropertyDefinition property = member as IPropertyDefinition;
if (property != null)
return property.Type;
IEventDefinition evnt = member as IEventDefinition;
if (evnt != null)
return evnt.Type;
IFieldDefinition field = member as IFieldDefinition;
if (field != null)
return field.Type;
return null;
}
public static IFieldDefinition GetHiddenBaseField(this IFieldDefinition field, ICciFilter filter = null)
{
foreach (ITypeReference baseClassRef in field.ContainingTypeDefinition.GetAllBaseTypes())
{
ITypeDefinition baseClass = baseClassRef.ResolvedType;
foreach (IFieldDefinition baseField in baseClass.GetMembersNamed(field.Name, false).OfType<IFieldDefinition>())
{
if (baseField.Visibility == TypeMemberVisibility.Private) continue;
if (IsAssembly(baseField) && !InSameUnit(baseField, field))
continue;
if (filter != null && !filter.Include(baseField))
continue;
return baseField;
}
}
return Dummy.Field;
}
public static IEventDefinition GetHiddenBaseEvent(this IEventDefinition evnt, ICciFilter filter = null)
{
IMethodDefinition eventRep = evnt.Adder.ResolvedMethod;
if (eventRep.IsVirtual && !eventRep.IsNewSlot) return Dummy.Event; // an override
foreach (ITypeReference baseClassRef in evnt.ContainingTypeDefinition.GetAllBaseTypes())
{
ITypeDefinition baseClass = baseClassRef.ResolvedType;
foreach (IEventDefinition baseEvent in baseClass.GetMembersNamed(evnt.Name, false).OfType<IEventDefinition>())
{
if (baseEvent.Visibility == TypeMemberVisibility.Private) continue;
if (IsAssembly(baseEvent) && !InSameUnit(baseEvent, evnt))
continue;
if (filter != null && !filter.Include(baseEvent))
continue;
return baseEvent;
}
}
return Dummy.Event;
}
public static IPropertyDefinition GetHiddenBaseProperty(this IPropertyDefinition property, ICciFilter filter = null)
{
IMethodDefinition propertyRep = property.Accessors.First().ResolvedMethod;
if (propertyRep.IsVirtual && !propertyRep.IsNewSlot) return Dummy.Property; // an override
ITypeDefinition type = property.ContainingTypeDefinition;
foreach (ITypeReference baseClassRef in type.GetAllBaseTypes())
{
ITypeDefinition baseClass = baseClassRef.ResolvedType;
foreach (IPropertyDefinition baseProperty in baseClass.GetMembersNamed(property.Name, false).OfType<IPropertyDefinition>())
{
if (baseProperty.Visibility == TypeMemberVisibility.Private) continue;
if (IsAssembly(baseProperty) && !InSameUnit(baseProperty, property))
continue;
if (filter != null && !filter.Include(baseProperty))
continue;
if (SignaturesParametersAreEqual(property, baseProperty))
return baseProperty;
}
}
return Dummy.Property;
}
public static IMethodDefinition GetHiddenBaseMethod(this IMethodDefinition method, ICciFilter filter = null)
{
if (method.IsConstructor) return Dummy.Method;
if (method.IsVirtual && !method.IsNewSlot) return Dummy.Method; // an override
ITypeDefinition type = method.ContainingTypeDefinition;
foreach (ITypeReference baseClassRef in type.GetAllBaseTypes())
{
ITypeDefinition baseClass = baseClassRef.ResolvedType;
foreach (IMethodDefinition baseMethod in baseClass.GetMembersNamed(method.Name, false).OfType<IMethodDefinition>())
{
if (baseMethod.Visibility == TypeMemberVisibility.Private) continue;
if (IsAssembly(baseMethod) && !InSameUnit(baseMethod, method))
continue;
if (filter != null && !filter.Include(baseMethod))
continue;
// NOTE: Do not check method.IsHiddenBySignature here. C# is *always* hide-by-signature regardless of the metadata flag.
// Do not check return type here, C# hides based on parameter types alone.
if (SignaturesParametersAreEqual(method, baseMethod))
{
if (!method.IsGeneric && !baseMethod.IsGeneric)
return baseMethod;
if (method.GenericParameterCount == baseMethod.GenericParameterCount)
return baseMethod;
}
}
}
return Dummy.Method;
}
public static bool SignaturesParametersAreEqual(this ISignature sig1, ISignature sig2)
{
return IteratorHelper.EnumerablesAreEqual<IParameterTypeInformation>(sig1.Parameters, sig2.Parameters, new ParameterInformationComparer());
}
private static Regex s_isKeywordRegex;
public static bool IsKeyword(string s)
{
if (s_isKeywordRegex == null)
s_isKeywordRegex = new Regex("^(abstract|as|break|case|catch|checked|class|const|continue|default|delegate|do|else|enum|event|explicit|extern|finally|foreach|for|get|goto|if|implicit|interface|internal|in|is|lock|namespace|new|operator|out|override|params|partial|private|protected|public|readonly|ref|return|sealed|set|sizeof|stackalloc|static|struct|switch|this|throw|try|typeof|unchecked|unsafe|using|virtual|volatile|while|yield|bool|byte|char|decimal|double|fixed|float|int|long|object|sbyte|short|string|uint|ulong|ushort|void)$", RegexOptions.Compiled);
return s_isKeywordRegex.IsMatch(s);
}
public static string GetMethodName(this IMethodDefinition method)
{
if (method.IsConstructor)
{
INamedEntity named = method.ContainingTypeDefinition.UnWrap() as INamedEntity;
if (named != null)
return named.Name.Value;
}
switch (method.Name.Value)
{
case "op_Decrement": return "operator --";
case "op_Increment": return "operator ++";
case "op_UnaryNegation": return "operator -";
case "op_UnaryPlus": return "operator +";
case "op_LogicalNot": return "operator !";
case "op_OnesComplement": return "operator ~";
case "op_True": return "operator true";
case "op_False": return "operator false";
case "op_Addition": return "operator +";
case "op_Subtraction": return "operator -";
case "op_Multiply": return "operator *";
case "op_Division": return "operator /";
case "op_Modulus": return "operator %";
case "op_ExclusiveOr": return "operator ^";
case "op_BitwiseAnd": return "operator &";
case "op_BitwiseOr": return "operator |";
case "op_LeftShift": return "operator <<";
case "op_RightShift": return "operator >>";
case "op_Equality": return "operator ==";
case "op_GreaterThan": return "operator >";
case "op_LessThan": return "operator <";
case "op_Inequality": return "operator !=";
case "op_GreaterThanOrEqual": return "operator >=";
case "op_LessThanOrEqual": return "operator <=";
case "op_Explicit": return "explicit operator";
case "op_Implicit": return "implicit operator";
default: return method.Name.Value; // return just the name
}
}
public static string GetNameWithoutExplicitType(this ITypeDefinitionMember member)
{
string name = member.Name.Value;
int index = name.LastIndexOf(".");
if (index < 0)
return name;
return name.Substring(index + 1);
}
public static bool IsExtensionMethod(this IMethodDefinition method)
{
if (!method.IsStatic)
return false;
return method.Attributes.Any(a => a.Type.AreEquivalent("System.Runtime.CompilerServices.ExtensionAttribute"));
}
public static bool IsEffectivelySealed(this ITypeDefinition type)
{
if (type.IsSealed)
return true;
if (type.IsInterface)
return false;
// Types with only private constructors are effectively sealed
if (!type.Methods
.Any(m =>
m.IsConstructor &&
!m.IsStaticConstructor &&
m.IsVisibleOutsideAssembly()))
return true;
return false;
}
public static bool IsException(this ITypeDefinition type)
{
foreach (var baseTypeRef in type.GetBaseTypes())
{
if (baseTypeRef.AreEquivalent("System.Exception"))
return true;
}
return false;
}
public static bool IsAttribute(this ITypeDefinition type)
{
foreach (var baseTypeRef in type.GetBaseTypes())
{
if (baseTypeRef.AreEquivalent("System.Attribute"))
return true;
}
return false;
}
private static IEnumerable<ITypeReference> GetBaseTypes(this ITypeReference typeRef)
{
ITypeDefinition type = typeRef.GetDefinitionOrNull();
if (type == null)
yield break;
foreach (var baseTypeRef in type.BaseClasses)
{
yield return baseTypeRef;
foreach (var nestedBaseTypeRef in GetBaseTypes(baseTypeRef))
yield return nestedBaseTypeRef;
}
}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the ds-2015-04-16.normal.json service model.
*/
using System;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using Amazon.DirectoryService.Model;
using Amazon.DirectoryService.Model.Internal.MarshallTransformations;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Auth;
using Amazon.Runtime.Internal.Transform;
namespace Amazon.DirectoryService
{
/// <summary>
/// Implementation for accessing DirectoryService
///
/// AWS Directory Service
/// <para>
/// This is the <i>AWS Directory Service API Reference</i>. This guide provides detailed
/// information about AWS Directory Service operations, data types, parameters, and errors.
/// </para>
/// </summary>
public partial class AmazonDirectoryServiceClient : AmazonServiceClient, IAmazonDirectoryService
{
#region Constructors
/// <summary>
/// Constructs AmazonDirectoryServiceClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
public AmazonDirectoryServiceClient()
: base(FallbackCredentialsFactory.GetCredentials(), new AmazonDirectoryServiceConfig()) { }
/// <summary>
/// Constructs AmazonDirectoryServiceClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="region">The region to connect.</param>
public AmazonDirectoryServiceClient(RegionEndpoint region)
: base(FallbackCredentialsFactory.GetCredentials(), new AmazonDirectoryServiceConfig{RegionEndpoint = region}) { }
/// <summary>
/// Constructs AmazonDirectoryServiceClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="config">The AmazonDirectoryServiceClient Configuration Object</param>
public AmazonDirectoryServiceClient(AmazonDirectoryServiceConfig config)
: base(FallbackCredentialsFactory.GetCredentials(), config) { }
/// <summary>
/// Constructs AmazonDirectoryServiceClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
public AmazonDirectoryServiceClient(AWSCredentials credentials)
: this(credentials, new AmazonDirectoryServiceConfig())
{
}
/// <summary>
/// Constructs AmazonDirectoryServiceClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="region">The region to connect.</param>
public AmazonDirectoryServiceClient(AWSCredentials credentials, RegionEndpoint region)
: this(credentials, new AmazonDirectoryServiceConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonDirectoryServiceClient with AWS Credentials and an
/// AmazonDirectoryServiceClient Configuration object.
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="clientConfig">The AmazonDirectoryServiceClient Configuration Object</param>
public AmazonDirectoryServiceClient(AWSCredentials credentials, AmazonDirectoryServiceConfig clientConfig)
: base(credentials, clientConfig)
{
}
/// <summary>
/// Constructs AmazonDirectoryServiceClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
public AmazonDirectoryServiceClient(string awsAccessKeyId, string awsSecretAccessKey)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonDirectoryServiceConfig())
{
}
/// <summary>
/// Constructs AmazonDirectoryServiceClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="region">The region to connect.</param>
public AmazonDirectoryServiceClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonDirectoryServiceConfig() {RegionEndpoint=region})
{
}
/// <summary>
/// Constructs AmazonDirectoryServiceClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonDirectoryServiceClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="clientConfig">The AmazonDirectoryServiceClient Configuration Object</param>
public AmazonDirectoryServiceClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonDirectoryServiceConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, clientConfig)
{
}
/// <summary>
/// Constructs AmazonDirectoryServiceClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
public AmazonDirectoryServiceClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonDirectoryServiceConfig())
{
}
/// <summary>
/// Constructs AmazonDirectoryServiceClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="region">The region to connect.</param>
public AmazonDirectoryServiceClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonDirectoryServiceConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonDirectoryServiceClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonDirectoryServiceClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="clientConfig">The AmazonDirectoryServiceClient Configuration Object</param>
public AmazonDirectoryServiceClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonDirectoryServiceConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, clientConfig)
{
}
#endregion
#region Overrides
/// <summary>
/// Creates the signer for the service.
/// </summary>
protected override AbstractAWSSigner CreateSigner()
{
return new AWS4Signer();
}
#endregion
#region Dispose
/// <summary>
/// Disposes the service client.
/// </summary>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
#endregion
#region ConnectDirectory
/// <summary>
/// Creates an AD Connector to connect an on-premises directory.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ConnectDirectory service method.</param>
///
/// <returns>The response from the ConnectDirectory service method, as returned by DirectoryService.</returns>
/// <exception cref="Amazon.DirectoryService.Model.ClientException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.DirectoryLimitExceededException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.InvalidParameterException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.ServiceException">
///
/// </exception>
public ConnectDirectoryResponse ConnectDirectory(ConnectDirectoryRequest request)
{
var marshaller = new ConnectDirectoryRequestMarshaller();
var unmarshaller = ConnectDirectoryResponseUnmarshaller.Instance;
return Invoke<ConnectDirectoryRequest,ConnectDirectoryResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the ConnectDirectory operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ConnectDirectory operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<ConnectDirectoryResponse> ConnectDirectoryAsync(ConnectDirectoryRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new ConnectDirectoryRequestMarshaller();
var unmarshaller = ConnectDirectoryResponseUnmarshaller.Instance;
return InvokeAsync<ConnectDirectoryRequest,ConnectDirectoryResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region CreateAlias
/// <summary>
/// Creates an alias for a directory and assigns the alias to the directory. The alias
/// is used to construct the access URL for the directory, such as <code>http://<alias>.awsapps.com</code>.
///
/// <important>
/// <para>
/// After an alias has been created, it cannot be deleted or reused, so this operation
/// should only be used when absolutely necessary.
/// </para>
/// </important>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateAlias service method.</param>
///
/// <returns>The response from the CreateAlias service method, as returned by DirectoryService.</returns>
/// <exception cref="Amazon.DirectoryService.Model.ClientException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.EntityAlreadyExistsException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.EntityDoesNotExistException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.InvalidParameterException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.ServiceException">
///
/// </exception>
public CreateAliasResponse CreateAlias(CreateAliasRequest request)
{
var marshaller = new CreateAliasRequestMarshaller();
var unmarshaller = CreateAliasResponseUnmarshaller.Instance;
return Invoke<CreateAliasRequest,CreateAliasResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the CreateAlias operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateAlias operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<CreateAliasResponse> CreateAliasAsync(CreateAliasRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new CreateAliasRequestMarshaller();
var unmarshaller = CreateAliasResponseUnmarshaller.Instance;
return InvokeAsync<CreateAliasRequest,CreateAliasResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region CreateComputer
/// <summary>
/// Creates a computer account in the specified directory, and joins the computer to the
/// directory.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateComputer service method.</param>
///
/// <returns>The response from the CreateComputer service method, as returned by DirectoryService.</returns>
/// <exception cref="Amazon.DirectoryService.Model.AuthenticationFailedException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.ClientException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.DirectoryUnavailableException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.EntityAlreadyExistsException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.EntityDoesNotExistException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.InvalidParameterException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.ServiceException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.UnsupportedOperationException">
///
/// </exception>
public CreateComputerResponse CreateComputer(CreateComputerRequest request)
{
var marshaller = new CreateComputerRequestMarshaller();
var unmarshaller = CreateComputerResponseUnmarshaller.Instance;
return Invoke<CreateComputerRequest,CreateComputerResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the CreateComputer operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateComputer operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<CreateComputerResponse> CreateComputerAsync(CreateComputerRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new CreateComputerRequestMarshaller();
var unmarshaller = CreateComputerResponseUnmarshaller.Instance;
return InvokeAsync<CreateComputerRequest,CreateComputerResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region CreateDirectory
/// <summary>
/// Creates a Simple AD directory.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateDirectory service method.</param>
///
/// <returns>The response from the CreateDirectory service method, as returned by DirectoryService.</returns>
/// <exception cref="Amazon.DirectoryService.Model.ClientException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.DirectoryLimitExceededException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.InvalidParameterException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.ServiceException">
///
/// </exception>
public CreateDirectoryResponse CreateDirectory(CreateDirectoryRequest request)
{
var marshaller = new CreateDirectoryRequestMarshaller();
var unmarshaller = CreateDirectoryResponseUnmarshaller.Instance;
return Invoke<CreateDirectoryRequest,CreateDirectoryResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the CreateDirectory operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateDirectory operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<CreateDirectoryResponse> CreateDirectoryAsync(CreateDirectoryRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new CreateDirectoryRequestMarshaller();
var unmarshaller = CreateDirectoryResponseUnmarshaller.Instance;
return InvokeAsync<CreateDirectoryRequest,CreateDirectoryResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region CreateSnapshot
/// <summary>
/// Creates a snapshot of an existing directory.
///
///
/// <para>
/// You cannot take snapshots of extended or connected directories.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateSnapshot service method.</param>
///
/// <returns>The response from the CreateSnapshot service method, as returned by DirectoryService.</returns>
/// <exception cref="Amazon.DirectoryService.Model.ClientException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.EntityDoesNotExistException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.InvalidParameterException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.ServiceException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.SnapshotLimitExceededException">
///
/// </exception>
public CreateSnapshotResponse CreateSnapshot(CreateSnapshotRequest request)
{
var marshaller = new CreateSnapshotRequestMarshaller();
var unmarshaller = CreateSnapshotResponseUnmarshaller.Instance;
return Invoke<CreateSnapshotRequest,CreateSnapshotResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the CreateSnapshot operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateSnapshot operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<CreateSnapshotResponse> CreateSnapshotAsync(CreateSnapshotRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new CreateSnapshotRequestMarshaller();
var unmarshaller = CreateSnapshotResponseUnmarshaller.Instance;
return InvokeAsync<CreateSnapshotRequest,CreateSnapshotResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region DeleteDirectory
/// <summary>
/// Deletes an AWS Directory Service directory.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteDirectory service method.</param>
///
/// <returns>The response from the DeleteDirectory service method, as returned by DirectoryService.</returns>
/// <exception cref="Amazon.DirectoryService.Model.ClientException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.EntityDoesNotExistException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.ServiceException">
///
/// </exception>
public DeleteDirectoryResponse DeleteDirectory(DeleteDirectoryRequest request)
{
var marshaller = new DeleteDirectoryRequestMarshaller();
var unmarshaller = DeleteDirectoryResponseUnmarshaller.Instance;
return Invoke<DeleteDirectoryRequest,DeleteDirectoryResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the DeleteDirectory operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteDirectory operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<DeleteDirectoryResponse> DeleteDirectoryAsync(DeleteDirectoryRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new DeleteDirectoryRequestMarshaller();
var unmarshaller = DeleteDirectoryResponseUnmarshaller.Instance;
return InvokeAsync<DeleteDirectoryRequest,DeleteDirectoryResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region DeleteSnapshot
/// <summary>
/// Deletes a directory snapshot.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteSnapshot service method.</param>
///
/// <returns>The response from the DeleteSnapshot service method, as returned by DirectoryService.</returns>
/// <exception cref="Amazon.DirectoryService.Model.ClientException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.EntityDoesNotExistException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.InvalidParameterException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.ServiceException">
///
/// </exception>
public DeleteSnapshotResponse DeleteSnapshot(DeleteSnapshotRequest request)
{
var marshaller = new DeleteSnapshotRequestMarshaller();
var unmarshaller = DeleteSnapshotResponseUnmarshaller.Instance;
return Invoke<DeleteSnapshotRequest,DeleteSnapshotResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the DeleteSnapshot operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteSnapshot operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<DeleteSnapshotResponse> DeleteSnapshotAsync(DeleteSnapshotRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new DeleteSnapshotRequestMarshaller();
var unmarshaller = DeleteSnapshotResponseUnmarshaller.Instance;
return InvokeAsync<DeleteSnapshotRequest,DeleteSnapshotResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region DescribeDirectories
/// <summary>
/// Obtains information about the directories that belong to this account.
///
///
/// <para>
/// You can retrieve information about specific directories by passing the directory identifiers
/// in the <i>DirectoryIds</i> parameter. Otherwise, all directories that belong to the
/// current account are returned.
/// </para>
///
/// <para>
/// This operation supports pagination with the use of the <i>NextToken</i> request and
/// response parameters. If more results are available, the <i>DescribeDirectoriesResult.NextToken</i>
/// member contains a token that you pass in the next call to <a>DescribeDirectories</a>
/// to retrieve the next set of items.
/// </para>
///
/// <para>
/// You can also specify a maximum number of return results with the <i>Limit</i> parameter.
/// </para>
/// </summary>
///
/// <returns>The response from the DescribeDirectories service method, as returned by DirectoryService.</returns>
/// <exception cref="Amazon.DirectoryService.Model.ClientException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.EntityDoesNotExistException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.InvalidNextTokenException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.InvalidParameterException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.ServiceException">
///
/// </exception>
public DescribeDirectoriesResponse DescribeDirectories()
{
return DescribeDirectories(new DescribeDirectoriesRequest());
}
/// <summary>
/// Obtains information about the directories that belong to this account.
///
///
/// <para>
/// You can retrieve information about specific directories by passing the directory identifiers
/// in the <i>DirectoryIds</i> parameter. Otherwise, all directories that belong to the
/// current account are returned.
/// </para>
///
/// <para>
/// This operation supports pagination with the use of the <i>NextToken</i> request and
/// response parameters. If more results are available, the <i>DescribeDirectoriesResult.NextToken</i>
/// member contains a token that you pass in the next call to <a>DescribeDirectories</a>
/// to retrieve the next set of items.
/// </para>
///
/// <para>
/// You can also specify a maximum number of return results with the <i>Limit</i> parameter.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeDirectories service method.</param>
///
/// <returns>The response from the DescribeDirectories service method, as returned by DirectoryService.</returns>
/// <exception cref="Amazon.DirectoryService.Model.ClientException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.EntityDoesNotExistException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.InvalidNextTokenException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.InvalidParameterException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.ServiceException">
///
/// </exception>
public DescribeDirectoriesResponse DescribeDirectories(DescribeDirectoriesRequest request)
{
var marshaller = new DescribeDirectoriesRequestMarshaller();
var unmarshaller = DescribeDirectoriesResponseUnmarshaller.Instance;
return Invoke<DescribeDirectoriesRequest,DescribeDirectoriesResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Obtains information about the directories that belong to this account.
///
///
/// <para>
/// You can retrieve information about specific directories by passing the directory identifiers
/// in the <i>DirectoryIds</i> parameter. Otherwise, all directories that belong to the
/// current account are returned.
/// </para>
///
/// <para>
/// This operation supports pagination with the use of the <i>NextToken</i> request and
/// response parameters. If more results are available, the <i>DescribeDirectoriesResult.NextToken</i>
/// member contains a token that you pass in the next call to <a>DescribeDirectories</a>
/// to retrieve the next set of items.
/// </para>
///
/// <para>
/// You can also specify a maximum number of return results with the <i>Limit</i> parameter.
/// </para>
/// </summary>
/// <param name="cancellationToken"> ttd1
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeDirectories service method, as returned by DirectoryService.</returns>
/// <exception cref="Amazon.DirectoryService.Model.ClientException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.EntityDoesNotExistException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.InvalidNextTokenException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.InvalidParameterException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.ServiceException">
///
/// </exception>
public Task<DescribeDirectoriesResponse> DescribeDirectoriesAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
return DescribeDirectoriesAsync(new DescribeDirectoriesRequest(), cancellationToken);
}
/// <summary>
/// Initiates the asynchronous execution of the DescribeDirectories operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeDirectories operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<DescribeDirectoriesResponse> DescribeDirectoriesAsync(DescribeDirectoriesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new DescribeDirectoriesRequestMarshaller();
var unmarshaller = DescribeDirectoriesResponseUnmarshaller.Instance;
return InvokeAsync<DescribeDirectoriesRequest,DescribeDirectoriesResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region DescribeSnapshots
/// <summary>
/// Obtains information about the directory snapshots that belong to this account.
///
///
/// <para>
/// This operation supports pagination with the use of the <i>NextToken</i> request and
/// response parameters. If more results are available, the <i>DescribeSnapshots.NextToken</i>
/// member contains a token that you pass in the next call to <a>DescribeSnapshots</a>
/// to retrieve the next set of items.
/// </para>
///
/// <para>
/// You can also specify a maximum number of return results with the <i>Limit</i> parameter.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeSnapshots service method.</param>
///
/// <returns>The response from the DescribeSnapshots service method, as returned by DirectoryService.</returns>
/// <exception cref="Amazon.DirectoryService.Model.ClientException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.EntityDoesNotExistException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.InvalidNextTokenException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.InvalidParameterException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.ServiceException">
///
/// </exception>
public DescribeSnapshotsResponse DescribeSnapshots(DescribeSnapshotsRequest request)
{
var marshaller = new DescribeSnapshotsRequestMarshaller();
var unmarshaller = DescribeSnapshotsResponseUnmarshaller.Instance;
return Invoke<DescribeSnapshotsRequest,DescribeSnapshotsResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the DescribeSnapshots operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeSnapshots operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<DescribeSnapshotsResponse> DescribeSnapshotsAsync(DescribeSnapshotsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new DescribeSnapshotsRequestMarshaller();
var unmarshaller = DescribeSnapshotsResponseUnmarshaller.Instance;
return InvokeAsync<DescribeSnapshotsRequest,DescribeSnapshotsResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region DisableRadius
/// <summary>
/// Disables multi-factor authentication (MFA) with Remote Authentication Dial In User
/// Service (RADIUS) for an AD Connector directory.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DisableRadius service method.</param>
///
/// <returns>The response from the DisableRadius service method, as returned by DirectoryService.</returns>
/// <exception cref="Amazon.DirectoryService.Model.ClientException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.EntityDoesNotExistException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.ServiceException">
///
/// </exception>
public DisableRadiusResponse DisableRadius(DisableRadiusRequest request)
{
var marshaller = new DisableRadiusRequestMarshaller();
var unmarshaller = DisableRadiusResponseUnmarshaller.Instance;
return Invoke<DisableRadiusRequest,DisableRadiusResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the DisableRadius operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DisableRadius operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<DisableRadiusResponse> DisableRadiusAsync(DisableRadiusRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new DisableRadiusRequestMarshaller();
var unmarshaller = DisableRadiusResponseUnmarshaller.Instance;
return InvokeAsync<DisableRadiusRequest,DisableRadiusResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region DisableSso
/// <summary>
/// Disables single-sign on for a directory.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DisableSso service method.</param>
///
/// <returns>The response from the DisableSso service method, as returned by DirectoryService.</returns>
/// <exception cref="Amazon.DirectoryService.Model.AuthenticationFailedException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.ClientException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.EntityDoesNotExistException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.InsufficientPermissionsException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.ServiceException">
///
/// </exception>
public DisableSsoResponse DisableSso(DisableSsoRequest request)
{
var marshaller = new DisableSsoRequestMarshaller();
var unmarshaller = DisableSsoResponseUnmarshaller.Instance;
return Invoke<DisableSsoRequest,DisableSsoResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the DisableSso operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DisableSso operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<DisableSsoResponse> DisableSsoAsync(DisableSsoRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new DisableSsoRequestMarshaller();
var unmarshaller = DisableSsoResponseUnmarshaller.Instance;
return InvokeAsync<DisableSsoRequest,DisableSsoResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region EnableRadius
/// <summary>
/// Enables multi-factor authentication (MFA) with Remote Authentication Dial In User
/// Service (RADIUS) for an AD Connector directory.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the EnableRadius service method.</param>
///
/// <returns>The response from the EnableRadius service method, as returned by DirectoryService.</returns>
/// <exception cref="Amazon.DirectoryService.Model.ClientException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.EntityAlreadyExistsException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.EntityDoesNotExistException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.InvalidParameterException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.ServiceException">
///
/// </exception>
public EnableRadiusResponse EnableRadius(EnableRadiusRequest request)
{
var marshaller = new EnableRadiusRequestMarshaller();
var unmarshaller = EnableRadiusResponseUnmarshaller.Instance;
return Invoke<EnableRadiusRequest,EnableRadiusResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the EnableRadius operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the EnableRadius operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<EnableRadiusResponse> EnableRadiusAsync(EnableRadiusRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new EnableRadiusRequestMarshaller();
var unmarshaller = EnableRadiusResponseUnmarshaller.Instance;
return InvokeAsync<EnableRadiusRequest,EnableRadiusResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region EnableSso
/// <summary>
/// Enables single-sign on for a directory.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the EnableSso service method.</param>
///
/// <returns>The response from the EnableSso service method, as returned by DirectoryService.</returns>
/// <exception cref="Amazon.DirectoryService.Model.AuthenticationFailedException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.ClientException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.EntityDoesNotExistException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.InsufficientPermissionsException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.ServiceException">
///
/// </exception>
public EnableSsoResponse EnableSso(EnableSsoRequest request)
{
var marshaller = new EnableSsoRequestMarshaller();
var unmarshaller = EnableSsoResponseUnmarshaller.Instance;
return Invoke<EnableSsoRequest,EnableSsoResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the EnableSso operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the EnableSso operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<EnableSsoResponse> EnableSsoAsync(EnableSsoRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new EnableSsoRequestMarshaller();
var unmarshaller = EnableSsoResponseUnmarshaller.Instance;
return InvokeAsync<EnableSsoRequest,EnableSsoResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region GetDirectoryLimits
/// <summary>
/// Obtains directory limit information for the current region.
/// </summary>
///
/// <returns>The response from the GetDirectoryLimits service method, as returned by DirectoryService.</returns>
/// <exception cref="Amazon.DirectoryService.Model.ClientException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.EntityDoesNotExistException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.ServiceException">
///
/// </exception>
public GetDirectoryLimitsResponse GetDirectoryLimits()
{
return GetDirectoryLimits(new GetDirectoryLimitsRequest());
}
/// <summary>
/// Obtains directory limit information for the current region.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetDirectoryLimits service method.</param>
///
/// <returns>The response from the GetDirectoryLimits service method, as returned by DirectoryService.</returns>
/// <exception cref="Amazon.DirectoryService.Model.ClientException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.EntityDoesNotExistException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.ServiceException">
///
/// </exception>
public GetDirectoryLimitsResponse GetDirectoryLimits(GetDirectoryLimitsRequest request)
{
var marshaller = new GetDirectoryLimitsRequestMarshaller();
var unmarshaller = GetDirectoryLimitsResponseUnmarshaller.Instance;
return Invoke<GetDirectoryLimitsRequest,GetDirectoryLimitsResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Obtains directory limit information for the current region.
/// </summary>
/// <param name="cancellationToken"> ttd1
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the GetDirectoryLimits service method, as returned by DirectoryService.</returns>
/// <exception cref="Amazon.DirectoryService.Model.ClientException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.EntityDoesNotExistException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.ServiceException">
///
/// </exception>
public Task<GetDirectoryLimitsResponse> GetDirectoryLimitsAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
return GetDirectoryLimitsAsync(new GetDirectoryLimitsRequest(), cancellationToken);
}
/// <summary>
/// Initiates the asynchronous execution of the GetDirectoryLimits operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetDirectoryLimits operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<GetDirectoryLimitsResponse> GetDirectoryLimitsAsync(GetDirectoryLimitsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new GetDirectoryLimitsRequestMarshaller();
var unmarshaller = GetDirectoryLimitsResponseUnmarshaller.Instance;
return InvokeAsync<GetDirectoryLimitsRequest,GetDirectoryLimitsResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region GetSnapshotLimits
/// <summary>
/// Obtains the manual snapshot limits for a directory.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetSnapshotLimits service method.</param>
///
/// <returns>The response from the GetSnapshotLimits service method, as returned by DirectoryService.</returns>
/// <exception cref="Amazon.DirectoryService.Model.ClientException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.EntityDoesNotExistException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.ServiceException">
///
/// </exception>
public GetSnapshotLimitsResponse GetSnapshotLimits(GetSnapshotLimitsRequest request)
{
var marshaller = new GetSnapshotLimitsRequestMarshaller();
var unmarshaller = GetSnapshotLimitsResponseUnmarshaller.Instance;
return Invoke<GetSnapshotLimitsRequest,GetSnapshotLimitsResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the GetSnapshotLimits operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetSnapshotLimits operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<GetSnapshotLimitsResponse> GetSnapshotLimitsAsync(GetSnapshotLimitsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new GetSnapshotLimitsRequestMarshaller();
var unmarshaller = GetSnapshotLimitsResponseUnmarshaller.Instance;
return InvokeAsync<GetSnapshotLimitsRequest,GetSnapshotLimitsResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region RestoreFromSnapshot
/// <summary>
/// Restores a directory using an existing directory snapshot.
///
///
/// <para>
/// When you restore a directory from a snapshot, any changes made to the directory after
/// the snapshot date are overwritten.
/// </para>
///
/// <para>
/// This action returns as soon as the restore operation is initiated. You can monitor
/// the progress of the restore operation by calling the <a>DescribeDirectories</a> operation
/// with the directory identifier. When the <b>DirectoryDescription.Stage</b> value changes
/// to <code>Active</code>, the restore operation is complete.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the RestoreFromSnapshot service method.</param>
///
/// <returns>The response from the RestoreFromSnapshot service method, as returned by DirectoryService.</returns>
/// <exception cref="Amazon.DirectoryService.Model.ClientException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.EntityDoesNotExistException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.InvalidParameterException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.ServiceException">
///
/// </exception>
public RestoreFromSnapshotResponse RestoreFromSnapshot(RestoreFromSnapshotRequest request)
{
var marshaller = new RestoreFromSnapshotRequestMarshaller();
var unmarshaller = RestoreFromSnapshotResponseUnmarshaller.Instance;
return Invoke<RestoreFromSnapshotRequest,RestoreFromSnapshotResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the RestoreFromSnapshot operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the RestoreFromSnapshot operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<RestoreFromSnapshotResponse> RestoreFromSnapshotAsync(RestoreFromSnapshotRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new RestoreFromSnapshotRequestMarshaller();
var unmarshaller = RestoreFromSnapshotResponseUnmarshaller.Instance;
return InvokeAsync<RestoreFromSnapshotRequest,RestoreFromSnapshotResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region UpdateRadius
/// <summary>
/// Updates the Remote Authentication Dial In User Service (RADIUS) server information
/// for an AD Connector directory.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateRadius service method.</param>
///
/// <returns>The response from the UpdateRadius service method, as returned by DirectoryService.</returns>
/// <exception cref="Amazon.DirectoryService.Model.ClientException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.EntityDoesNotExistException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.InvalidParameterException">
///
/// </exception>
/// <exception cref="Amazon.DirectoryService.Model.ServiceException">
///
/// </exception>
public UpdateRadiusResponse UpdateRadius(UpdateRadiusRequest request)
{
var marshaller = new UpdateRadiusRequestMarshaller();
var unmarshaller = UpdateRadiusResponseUnmarshaller.Instance;
return Invoke<UpdateRadiusRequest,UpdateRadiusResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the UpdateRadius operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the UpdateRadius operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<UpdateRadiusResponse> UpdateRadiusAsync(UpdateRadiusRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new UpdateRadiusRequestMarshaller();
var unmarshaller = UpdateRadiusResponseUnmarshaller.Instance;
return InvokeAsync<UpdateRadiusRequest,UpdateRadiusResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Runtime.InteropServices;
namespace System.Numerics.Matrices
{
/// <summary>
/// Represents a matrix of double precision floating-point values defined by its number of columns and rows
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct Matrix4x2: IEquatable<Matrix4x2>, IMatrix
{
public const int ColumnCount = 4;
public const int RowCount = 2;
static Matrix4x2()
{
Zero = new Matrix4x2(0);
}
/// <summary>
/// Gets the smallest value used to determine equality
/// </summary>
public double Epsilon { get { return MatrixHelper.Epsilon; } }
/// <summary>
/// Constant Matrix4x2 with all values initialized to zero
/// </summary>
public static readonly Matrix4x2 Zero;
/// <summary>
/// Initializes a Matrix4x2 with all of it values specifically set
/// </summary>
/// <param name="m11">The column 1, row 1 value</param>
/// <param name="m21">The column 2, row 1 value</param>
/// <param name="m31">The column 3, row 1 value</param>
/// <param name="m41">The column 4, row 1 value</param>
/// <param name="m12">The column 1, row 2 value</param>
/// <param name="m22">The column 2, row 2 value</param>
/// <param name="m32">The column 3, row 2 value</param>
/// <param name="m42">The column 4, row 2 value</param>
public Matrix4x2(double m11, double m21, double m31, double m41,
double m12, double m22, double m32, double m42)
{
M11 = m11; M21 = m21; M31 = m31; M41 = m41;
M12 = m12; M22 = m22; M32 = m32; M42 = m42;
}
/// <summary>
/// Initialized a Matrix4x2 with all values set to the same value
/// </summary>
/// <param name="value">The value to set all values to</param>
public Matrix4x2(double value)
{
M11 = M21 = M31 = M41 =
M12 = M22 = M32 = M42 = value;
}
public double M11;
public double M21;
public double M31;
public double M41;
public double M12;
public double M22;
public double M32;
public double M42;
public unsafe double this[int col, int row]
{
get
{
if (col < 0 || col >= ColumnCount)
throw new ArgumentOutOfRangeException("col", String.Format("Expected greater than or equal to 0 and less than {0}, found {1}.", ColumnCount, col));
if (row < 0 || row >= RowCount)
throw new ArgumentOutOfRangeException("row", String.Format("Expected greater than or equal to 0 and less than {0}, found {1}.", RowCount, row));
fixed (Matrix4x2* p = &this)
{
double* d = (double*)p;
return d[row * ColumnCount + col];
}
}
set
{
if (col < 0 || col >= ColumnCount)
throw new ArgumentOutOfRangeException("col", String.Format("Expected greater than or equal to 0 and less than {0}, found {1}.", ColumnCount, col));
if (row < 0 || row >= RowCount)
throw new ArgumentOutOfRangeException("row", String.Format("Expected greater than or equal to 0 and less than {0}, found {1}.", RowCount, row));
fixed (Matrix4x2* p = &this)
{
double* d = (double*)p;
d[row * ColumnCount + col] = value;
}
}
}
/// <summary>
/// Gets the number of columns in the matrix
/// </summary>
public int Columns { get { return ColumnCount; } }
/// <summary>
/// Get the number of rows in the matrix
/// </summary>
public int Rows { get { return RowCount; } }
/// <summary>
/// Gets a new Matrix1x2 containing the values of column 1
/// </summary>
public Matrix1x2 Column1 { get { return new Matrix1x2(M11, M12); } }
/// <summary>
/// Gets a new Matrix1x2 containing the values of column 2
/// </summary>
public Matrix1x2 Column2 { get { return new Matrix1x2(M21, M22); } }
/// <summary>
/// Gets a new Matrix1x2 containing the values of column 3
/// </summary>
public Matrix1x2 Column3 { get { return new Matrix1x2(M31, M32); } }
/// <summary>
/// Gets a new Matrix1x2 containing the values of column 4
/// </summary>
public Matrix1x2 Column4 { get { return new Matrix1x2(M41, M42); } }
/// <summary>
/// Gets a new Matrix4x1 containing the values of column 1
/// </summary>
public Matrix4x1 Row1 { get { return new Matrix4x1(M11, M21, M31, M41); } }
/// <summary>
/// Gets a new Matrix4x1 containing the values of column 2
/// </summary>
public Matrix4x1 Row2 { get { return new Matrix4x1(M12, M22, M32, M42); } }
public override bool Equals(object obj)
{
if (obj is Matrix4x2)
return this == (Matrix4x2)obj;
return false;
}
public bool Equals(Matrix4x2 other)
{
return this == other;
}
public unsafe override int GetHashCode()
{
fixed (Matrix4x2* p = &this)
{
int* x = (int*)p;
unchecked
{
return 0xFFE1
+ 7 * ((((x[00] ^ x[01]) << 0) + ((x[02] ^ x[03]) << 1) + ((x[04] ^ x[05]) << 2) + ((x[06] ^ x[07]) << 3)) << 0)
+ 7 * ((((x[04] ^ x[05]) << 0) + ((x[06] ^ x[07]) << 1) + ((x[08] ^ x[09]) << 2) + ((x[10] ^ x[11]) << 3)) << 1);
}
}
}
public override string ToString()
{
return "Matrix4x2: "
+ String.Format("{{|{0:00}|{1:00}|{2:00}|{3:00}|}}", M11, M21, M31, M41)
+ String.Format("{{|{0:00}|{1:00}|{2:00}|{3:00}|}}", M12, M22, M32, M42);
}
/// <summary>
/// Creates and returns a transposed matrix
/// </summary>
/// <returns>Matrix with transposed values</returns>
public Matrix2x4 Transpose()
{
return new Matrix2x4(M11, M12,
M21, M22,
M31, M32,
M41, M42);
}
public static bool operator ==(Matrix4x2 matrix1, Matrix4x2 matrix2)
{
return MatrixHelper.AreEqual(matrix1.M11, matrix2.M11)
&& MatrixHelper.AreEqual(matrix1.M21, matrix2.M21)
&& MatrixHelper.AreEqual(matrix1.M31, matrix2.M31)
&& MatrixHelper.AreEqual(matrix1.M41, matrix2.M41)
&& MatrixHelper.AreEqual(matrix1.M12, matrix2.M12)
&& MatrixHelper.AreEqual(matrix1.M22, matrix2.M22)
&& MatrixHelper.AreEqual(matrix1.M32, matrix2.M32)
&& MatrixHelper.AreEqual(matrix1.M42, matrix2.M42);
}
public static bool operator !=(Matrix4x2 matrix1, Matrix4x2 matrix2)
{
return MatrixHelper.NotEqual(matrix1.M11, matrix2.M11)
|| MatrixHelper.NotEqual(matrix1.M21, matrix2.M21)
|| MatrixHelper.NotEqual(matrix1.M31, matrix2.M31)
|| MatrixHelper.NotEqual(matrix1.M41, matrix2.M41)
|| MatrixHelper.NotEqual(matrix1.M12, matrix2.M12)
|| MatrixHelper.NotEqual(matrix1.M22, matrix2.M22)
|| MatrixHelper.NotEqual(matrix1.M32, matrix2.M32)
|| MatrixHelper.NotEqual(matrix1.M42, matrix2.M42);
}
public static Matrix4x2 operator +(Matrix4x2 matrix1, Matrix4x2 matrix2)
{
double m11 = matrix1.M11 + matrix2.M11;
double m21 = matrix1.M21 + matrix2.M21;
double m31 = matrix1.M31 + matrix2.M31;
double m41 = matrix1.M41 + matrix2.M41;
double m12 = matrix1.M12 + matrix2.M12;
double m22 = matrix1.M22 + matrix2.M22;
double m32 = matrix1.M32 + matrix2.M32;
double m42 = matrix1.M42 + matrix2.M42;
return new Matrix4x2(m11, m21, m31, m41,
m12, m22, m32, m42);
}
public static Matrix4x2 operator -(Matrix4x2 matrix1, Matrix4x2 matrix2)
{
double m11 = matrix1.M11 - matrix2.M11;
double m21 = matrix1.M21 - matrix2.M21;
double m31 = matrix1.M31 - matrix2.M31;
double m41 = matrix1.M41 - matrix2.M41;
double m12 = matrix1.M12 - matrix2.M12;
double m22 = matrix1.M22 - matrix2.M22;
double m32 = matrix1.M32 - matrix2.M32;
double m42 = matrix1.M42 - matrix2.M42;
return new Matrix4x2(m11, m21, m31, m41,
m12, m22, m32, m42);
}
public static Matrix4x2 operator *(Matrix4x2 matrix, double scalar)
{
double m11 = matrix.M11 * scalar;
double m21 = matrix.M21 * scalar;
double m31 = matrix.M31 * scalar;
double m41 = matrix.M41 * scalar;
double m12 = matrix.M12 * scalar;
double m22 = matrix.M22 * scalar;
double m32 = matrix.M32 * scalar;
double m42 = matrix.M42 * scalar;
return new Matrix4x2(m11, m21, m31, m41,
m12, m22, m32, m42);
}
public static Matrix4x2 operator *(double scalar, Matrix4x2 matrix)
{
double m11 = scalar * matrix.M11;
double m21 = scalar * matrix.M21;
double m31 = scalar * matrix.M31;
double m41 = scalar * matrix.M41;
double m12 = scalar * matrix.M12;
double m22 = scalar * matrix.M22;
double m32 = scalar * matrix.M32;
double m42 = scalar * matrix.M42;
return new Matrix4x2(m11, m21, m31, m41,
m12, m22, m32, m42);
}
public static Matrix1x2 operator *(Matrix4x2 matrix1, Matrix1x4 matrix2)
{
double m11 = matrix1.M11 * matrix2.M11 + matrix1.M21 * matrix2.M12 + matrix1.M31 * matrix2.M13 + matrix1.M41 * matrix2.M14;
double m12 = matrix1.M12 * matrix2.M11 + matrix1.M22 * matrix2.M12 + matrix1.M32 * matrix2.M13 + matrix1.M42 * matrix2.M14;
return new Matrix1x2(m11,
m12);
}
public static Matrix2x2 operator *(Matrix4x2 matrix1, Matrix2x4 matrix2)
{
double m11 = matrix1.M11 * matrix2.M11 + matrix1.M21 * matrix2.M12 + matrix1.M31 * matrix2.M13 + matrix1.M41 * matrix2.M14;
double m21 = matrix1.M11 * matrix2.M21 + matrix1.M21 * matrix2.M22 + matrix1.M31 * matrix2.M23 + matrix1.M41 * matrix2.M24;
double m12 = matrix1.M12 * matrix2.M11 + matrix1.M22 * matrix2.M12 + matrix1.M32 * matrix2.M13 + matrix1.M42 * matrix2.M14;
double m22 = matrix1.M12 * matrix2.M21 + matrix1.M22 * matrix2.M22 + matrix1.M32 * matrix2.M23 + matrix1.M42 * matrix2.M24;
return new Matrix2x2(m11, m21,
m12, m22);
}
public static Matrix3x2 operator *(Matrix4x2 matrix1, Matrix3x4 matrix2)
{
double m11 = matrix1.M11 * matrix2.M11 + matrix1.M21 * matrix2.M12 + matrix1.M31 * matrix2.M13 + matrix1.M41 * matrix2.M14;
double m21 = matrix1.M11 * matrix2.M21 + matrix1.M21 * matrix2.M22 + matrix1.M31 * matrix2.M23 + matrix1.M41 * matrix2.M24;
double m31 = matrix1.M11 * matrix2.M31 + matrix1.M21 * matrix2.M32 + matrix1.M31 * matrix2.M33 + matrix1.M41 * matrix2.M34;
double m12 = matrix1.M12 * matrix2.M11 + matrix1.M22 * matrix2.M12 + matrix1.M32 * matrix2.M13 + matrix1.M42 * matrix2.M14;
double m22 = matrix1.M12 * matrix2.M21 + matrix1.M22 * matrix2.M22 + matrix1.M32 * matrix2.M23 + matrix1.M42 * matrix2.M24;
double m32 = matrix1.M12 * matrix2.M31 + matrix1.M22 * matrix2.M32 + matrix1.M32 * matrix2.M33 + matrix1.M42 * matrix2.M34;
return new Matrix3x2(m11, m21, m31,
m12, m22, m32);
}
public static Matrix4x2 operator *(Matrix4x2 matrix1, Matrix4x4 matrix2)
{
double m11 = matrix1.M11 * matrix2.M11 + matrix1.M21 * matrix2.M12 + matrix1.M31 * matrix2.M13 + matrix1.M41 * matrix2.M14;
double m21 = matrix1.M11 * matrix2.M21 + matrix1.M21 * matrix2.M22 + matrix1.M31 * matrix2.M23 + matrix1.M41 * matrix2.M24;
double m31 = matrix1.M11 * matrix2.M31 + matrix1.M21 * matrix2.M32 + matrix1.M31 * matrix2.M33 + matrix1.M41 * matrix2.M34;
double m41 = matrix1.M11 * matrix2.M41 + matrix1.M21 * matrix2.M42 + matrix1.M31 * matrix2.M43 + matrix1.M41 * matrix2.M44;
double m12 = matrix1.M12 * matrix2.M11 + matrix1.M22 * matrix2.M12 + matrix1.M32 * matrix2.M13 + matrix1.M42 * matrix2.M14;
double m22 = matrix1.M12 * matrix2.M21 + matrix1.M22 * matrix2.M22 + matrix1.M32 * matrix2.M23 + matrix1.M42 * matrix2.M24;
double m32 = matrix1.M12 * matrix2.M31 + matrix1.M22 * matrix2.M32 + matrix1.M32 * matrix2.M33 + matrix1.M42 * matrix2.M34;
double m42 = matrix1.M12 * matrix2.M41 + matrix1.M22 * matrix2.M42 + matrix1.M32 * matrix2.M43 + matrix1.M42 * matrix2.M44;
return new Matrix4x2(m11, m21, m31, m41,
m12, m22, m32, m42);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.