context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Localization;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Localization;
using OpenIddict.Abstractions;
using OrchardCore.Admin;
using OrchardCore.DisplayManagement;
using OrchardCore.DisplayManagement.Notify;
using OrchardCore.Environment.Shell.Descriptor.Models;
using OrchardCore.Modules;
using OrchardCore.Navigation;
using OrchardCore.OpenId.Abstractions.Descriptors;
using OrchardCore.OpenId.Abstractions.Managers;
using OrchardCore.OpenId.Services;
using OrchardCore.OpenId.Settings;
using OrchardCore.OpenId.ViewModels;
using OrchardCore.Security.Services;
using OrchardCore.Settings;
namespace OrchardCore.OpenId.Controllers
{
[Admin, Feature(OpenIdConstants.Features.Management)]
public class ApplicationController : Controller
{
private readonly IAuthorizationService _authorizationService;
private readonly IStringLocalizer S;
private readonly IHtmlLocalizer H;
private readonly ISiteService _siteService;
private readonly IOpenIdApplicationManager _applicationManager;
private readonly INotifier _notifier;
private readonly ShellDescriptor _shellDescriptor;
private readonly dynamic New;
public ApplicationController(
IShapeFactory shapeFactory,
ISiteService siteService,
IStringLocalizer<ApplicationController> stringLocalizer,
IAuthorizationService authorizationService,
IOpenIdApplicationManager applicationManager,
IHtmlLocalizer<ApplicationController> htmlLocalizer,
INotifier notifier,
ShellDescriptor shellDescriptor)
{
New = shapeFactory;
_siteService = siteService;
S = stringLocalizer;
H = htmlLocalizer;
_authorizationService = authorizationService;
_applicationManager = applicationManager;
_notifier = notifier;
_shellDescriptor = shellDescriptor;
}
public async Task<ActionResult> Index(PagerParameters pagerParameters)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageApplications))
{
return Forbid();
}
var siteSettings = await _siteService.GetSiteSettingsAsync();
var pager = new Pager(pagerParameters, siteSettings.PageSize);
var count = await _applicationManager.CountAsync();
var model = new OpenIdApplicationsIndexViewModel
{
Pager = (await New.Pager(pager)).TotalItemCount(count)
};
foreach (var application in await _applicationManager.ListAsync(pager.PageSize, pager.GetStartIndex()))
{
model.Applications.Add(new OpenIdApplicationEntry
{
DisplayName = await _applicationManager.GetDisplayNameAsync(application),
Id = await _applicationManager.GetPhysicalIdAsync(application)
});
}
return View(model);
}
[HttpGet]
public async Task<IActionResult> Create(string returnUrl = null)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageApplications))
{
return Forbid();
}
var model = new CreateOpenIdApplicationViewModel();
var roleService = HttpContext.RequestServices?.GetService<IRoleService>();
if (roleService != null)
{
foreach (var role in await roleService.GetRoleNamesAsync())
{
model.RoleEntries.Add(new CreateOpenIdApplicationViewModel.RoleEntry
{
Name = role
});
}
}
else
{
_notifier.Warning(H["There are no registered services to provide roles."]);
}
ViewData[nameof(OpenIdServerSettings)] = await GetServerSettingsAsync();
ViewData["ReturnUrl"] = returnUrl;
return View(model);
}
[HttpPost]
public async Task<IActionResult> Create(CreateOpenIdApplicationViewModel model, string returnUrl = null)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageApplications))
{
return Forbid();
}
if (!string.IsNullOrEmpty(model.ClientSecret) &&
string.Equals(model.Type, OpenIddictConstants.ClientTypes.Public, StringComparison.OrdinalIgnoreCase))
{
ModelState.AddModelError(nameof(model.ClientSecret), S["No client secret can be set for public applications."]);
}
else if (string.IsNullOrEmpty(model.ClientSecret) &&
string.Equals(model.Type, OpenIddictConstants.ClientTypes.Confidential, StringComparison.OrdinalIgnoreCase))
{
ModelState.AddModelError(nameof(model.ClientSecret), S["The client secret is required for confidential applications."]);
}
if (!string.IsNullOrEmpty(model.ClientId) && await _applicationManager.FindByClientIdAsync(model.ClientId) != null)
{
ModelState.AddModelError(nameof(model.ClientId), S["The client identifier is already taken by another application."]);
}
if (!ModelState.IsValid)
{
ViewData[nameof(OpenIdServerSettings)] = await GetServerSettingsAsync();
ViewData["ReturnUrl"] = returnUrl;
return View(model);
}
var descriptor = new OpenIdApplicationDescriptor
{
ClientId = model.ClientId,
ClientSecret = model.ClientSecret,
ConsentType = model.ConsentType,
DisplayName = model.DisplayName,
Type = model.Type
};
if (model.AllowLogoutEndpoint)
{
descriptor.Permissions.Add(OpenIddictConstants.Permissions.Endpoints.Logout);
}
else
{
descriptor.Permissions.Remove(OpenIddictConstants.Permissions.Endpoints.Logout);
}
if (model.AllowAuthorizationCodeFlow)
{
descriptor.Permissions.Add(OpenIddictConstants.Permissions.GrantTypes.AuthorizationCode);
}
if (model.AllowClientCredentialsFlow)
{
descriptor.Permissions.Add(OpenIddictConstants.Permissions.GrantTypes.ClientCredentials);
}
if (model.AllowImplicitFlow)
{
descriptor.Permissions.Add(OpenIddictConstants.Permissions.GrantTypes.Implicit);
}
if (model.AllowPasswordFlow)
{
descriptor.Permissions.Add(OpenIddictConstants.Permissions.GrantTypes.Password);
}
if (model.AllowRefreshTokenFlow)
{
descriptor.Permissions.Add(OpenIddictConstants.Permissions.GrantTypes.RefreshToken);
}
if (model.AllowAuthorizationCodeFlow || model.AllowImplicitFlow)
{
descriptor.Permissions.Add(OpenIddictConstants.Permissions.Endpoints.Authorization);
}
if (model.AllowAuthorizationCodeFlow || model.AllowClientCredentialsFlow ||
model.AllowPasswordFlow || model.AllowRefreshTokenFlow)
{
descriptor.Permissions.Add(OpenIddictConstants.Permissions.Endpoints.Token);
}
descriptor.PostLogoutRedirectUris.UnionWith(
from uri in model.PostLogoutRedirectUris?.Split(new[] { " ", "," }, StringSplitOptions.RemoveEmptyEntries) ?? Array.Empty<string>()
select new Uri(uri, UriKind.Absolute));
descriptor.RedirectUris.UnionWith(
from uri in model.RedirectUris?.Split(new[] { " ", "," }, StringSplitOptions.RemoveEmptyEntries) ?? Array.Empty<string>()
select new Uri(uri, UriKind.Absolute));
descriptor.Roles.UnionWith(model.RoleEntries
.Where(role => role.Selected)
.Select(role => role.Name));
await _applicationManager.CreateAsync(descriptor);
if (string.IsNullOrEmpty(returnUrl))
{
return RedirectToAction("Index");
}
return LocalRedirect(returnUrl);
}
public async Task<IActionResult> Edit(string id, string returnUrl = null)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageApplications))
{
return Forbid();
}
var application = await _applicationManager.FindByPhysicalIdAsync(id);
if (application == null)
{
return NotFound();
}
Task<bool> HasPermissionAsync(string permission) => _applicationManager.HasPermissionAsync(application, permission);
var model = new EditOpenIdApplicationViewModel
{
AllowAuthorizationCodeFlow = await HasPermissionAsync(OpenIddictConstants.Permissions.GrantTypes.AuthorizationCode),
AllowClientCredentialsFlow = await HasPermissionAsync(OpenIddictConstants.Permissions.GrantTypes.ClientCredentials),
AllowImplicitFlow = await HasPermissionAsync(OpenIddictConstants.Permissions.GrantTypes.Implicit),
AllowPasswordFlow = await HasPermissionAsync(OpenIddictConstants.Permissions.GrantTypes.Password),
AllowRefreshTokenFlow = await HasPermissionAsync(OpenIddictConstants.Permissions.GrantTypes.RefreshToken),
AllowLogoutEndpoint = await HasPermissionAsync(OpenIddictConstants.Permissions.Endpoints.Logout),
ClientId = await _applicationManager.GetClientIdAsync(application),
ConsentType = await _applicationManager.GetConsentTypeAsync(application),
DisplayName = await _applicationManager.GetDisplayNameAsync(application),
Id = await _applicationManager.GetPhysicalIdAsync(application),
PostLogoutRedirectUris = string.Join(" ", await _applicationManager.GetPostLogoutRedirectUrisAsync(application)),
RedirectUris = string.Join(" ", await _applicationManager.GetRedirectUrisAsync(application)),
Type = await _applicationManager.GetClientTypeAsync(application)
};
var roleService = HttpContext.RequestServices?.GetService<IRoleService>();
if (roleService != null)
{
var roles = await _applicationManager.GetRolesAsync(application);
foreach (var role in await roleService.GetRoleNamesAsync())
{
model.RoleEntries.Add(new EditOpenIdApplicationViewModel.RoleEntry
{
Name = role,
Selected = roles.Contains(role, StringComparer.OrdinalIgnoreCase)
});
}
}
else
{
_notifier.Warning(H["There are no registered services to provide roles."]);
}
ViewData[nameof(OpenIdServerSettings)] = await GetServerSettingsAsync();
ViewData["ReturnUrl"] = returnUrl;
return View(model);
}
[HttpPost]
public async Task<IActionResult> Edit(EditOpenIdApplicationViewModel model, string returnUrl = null)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageApplications))
{
return Forbid();
}
var application = await _applicationManager.FindByPhysicalIdAsync(model.Id);
if (application == null)
{
return NotFound();
}
// If the application was a public client and is now a confidential client, ensure a client secret was provided.
if (string.IsNullOrEmpty(model.ClientSecret) &&
!string.Equals(model.Type, OpenIddictConstants.ClientTypes.Public, StringComparison.OrdinalIgnoreCase) &&
await _applicationManager.IsPublicAsync(application))
{
ModelState.AddModelError(nameof(model.ClientSecret), S["Setting a new client secret is required."]);
}
if (!string.IsNullOrEmpty(model.ClientSecret) &&
string.Equals(model.Type, OpenIddictConstants.ClientTypes.Public, StringComparison.OrdinalIgnoreCase))
{
ModelState.AddModelError(nameof(model.ClientSecret), S["No client secret can be set for public applications."]);
}
if (ModelState.IsValid)
{
var other = await _applicationManager.FindByClientIdAsync(model.ClientId);
if (other != null && !string.Equals(
await _applicationManager.GetIdAsync(other),
await _applicationManager.GetIdAsync(application), StringComparison.Ordinal))
{
ModelState.AddModelError(nameof(model.ClientId), S["The client identifier is already taken by another application."]);
}
}
if (!ModelState.IsValid)
{
ViewData[nameof(OpenIdServerSettings)] = await GetServerSettingsAsync();
ViewData["ReturnUrl"] = returnUrl;
return View(model);
}
var descriptor = new OpenIdApplicationDescriptor();
await _applicationManager.PopulateAsync(descriptor, application);
descriptor.ClientId = model.ClientId;
descriptor.ConsentType = model.ConsentType;
descriptor.DisplayName = model.DisplayName;
descriptor.Type = model.Type;
if (!string.IsNullOrEmpty(model.ClientSecret))
{
descriptor.ClientSecret = model.ClientSecret;
}
if (string.Equals(descriptor.Type, OpenIddictConstants.ClientTypes.Public, StringComparison.OrdinalIgnoreCase))
{
descriptor.ClientSecret = null;
}
if (model.AllowLogoutEndpoint)
{
descriptor.Permissions.Add(OpenIddictConstants.Permissions.Endpoints.Logout);
}
else
{
descriptor.Permissions.Remove(OpenIddictConstants.Permissions.Endpoints.Logout);
}
if (model.AllowAuthorizationCodeFlow)
{
descriptor.Permissions.Add(OpenIddictConstants.Permissions.GrantTypes.AuthorizationCode);
}
else
{
descriptor.Permissions.Remove(OpenIddictConstants.Permissions.GrantTypes.AuthorizationCode);
}
if (model.AllowClientCredentialsFlow)
{
descriptor.Permissions.Add(OpenIddictConstants.Permissions.GrantTypes.ClientCredentials);
}
else
{
descriptor.Permissions.Remove(OpenIddictConstants.Permissions.GrantTypes.ClientCredentials);
}
if (model.AllowImplicitFlow)
{
descriptor.Permissions.Add(OpenIddictConstants.Permissions.GrantTypes.Implicit);
}
else
{
descriptor.Permissions.Remove(OpenIddictConstants.Permissions.GrantTypes.Implicit);
}
if (model.AllowPasswordFlow)
{
descriptor.Permissions.Add(OpenIddictConstants.Permissions.GrantTypes.Password);
}
else
{
descriptor.Permissions.Remove(OpenIddictConstants.Permissions.GrantTypes.Password);
}
if (model.AllowRefreshTokenFlow)
{
descriptor.Permissions.Add(OpenIddictConstants.Permissions.GrantTypes.RefreshToken);
}
else
{
descriptor.Permissions.Remove(OpenIddictConstants.Permissions.GrantTypes.RefreshToken);
}
if (model.AllowAuthorizationCodeFlow || model.AllowImplicitFlow)
{
descriptor.Permissions.Add(OpenIddictConstants.Permissions.Endpoints.Authorization);
}
else
{
descriptor.Permissions.Remove(OpenIddictConstants.Permissions.Endpoints.Authorization);
}
if (model.AllowAuthorizationCodeFlow || model.AllowClientCredentialsFlow ||
model.AllowPasswordFlow || model.AllowRefreshTokenFlow)
{
descriptor.Permissions.Add(OpenIddictConstants.Permissions.Endpoints.Token);
}
else
{
descriptor.Permissions.Remove(OpenIddictConstants.Permissions.Endpoints.Token);
}
descriptor.Roles.Clear();
foreach (string selectedRole in (model.RoleEntries
.Where(role => role.Selected)
.Select(role => role.Name)))
{
descriptor.Roles.Add(selectedRole);
}
descriptor.PostLogoutRedirectUris.Clear();
foreach (Uri uri in
(from uri in model.PostLogoutRedirectUris?.Split(new[] { " ", "," }, StringSplitOptions.RemoveEmptyEntries) ?? Array.Empty<string>()
select new Uri(uri, UriKind.Absolute)))
{
descriptor.PostLogoutRedirectUris.Add(uri);
}
descriptor.RedirectUris.Clear();
foreach (Uri uri in
(from uri in model.RedirectUris?.Split(new[] { " ", "," }, StringSplitOptions.RemoveEmptyEntries) ?? Array.Empty<string>()
select new Uri(uri, UriKind.Absolute)))
{
descriptor.RedirectUris.Add(uri);
}
await _applicationManager.UpdateAsync(application, descriptor);
if (string.IsNullOrEmpty(returnUrl))
{
return RedirectToAction("Index");
}
return LocalRedirect(returnUrl);
}
[HttpPost]
public async Task<IActionResult> Delete(string id)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageApplications))
{
return Forbid();
}
var application = await _applicationManager.FindByPhysicalIdAsync(id);
if (application == null)
{
return NotFound();
}
await _applicationManager.DeleteAsync(application);
return RedirectToAction(nameof(Index));
}
private async Task<OpenIdServerSettings> GetServerSettingsAsync()
{
if (_shellDescriptor.Features.Any(feature => feature.Id == OpenIdConstants.Features.Server))
{
var service = HttpContext.RequestServices.GetRequiredService<IOpenIdServerService>();
var settings = await service.GetSettingsAsync();
if ((await service.ValidateSettingsAsync(settings)).Any(result => result != ValidationResult.Success))
{
_notifier.Warning(H["OpenID Connect settings are not properly configured."]);
}
return settings;
}
return null;
}
}
}
| |
using System;
using System.Text;
namespace LiteNetLib.Utils
{
public class NetDataWriter
{
protected byte[] _data;
protected int _position;
private int _maxLength;
private readonly bool _autoResize;
public NetDataWriter()
{
_maxLength = 64;
_data = new byte[_maxLength];
_autoResize = true;
}
public NetDataWriter(bool autoResize)
{
_maxLength = 64;
_data = new byte[_maxLength];
_autoResize = autoResize;
}
public NetDataWriter(bool autoResize, int initialSize)
{
_maxLength = initialSize;
_data = new byte[_maxLength];
_autoResize = autoResize;
}
public void ResizeIfNeed(int newSize)
{
if (_maxLength < newSize)
{
while (_maxLength < newSize)
{
_maxLength *= 2;
}
Array.Resize(ref _data, _maxLength);
}
}
public void Reset(int size)
{
ResizeIfNeed(size);
_position = 0;
}
public void Reset()
{
_position = 0;
}
public byte[] CopyData()
{
byte[] resultData = new byte[_position];
Buffer.BlockCopy(_data, 0, resultData, 0, _position);
return resultData;
}
public byte[] Data
{
get { return _data; }
}
public int Length
{
get { return _position; }
}
public void Put(float value)
{
if (_autoResize)
ResizeIfNeed(_position + 4);
FastBitConverter.GetBytes(_data, _position, value);
_position += 4;
}
public void Put(double value)
{
if (_autoResize)
ResizeIfNeed(_position + 8);
FastBitConverter.GetBytes(_data, _position, value);
_position += 8;
}
public void Put(long value)
{
if (_autoResize)
ResizeIfNeed(_position + 8);
FastBitConverter.GetBytes(_data, _position, value);
_position += 8;
}
public void Put(ulong value)
{
if (_autoResize)
ResizeIfNeed(_position + 8);
FastBitConverter.GetBytes(_data, _position, value);
_position += 8;
}
public void Put(int value)
{
if (_autoResize)
ResizeIfNeed(_position + 4);
FastBitConverter.GetBytes(_data, _position, value);
_position += 4;
}
public void Put(uint value)
{
if (_autoResize)
ResizeIfNeed(_position + 4);
FastBitConverter.GetBytes(_data, _position, value);
_position += 4;
}
public void Put(ushort value)
{
if (_autoResize)
ResizeIfNeed(_position + 2);
FastBitConverter.GetBytes(_data, _position, value);
_position += 2;
}
public void Put(short value)
{
if (_autoResize)
ResizeIfNeed(_position + 2);
FastBitConverter.GetBytes(_data, _position, value);
_position += 2;
}
public void Put(sbyte value)
{
if (_autoResize)
ResizeIfNeed(_position + 1);
_data[_position] = (byte)value;
_position++;
}
public void Put(byte value)
{
if (_autoResize)
ResizeIfNeed(_position + 1);
_data[_position] = value;
_position++;
}
public void Put(byte[] data, int offset, int length)
{
if (_autoResize)
ResizeIfNeed(_position + length);
Buffer.BlockCopy(data, offset, _data, _position, length);
_position += length;
}
public void Put(byte[] data)
{
if (_autoResize)
ResizeIfNeed(_position + data.Length);
Buffer.BlockCopy(data, 0, _data, _position, data.Length);
_position += data.Length;
}
public void PutBytesWithLength(byte[] data, int offset, int length)
{
if (_autoResize)
ResizeIfNeed(_position + length);
Put(length);
Buffer.BlockCopy(data, offset, _data, _position, length);
_position += length;
}
public void PutBytesWithLength(byte[] data)
{
if (_autoResize)
ResizeIfNeed(_position + data.Length);
Put(data.Length);
Buffer.BlockCopy(data, 0, _data, _position, data.Length);
_position += data.Length;
}
public void Put(bool value)
{
if (_autoResize)
ResizeIfNeed(_position + 1);
_data[_position] = (byte)(value ? 1 : 0);
_position++;
}
public void PutArray(float[] value)
{
ushort len = value == null ? (ushort)0 : (ushort)value.Length;
if (_autoResize)
ResizeIfNeed(_position + len * 4 + 2);
Put(len);
for (int i = 0; i < len; i++)
{
Put(value[i]);
}
}
public void PutArray(double[] value)
{
ushort len = value == null ? (ushort)0 : (ushort)value.Length;
if (_autoResize)
ResizeIfNeed(_position + len * 8 + 2);
Put(len);
for (int i = 0; i < len; i++)
{
Put(value[i]);
}
}
public void PutArray(long[] value)
{
ushort len = value == null ? (ushort)0 : (ushort)value.Length;
if (_autoResize)
ResizeIfNeed(_position + len * 8 + 2);
Put(len);
for (int i = 0; i < len; i++)
{
Put(value[i]);
}
}
public void PutArray(ulong[] value)
{
ushort len = value == null ? (ushort)0 : (ushort)value.Length;
if (_autoResize)
ResizeIfNeed(_position + len * 8 + 2);
Put(len);
for (int i = 0; i < len; i++)
{
Put(value[i]);
}
}
public void PutArray(int[] value)
{
ushort len = value == null ? (ushort)0 : (ushort)value.Length;
if (_autoResize)
ResizeIfNeed(_position + len * 4 + 2);
Put(len);
for (int i = 0; i < len; i++)
{
Put(value[i]);
}
}
public void PutArray(uint[] value)
{
ushort len = value == null ? (ushort)0 : (ushort)value.Length;
if (_autoResize)
ResizeIfNeed(_position + len * 4 + 2);
Put(len);
for (int i = 0; i < len; i++)
{
Put(value[i]);
}
}
public void PutArray(ushort[] value)
{
ushort len = value == null ? (ushort)0 : (ushort)value.Length;
if (_autoResize)
ResizeIfNeed(_position + len * 2 + 2);
Put(len);
for (int i = 0; i < len; i++)
{
Put(value[i]);
}
}
public void PutArray(short[] value)
{
ushort len = value == null ? (ushort)0 : (ushort)value.Length;
if (_autoResize)
ResizeIfNeed(_position + len * 2 + 2);
Put(len);
for (int i = 0; i < len; i++)
{
Put(value[i]);
}
}
public void PutArray(bool[] value)
{
ushort len = value == null ? (ushort)0 : (ushort)value.Length;
if (_autoResize)
ResizeIfNeed(_position + len + 2);
Put(len);
for (int i = 0; i < len; i++)
{
Put(value[i]);
}
}
public void PutArray(string[] value)
{
ushort len = value == null ? (ushort)0 : (ushort)value.Length;
Put(len);
for (int i = 0; i < value.Length; i++)
{
Put(value[i]);
}
}
public void PutArray(string[] value, int maxLength)
{
ushort len = value == null ? (ushort)0 : (ushort)value.Length;
Put(len);
for (int i = 0; i < len; i++)
{
Put(value[i], maxLength);
}
}
public void Put(NetEndPoint endPoint)
{
Put(endPoint.Host);
Put(endPoint.Port);
}
public void Put(string value)
{
if (string.IsNullOrEmpty(value))
{
Put(0);
return;
}
//put bytes count
int bytesCount = Encoding.UTF8.GetByteCount(value);
if (_autoResize)
ResizeIfNeed(_position + bytesCount + 4);
Put(bytesCount);
//put string
Encoding.UTF8.GetBytes(value, 0, value.Length, _data, _position);
_position += bytesCount;
}
public void Put(string value, int maxLength)
{
if (string.IsNullOrEmpty(value))
{
Put(0);
return;
}
int length = value.Length > maxLength ? maxLength : value.Length;
//calculate max count
int bytesCount = Encoding.UTF8.GetByteCount(value);
if (_autoResize)
ResizeIfNeed(_position + bytesCount + 4);
//put bytes count
Put(bytesCount);
//put string
Encoding.UTF8.GetBytes(value, 0, length, _data, _position);
_position += bytesCount;
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Localisation;
using osu.Game.Beatmaps;
using osu.Game.Graphics;
using osu.Game.Graphics.Sprites;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.UI;
using osu.Game.Scoring;
using osuTK;
namespace osu.Game.Overlays.BeatmapSet.Scores
{
public class TopScoreStatisticsSection : CompositeDrawable
{
private const float margin = 10;
private const float top_columns_min_width = 64;
private const float bottom_columns_min_width = 45;
private readonly FontUsage smallFont = OsuFont.GetFont(size: 16);
private readonly FontUsage largeFont = OsuFont.GetFont(size: 22, weight: FontWeight.Light);
private readonly TextColumn totalScoreColumn;
private readonly TextColumn accuracyColumn;
private readonly TextColumn maxComboColumn;
private readonly TextColumn ppColumn;
private readonly FillFlowContainer<InfoColumn> statisticsColumns;
private readonly ModsInfoColumn modsColumn;
[Resolved]
private ScoreManager scoreManager { get; set; }
public TopScoreStatisticsSection()
{
RelativeSizeAxes = Axes.X;
AutoSizeAxes = Axes.Y;
InternalChild = new FillFlowContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Direction = FillDirection.Vertical,
Children = new Drawable[]
{
new FillFlowContainer
{
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
AutoSizeAxes = Axes.Both,
Direction = FillDirection.Horizontal,
Spacing = new Vector2(margin, 0),
Children = new Drawable[]
{
totalScoreColumn = new TextColumn("total score", largeFont, top_columns_min_width),
accuracyColumn = new TextColumn("accuracy", largeFont, top_columns_min_width),
maxComboColumn = new TextColumn("max combo", largeFont, top_columns_min_width)
}
},
new FillFlowContainer
{
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
AutoSizeAxes = Axes.Both,
Direction = FillDirection.Horizontal,
Spacing = new Vector2(margin, 0),
Children = new Drawable[]
{
statisticsColumns = new FillFlowContainer<InfoColumn>
{
AutoSizeAxes = Axes.Both,
Direction = FillDirection.Horizontal,
Spacing = new Vector2(margin, 0),
},
ppColumn = new TextColumn("pp", smallFont, bottom_columns_min_width),
modsColumn = new ModsInfoColumn(),
}
},
}
};
}
[BackgroundDependencyLoader]
private void load()
{
if (score != null)
totalScoreColumn.Current = scoreManager.GetBindableTotalScoreString(score);
}
private ScoreInfo score;
/// <summary>
/// Sets the score to be displayed.
/// </summary>
public ScoreInfo Score
{
set
{
if (score == value)
return;
score = value;
accuracyColumn.Text = value.DisplayAccuracy;
maxComboColumn.Text = $@"{value.MaxCombo:N0}x";
ppColumn.Alpha = value.Beatmap?.Status.GrantsPerformancePoints() == true ? 1 : 0;
ppColumn.Text = $@"{value.PP:N0}";
statisticsColumns.ChildrenEnumerable = value.GetStatisticsForDisplay().Select(createStatisticsColumn);
modsColumn.Mods = value.Mods;
if (scoreManager != null)
totalScoreColumn.Current = scoreManager.GetBindableTotalScoreString(value);
}
}
private TextColumn createStatisticsColumn(HitResultDisplayStatistic stat) => new TextColumn(stat.DisplayName, smallFont, bottom_columns_min_width)
{
Text = stat.MaxCount == null ? $"{stat.Count}" : $"{stat.Count}/{stat.MaxCount}"
};
private class InfoColumn : CompositeDrawable
{
private readonly Box separator;
private readonly OsuSpriteText text;
public InfoColumn(string title, Drawable content, float? minWidth = null)
{
AutoSizeAxes = Axes.Both;
Margin = new MarginPadding { Vertical = 5 };
InternalChild = new GridContainer
{
AutoSizeAxes = Axes.Both,
ColumnDimensions = new[]
{
new Dimension(GridSizeMode.AutoSize, minSize: minWidth ?? 0)
},
RowDimensions = new[]
{
new Dimension(GridSizeMode.AutoSize),
new Dimension(GridSizeMode.Absolute, 2),
new Dimension(GridSizeMode.AutoSize)
},
Content = new[]
{
new Drawable[]
{
text = new OsuSpriteText
{
Font = OsuFont.GetFont(size: 10, weight: FontWeight.Bold),
Text = title.ToUpper(),
// 2px padding bottom + 1px vertical to compensate for the additional spacing because of 1.25 line-height in osu-web
Padding = new MarginPadding { Top = 1, Bottom = 3 }
}
},
new Drawable[]
{
separator = new Box
{
Anchor = Anchor.TopLeft,
RelativeSizeAxes = Axes.X,
Height = 2,
},
},
new[]
{
// osu-web has 4px margin here but also uses 0.9 line-height, reducing margin to 2px seems like a good alternative to that
content.With(c => c.Margin = new MarginPadding { Top = 2 })
}
}
};
}
[BackgroundDependencyLoader]
private void load(OverlayColourProvider colourProvider)
{
text.Colour = colourProvider.Foreground1;
separator.Colour = colourProvider.Background3;
}
}
private class TextColumn : InfoColumn
{
private readonly SpriteText text;
public TextColumn(string title, FontUsage font, float? minWidth = null)
: this(title, new OsuSpriteText { Font = font }, minWidth)
{
}
private TextColumn(string title, SpriteText text, float? minWidth = null)
: base(title, text, minWidth)
{
this.text = text;
}
public LocalisableString Text
{
set => text.Text = value;
}
public Bindable<string> Current
{
get => text.Current;
set => text.Current = value;
}
}
private class ModsInfoColumn : InfoColumn
{
private readonly FillFlowContainer modsContainer;
public ModsInfoColumn()
: this(new FillFlowContainer
{
AutoSizeAxes = Axes.X,
Direction = FillDirection.Horizontal,
Spacing = new Vector2(1),
Height = 18f
})
{
}
private ModsInfoColumn(FillFlowContainer modsContainer)
: base("mods", modsContainer)
{
this.modsContainer = modsContainer;
}
public IEnumerable<Mod> Mods
{
set
{
modsContainer.Clear();
modsContainer.Children = value.Select(mod => new ModIcon(mod)
{
AutoSizeAxes = Axes.Both,
Scale = new Vector2(0.25f),
}).ToList();
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using gbp.AI.GeneticAlgorithms;
namespace Bipedal5LinkTest
{
public partial class Form1 : Form
{
private Bipedal5Link.Bipedal5Link B;
private Bipedal5Link.CentralPatternGenerator CPG;
private bool Abort;
private Bitmap DisplayBuffer;
private Graphics DisplayBufferG;
private Graphics LabelDisplayG;
private Bitmap StatusBuffer;
private Graphics StatusBufferG;
private Graphics LabelStatusG;
private Graphics LabelStatus2G;
private Bitmap CPGBuffer;
private Graphics CPGBufferG;
private Graphics LabelCPGG;
private Color C1;
private Font F1;
private double PiOverTwo;
private Bipedal5Link.ServoController Hardware;
private gbp.AI.GeneticAlgorithms.GeneticAlgorithms GA;
public Form1()
{
InitializeComponent();
DisplayBuffer = new Bitmap(1260, 350);
DisplayBufferG = Graphics.FromImage(DisplayBuffer);
DisplayBufferG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
LabelDisplayG = labelDisplay.CreateGraphics();
LabelDisplayG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
StatusBuffer = new Bitmap(950, 170);
StatusBufferG = Graphics.FromImage(StatusBuffer);
//StatusBufferG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
LabelStatusG = labelStatus.CreateGraphics();
LabelStatus2G = labelStatus2.CreateGraphics();
//LabelStatusG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
CPGBuffer = new Bitmap(300, 240);
CPGBufferG = Graphics.FromImage(CPGBuffer);
CPGBufferG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
LabelCPGG = labelCPG.CreateGraphics();
LabelCPGG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
NewBipedal5Link();
NewCentralPatternGenerator();
C1 = Color.FromArgb(35, 22, 0);
F1 = new Font("Arial", 8);
PiOverTwo = Math.PI / 2;
Hardware = new Bipedal5Link.ServoController("COM1");
}
private double YGroundFlat(double x)
{
return 0;
//return x / 80;
}
private void NewBipedal5Link()
{
double m = double.Parse(textBoxMsM.Text);
double m1 = double.Parse(textBoxMsM1.Text);
double l1 = double.Parse(textBoxMsL1.Text);
double m2 = double.Parse(textBoxMsM2.Text);
double l2 = double.Parse(textBoxMsL2.Text);
double b1 = double.Parse(textBoxMsB1.Text);
double b2 = double.Parse(textBoxMsB2.Text);
double kk = double.Parse(textBoxMsKk.Text);
double bk = double.Parse(textBoxMsBk.Text);
double kg = double.Parse(textBoxMsKg.Text);
double bg = double.Parse(textBoxMsBg.Text);
double ss = double.Parse(textBoxMsSS.Text);
double g = double.Parse(textBoxMsG.Text);
double hipx = double.Parse(textBoxMsHipX.Text);
double hipy = double.Parse(textBoxMsHipY.Text);
double theta = double.Parse(textBoxMsTheta.Text);
double theta1 = double.Parse(textBoxMsTheta1.Text);
double theta2 = double.Parse(textBoxMsTheta2.Text);
double theta3 = double.Parse(textBoxMsTheta3.Text);
double theta4 = double.Parse(textBoxMsTheta4.Text);
B = new Bipedal5Link.Bipedal5Link(m, m1, m2, l1, l2, kg, bg, g, new Bipedal5Link.PointD(hipx, hipy), new double[] {theta, theta1, theta2, theta3, theta4}, ss, new Bipedal5Link.Bipedal5Link.YGroundDelegate(YGroundFlat));
//B.RunStep(0);
DisplayBufferG.Clear(C1);
B.Draw(DisplayBufferG, new PointF(10, 210), 500);
LabelDisplayG.DrawImage(DisplayBuffer, 0, 0);
}
private void NewCentralPatternGenerator()
{
double hipTauU = double.Parse(textBoxCpgHipTauU.Text);
double hipTauV = double.Parse(textBoxCpgHipTauV.Text);
double hipBeta = double.Parse(textBoxCpgHipBeta.Text);
double kneeTauU = double.Parse(textBoxCpgKneeTauU.Text);
double kneeTauV = double.Parse(textBoxCpgKneeTauV.Text);
double kneeBeta = double.Parse(textBoxCpgKneeBeta.Text);
double wfe = double.Parse(textBoxCpgWFE.Text);
double w0 = double.Parse(textBoxCpgW1.Text);
double w1 = double.Parse(textBoxCpgW2.Text);
double w2 = double.Parse(textBoxCpgW3.Text);
double w3 = double.Parse(textBoxCpgW4.Text);
double w4 = double.Parse(textBoxCpgW5.Text);
double w5 = double.Parse(textBoxCpgW6.Text);
double w6 = double.Parse(textBoxCpgW7.Text);
double w7 = double.Parse(textBoxCpgW8.Text);
double[,] weights = new double[9, 9];
weights[1, 2] = wfe;
weights[1, 3] = w0;
weights[1, 4] = w1;
weights[2, 1] = wfe;
weights[2, 3] = w2;
weights[2, 4] = w3;
weights[3, 1] = w0;
weights[3, 2] = w1;
weights[3, 4] = wfe;
weights[4, 1] = w2;
weights[4, 2] = w3;
weights[4, 3] = wfe;
weights[5, 1] = w4;
weights[5, 2] = w5;
weights[5, 6] = wfe;
weights[6, 1] = w6;
weights[6, 2] = w7;
weights[6, 5] = wfe;
weights[7, 3] = w4;
weights[7, 4] = w5;
weights[7, 8] = wfe;
weights[8, 3] = w6;
weights[8, 4] = w7;
weights[8, 7] = wfe;
CPG = new Bipedal5Link.CentralPatternGenerator(hipTauU, hipTauV, hipBeta, kneeTauU, kneeTauV, kneeBeta, weights);
}
private void linkLabelNew_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
NewBipedal5Link();
}
private void linkLabelRun_LinkClickedOriginal(object sender, LinkLabelLinkClickedEventArgs e)
{
NewBipedal5Link();
NewCentralPatternGenerator();
timerUnstable.Stop();
panelUnstable.Hide();
int steps = int.Parse(textBoxSteps.Text);
double deltatime = double.Parse(textBoxDeltaTime.Text);
double u0 = double.Parse(textBoxCpgU0.Text);
double a1 = double.Parse(textBoxCouplingA1.Text);
double a2 = double.Parse(textBoxCouplingA2.Text);
int hipfixsteps = int.Parse(textBoxMsHipFixSteps.Text);
StatusBufferG.Clear(Color.Black);
StatusBufferG.DrawString(B.Parameters(), F1, Brushes.DarkOrange, 0, 10);
StatusBufferG.DrawString(CPG.Parameters(), F1, Brushes.DarkOrange, 440, 10);
double[] joints;
double[] feedback = new double[9];
double f1;
double f2;
double f3;
double f4;
double f5;
double f6;
double f7;
double f8;
for (int s = 0 ; s < 100000 ; s++)
joints = CPG.RunStep(u0, feedback, deltatime);
B.HipFixed = true;
Abort = false;
// time coupling
double simulationtime = 0;
DateTime realtimestart = DateTime.Now;
TimeSpan realtime;
DisplayBufferG.Clear(Color.White);
for (int s = 0 ; (s < steps) & !Abort ; s++)
{
// Run CPG step
f1 = -a1 * feedback[1] + a1 * feedback[2] + a1 * feedback[6];
f2 = -f1;
f3 = -a1 * feedback[2] + a1 * feedback[1] + a1 * feedback[5];
f4 = -f3;
f5 = a2 * feedback[6] * feedback[4];
f6 = -f5;
f7 = a2 * feedback[5] * feedback[3];
f8 = -f7;
joints = CPG.RunStep(u0, new double[] { 0, f1, f2, f3, f4, f5, f6, f7, f8 }, deltatime);
// Run Musculo-Skeletal system step
if (s > hipfixsteps)
B.HipFixed = false;
feedback = B.RunStep(joints, deltatime);
if (!B.IsStable())
timerUnstable.Start();
simulationtime = s * deltatime;
realtime = DateTime.Now.Subtract(realtimestart);
if (simulationtime > realtime.TotalSeconds)
{
//DisplayBufferG.Clear(C1);
B.Draw(DisplayBufferG, new PointF(10, 240), 500);
LabelDisplayG.DrawImage(DisplayBuffer, 0, 0);
StatusBufferG.FillRectangle(Brushes.Black, 240, 0, 200, 160);
StatusBufferG.DrawString(B.Status(), F1, Brushes.DarkOrange, 240, 10);
StatusBufferG.FillRectangle(Brushes.Black, 640, 0, 200, 160);
StatusBufferG.DrawString(CPG.Status(), F1, Brushes.DarkOrange, 640, 10);
LabelStatusG.DrawImage(StatusBuffer, 0, 0);
CPGBufferG.Clear(Color.Black);
CPG.Draw(CPGBufferG);
LabelCPGG.DrawImage(CPGBuffer, 0, 0);
System.Windows.Forms.Application.DoEvents();
}
}
}
private void linkLabelRun_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
NewBipedal5Link();
NewCentralPatternGenerator();
timerUnstable.Stop();
panelUnstable.Hide();
int steps = int.Parse(textBoxSteps.Text);
double deltatime = double.Parse(textBoxDeltaTime.Text);
double u0 = double.Parse(textBoxCpgU0.Text);
double a1 = double.Parse(textBoxCouplingA1.Text);
double a2 = double.Parse(textBoxCouplingA2.Text);
int hipfixsteps = int.Parse(textBoxMsHipFixSteps.Text);
StatusBufferG.Clear(Color.Black);
StatusBufferG.DrawString(B.Parameters(), F1, Brushes.DarkOrange, 0, 10);
StatusBufferG.DrawString(CPG.Parameters(), F1, Brushes.DarkOrange, 440, 10);
double[] joints;
double[] feedback = new double[9];
double f1;
double f2;
double f3;
double f4;
double f5;
double f6;
double f7;
double f8;
for (int s = 0 ; s < 100000 ; s++)
joints = CPG.RunStep(u0, feedback, deltatime);
B.HipFixed = true;
Abort = false;
// time coupling
double simulationtime = 0;
DateTime realtimestart = DateTime.Now;
TimeSpan realtime;
DisplayBufferG.Clear(Color.White);
for (int s = 0 ; (s < steps) & !Abort ; s++)
{
// Run CPG step
f1 = -a1 * feedback[1] + a1 * feedback[2] + a1 * feedback[6];
f2 = -f1;
f3 = -a1 * feedback[2] + a1 * feedback[1] + a1 * feedback[5];
f4 = -f3;
f5 = a2 * feedback[6] * feedback[4];
f6 = -f5;
f7 = a2 * feedback[5] * feedback[3];
f8 = -f7;
joints = CPG.RunStep(u0, new double[] { 0, f1, f2, f3, f4, f5, f6, f7, f8 }, deltatime);
// Run Musculo-Skeletal system step
if (s > hipfixsteps)
B.HipFixed = false;
feedback = B.RunStep(joints, deltatime);
if (!B.IsStable())
timerUnstable.Start();
simulationtime = s * deltatime;
realtime = DateTime.Now.Subtract(realtimestart);
//if (s % 10000 == 0)
if (simulationtime > realtime.TotalSeconds)
{
DisplayBufferG.Clear(C1);
B.Draw(DisplayBufferG, new PointF(10, 210), 500);
LabelDisplayG.DrawImage(DisplayBuffer, 0, 0);
StatusBufferG.FillRectangle(Brushes.Black, 240, 0, 200, 160);
StatusBufferG.DrawString(B.Status(), F1, Brushes.DarkOrange, 240, 10);
StatusBufferG.FillRectangle(Brushes.Black, 640, 0, 200, 160);
StatusBufferG.DrawString(CPG.Status(), F1, Brushes.DarkOrange, 640, 10);
LabelStatusG.DrawImage(StatusBuffer, 0, 0);
CPGBufferG.Clear(Color.Black);
CPG.Draw(CPGBufferG);
LabelCPGG.DrawImage(CPGBuffer, 0, 0);
System.Windows.Forms.Application.DoEvents();
}
}
}
private void linkLabelStop_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
Abort = true;
timerUnstable.Stop();
panelUnstable.Hide();
}
private void labelDisplay_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawImage(DisplayBuffer, 0, 0);
}
private void linkLabelExit_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
Abort = true;
if (Hardware.Running)
Hardware.Stop();
this.Close();
}
private void labelStatus_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawImage(StatusBuffer, 0, 0);
}
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
NewCentralPatternGenerator();
}
private void timerUnstable_Tick(object sender, EventArgs e)
{
panelUnstable.Visible = !panelUnstable.Visible;
}
private void labelCPG_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawImage(CPGBuffer, 0, 0);
}
private void textBoxMsTheta1_TextChanged(object sender, EventArgs e)
{
}
private void textBoxMsTheta3_TextChanged(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
labelVersion.Text = "v1.0.4";
CheckForIllegalCrossThreadCalls = false;
}
private void linkLabelRunGA_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
int steps = int.Parse(textBoxSteps.Text);
double deltatime = double.Parse(textBoxDeltaTime.Text);
int hipfixsteps = int.Parse(textBoxMsHipFixSteps.Text);
int size = int.Parse(textBoxGASize.Text);
int generations = int.Parse(textBoxGAGenerations.Text);
float fitnesstreshold = float.Parse(textBoxGAFitnessTreshold.Text);
float crossover = float.Parse(textBoxGACrossover.Text);
float mutation = float.Parse(textBoxGAMutation.Text);
bool elitism = checkBoxGAElitism.Checked;
int tournamentsize = int.Parse(textBoxGATournamentSize.Text);
float tournamentchance = float.Parse(textBoxGATournamentChance.Text);
double m = double.Parse(textBoxMsM.Text);
double m1 = double.Parse(textBoxMsM1.Text);
double l1 = double.Parse(textBoxMsL1.Text);
double m2 = double.Parse(textBoxMsM2.Text);
double l2 = double.Parse(textBoxMsL2.Text);
double kg = double.Parse(textBoxMsKg.Text);
double bg = double.Parse(textBoxMsBg.Text);
double ss = double.Parse(textBoxMsSS.Text);
double g = double.Parse(textBoxMsG.Text);
double hipx = double.Parse(textBoxMsHipX.Text);
double hipy = double.Parse(textBoxMsHipY.Text);
double theta = double.Parse(textBoxMsTheta.Text);
double theta1 = double.Parse(textBoxMsTheta1.Text);
double theta2 = double.Parse(textBoxMsTheta2.Text);
double theta3 = double.Parse(textBoxMsTheta3.Text);
double theta4 = double.Parse(textBoxMsTheta4.Text);
GA = new GABipedal5Link(size, 22, 0f, 1f, generations, crossover, mutation, tournamentsize, tournamentchance, elitism, fitnesstreshold, new SolutionFoundDelegate(GASolutionFound), new StoppedDelegate(GAStopped), new ImprovementDelegate(Improvement), LabelStatusG, LabelCPGG, LabelStatus2G, LabelDisplayG, Color.Black, Color.Orange, Color.DarkOrange, steps, deltatime, hipfixsteps, m, m1, m2, l1, l2, kg, bg, g, new Bipedal5Link.PointD(hipx, hipy), new double[] { theta, theta1, theta2, theta3, theta4 }, ss, new Bipedal5Link.Bipedal5Link.YGroundDelegate(YGroundFlat));
GA.ShowEvaluation = checkBoxGAEvaluation.Checked;
GA.Evolve();
}
private void Improvement(string text)
{
textBoxImprovement.Text += text;
}
private void GASolutionFound(float[] genome, int generation)
{
double w0 = -genome[0] * 2;
double w1 = -genome[1] * 2;
double w2 = -genome[2] * 2;
double w3 = -genome[3] * 2;
double w4 = -genome[4] * 2;
double w5 = -genome[5] * 2;
double w6 = -genome[6] * 2;
double w7 = -genome[7] * 2;
double x0 = genome[8] > 0.5 ? 1 : 0;
double x1 = genome[9] > 0.5 ? 1 : 0;
double x2 = genome[10] > 0.5 ? 1 : 0;
double x3 = genome[11] > 0.5 ? 1 : 0;
double x4 = genome[12] > 0.5 ? 1 : 0;
double x5 = genome[13] > 0.5 ? 1 : 0;
double x6 = genome[14] > 0.5 ? 1 : 0;
double x7 = genome[15] > 0.5 ? 1 : 0;
w0 = w0 * x0;
w1 = w1 * x1;
w2 = w2 * x2;
w3 = w3 * x3;
w4 = w4 * x4;
w5 = w5 * x5;
w6 = w6 * x6;
w7 = w7 * x7;
double wfe = -2;
double u0 = genome[16] * 5;
double hipTauU = genome[17] / 2;
double hipTauV = genome[18] / 2;
double hipBeta = genome[19] * 5;
double kneeTauU = hipTauU / 2;
double kneeTauV = hipTauV / 2;
double kneeBeta = hipBeta;
double a1 = genome[20] * 2;
double a2 = genome[21] * 2;
double[,] weights = new double[9, 9];
weights[1, 2] = wfe;
weights[1, 3] = w0;
weights[1, 4] = w1;
weights[2, 1] = wfe;
weights[2, 3] = w2;
weights[2, 4] = w3;
weights[3, 1] = w0;
weights[3, 2] = w1;
weights[3, 4] = wfe;
weights[4, 1] = w2;
weights[4, 2] = w3;
weights[4, 3] = wfe;
weights[5, 1] = w4;
weights[5, 2] = w5;
weights[5, 6] = wfe;
weights[6, 1] = w6;
weights[6, 2] = w7;
weights[6, 5] = wfe;
weights[7, 3] = w4;
weights[7, 4] = w5;
weights[7, 8] = wfe;
weights[8, 3] = w6;
weights[8, 4] = w7;
weights[8, 7] = wfe;
textBoxCpgHipTauU.Text = hipTauU.ToString("f3");
textBoxCpgHipTauV.Text = hipTauV.ToString("f3");
textBoxCpgHipBeta.Text = hipBeta.ToString("f3");
textBoxCpgKneeTauU.Text = kneeTauU.ToString("f3");
textBoxCpgKneeTauV.Text = kneeTauV.ToString("f3");
textBoxCpgKneeBeta.Text = kneeBeta.ToString("f3");
textBoxCpgU0.Text = u0.ToString("f3");
textBoxCpgWFE.Text = wfe.ToString("f3");
textBoxCpgW1.Text = w0.ToString("f3");
textBoxCpgW2.Text = w1.ToString("f3");
textBoxCpgW3.Text = w2.ToString("f3");
textBoxCpgW4.Text = w3.ToString("f3");
textBoxCpgW5.Text = w4.ToString("f3");
textBoxCpgW6.Text = w5.ToString("f3");
textBoxCpgW7.Text = w6.ToString("f3");
textBoxCpgW8.Text = w7.ToString("f3");
textBoxCouplingA1.Text = a1.ToString("f3");
textBoxCouplingA2.Text = a2.ToString("f3");
}
private void GASolutionFound2(float[] solution, int generation)
{
//double w0 = -solution[0] * 2;
//double w1 = -solution[1] * 2;
//double w2 = -solution[2] * 2;
//double w3 = -solution[3] * 2;
//double w4 = -solution[4] * 2;
//double w5 = -solution[5] * 2;
//double w6 = -solution[6] * 2;
//double w7 = -solution[7] * 2;
//double x0 = solution[8] > 0.5 ? 1 : 0;
//double x1 = solution[9] > 0.5 ? 1 : 0;
//double x2 = solution[10] > 0.5 ? 1 : 0;
//double x3 = solution[11] > 0.5 ? 1 : 0;
//double x4 = solution[12] > 0.5 ? 1 : 0;
//double x5 = solution[13] > 0.5 ? 1 : 0;
//double x6 = solution[14] > 0.5 ? 1 : 0;
//double x7 = solution[15] > 0.5 ? 1 : 0;
double w0 = -1;
double w1 = 0;
double w2 = 0;
double w3 = -1;
double w4 = 0;
double w5 = -2;
double w6 = -2;
double w7 = -0;
double x0 = 1;
double x1 = 0;
double x2 = 0;
double x3 = 1;
double x4 = 0;
double x5 = 1;
double x6 = 1;
double x7 = 0;
double wfe = -2;
double u0 = solution[0] * 5;
double hipTauU = solution[1] / 10;
double hipTauV = solution[2] / 10;
double hipBeta = solution[3] * 5;
double kneeTauU = hipTauU / 2;
double kneeTauV = hipTauV / 2;
double kneeBeta = hipBeta;
w0 = w0 * x0;
w1 = w1 * x1;
w2 = w2 * x2;
w3 = w3 * x3;
w4 = w4 * x4;
w5 = w5 * x5;
w6 = w6 * x6;
w7 = w7 * x7;
textBoxCpgHipTauU.Text = hipTauU.ToString("f3");
textBoxCpgHipTauV.Text = hipTauV.ToString("f3");
textBoxCpgHipBeta.Text = hipBeta.ToString("f3");
textBoxCpgKneeTauU.Text = kneeTauU.ToString("f3");
textBoxCpgKneeTauV.Text = kneeTauV.ToString("f3");
textBoxCpgKneeBeta.Text = kneeBeta.ToString("f3");
textBoxCpgU0.Text = u0.ToString("f3");
textBoxCpgWFE.Text = wfe.ToString("f3");
textBoxCpgW1.Text = w0.ToString("f3");
textBoxCpgW2.Text = w1.ToString("f3");
textBoxCpgW3.Text = w2.ToString("f3");
textBoxCpgW4.Text = w3.ToString("f3");
textBoxCpgW5.Text = w4.ToString("f3");
textBoxCpgW6.Text = w5.ToString("f3");
textBoxCpgW7.Text = w6.ToString("f3");
textBoxCpgW8.Text = w7.ToString("f3");
}
private void GAStopped()
{
labelGAStatus.Text = ".";
}
private class GABipedal5Link : gbp.AI.GeneticAlgorithms.GeneticAlgorithms
{
private int Steps;
private double DeltaTime;
private int HipFixSteps;
private double M;
private double M1;
private double M2;
private double G;
private double KG;
private double BG;
private double L1;
private double L2;
private double ServoSpeed;
private Bipedal5Link.Bipedal5Link.YGroundDelegate YGround;
private Bipedal5Link.PointD Hip;
private double[] Theta;
private Color C1;
private Font F1;
public GABipedal5Link(int size, int chromosomeLength, float geneMinimum, float geneMaximum, int generations, float crossoverChance, float mutationChance, int tournamentSize, float tournamentChance, bool elitism, float fitnessTreshold, SolutionFoundDelegate sf, StoppedDelegate stp, ImprovementDelegate imp, Graphics gReport, Graphics gReport2, Graphics gReport3, Graphics gFitness, Color backColor, Color foreColor1, Color foreColor2, int steps, double deltaTime, int hipFixSteps, double m, double m1, double m2, double l1, double l2, double kg, double bg, double g, Bipedal5Link.PointD hip, double[] theta, double servoSpeed, Bipedal5Link.Bipedal5Link.YGroundDelegate yGround)
: base(size, chromosomeLength, geneMinimum, geneMaximum, generations, crossoverChance, mutationChance, tournamentSize, tournamentChance, elitism, fitnessTreshold, sf, stp, imp, gReport, gReport2, gReport3, gFitness, backColor, foreColor1, foreColor2)
{
Steps = steps;
DeltaTime = deltaTime;
HipFixSteps = hipFixSteps;
M = m;
M1 = m1;
M2 = m2;
G = g;
KG = kg;
BG = bg;
L1 = l1;
L2 = l2;
ServoSpeed = servoSpeed;
YGround = yGround;
Hip = hip;
Theta = theta;
IndividualsDrawn = false;
C1 = Color.FromArgb(35, 22, 0);
F1 = new Font("Arial", 8);
}
public override void DrawIndividual(float[] individual, Graphics g, RectangleF position)
{
}
public float Fitness2(float[] individual, int index, bool showEvaluation)
{
//DrawIndividual(individual, GFitnessBufferG, new RectangleF(0, 0, 200, 100));
double wfe = -2;
double wlr = -1;
double whk = -1;
double u0 = individual[0] * 5;
double hipTauU = individual[1] / 10;
double hipTauV = individual[2] / 10;
double hipBeta = individual[3] * 5;
double kneeTauU = hipTauU / 2;
double kneeTauV = hipTauV / 2;
double kneeBeta = hipBeta;
string parameters = "u0 = " + u0.ToString("f2") + ", hTauU = " + hipTauU.ToString("f2") + ", hTauV = " + hipTauV.ToString("f2") + ", hBeta = " + hipBeta.ToString("f2") + ", kTauU = " + kneeTauU.ToString("f2") + ", kTauV = " + kneeTauV.ToString("f2") + ", kBeta = " + kneeBeta.ToString("f2");
Bipedal5Link.CentralPatternGenerator cpg = new Bipedal5Link.CentralPatternGenerator(hipTauU, hipTauV, hipBeta, kneeTauU, kneeTauV, kneeBeta, wfe, whk, wlr);
Bipedal5Link.Bipedal5Link b = new Bipedal5Link.Bipedal5Link(M, M1, M2, L1, L2, KG, BG, G, Hip, Theta, ServoSpeed, YGround);
int update = (int)(0.005 / DeltaTime);
double[] joints;
double[] feedback = new double[9];
for (int s = 0 ; s < 100000 ; s++)
joints = cpg.RunStep(u0, feedback, DeltaTime);
b.HipFixed = true;
for (int s = 0 ; s < Steps ; s++)
{
// Run CPG step
joints = cpg.RunStep(u0, new double[] { 0, feedback[1], -feedback[1], feedback[2], -feedback[2], feedback[3], -feedback[3], feedback[4], -feedback[4] }, DeltaTime);
// Run Musculo-Skeletal system step
if (s > HipFixSteps)
b.HipFixed = false;
feedback = b.RunStep(joints, DeltaTime);
if (!b.IsStable())
break;
if (showEvaluation && (s % update == 0))
{
GFitnessBufferG.Clear(C1);
b.Draw(GFitnessBufferG, new PointF(10, 210), 500);
GFitnessBufferG.DrawString("individual " + index.ToString() + ": " + parameters, F1, Brushes.Orange, 0, 0);
GFitness.DrawImage(GFitnessBuffer, 0, 0);
//StatusBufferG.FillRectangle(Brushes.Black, 240, 0, 200, 160);
//StatusBufferG.DrawString(B.Status(), F1, Brushes.DarkOrange, 240, 10);
//StatusBufferG.FillRectangle(Brushes.Black, 640, 0, 200, 160);
//StatusBufferG.DrawString(CPG.Status(), F1, Brushes.DarkOrange, 640, 10);
//LabelStatusG.DrawImage(StatusBuffer, 0, 0);
GReport2BufferG.Clear(Color.Black);
cpg.Draw(GReport2BufferG);
GReport2.DrawImage(GReport2Buffer, 0, 0);
}
}
return (float)Math.Max(b.BehindPosition().X, 0.001);
}
public override float Fitness(float[] genome, int generation, int index, bool showEvaluation)
{
//DrawIndividual(individual, GFitnessBufferG, new RectangleF(0, 0, 200, 100));
double w0 = -genome[0] * 2;
double w1 = -genome[1] * 2;
double w2 = -genome[2] * 2;
double w3 = -genome[3] * 2;
double w4 = -genome[4] * 2;
double w5 = -genome[5] * 2;
double w6 = -genome[6] * 2;
double w7 = -genome[7] * 2;
double x0 = genome[8] > 0.5 ? 1 : 0;
double x1 = genome[9] > 0.5 ? 1 : 0;
double x2 = genome[10] > 0.5 ? 1 : 0;
double x3 = genome[11] > 0.5 ? 1 : 0;
double x4 = genome[12] > 0.5 ? 1 : 0;
double x5 = genome[13] > 0.5 ? 1 : 0;
double x6 = genome[14] > 0.5 ? 1 : 0;
double x7 = genome[15] > 0.5 ? 1 : 0;
w0 = w0 * x0;
w1 = w1 * x1;
w2 = w2 * x2;
w3 = w3 * x3;
w4 = w4 * x4;
w5 = w5 * x5;
w6 = w6 * x6;
w7 = w7 * x7;
double wfe = -2;
double u0 = genome[16] * 5;
double hipTauU = genome[17] / 2;
double hipTauV = genome[18] / 2;
double hipBeta = genome[19] * 5;
double kneeTauU = hipTauU / 2;
double kneeTauV = hipTauV / 2;
double kneeBeta = hipBeta;
double a1 = genome[20] * 2;
double a2 = genome[21] * 2;
double[,] weights = new double[9, 9];
weights[1, 2] = wfe;
weights[1, 3] = w0;
weights[1, 4] = w1;
weights[2, 1] = wfe;
weights[2, 3] = w2;
weights[2, 4] = w3;
weights[3, 1] = w0;
weights[3, 2] = w1;
weights[3, 4] = wfe;
weights[4, 1] = w2;
weights[4, 2] = w3;
weights[4, 3] = wfe;
weights[5, 1] = w4;
weights[5, 2] = w5;
weights[5, 6] = wfe;
weights[6, 1] = w6;
weights[6, 2] = w7;
weights[6, 5] = wfe;
weights[7, 3] = w4;
weights[7, 4] = w5;
weights[7, 8] = wfe;
weights[8, 3] = w6;
weights[8, 4] = w7;
weights[8, 7] = wfe;
string parameters = "u0 = " + u0.ToString("f2") + ", hTauU = " + hipTauU.ToString("f2") + ", hTauV = " + hipTauV.ToString("f2") + ", hBeta = " + hipBeta.ToString("f2") + ", kTauU = " + kneeTauU.ToString("f2") + ", kTauV = " + kneeTauV.ToString("f2") + ", kBeta = " + kneeBeta.ToString("f2");
Bipedal5Link.CentralPatternGenerator cpg = new Bipedal5Link.CentralPatternGenerator(hipTauU, hipTauV, hipBeta, kneeTauU, kneeTauV, kneeBeta, weights);
Bipedal5Link.Bipedal5Link b = new Bipedal5Link.Bipedal5Link(M, M1, M2, L1, L2, KG, BG, G, Hip, Theta, ServoSpeed, YGround);
double[] joints;
double[] feedback = new double[9];
double f1;
double f2;
double f3;
double f4;
double f5;
double f6;
double f7;
double f8;
for (int s = 0 ; s < 100000 ; s++)
joints = cpg.RunStep(u0, feedback, DeltaTime);
b.HipFixed = true;
// time coupling
double simulationtime = 0;
DateTime realtimestart = DateTime.Now;
TimeSpan realtime;
for (int s = 0 ; s < Steps ; s++)
{
// Run CPG step
//f1 = a1 * feedback[1] + a2 * feedback[4];
//f2 = -a1 * feedback[1] - a2 * feedback[4];
//f3 = a1 * feedback[2] + a2 * feedback[3];
//f4 = -a1 * feedback[2] - a2 * feedback[3];
f1 = -a1 * feedback[1] + a1 * feedback[2] + a1 * feedback[6];
f2 = -f1;
f3 = -a1 * feedback[2] + a1 * feedback[1] + a1 * feedback[5];
f4 = -f3;
f5 = a2 * feedback[6] * feedback[4];
f6 = -f5;
f7 = a2 * feedback[5] * feedback[3];
f8 = -f7;
joints = cpg.RunStep(u0, new double[] { 0, f1, f2, f3, f4, f5, f6, f7, f8 }, DeltaTime);
// Run Musculo-Skeletal system step
if (s > HipFixSteps)
b.HipFixed = false;
feedback = b.RunStep(joints, DeltaTime);
if (!b.IsStable())
break;
if (showEvaluation)
{
simulationtime = s * DeltaTime;
realtime = DateTime.Now.Subtract(realtimestart);
if (simulationtime > realtime.TotalSeconds)
{
GFitnessBufferG.Clear(C1);
b.Draw(GFitnessBufferG, new PointF(10, 210), 500);
GFitnessBufferG.DrawString("individual " + index.ToString() + ": " + parameters, F1, Brushes.Orange, 0, 0);
GFitness.DrawImage(GFitnessBuffer, 0, 0);
//StatusBufferG.FillRectangle(Brushes.Black, 240, 0, 200, 160);
//StatusBufferG.DrawString(B.Status(), F1, Brushes.DarkOrange, 240, 10);
//StatusBufferG.FillRectangle(Brushes.Black, 640, 0, 200, 160);
//StatusBufferG.DrawString(CPG.Status(), F1, Brushes.DarkOrange, 640, 10);
//LabelStatusG.DrawImage(StatusBuffer, 0, 0);
GReport2BufferG.Clear(Color.Black);
cpg.Draw(GReport2BufferG);
GReport2.DrawImage(GReport2Buffer, 0, 0);
}
}
}
float fit = (float)Math.Max(b.BehindPosition().X, 0.001);
if (showEvaluation)
{
StringBuilder sb = new StringBuilder();
sb.Append("Fit: ");
sb.Append(fit.ToString("f3"));
sb.Append("; Gen: ");
sb.Append(generation);
sb.Append("; Ind: ");
sb.Append(index);
sb.Append("; a1: ");
sb.Append(a1.ToString("f3"));
sb.Append("; a2: ");
sb.Append(a2.ToString("f3"));
sb.Append("; wfe: ");
sb.Append(wfe.ToString("f3"));
sb.Append("; u0: ");
sb.Append(u0.ToString("f3"));
sb.Append("; hipTauU: ");
sb.Append(hipTauU.ToString("f3"));
sb.Append("; hipTauV: ");
sb.Append(hipTauV.ToString("f3"));
sb.Append("; hipBeta: ");
sb.Append(hipBeta.ToString("f3"));
sb.Append("; kneeTauU: ");
sb.Append(kneeTauU.ToString("f3"));
sb.Append("; kneeTauV: ");
sb.Append(kneeTauV.ToString("f3"));
sb.Append("; kneeBeta: ");
sb.Append(kneeBeta.ToString("f3"));
sb.Append("; w0: ");
sb.Append(w0.ToString("f3"));
sb.Append("; w1: ");
sb.Append(w1.ToString("f3"));
sb.Append("; w2: ");
sb.Append(w2.ToString("f3"));
sb.Append("; w3: ");
sb.Append(w3.ToString("f3"));
sb.Append("; w4: ");
sb.Append(w4.ToString("f3"));
sb.Append("; w5: ");
sb.Append(w5.ToString("f3"));
sb.Append("; w6: ");
sb.Append(w6.ToString("f3"));
sb.Append("; w7: ");
sb.Append(w7.ToString("f3"));
sb.Append(Environment.NewLine);
IMP(sb.ToString());
}
return fit;
}
}
private void linkLabelStopGA_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
if (GA != null)
{
labelGAStatus.Text = "stopping...";
GA.Stop();
}
}
private void checkBoxGAEvaluation_CheckedChanged(object sender, EventArgs e)
{
if (GA != null)
GA.ShowEvaluation = checkBoxGAEvaluation.Checked;
}
private void checkBoxGAImprovement_CheckedChanged(object sender, EventArgs e)
{
if (GA != null)
GA.ShowImprovements = checkBoxGAImprovement.Checked;
}
private void linkLabelRunHardware_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
double m = double.Parse(textBoxMsM.Text);
double m1 = double.Parse(textBoxMsM1.Text);
double l1 = double.Parse(textBoxMsL1.Text);
double m2 = double.Parse(textBoxMsM2.Text);
double l2 = double.Parse(textBoxMsL2.Text);
double ss = double.Parse(textBoxMsSS.Text);
double theta = double.Parse(textBoxMsTheta.Text);
double theta1 = double.Parse(textBoxMsTheta1.Text);
double theta2 = double.Parse(textBoxMsTheta2.Text);
double theta3 = double.Parse(textBoxMsTheta3.Text);
double theta4 = double.Parse(textBoxMsTheta4.Text);
Bipedal5Link.Bipedal5LinkHardware b = new Bipedal5Link.Bipedal5LinkHardware(m, m1, m2, l1, l2, new Bipedal5Link.PointD(0.92, 0.32), new double[] { theta, theta1, theta2, theta3, theta4 }, ss, Hardware);
NewCentralPatternGenerator();
timerUnstable.Stop();
panelUnstable.Hide();
int steps = int.Parse(textBoxSteps.Text);
double deltatime = double.Parse(textBoxDeltaTime.Text);
double u0 = double.Parse(textBoxCpgU0.Text);
StatusBufferG.Clear(Color.Black);
StatusBufferG.DrawString(B.Parameters(), F1, Brushes.DarkOrange, 0, 10);
StatusBufferG.DrawString(CPG.Parameters(), F1, Brushes.DarkOrange, 440, 10);
double[] joints;
double[] feedback = new double[9];
for (int s = 0 ; s < 100000 ; s++)
joints = CPG.RunStep(u0, feedback, deltatime);
Abort = false;
labelHardwareStatus.Text = "starting..";
System.Windows.Forms.Application.DoEvents();
Hardware.Start();
labelHardwareStatus.Text = "running..";
// time coupling
double simulationtime = 0;
DateTime realtimestart = DateTime.Now;
TimeSpan realtime;
for (int s = 0 ; (s < steps) & !Abort ; s++)
{
// Run CPG step
joints = CPG.RunStep(u0, new double[] { 0, feedback[1], -feedback[1], feedback[2], -feedback[2], 0, 0, 0, 0 }, deltatime);
// Run Musculo-Skeletal system step
feedback = b.RunStep(joints, deltatime);
simulationtime = s * deltatime;
realtime = DateTime.Now.Subtract(realtimestart);
if (simulationtime > realtime.TotalSeconds)
{
b.UpdateHardware();
DisplayBufferG.Clear(C1);
b.Draw(DisplayBufferG, new PointF(10, 240), 500);
DisplayBufferG.DrawString("running on hardware...", F1, Brushes.Orange, 550, 170);
LabelDisplayG.DrawImage(DisplayBuffer, 0, 0);
StatusBufferG.FillRectangle(Brushes.Black, 240, 0, 200, 160);
StatusBufferG.DrawString(b.Status(), F1, Brushes.DarkOrange, 240, 10);
StatusBufferG.FillRectangle(Brushes.Black, 640, 0, 200, 160);
StatusBufferG.DrawString(CPG.Status(), F1, Brushes.DarkOrange, 640, 10);
LabelStatusG.DrawImage(StatusBuffer, 0, 0);
CPGBufferG.Clear(Color.Black);
CPG.Draw(CPGBufferG);
LabelCPGG.DrawImage(CPGBuffer, 0, 0);
System.Windows.Forms.Application.DoEvents();
}
}
labelHardwareStatus.Text = "stopping..";
System.Windows.Forms.Application.DoEvents();
Hardware.Stop();
labelHardwareStatus.Text = "stopped";
}
private void linkLabelStopHardware_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
Abort = true;
}
private void linkLabelResetHardware_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
Hardware.Reset();
}
private void textBoxSteps_TextChanged(object sender, EventArgs e)
{
try
{
double st = double.Parse(textBoxSteps.Text);
double dtt = double.Parse(textBoxDeltaTime.Text);
double tt = st * dtt;
labelTotalTime.Text = "total: " + tt.ToString("f2") + " sec";
}
catch
{
}
}
private void textBoxDeltaTime_TextChanged(object sender, EventArgs e)
{
try
{
double st = double.Parse(textBoxSteps.Text);
double dtt = double.Parse(textBoxDeltaTime.Text);
double tt = st * dtt;
labelTotalTime.Text = "total: " + tt.ToString("f2") + " sec";
}
catch
{
}
}
private void textBoxSuper_TextChanged(object sender, EventArgs e)
{
labelSuper.Text = textBoxSuper.Text;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace EP.IdentityIsolation.API.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// 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.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading;
using Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption;
using Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel;
using Microsoft.AspNetCore.DataProtection.KeyManagement.Internal;
using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using Moq;
using Xunit;
namespace Microsoft.AspNetCore.DataProtection.KeyManagement
{
public class KeyRingBasedDataProtectorTests
{
[Fact]
public void Protect_NullPlaintext_Throws()
{
// Arrange
IDataProtector protector = new KeyRingBasedDataProtector(
keyRingProvider: new Mock<IKeyRingProvider>().Object,
logger: GetLogger(),
originalPurposes: null,
newPurpose: "purpose");
// Act & assert
ExceptionAssert.ThrowsArgumentNull(() => protector.Protect(plaintext: null), "plaintext");
}
[Fact]
public void Protect_EncryptsToDefaultProtector_MultiplePurposes()
{
// Arrange
Guid defaultKey = new Guid("ba73c9ce-d322-4e45-af90-341307e11c38");
byte[] expectedPlaintext = new byte[] { 0x03, 0x05, 0x07, 0x11, 0x13, 0x17, 0x19 };
byte[] expectedAad = BuildAadFromPurposeStrings(defaultKey, "purpose1", "purpose2", "yet another purpose");
byte[] expectedProtectedData = BuildProtectedDataFromCiphertext(defaultKey, new byte[] { 0x23, 0x29, 0x31, 0x37 });
var mockEncryptor = new Mock<IAuthenticatedEncryptor>();
mockEncryptor
.Setup(o => o.Encrypt(It.IsAny<ArraySegment<byte>>(), It.IsAny<ArraySegment<byte>>()))
.Returns<ArraySegment<byte>, ArraySegment<byte>>((actualPlaintext, actualAad) =>
{
Assert.Equal(expectedPlaintext, actualPlaintext);
Assert.Equal(expectedAad, actualAad);
return new byte[] { 0x23, 0x29, 0x31, 0x37 }; // ciphertext + tag
});
var mockKeyRing = new Mock<IKeyRing>(MockBehavior.Strict);
mockKeyRing.Setup(o => o.DefaultKeyId).Returns(defaultKey);
mockKeyRing.Setup(o => o.DefaultAuthenticatedEncryptor).Returns(mockEncryptor.Object);
var mockKeyRingProvider = new Mock<IKeyRingProvider>();
mockKeyRingProvider.Setup(o => o.GetCurrentKeyRing()).Returns(mockKeyRing.Object);
IDataProtector protector = new KeyRingBasedDataProtector(
keyRingProvider: mockKeyRingProvider.Object,
logger: GetLogger(),
originalPurposes: new[] { "purpose1", "purpose2" },
newPurpose: "yet another purpose");
// Act
byte[] retVal = protector.Protect(expectedPlaintext);
// Assert
Assert.Equal(expectedProtectedData, retVal);
}
[Fact]
public void Protect_EncryptsToDefaultProtector_SinglePurpose()
{
// Arrange
Guid defaultKey = new Guid("ba73c9ce-d322-4e45-af90-341307e11c38");
byte[] expectedPlaintext = new byte[] { 0x03, 0x05, 0x07, 0x11, 0x13, 0x17, 0x19 };
byte[] expectedAad = BuildAadFromPurposeStrings(defaultKey, "single purpose");
byte[] expectedProtectedData = BuildProtectedDataFromCiphertext(defaultKey, new byte[] { 0x23, 0x29, 0x31, 0x37 });
var mockEncryptor = new Mock<IAuthenticatedEncryptor>();
mockEncryptor
.Setup(o => o.Encrypt(It.IsAny<ArraySegment<byte>>(), It.IsAny<ArraySegment<byte>>()))
.Returns<ArraySegment<byte>, ArraySegment<byte>>((actualPlaintext, actualAad) =>
{
Assert.Equal(expectedPlaintext, actualPlaintext);
Assert.Equal(expectedAad, actualAad);
return new byte[] { 0x23, 0x29, 0x31, 0x37 }; // ciphertext + tag
});
var mockKeyRing = new Mock<IKeyRing>(MockBehavior.Strict);
mockKeyRing.Setup(o => o.DefaultKeyId).Returns(defaultKey);
mockKeyRing.Setup(o => o.DefaultAuthenticatedEncryptor).Returns(mockEncryptor.Object);
var mockKeyRingProvider = new Mock<IKeyRingProvider>();
mockKeyRingProvider.Setup(o => o.GetCurrentKeyRing()).Returns(mockKeyRing.Object);
IDataProtector protector = new KeyRingBasedDataProtector(
keyRingProvider: mockKeyRingProvider.Object,
logger: GetLogger(),
originalPurposes: new string[0],
newPurpose: "single purpose");
// Act
byte[] retVal = protector.Protect(expectedPlaintext);
// Assert
Assert.Equal(expectedProtectedData, retVal);
}
[Fact]
public void Protect_HomogenizesExceptionsToCryptographicException()
{
// Arrange
IDataProtector protector = new KeyRingBasedDataProtector(
keyRingProvider: new Mock<IKeyRingProvider>(MockBehavior.Strict).Object,
logger: GetLogger(),
originalPurposes: null,
newPurpose: "purpose");
// Act & assert
var ex = ExceptionAssert2.ThrowsCryptographicException(() => protector.Protect(new byte[0]));
Assert.IsAssignableFrom<MockException>(ex.InnerException);
}
[Fact]
public void Unprotect_NullProtectedData_Throws()
{
// Arrange
IDataProtector protector = new KeyRingBasedDataProtector(
keyRingProvider: new Mock<IKeyRingProvider>().Object,
logger: GetLogger(),
originalPurposes: null,
newPurpose: "purpose");
// Act & assert
ExceptionAssert.ThrowsArgumentNull(() => protector.Unprotect(protectedData: null), "protectedData");
}
[Fact]
public void Unprotect_PayloadTooShort_ThrowsBadMagicHeader()
{
// Arrange
IDataProtector protector = new KeyRingBasedDataProtector(
keyRingProvider: new Mock<IKeyRingProvider>().Object,
logger: GetLogger(),
originalPurposes: null,
newPurpose: "purpose");
byte[] badProtectedPayload = BuildProtectedDataFromCiphertext(Guid.NewGuid(), new byte[0]);
badProtectedPayload = badProtectedPayload.Take(badProtectedPayload.Length - 1).ToArray(); // chop off the last byte
// Act & assert
var ex = ExceptionAssert2.ThrowsCryptographicException(() => protector.Unprotect(badProtectedPayload));
Assert.Equal(Resources.ProtectionProvider_BadMagicHeader, ex.Message);
}
[Fact]
public void Unprotect_PayloadHasBadMagicHeader_ThrowsBadMagicHeader()
{
// Arrange
IDataProtector protector = new KeyRingBasedDataProtector(
keyRingProvider: new Mock<IKeyRingProvider>().Object,
logger: GetLogger(),
originalPurposes: null,
newPurpose: "purpose");
byte[] badProtectedPayload = BuildProtectedDataFromCiphertext(Guid.NewGuid(), new byte[0]);
badProtectedPayload[0]++; // corrupt the magic header
// Act & assert
var ex = ExceptionAssert2.ThrowsCryptographicException(() => protector.Unprotect(badProtectedPayload));
Assert.Equal(Resources.ProtectionProvider_BadMagicHeader, ex.Message);
}
[Fact]
public void Unprotect_PayloadHasIncorrectVersionMarker_ThrowsNewerVersion()
{
// Arrange
IDataProtector protector = new KeyRingBasedDataProtector(
keyRingProvider: new Mock<IKeyRingProvider>().Object,
logger: GetLogger(),
originalPurposes: null,
newPurpose: "purpose");
byte[] badProtectedPayload = BuildProtectedDataFromCiphertext(Guid.NewGuid(), new byte[0]);
badProtectedPayload[3]++; // bump the version payload
// Act & assert
var ex = ExceptionAssert2.ThrowsCryptographicException(() => protector.Unprotect(badProtectedPayload));
Assert.Equal(Resources.ProtectionProvider_BadVersion, ex.Message);
}
[Fact]
public void Unprotect_KeyNotFound_ThrowsKeyNotFound()
{
// Arrange
Guid notFoundKeyId = new Guid("654057ab-2491-4471-a72a-b3b114afda38");
byte[] protectedData = BuildProtectedDataFromCiphertext(
keyId: notFoundKeyId,
ciphertext: new byte[0]);
var mockDescriptor = new Mock<IAuthenticatedEncryptorDescriptor>();
var mockEncryptorFactory = new Mock<IAuthenticatedEncryptorFactory>();
mockEncryptorFactory.Setup(o => o.CreateEncryptorInstance(It.IsAny<IKey>())).Returns(new Mock<IAuthenticatedEncryptor>().Object);
var encryptorFactory = new AuthenticatedEncryptorFactory(NullLoggerFactory.Instance);
// the keyring has only one key
Key key = new Key(Guid.Empty, DateTimeOffset.Now, DateTimeOffset.Now, DateTimeOffset.Now, mockDescriptor.Object, new[] { mockEncryptorFactory.Object });
var keyRing = new KeyRing(key, new[] { key });
var mockKeyRingProvider = new Mock<IKeyRingProvider>();
mockKeyRingProvider.Setup(o => o.GetCurrentKeyRing()).Returns(keyRing);
IDataProtector protector = new KeyRingBasedDataProtector(
keyRingProvider: mockKeyRingProvider.Object,
logger: GetLogger(),
originalPurposes: null,
newPurpose: "purpose");
// Act & assert
var ex = ExceptionAssert2.ThrowsCryptographicException(() => protector.Unprotect(protectedData));
Assert.Equal(Error.Common_KeyNotFound(notFoundKeyId).Message, ex.Message);
}
private static DateTime StringToDateTime(string input)
{
return DateTimeOffset.ParseExact(input, "u", CultureInfo.InvariantCulture).UtcDateTime;
}
private static KeyRingProvider CreateKeyRingProvider(ICacheableKeyRingProvider cacheableKeyRingProvider)
{
var mockEncryptorFactory = new Mock<IAuthenticatedEncryptorFactory>();
mockEncryptorFactory.Setup(m => m.CreateEncryptorInstance(It.IsAny<IKey>())).Returns(new Mock<IAuthenticatedEncryptor>().Object);
var options = new KeyManagementOptions();
options.AuthenticatedEncryptorFactories.Add(mockEncryptorFactory.Object);
return new KeyRingProvider(
keyManager: null,
keyManagementOptions: Options.Create(options),
defaultKeyResolver: null,
loggerFactory: NullLoggerFactory.Instance)
{
CacheableKeyRingProvider = cacheableKeyRingProvider
};
}
[Fact]
public void Unprotect_KeyNotFound_RefreshOnce_ThrowsKeyNotFound()
{
// Arrange
Guid notFoundKeyId = new Guid("654057ab-2491-4471-a72a-b3b114afda38");
byte[] protectedData = BuildProtectedDataFromCiphertext(
keyId: notFoundKeyId,
ciphertext: new byte[0]);
var mockDescriptor = new Mock<IAuthenticatedEncryptorDescriptor>();
var mockEncryptorFactory = new Mock<IAuthenticatedEncryptorFactory>();
mockEncryptorFactory.Setup(o => o.CreateEncryptorInstance(It.IsAny<IKey>())).Returns(new Mock<IAuthenticatedEncryptor>().Object);
var encryptorFactory = new AuthenticatedEncryptorFactory(NullLoggerFactory.Instance);
// the keyring has only one key
Key key = new Key(Guid.Empty, DateTimeOffset.Now, DateTimeOffset.Now, DateTimeOffset.Now, mockDescriptor.Object, new[] { mockEncryptorFactory.Object });
var keyRing = new CacheableKeyRing(CancellationToken.None, DateTimeOffset.MaxValue, key, new[] { key });
var keyRingProvider = CreateKeyRingProvider(new TestKeyRingProvider(keyRing));
IDataProtector protector = new KeyRingBasedDataProtector(
keyRingProvider: keyRingProvider,
logger: GetLogger(),
originalPurposes: null,
newPurpose: "purpose");
// Act & assert
var ex = ExceptionAssert2.ThrowsCryptographicException(() => protector.Unprotect(protectedData));
Assert.Equal(Error.Common_KeyNotFound(notFoundKeyId).Message, ex.Message);
}
[Fact]
public void Unprotect_KeyNotFound_WontRefreshOnce_AfterTooLong()
{
// Arrange
Guid notFoundKeyId = new Guid("654057ab-2491-4471-a72a-b3b114afda38");
byte[] protectedData = BuildProtectedDataFromCiphertext(
keyId: notFoundKeyId,
ciphertext: new byte[0]);
var mockDescriptor = new Mock<IAuthenticatedEncryptorDescriptor>();
var mockEncryptorFactory = new Mock<IAuthenticatedEncryptorFactory>();
mockEncryptorFactory.Setup(o => o.CreateEncryptorInstance(It.IsAny<IKey>())).Returns(new Mock<IAuthenticatedEncryptor>().Object);
var encryptorFactory = new AuthenticatedEncryptorFactory(NullLoggerFactory.Instance);
// the keyring has only one key
Key key = new Key(Guid.Empty, DateTimeOffset.Now, DateTimeOffset.Now, DateTimeOffset.Now, mockDescriptor.Object, new[] { mockEncryptorFactory.Object });
var keyRing = new CacheableKeyRing(CancellationToken.None, DateTimeOffset.MaxValue, key, new[] { key });
// the refresh keyring has the notfound key
Key key2 = new Key(notFoundKeyId, DateTimeOffset.Now, DateTimeOffset.Now, DateTimeOffset.Now, mockDescriptor.Object, new[] { mockEncryptorFactory.Object });
var keyRing2 = new CacheableKeyRing(CancellationToken.None, DateTimeOffset.MaxValue, key, new[] { key2 });
var keyRingProvider = CreateKeyRingProvider(new RefreshTestKeyRingProvider(keyRing, keyRing2));
keyRingProvider.AutoRefreshWindowEnd = DateTime.UtcNow;
IDataProtector protector = new KeyRingBasedDataProtector(
keyRingProvider: keyRingProvider,
logger: GetLogger(),
originalPurposes: null,
newPurpose: "purpose");
// Act & assert
var ex = ExceptionAssert2.ThrowsCryptographicException(() => protector.Unprotect(protectedData));
Assert.Equal(Error.Common_KeyNotFound(notFoundKeyId).Message, ex.Message);
}
[Fact]
public void Unprotect_KeyNotFound_RefreshOnce_CanFindKey()
{
// Arrange
Guid notFoundKeyId = new Guid("654057ab-2491-4471-a72a-b3b114afda38");
byte[] protectedData = BuildProtectedDataFromCiphertext(
keyId: notFoundKeyId,
ciphertext: new byte[0]);
var mockDescriptor = new Mock<IAuthenticatedEncryptorDescriptor>();
var mockEncryptorFactory = new Mock<IAuthenticatedEncryptorFactory>();
mockEncryptorFactory.Setup(o => o.CreateEncryptorInstance(It.IsAny<IKey>())).Returns(new Mock<IAuthenticatedEncryptor>().Object);
var encryptorFactory = new AuthenticatedEncryptorFactory(NullLoggerFactory.Instance);
// the keyring has only one key
Key key = new Key(Guid.Empty, DateTimeOffset.Now, DateTimeOffset.Now, DateTimeOffset.Now, mockDescriptor.Object, new[] { mockEncryptorFactory.Object });
var keyRing = new CacheableKeyRing(CancellationToken.None, DateTimeOffset.MaxValue, key, new[] { key });
// the refresh keyring has the notfound key
Key key2 = new Key(notFoundKeyId, DateTimeOffset.Now, DateTimeOffset.Now, DateTimeOffset.Now, mockDescriptor.Object, new[] { mockEncryptorFactory.Object });
var keyRing2 = new CacheableKeyRing(CancellationToken.None, DateTimeOffset.MaxValue, key, new[] { key2 });
var keyRingProvider = CreateKeyRingProvider(new RefreshTestKeyRingProvider(keyRing, keyRing2));
IDataProtector protector = new KeyRingBasedDataProtector(
keyRingProvider: keyRingProvider,
logger: GetLogger(),
originalPurposes: null,
newPurpose: "purpose");
// Act & assert
var result = protector.Unprotect(protectedData);
Assert.Empty(result);
}
private class TestKeyRingProvider : ICacheableKeyRingProvider
{
private CacheableKeyRing _keyRing;
public TestKeyRingProvider(CacheableKeyRing keys) => _keyRing = keys;
public CacheableKeyRing GetCacheableKeyRing(DateTimeOffset now) => _keyRing;
}
private class RefreshTestKeyRingProvider : ICacheableKeyRingProvider
{
private CacheableKeyRing _keyRing;
private CacheableKeyRing _refreshKeyRing;
private bool _called;
public RefreshTestKeyRingProvider(CacheableKeyRing keys, CacheableKeyRing refreshKeys)
{
_keyRing = keys;
_refreshKeyRing = refreshKeys;
}
public CacheableKeyRing GetCacheableKeyRing(DateTimeOffset now)
{
if (!_called)
{
_called = true;
return _keyRing;
}
return _refreshKeyRing;
}
}
[Fact]
public void Unprotect_KeyRevoked_RevocationDisallowed_ThrowsKeyRevoked()
{
// Arrange
Guid keyId = new Guid("654057ab-2491-4471-a72a-b3b114afda38");
byte[] protectedData = BuildProtectedDataFromCiphertext(
keyId: keyId,
ciphertext: new byte[0]);
var mockDescriptor = new Mock<IAuthenticatedEncryptorDescriptor>();
var mockEncryptorFactory = new Mock<IAuthenticatedEncryptorFactory>();
mockEncryptorFactory.Setup(o => o.CreateEncryptorInstance(It.IsAny<IKey>())).Returns(new Mock<IAuthenticatedEncryptor>().Object);
// the keyring has only one key
Key key = new Key(keyId, DateTimeOffset.Now, DateTimeOffset.Now, DateTimeOffset.Now, mockDescriptor.Object, new[] { mockEncryptorFactory.Object });
key.SetRevoked();
var keyRing = new KeyRing(key, new[] { key });
var mockKeyRingProvider = new Mock<IKeyRingProvider>();
mockKeyRingProvider.Setup(o => o.GetCurrentKeyRing()).Returns(keyRing);
IDataProtector protector = new KeyRingBasedDataProtector(
keyRingProvider: mockKeyRingProvider.Object,
logger: GetLogger(),
originalPurposes: null,
newPurpose: "purpose");
// Act & assert
var ex = ExceptionAssert2.ThrowsCryptographicException(() => protector.Unprotect(protectedData));
Assert.Equal(Error.Common_KeyRevoked(keyId).Message, ex.Message);
}
[Fact]
public void Unprotect_KeyRevoked_RevocationAllowed_ReturnsOriginalData_SetsRevokedAndMigrationFlags()
{
// Arrange
Guid defaultKeyId = new Guid("ba73c9ce-d322-4e45-af90-341307e11c38");
byte[] expectedCiphertext = new byte[] { 0x03, 0x05, 0x07, 0x11, 0x13, 0x17, 0x19 };
byte[] protectedData = BuildProtectedDataFromCiphertext(defaultKeyId, expectedCiphertext);
byte[] expectedAad = BuildAadFromPurposeStrings(defaultKeyId, "purpose");
byte[] expectedPlaintext = new byte[] { 0x23, 0x29, 0x31, 0x37 };
var mockEncryptor = new Mock<IAuthenticatedEncryptor>();
mockEncryptor
.Setup(o => o.Decrypt(It.IsAny<ArraySegment<byte>>(), It.IsAny<ArraySegment<byte>>()))
.Returns<ArraySegment<byte>, ArraySegment<byte>>((actualCiphertext, actualAad) =>
{
Assert.Equal(expectedCiphertext, actualCiphertext);
Assert.Equal(expectedAad, actualAad);
return expectedPlaintext;
});
var mockDescriptor = new Mock<IAuthenticatedEncryptorDescriptor>();
var mockEncryptorFactory = new Mock<IAuthenticatedEncryptorFactory>();
mockEncryptorFactory.Setup(o => o.CreateEncryptorInstance(It.IsAny<IKey>())).Returns(mockEncryptor.Object);
Key defaultKey = new Key(defaultKeyId, DateTimeOffset.Now, DateTimeOffset.Now, DateTimeOffset.Now, mockDescriptor.Object, new[] { mockEncryptorFactory.Object });
defaultKey.SetRevoked();
var keyRing = new KeyRing(defaultKey, new[] { defaultKey });
var mockKeyRingProvider = new Mock<IKeyRingProvider>();
mockKeyRingProvider.Setup(o => o.GetCurrentKeyRing()).Returns(keyRing);
IDataProtector protector = new KeyRingBasedDataProtector(
keyRingProvider: mockKeyRingProvider.Object,
logger: GetLogger(),
originalPurposes: null,
newPurpose: "purpose");
// Act
byte[] retVal = ((IPersistedDataProtector)protector).DangerousUnprotect(protectedData,
ignoreRevocationErrors: true,
requiresMigration: out var requiresMigration,
wasRevoked: out var wasRevoked);
// Assert
Assert.Equal(expectedPlaintext, retVal);
Assert.True(requiresMigration);
Assert.True(wasRevoked);
}
[Fact]
public void Unprotect_IsAlsoDefaultKey_Success_NoMigrationRequired()
{
// Arrange
Guid defaultKeyId = new Guid("ba73c9ce-d322-4e45-af90-341307e11c38");
byte[] expectedCiphertext = new byte[] { 0x03, 0x05, 0x07, 0x11, 0x13, 0x17, 0x19 };
byte[] protectedData = BuildProtectedDataFromCiphertext(defaultKeyId, expectedCiphertext);
byte[] expectedAad = BuildAadFromPurposeStrings(defaultKeyId, "purpose");
byte[] expectedPlaintext = new byte[] { 0x23, 0x29, 0x31, 0x37 };
var mockEncryptor = new Mock<IAuthenticatedEncryptor>();
mockEncryptor
.Setup(o => o.Decrypt(It.IsAny<ArraySegment<byte>>(), It.IsAny<ArraySegment<byte>>()))
.Returns<ArraySegment<byte>, ArraySegment<byte>>((actualCiphertext, actualAad) =>
{
Assert.Equal(expectedCiphertext, actualCiphertext);
Assert.Equal(expectedAad, actualAad);
return expectedPlaintext;
});
var mockDescriptor = new Mock<IAuthenticatedEncryptorDescriptor>();
var mockEncryptorFactory = new Mock<IAuthenticatedEncryptorFactory>();
mockEncryptorFactory.Setup(o => o.CreateEncryptorInstance(It.IsAny<IKey>())).Returns(mockEncryptor.Object);
Key defaultKey = new Key(defaultKeyId, DateTimeOffset.Now, DateTimeOffset.Now, DateTimeOffset.Now, mockDescriptor.Object, new[] { mockEncryptorFactory.Object });
var keyRing = new KeyRing(defaultKey, new[] { defaultKey });
var mockKeyRingProvider = new Mock<IKeyRingProvider>();
mockKeyRingProvider.Setup(o => o.GetCurrentKeyRing()).Returns(keyRing);
IDataProtector protector = new KeyRingBasedDataProtector(
keyRingProvider: mockKeyRingProvider.Object,
logger: GetLogger(),
originalPurposes: null,
newPurpose: "purpose");
// Act & assert - IDataProtector
byte[] retVal = protector.Unprotect(protectedData);
Assert.Equal(expectedPlaintext, retVal);
// Act & assert - IPersistedDataProtector
retVal = ((IPersistedDataProtector)protector).DangerousUnprotect(protectedData,
ignoreRevocationErrors: false,
requiresMigration: out var requiresMigration,
wasRevoked: out var wasRevoked);
Assert.Equal(expectedPlaintext, retVal);
Assert.False(requiresMigration);
Assert.False(wasRevoked);
}
[Fact]
public void Unprotect_IsNotDefaultKey_Success_RequiresMigration()
{
// Arrange
Guid defaultKeyId = new Guid("ba73c9ce-d322-4e45-af90-341307e11c38");
Guid embeddedKeyId = new Guid("9b5d2db3-299f-4eac-89e9-e9067a5c1853");
byte[] expectedCiphertext = new byte[] { 0x03, 0x05, 0x07, 0x11, 0x13, 0x17, 0x19 };
byte[] protectedData = BuildProtectedDataFromCiphertext(embeddedKeyId, expectedCiphertext);
byte[] expectedAad = BuildAadFromPurposeStrings(embeddedKeyId, "purpose");
byte[] expectedPlaintext = new byte[] { 0x23, 0x29, 0x31, 0x37 };
var mockEncryptor = new Mock<IAuthenticatedEncryptor>();
mockEncryptor
.Setup(o => o.Decrypt(It.IsAny<ArraySegment<byte>>(), It.IsAny<ArraySegment<byte>>()))
.Returns<ArraySegment<byte>, ArraySegment<byte>>((actualCiphertext, actualAad) =>
{
Assert.Equal(expectedCiphertext, actualCiphertext);
Assert.Equal(expectedAad, actualAad);
return expectedPlaintext;
});
var mockDescriptor = new Mock<IAuthenticatedEncryptorDescriptor>();
var mockEncryptorFactory = new Mock<IAuthenticatedEncryptorFactory>();
mockEncryptorFactory.Setup(o => o.CreateEncryptorInstance(It.IsAny<IKey>())).Returns(mockEncryptor.Object);
Key defaultKey = new Key(defaultKeyId, DateTimeOffset.Now, DateTimeOffset.Now, DateTimeOffset.Now, new Mock<IAuthenticatedEncryptorDescriptor>().Object, new[] { mockEncryptorFactory.Object });
Key embeddedKey = new Key(embeddedKeyId, DateTimeOffset.Now, DateTimeOffset.Now, DateTimeOffset.Now, mockDescriptor.Object, new[] { mockEncryptorFactory.Object });
var keyRing = new KeyRing(defaultKey, new[] { defaultKey, embeddedKey });
var mockKeyRingProvider = new Mock<IKeyRingProvider>();
mockKeyRingProvider.Setup(o => o.GetCurrentKeyRing()).Returns(keyRing);
IDataProtector protector = new KeyRingBasedDataProtector(
keyRingProvider: mockKeyRingProvider.Object,
logger: GetLogger(),
originalPurposes: null,
newPurpose: "purpose");
// Act & assert - IDataProtector
byte[] retVal = protector.Unprotect(protectedData);
Assert.Equal(expectedPlaintext, retVal);
// Act & assert - IPersistedDataProtector
retVal = ((IPersistedDataProtector)protector).DangerousUnprotect(protectedData,
ignoreRevocationErrors: false,
requiresMigration: out var requiresMigration,
wasRevoked: out var wasRevoked);
Assert.Equal(expectedPlaintext, retVal);
Assert.True(requiresMigration);
Assert.False(wasRevoked);
}
[Fact]
public void Protect_Unprotect_RoundTripsProperly()
{
// Arrange
byte[] plaintext = new byte[] { 0x10, 0x20, 0x30, 0x40, 0x50 };
var encryptorFactory = new AuthenticatedEncryptorFactory(NullLoggerFactory.Instance);
Key key = new Key(Guid.NewGuid(), DateTimeOffset.Now, DateTimeOffset.Now, DateTimeOffset.Now, new AuthenticatedEncryptorConfiguration().CreateNewDescriptor(), new[] { encryptorFactory });
var keyRing = new KeyRing(key, new[] { key });
var mockKeyRingProvider = new Mock<IKeyRingProvider>();
mockKeyRingProvider.Setup(o => o.GetCurrentKeyRing()).Returns(keyRing);
var protector = new KeyRingBasedDataProtector(
keyRingProvider: mockKeyRingProvider.Object,
logger: GetLogger(),
originalPurposes: null,
newPurpose: "purpose");
// Act - protect
byte[] protectedData = protector.Protect(plaintext);
Assert.NotNull(protectedData);
Assert.NotEqual(plaintext, protectedData);
// Act - unprotect
byte[] roundTrippedPlaintext = protector.Unprotect(protectedData);
Assert.Equal(plaintext, roundTrippedPlaintext);
}
[Fact]
public void CreateProtector_ChainsPurposes()
{
// Arrange
Guid defaultKey = new Guid("ba73c9ce-d322-4e45-af90-341307e11c38");
byte[] expectedPlaintext = new byte[] { 0x03, 0x05, 0x07, 0x11, 0x13, 0x17, 0x19 };
byte[] expectedAad = BuildAadFromPurposeStrings(defaultKey, "purpose1", "purpose2");
byte[] expectedProtectedData = BuildProtectedDataFromCiphertext(defaultKey, new byte[] { 0x23, 0x29, 0x31, 0x37 });
var mockEncryptor = new Mock<IAuthenticatedEncryptor>();
mockEncryptor
.Setup(o => o.Encrypt(It.IsAny<ArraySegment<byte>>(), It.IsAny<ArraySegment<byte>>()))
.Returns<ArraySegment<byte>, ArraySegment<byte>>((actualPlaintext, actualAad) =>
{
Assert.Equal(expectedPlaintext, actualPlaintext);
Assert.Equal(expectedAad, actualAad);
return new byte[] { 0x23, 0x29, 0x31, 0x37 }; // ciphertext + tag
});
var mockKeyRing = new Mock<IKeyRing>(MockBehavior.Strict);
mockKeyRing.Setup(o => o.DefaultKeyId).Returns(defaultKey);
mockKeyRing.Setup(o => o.DefaultAuthenticatedEncryptor).Returns(mockEncryptor.Object);
var mockKeyRingProvider = new Mock<IKeyRingProvider>();
mockKeyRingProvider.Setup(o => o.GetCurrentKeyRing()).Returns(mockKeyRing.Object);
IDataProtector protector = new KeyRingBasedDataProtector(
keyRingProvider: mockKeyRingProvider.Object,
logger: GetLogger(),
originalPurposes: null,
newPurpose: "purpose1").CreateProtector("purpose2");
// Act
byte[] retVal = protector.Protect(expectedPlaintext);
// Assert
Assert.Equal(expectedProtectedData, retVal);
}
private static byte[] BuildAadFromPurposeStrings(Guid keyId, params string[] purposes)
{
var expectedAad = new byte[] { 0x09, 0xF0, 0xC9, 0xF0 } // magic header
.Concat(keyId.ToByteArray()) // key id
.Concat(BitConverter.GetBytes(IPAddress.HostToNetworkOrder(purposes.Length))); // purposeCount
foreach (string purpose in purposes)
{
var memStream = new MemoryStream();
var writer = new BinaryWriter(memStream, encoding: new UTF8Encoding(encoderShouldEmitUTF8Identifier: false), leaveOpen: true);
writer.Write(purpose); // also writes 7-bit encoded int length
writer.Dispose();
expectedAad = expectedAad.Concat(memStream.ToArray());
}
return expectedAad.ToArray();
}
private static byte[] BuildProtectedDataFromCiphertext(Guid keyId, byte[] ciphertext)
{
return new byte[] { 0x09, 0xF0, 0xC9, 0xF0 } // magic header
.Concat(keyId.ToByteArray()) // key id
.Concat(ciphertext).ToArray();
}
private static ILogger GetLogger()
{
var loggerFactory = NullLoggerFactory.Instance;
return loggerFactory.CreateLogger(typeof(KeyRingBasedDataProtector));
}
}
}
| |
// <copyright file="WebDriverCommandProcessor.cs" company="WebDriver Committers">
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using System.Collections.Generic;
using System.Globalization;
using OpenQA.Selenium;
using Selenium.Internal;
using Selenium.Internal.SeleniumEmulation;
namespace Selenium
{
/// <summary>
/// Provides an implementation the ICommandProcessor interface which uses WebDriver to complete
/// the Selenium commands.
/// </summary>
public class WebDriverCommandProcessor : ICommandProcessor
{
#region Private members
private IWebDriver driver;
private Uri baseUrl;
private Dictionary<string, SeleneseCommand> seleneseMethods = new Dictionary<string, SeleneseCommand>();
private ElementFinder elementFinder = new ElementFinder();
private CommandTimer timer;
private AlertOverride alertOverride;
private IScriptMutator mutator;
#endregion
/// <summary>
/// Initializes a new instance of the <see cref="WebDriverCommandProcessor"/> class.
/// </summary>
/// <param name="baseUrl">The base URL of the Selenium server.</param>
/// <param name="baseDriver">The IWebDriver object used for executing commands.</param>
public WebDriverCommandProcessor(string baseUrl, IWebDriver baseDriver)
: this(new Uri(baseUrl), baseDriver)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="WebDriverCommandProcessor"/> class.
/// </summary>
/// <param name="baseUrl">The base URL of the Selenium server.</param>
/// <param name="baseDriver">The IWebDriver object used for executing commands.</param>
public WebDriverCommandProcessor(Uri baseUrl, IWebDriver baseDriver)
{
if (baseUrl == null)
{
throw new ArgumentNullException("baseUrl", "baseUrl cannot be null");
}
this.driver = baseDriver;
this.baseUrl = baseUrl;
this.mutator = new CompoundMutator(baseUrl.ToString());
this.timer = new CommandTimer(30000);
this.alertOverride = new AlertOverride(baseDriver);
}
/// <summary>
/// Gets the <see cref="IWebDriver"/> object that executes the commands for this command processor.
/// </summary>
public IWebDriver UnderlyingWebDriver
{
get { return this.driver; }
}
/// <summary>
/// Sends the specified remote command to the browser to be performed
/// </summary>
/// <param name="command">The remote command verb.</param>
/// <param name="args">The arguments to the remote command (depends on the verb).</param>
/// <returns>the command result, defined by the remote JavaScript. "getX" style
/// commands may return data from the browser</returns>
public string DoCommand(string command, string[] args)
{
object val = this.Execute(command, args);
if (val == null)
{
return null;
}
return val.ToString();
}
/// <summary>
/// Sets the script to use as user extensions.
/// </summary>
/// <param name="extensionJs">The script to use as user extensions.</param>
public void SetExtensionJs(string extensionJs)
{
throw new NotImplementedException();
}
/// <summary>
/// Starts the command processor.
/// </summary>
public void Start()
{
this.PopulateSeleneseMethods();
}
/// <summary>
/// Starts the command processor using the specified options.
/// </summary>
/// <param name="optionsString">A string representing the options to use.</param>
public void Start(string optionsString)
{
// Not porting this till other process is decided
throw new NotImplementedException("This is not been ported to WebDriverBackedSelenium");
}
/// <summary>
/// Starts the command processor using the specified options.
/// </summary>
/// <param name="optionsObject">An object representing the options to use.</param>
public void Start(object optionsObject)
{
// Not porting this till other process is decided
throw new NotImplementedException("This is not been ported to WebDriverBackedSelenium");
}
/// <summary>
/// Stops the command processor.
/// </summary>
public void Stop()
{
if (this.driver != null)
{
this.driver.Quit();
}
this.driver = null;
}
/// <summary>
/// Gets a string from the command processor.
/// </summary>
/// <param name="command">The command to send.</param>
/// <param name="args">The arguments of the command.</param>
/// <returns>The result of the command.</returns>
public string GetString(string command, string[] args)
{
return (string)this.Execute(command, args);
}
/// <summary>
/// Gets a string array from the command processor.
/// </summary>
/// <param name="command">The command to send.</param>
/// <param name="args">The arguments of the command.</param>
/// <returns>The result of the command.</returns>
public string[] GetStringArray(string command, string[] args)
{
return (string[])this.Execute(command, args);
}
/// <summary>
/// Gets a number from the command processor.
/// </summary>
/// <param name="command">The command to send.</param>
/// <param name="args">The arguments of the command.</param>
/// <returns>The result of the command.</returns>
public decimal GetNumber(string command, string[] args)
{
return Convert.ToDecimal(this.Execute(command, args), CultureInfo.InvariantCulture);
}
/// <summary>
/// Gets a number array from the command processor.
/// </summary>
/// <param name="command">The command to send.</param>
/// <param name="args">The arguments of the command.</param>
/// <returns>The result of the command.</returns>
public decimal[] GetNumberArray(string command, string[] args)
{
throw new NotImplementedException();
}
/// <summary>
/// Gets a boolean value from the command processor.
/// </summary>
/// <param name="command">The command to send.</param>
/// <param name="args">The arguments of the command.</param>
/// <returns>The result of the command.</returns>
public bool GetBoolean(string command, string[] args)
{
return (bool)this.Execute(command, args);
}
/// <summary>
/// Gets an array of boolean values from the command processor.
/// </summary>
/// <param name="command">The command to send.</param>
/// <param name="args">The arguments of the command.</param>
/// <returns>The result of the command.</returns>
public bool[] GetBooleanArray(string command, string[] args)
{
throw new NotImplementedException();
}
private object Execute(string commandName, string[] args)
{
SeleneseCommand command;
if (!this.seleneseMethods.TryGetValue(commandName, out command))
{
if (this.seleneseMethods.Count == 0)
{
throw new NotSupportedException(commandName + " is not supported\n" +
"Note: Start() must be called before any other methods may be called - make sure you've called Start().");
}
throw new NotSupportedException(commandName);
}
// return command.Apply(driver, args);
return this.timer.Execute(command, this.driver, args);
}
private void PopulateSeleneseMethods()
{
KeyState keyState = new KeyState();
WindowSelector windows = new WindowSelector(this.driver);
// Note the we use the names used by the CommandProcessor
this.seleneseMethods.Add("addLocationStrategy", new AddLocationStrategy(this.elementFinder));
this.seleneseMethods.Add("addSelection", new AddSelection(this.elementFinder));
this.seleneseMethods.Add("altKeyDown", new AltKeyDown(keyState));
this.seleneseMethods.Add("altKeyUp", new AltKeyUp(keyState));
this.seleneseMethods.Add("assignId", new AssignId(this.elementFinder));
this.seleneseMethods.Add("attachFile", new AttachFile(this.elementFinder));
this.seleneseMethods.Add("captureScreenshotToString", new CaptureScreenshotToString());
this.seleneseMethods.Add("click", new Click(this.alertOverride, this.elementFinder));
this.seleneseMethods.Add("clickAt", new ClickAt(this.alertOverride, this.elementFinder));
this.seleneseMethods.Add("check", new Check(this.alertOverride, this.elementFinder));
this.seleneseMethods.Add("chooseCancelOnNextConfirmation", new SetNextConfirmationState(false));
this.seleneseMethods.Add("chooseOkOnNextConfirmation", new SetNextConfirmationState(true));
this.seleneseMethods.Add("close", new Close());
this.seleneseMethods.Add("createCookie", new CreateCookie());
this.seleneseMethods.Add("controlKeyDown", new ControlKeyDown(keyState));
this.seleneseMethods.Add("controlKeyUp", new ControlKeyUp(keyState));
this.seleneseMethods.Add("deleteAllVisibleCookies", new DeleteAllVisibleCookies());
this.seleneseMethods.Add("deleteCookie", new DeleteCookie());
this.seleneseMethods.Add("doubleClick", new DoubleClick(this.elementFinder));
this.seleneseMethods.Add("dragdrop", new DragAndDrop(this.elementFinder));
this.seleneseMethods.Add("dragAndDrop", new DragAndDrop(this.elementFinder));
this.seleneseMethods.Add("dragAndDropToObject", new DragAndDropToObject(this.elementFinder));
this.seleneseMethods.Add("fireEvent", new FireEvent(this.elementFinder));
this.seleneseMethods.Add("focus", new FireNamedEvent(this.elementFinder, "focus"));
this.seleneseMethods.Add("getAlert", new GetAlert(this.alertOverride));
this.seleneseMethods.Add("getAllButtons", new GetAllButtons());
this.seleneseMethods.Add("getAllFields", new GetAllFields());
this.seleneseMethods.Add("getAllLinks", new GetAllLinks());
this.seleneseMethods.Add("getAllWindowTitles", new GetAllWindowTitles());
this.seleneseMethods.Add("getAttribute", new GetAttribute(this.elementFinder));
this.seleneseMethods.Add("getAttributeFromAllWindows", new GetAttributeFromAllWindows());
this.seleneseMethods.Add("getBodyText", new GetBodyText());
this.seleneseMethods.Add("getConfirmation", new GetConfirmation(this.alertOverride));
this.seleneseMethods.Add("getCookie", new GetCookie());
this.seleneseMethods.Add("getCookieByName", new GetCookieByName());
this.seleneseMethods.Add("getElementHeight", new GetElementHeight(this.elementFinder));
this.seleneseMethods.Add("getElementIndex", new GetElementIndex(this.elementFinder));
this.seleneseMethods.Add("getElementPositionLeft", new GetElementPositionLeft(this.elementFinder));
this.seleneseMethods.Add("getElementPositionTop", new GetElementPositionTop(this.elementFinder));
this.seleneseMethods.Add("getElementWidth", new GetElementWidth(this.elementFinder));
this.seleneseMethods.Add("getEval", new GetEval(this.mutator));
this.seleneseMethods.Add("getHtmlSource", new GetHtmlSource());
this.seleneseMethods.Add("getLocation", new GetLocation());
this.seleneseMethods.Add("getSelectedId", new FindFirstSelectedOptionProperty(this.elementFinder, "id"));
this.seleneseMethods.Add("getSelectedIds", new FindSelectedOptionProperties(this.elementFinder, "id"));
this.seleneseMethods.Add("getSelectedIndex", new FindFirstSelectedOptionProperty(this.elementFinder, "index"));
this.seleneseMethods.Add("getSelectedIndexes", new FindSelectedOptionProperties(this.elementFinder, "index"));
this.seleneseMethods.Add("getSelectedLabel", new FindFirstSelectedOptionProperty(this.elementFinder, "text"));
this.seleneseMethods.Add("getSelectedLabels", new FindSelectedOptionProperties(this.elementFinder, "text"));
this.seleneseMethods.Add("getSelectedValue", new FindFirstSelectedOptionProperty(this.elementFinder, "value"));
this.seleneseMethods.Add("getSelectedValues", new FindSelectedOptionProperties(this.elementFinder, "value"));
this.seleneseMethods.Add("getSelectOptions", new GetSelectOptions(this.elementFinder));
this.seleneseMethods.Add("getSpeed", new NoOp("0"));
this.seleneseMethods.Add("getTable", new GetTable(this.elementFinder));
this.seleneseMethods.Add("getText", new GetText(this.elementFinder));
this.seleneseMethods.Add("getTitle", new GetTitle());
this.seleneseMethods.Add("getValue", new GetValue(this.elementFinder));
this.seleneseMethods.Add("getXpathCount", new GetXpathCount());
this.seleneseMethods.Add("getCssCount", new GetCssCount());
this.seleneseMethods.Add("goBack", new GoBack());
this.seleneseMethods.Add("highlight", new Highlight(this.elementFinder));
this.seleneseMethods.Add("isAlertPresent", new IsAlertPresent(this.alertOverride));
this.seleneseMethods.Add("isChecked", new IsChecked(this.elementFinder));
this.seleneseMethods.Add("isConfirmationPresent", new IsConfirmationPresent(this.alertOverride));
this.seleneseMethods.Add("isCookiePresent", new IsCookiePresent());
this.seleneseMethods.Add("isEditable", new IsEditable(this.elementFinder));
this.seleneseMethods.Add("isElementPresent", new IsElementPresent(this.elementFinder));
this.seleneseMethods.Add("isOrdered", new IsOrdered(this.elementFinder));
this.seleneseMethods.Add("isSomethingSelected", new IsSomethingSelected());
this.seleneseMethods.Add("isTextPresent", new IsTextPresent());
this.seleneseMethods.Add("isVisible", new IsVisible(this.elementFinder));
this.seleneseMethods.Add("keyDown", new KeyEvent(this.elementFinder, keyState, "doKeyDown"));
this.seleneseMethods.Add("keyPress", new TypeKeys(this.alertOverride, this.elementFinder));
this.seleneseMethods.Add("keyUp", new KeyEvent(this.elementFinder, keyState, "doKeyUp"));
this.seleneseMethods.Add("metaKeyDown", new MetaKeyDown(keyState));
this.seleneseMethods.Add("metaKeyUp", new MetaKeyUp(keyState));
this.seleneseMethods.Add("mouseOver", new MouseEvent(this.elementFinder, "mouseover"));
this.seleneseMethods.Add("mouseOut", new MouseEvent(this.elementFinder, "mouseout"));
this.seleneseMethods.Add("mouseDown", new MouseEvent(this.elementFinder, "mousedown"));
this.seleneseMethods.Add("mouseDownAt", new MouseEventAt(this.elementFinder, "mousedown"));
this.seleneseMethods.Add("mouseMove", new MouseEvent(this.elementFinder, "mousemove"));
this.seleneseMethods.Add("mouseMoveAt", new MouseEventAt(this.elementFinder, "mousemove"));
this.seleneseMethods.Add("mouseUp", new MouseEvent(this.elementFinder, "mouseup"));
this.seleneseMethods.Add("mouseUpAt", new MouseEventAt(this.elementFinder, "mouseup"));
this.seleneseMethods.Add("open", new Open(this.baseUrl));
this.seleneseMethods.Add("openWindow", new OpenWindow(new GetEval(this.mutator)));
this.seleneseMethods.Add("refresh", new Refresh());
this.seleneseMethods.Add("removeAllSelections", new RemoveAllSelections(this.elementFinder));
this.seleneseMethods.Add("removeSelection", new RemoveSelection(this.elementFinder));
this.seleneseMethods.Add("runScript", new RunScript(this.mutator));
this.seleneseMethods.Add("select", new SelectOption(this.alertOverride, this.elementFinder));
this.seleneseMethods.Add("selectFrame", new SelectFrame(windows));
this.seleneseMethods.Add("selectWindow", new SelectWindow(windows));
this.seleneseMethods.Add("setBrowserLogLevel", new NoOp(null));
this.seleneseMethods.Add("setContext", new NoOp(null));
this.seleneseMethods.Add("setSpeed", new NoOp(null));
this.seleneseMethods.Add("setTimeout", new SetTimeout(this.timer));
this.seleneseMethods.Add("shiftKeyDown", new ShiftKeyDown(keyState));
this.seleneseMethods.Add("shiftKeyUp", new ShiftKeyUp(keyState));
this.seleneseMethods.Add("submit", new Submit(this.alertOverride, this.elementFinder));
this.seleneseMethods.Add("type", new Selenium.Internal.SeleniumEmulation.Type(this.alertOverride, this.elementFinder, keyState));
this.seleneseMethods.Add("typeKeys", new TypeKeys(this.alertOverride, this.elementFinder));
this.seleneseMethods.Add("uncheck", new Uncheck(this.elementFinder));
this.seleneseMethods.Add("useXpathLibrary", new NoOp(null));
this.seleneseMethods.Add("waitForCondition", new WaitForCondition(this.mutator));
this.seleneseMethods.Add("waitForFrameToLoad", new NoOp(null));
this.seleneseMethods.Add("waitForPageToLoad", new WaitForPageToLoad());
this.seleneseMethods.Add("waitForPopUp", new WaitForPopup(windows));
this.seleneseMethods.Add("windowFocus", new WindowFocus());
this.seleneseMethods.Add("windowMaximize", new WindowMaximize());
}
}
}
| |
// 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.Xml.XPath;
using System.Diagnostics;
using System.Globalization;
namespace System.Xml
{
/// <summary>
/// Contains various static functions and methods for parsing and validating:
/// NCName (not namespace-aware, no colons allowed)
/// QName (prefix:local-name)
/// </summary>
internal static class ValidateNames
{
internal enum Flags
{
NCNames = 0x1, // Validate that each non-empty prefix and localName is a valid NCName
CheckLocalName = 0x2, // Validate the local-name
CheckPrefixMapping = 0x4, // Validate the prefix --> namespace mapping
All = 0x7,
AllExceptNCNames = 0x6,
AllExceptPrefixMapping = 0x3,
};
private static XmlCharType s_xmlCharType = XmlCharType.Instance;
//-----------------------------------------------
// Nmtoken parsing
//-----------------------------------------------
/// <summary>
/// Attempts to parse the input string as an Nmtoken (see the XML spec production [7] && XML Namespaces spec).
/// Quits parsing when an invalid Nmtoken char is reached or the end of string is reached.
/// Returns the number of valid Nmtoken chars that were parsed.
/// </summary>
internal static unsafe int ParseNmtoken(string s, int offset)
{
Debug.Assert(s != null && offset <= s.Length);
// Keep parsing until the end of string or an invalid NCName character is reached
int i = offset;
while (i < s.Length)
{
if (s_xmlCharType.IsNCNameSingleChar(s[i]))
{
i++;
}
#if XML10_FIFTH_EDITION
else if (xmlCharType.IsNCNameSurrogateChar(s, i)) {
i += 2;
}
#endif
else
{
break;
}
}
return i - offset;
}
//-----------------------------------------------
// Nmtoken parsing (no XML namespaces support)
//-----------------------------------------------
/// <summary>
/// Attempts to parse the input string as an Nmtoken (see the XML spec production [7]) without taking
/// into account the XML Namespaces spec. What it means is that the ':' character is allowed at any
/// position and any number of times in the token.
/// Quits parsing when an invalid Nmtoken char is reached or the end of string is reached.
/// Returns the number of valid Nmtoken chars that were parsed.
/// </summary>
[System.Security.SecuritySafeCritical]
internal static unsafe int ParseNmtokenNoNamespaces(string s, int offset)
{
Debug.Assert(s != null && offset <= s.Length);
// Keep parsing until the end of string or an invalid Name character is reached
int i = offset;
while (i < s.Length)
{
if (s_xmlCharType.IsNameSingleChar(s[i]) || s[i] == ':')
{
i++;
}
#if XML10_FIFTH_EDITION
else if (xmlCharType.IsNCNameSurrogateChar(s, i))
{
i += 2;
}
#endif
else
{
break;
}
}
return i - offset;
}
// helper methods
internal static bool IsNmtokenNoNamespaces(string s)
{
int endPos = ParseNmtokenNoNamespaces(s, 0);
return endPos > 0 && endPos == s.Length;
}
//-----------------------------------------------
// Name parsing (no XML namespaces support)
//-----------------------------------------------
/// <summary>
/// Attempts to parse the input string as a Name without taking into account the XML Namespaces spec.
/// What it means is that the ':' character does not delimiter prefix and local name, but it is a regular
/// name character, which is allowed to appear at any position and any number of times in the name.
/// Quits parsing when an invalid Name char is reached or the end of string is reached.
/// Returns the number of valid Name chars that were parsed.
/// </summary>
[System.Security.SecuritySafeCritical]
internal static unsafe int ParseNameNoNamespaces(string s, int offset)
{
Debug.Assert(s != null && offset <= s.Length);
// Quit if the first character is not a valid NCName starting character
int i = offset;
if (i < s.Length)
{
if (s_xmlCharType.IsStartNCNameSingleChar(s[i]) || s[i] == ':')
{
i++;
}
#if XML10_FIFTH_EDITION
else if (xmlCharType.IsNCNameSurrogateChar(s, i))
{
i += 2;
}
#endif
else
{
return 0; // no valid StartNCName char
}
// Keep parsing until the end of string or an invalid NCName character is reached
while (i < s.Length)
{
if (s_xmlCharType.IsNCNameSingleChar(s[i]) || s[i] == ':')
{
i++;
}
#if XML10_FIFTH_EDITION
else if (xmlCharType.IsNCNameSurrogateChar(s, i))
{
i += 2;
}
#endif
else
{
break;
}
}
}
return i - offset;
}
// helper methods
internal static bool IsNameNoNamespaces(string s)
{
int endPos = ParseNameNoNamespaces(s, 0);
return endPos > 0 && endPos == s.Length;
}
//-----------------------------------------------
// NCName parsing
//-----------------------------------------------
/// <summary>
/// Attempts to parse the input string as an NCName (see the XML Namespace spec).
/// Quits parsing when an invalid NCName char is reached or the end of string is reached.
/// Returns the number of valid NCName chars that were parsed.
/// </summary>
[System.Security.SecuritySafeCritical]
internal static unsafe int ParseNCName(string s, int offset)
{
Debug.Assert(s != null && offset <= s.Length);
// Quit if the first character is not a valid NCName starting character
int i = offset;
if (i < s.Length)
{
if (s_xmlCharType.IsStartNCNameSingleChar(s[i]))
{
i++;
}
#if XML10_FIFTH_EDITION
else if (s_xmlCharType.IsNCNameSurrogateChar(s, i)) {
i += 2;
}
#endif
else
{
return 0; // no valid StartNCName char
}
// Keep parsing until the end of string or an invalid NCName character is reached
while (i < s.Length)
{
if (s_xmlCharType.IsNCNameSingleChar(s[i]))
{
i++;
}
#if XML10_FIFTH_EDITION
else if (s_xmlCharType.IsNCNameSurrogateChar(s, i)) {
i += 2;
}
#endif
else
{
break;
}
}
}
return i - offset;
}
internal static int ParseNCName(string s)
{
return ParseNCName(s, 0);
}
/// <summary>
/// Calls parseName and throws exception if the resulting name is not a valid NCName.
/// Returns the input string if there is no error.
/// </summary>
internal static string ParseNCNameThrow(string s)
{
// throwOnError = true
ParseNCNameInternal(s, true);
return s;
}
/// <summary>
/// Calls parseName and returns false or throws exception if the resulting name is not
/// a valid NCName. Returns the input string if there is no error.
/// </summary>
private static bool ParseNCNameInternal(string s, bool throwOnError)
{
int len = ParseNCName(s, 0);
if (len == 0 || len != s.Length)
{
// If the string is not a valid NCName, then throw or return false
if (throwOnError) ThrowInvalidName(s, 0, len);
return false;
}
return true;
}
//-----------------------------------------------
// QName parsing
//-----------------------------------------------
/// <summary>
/// Attempts to parse the input string as a QName (see the XML Namespace spec).
/// Quits parsing when an invalid QName char is reached or the end of string is reached.
/// Returns the number of valid QName chars that were parsed.
/// Sets colonOffset to the offset of a colon character if it exists, or 0 otherwise.
/// </summary>
internal static int ParseQName(string s, int offset, out int colonOffset)
{
int len, lenLocal;
// Assume no colon
colonOffset = 0;
// Parse NCName (may be prefix, may be local name)
len = ParseNCName(s, offset);
if (len != 0)
{
// Non-empty NCName, so look for colon if there are any characters left
offset += len;
if (offset < s.Length && s[offset] == ':')
{
// First NCName was prefix, so look for local name part
lenLocal = ParseNCName(s, offset + 1);
if (lenLocal != 0)
{
// Local name part found, so increase total QName length (add 1 for colon)
colonOffset = offset;
len += lenLocal + 1;
}
}
}
return len;
}
/// <summary>
/// Calls parseQName and throws exception if the resulting name is not a valid QName.
/// Returns the prefix and local name parts.
/// </summary>
internal static void ParseQNameThrow(string s, out string prefix, out string localName)
{
int colonOffset;
int len = ParseQName(s, 0, out colonOffset);
if (len == 0 || len != s.Length)
{
// If the string is not a valid QName, then throw
ThrowInvalidName(s, 0, len);
}
if (colonOffset != 0)
{
prefix = s.Substring(0, colonOffset);
localName = s.Substring(colonOffset + 1);
}
else
{
prefix = "";
localName = s;
}
}
/// <summary>
/// Parses the input string as a NameTest (see the XPath spec), returning the prefix and
/// local name parts. Throws an exception if the given string is not a valid NameTest.
/// If the NameTest contains a star, null values for localName (case NCName':*'), or for
/// both localName and prefix (case '*') are returned.
/// </summary>
internal static void ParseNameTestThrow(string s, out string prefix, out string localName)
{
int len, lenLocal, offset;
if (s.Length != 0 && s[0] == '*')
{
// '*' as a NameTest
prefix = localName = null;
len = 1;
}
else
{
// Parse NCName (may be prefix, may be local name)
len = ParseNCName(s, 0);
if (len != 0)
{
// Non-empty NCName, so look for colon if there are any characters left
localName = s.Substring(0, len);
if (len < s.Length && s[len] == ':')
{
// First NCName was prefix, so look for local name part
prefix = localName;
offset = len + 1;
if (offset < s.Length && s[offset] == '*')
{
// '*' as a local name part, add 2 to len for colon and star
localName = null;
len += 2;
}
else
{
lenLocal = ParseNCName(s, offset);
if (lenLocal != 0)
{
// Local name part found, so increase total NameTest length
localName = s.Substring(offset, lenLocal);
len += lenLocal + 1;
}
}
}
else
{
prefix = string.Empty;
}
}
else
{
// Make the compiler happy
prefix = localName = null;
}
}
if (len == 0 || len != s.Length)
{
// If the string is not a valid NameTest, then throw
ThrowInvalidName(s, 0, len);
}
}
/// <summary>
/// Throws an invalid name exception.
/// </summary>
/// <param name="s">String that was parsed.</param>
/// <param name="offsetStartChar">Offset in string where parsing began.</param>
/// <param name="offsetBadChar">Offset in string where parsing failed.</param>
internal static void ThrowInvalidName(string s, int offsetStartChar, int offsetBadChar)
{
// If the name is empty, throw an exception
if (offsetStartChar >= s.Length)
throw new XmlException(SR.Format(SR.Xml_EmptyName, string.Empty));
Debug.Assert(offsetBadChar < s.Length);
if (s_xmlCharType.IsNCNameSingleChar(s[offsetBadChar]) && !XmlCharType.Instance.IsStartNCNameSingleChar(s[offsetBadChar]))
{
// The error character is a valid name character, but is not a valid start name character
throw new XmlException(SR.Xml_BadStartNameChar, XmlException.BuildCharExceptionArgs(s, offsetBadChar));
}
else
{
// The error character is an invalid name character
throw new XmlException(SR.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(s, offsetBadChar));
}
}
internal static Exception GetInvalidNameException(string s, int offsetStartChar, int offsetBadChar)
{
// If the name is empty, throw an exception
if (offsetStartChar >= s.Length)
return new XmlException(SR.Xml_EmptyName, string.Empty);
Debug.Assert(offsetBadChar < s.Length);
if (s_xmlCharType.IsNCNameSingleChar(s[offsetBadChar]) && !s_xmlCharType.IsStartNCNameSingleChar(s[offsetBadChar]))
{
// The error character is a valid name character, but is not a valid start name character
return new XmlException(SR.Xml_BadStartNameChar, XmlException.BuildCharExceptionArgs(s, offsetBadChar));
}
else
{
// The error character is an invalid name character
return new XmlException(SR.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(s, offsetBadChar));
}
}
/// <summary>
/// Returns true if "prefix" starts with the characters 'x', 'm', 'l' (case-insensitive).
/// </summary>
internal static bool StartsWithXml(string s)
{
if (s.Length < 3)
return false;
if (s[0] != 'x' && s[0] != 'X')
return false;
if (s[1] != 'm' && s[1] != 'M')
return false;
if (s[2] != 'l' && s[2] != 'L')
return false;
return true;
}
/// <summary>
/// Returns true if "s" is a namespace that is reserved by Xml 1.0 or Namespace 1.0.
/// </summary>
internal static bool IsReservedNamespace(string s)
{
return s.Equals(XmlReservedNs.NsXml) || s.Equals(XmlReservedNs.NsXmlNs);
}
/// <summary>
/// Throw if the specified name parts are not valid according to the rules of "nodeKind". Check only rules that are
/// specified by the Flags.
/// NOTE: Namespaces should be passed using a prefix, ns pair. "localName" is always string.Empty.
/// </summary>
internal static void ValidateNameThrow(string prefix, string localName, string ns, XPathNodeType nodeKind, Flags flags)
{
// throwOnError = true
ValidateNameInternal(prefix, localName, ns, nodeKind, flags, true);
}
/// <summary>
/// Return false if the specified name parts are not valid according to the rules of "nodeKind". Check only rules that are
/// specified by the Flags.
/// NOTE: Namespaces should be passed using a prefix, ns pair. "localName" is always string.Empty.
/// </summary>
internal static bool ValidateName(string prefix, string localName, string ns, XPathNodeType nodeKind, Flags flags)
{
// throwOnError = false
return ValidateNameInternal(prefix, localName, ns, nodeKind, flags, false);
}
/// <summary>
/// Return false or throw if the specified name parts are not valid according to the rules of "nodeKind". Check only rules
/// that are specified by the Flags.
/// NOTE: Namespaces should be passed using a prefix, ns pair. "localName" is always string.Empty.
/// </summary>
private static bool ValidateNameInternal(string prefix, string localName, string ns, XPathNodeType nodeKind, Flags flags, bool throwOnError)
{
Debug.Assert(prefix != null && localName != null && ns != null);
if ((flags & Flags.NCNames) != 0)
{
// 1. Verify that each non-empty prefix and localName is a valid NCName
if (prefix.Length != 0)
if (!ParseNCNameInternal(prefix, throwOnError))
{
return false;
}
if (localName.Length != 0)
if (!ParseNCNameInternal(localName, throwOnError))
{
return false;
}
}
if ((flags & Flags.CheckLocalName) != 0)
{
// 2. Determine whether the local name is valid
switch (nodeKind)
{
case XPathNodeType.Element:
// Elements and attributes must have a non-empty local name
if (localName.Length == 0)
{
if (throwOnError) throw new XmlException(SR.Xdom_Empty_LocalName, string.Empty);
return false;
}
break;
case XPathNodeType.Attribute:
// Attribute local name cannot be "xmlns" if namespace is empty
if (ns.Length == 0 && localName.Equals("xmlns"))
{
if (throwOnError) throw new XmlException(SR.XmlBadName, new string[] { nodeKind.ToString(), localName });
return false;
}
goto case XPathNodeType.Element;
case XPathNodeType.ProcessingInstruction:
// PI's local-name must be non-empty and cannot be 'xml' (case-insensitive)
if (localName.Length == 0 || (localName.Length == 3 && StartsWithXml(localName)))
{
if (throwOnError) throw new XmlException(SR.Xml_InvalidPIName, localName);
return false;
}
break;
default:
// All other node types must have empty local-name
if (localName.Length != 0)
{
if (throwOnError) throw new XmlException(SR.XmlNoNameAllowed, nodeKind.ToString());
return false;
}
break;
}
}
if ((flags & Flags.CheckPrefixMapping) != 0)
{
// 3. Determine whether the prefix is valid
switch (nodeKind)
{
case XPathNodeType.Element:
case XPathNodeType.Attribute:
case XPathNodeType.Namespace:
if (ns.Length == 0)
{
// If namespace is empty, then prefix must be empty
if (prefix.Length != 0)
{
if (throwOnError) throw new XmlException(SR.Xml_PrefixForEmptyNs, string.Empty);
return false;
}
}
else
{
// Don't allow empty attribute prefix since namespace is non-empty
if (prefix.Length == 0 && nodeKind == XPathNodeType.Attribute)
{
if (throwOnError) throw new XmlException(SR.XmlBadName, new string[] { nodeKind.ToString(), localName });
return false;
}
if (prefix.Equals("xml"))
{
// xml prefix must be mapped to the xml namespace
if (!ns.Equals(XmlReservedNs.NsXml))
{
if (throwOnError) throw new XmlException(SR.Xml_XmlPrefix, string.Empty);
return false;
}
}
else if (prefix.Equals("xmlns"))
{
// Prefix may never be 'xmlns'
if (throwOnError) throw new XmlException(SR.Xml_XmlnsPrefix, string.Empty);
return false;
}
else if (IsReservedNamespace(ns))
{
// Don't allow non-reserved prefixes to map to xml or xmlns namespaces
if (throwOnError) throw new XmlException(SR.Xml_NamespaceDeclXmlXmlns, string.Empty);
return false;
}
}
break;
case XPathNodeType.ProcessingInstruction:
// PI's prefix and namespace must be empty
if (prefix.Length != 0 || ns.Length != 0)
{
if (throwOnError) throw new XmlException(SR.Xml_InvalidPIName, CreateName(prefix, localName));
return false;
}
break;
default:
// All other node types must have empty prefix and namespace
if (prefix.Length != 0 || ns.Length != 0)
{
if (throwOnError) throw new XmlException(SR.XmlNoNameAllowed, nodeKind.ToString());
return false;
}
break;
}
}
return true;
}
/// <summary>
/// Creates a colon-delimited qname from prefix and local name parts.
/// </summary>
private static string CreateName(string prefix, string localName)
{
return (prefix.Length != 0) ? prefix + ":" + localName : localName;
}
/// <summary>
/// Split a QualifiedName into prefix and localname, w/o any checking.
/// (Used for XmlReader/XPathNavigator MoveTo(name) methods)
/// </summary>
internal static void SplitQName(string name, out string prefix, out string lname)
{
int colonPos = name.IndexOf(':');
if (-1 == colonPos)
{
prefix = string.Empty;
lname = name;
}
else if (0 == colonPos || (name.Length - 1) == colonPos)
{
throw new ArgumentException(SR.Format(SR.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(':', '\0')), "name");
}
else
{
prefix = name.Substring(0, colonPos);
colonPos++; // move after colon
lname = name.Substring(colonPos, name.Length - colonPos);
}
}
}
}
| |
/******************************************************************************
* Spine Runtimes Software License
* Version 2.3
*
* Copyright (c) 2013-2015, Esoteric Software
* All rights reserved.
*
* You are granted a perpetual, non-exclusive, non-sublicensable and
* non-transferable license to use, install, execute and perform the Spine
* Runtimes Software (the "Software") and derivative works solely for personal
* or internal use. Without the written permission of Esoteric Software (see
* Section 2 of the Spine Software License Agreement), you may not (a) modify,
* translate, adapt or otherwise create derivative works, improvements of the
* Software or develop new applications using the Software or (b) remove,
* delete, alter or obscure any trademarks or any copyright, trademark, patent
* or other intellectual property or proprietary rights notices on or in the
* Software, including any copy thereof. Redistributions in binary or source
* form must include this license and terms.
*
* THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "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 ESOTERIC SOFTWARE 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;
namespace Spine {
public class AnimationState {
private AnimationStateData data;
private ExposedList<TrackEntry> tracks = new ExposedList<TrackEntry>();
private ExposedList<Event> events = new ExposedList<Event>();
private float timeScale = 1;
public AnimationStateData Data { get { return data; } }
public float TimeScale { get { return timeScale; } set { timeScale = value; } }
public delegate void StartEndDelegate(AnimationState state, int trackIndex);
public event StartEndDelegate Start;
public event StartEndDelegate End;
public delegate void EventDelegate(AnimationState state, int trackIndex, Event e);
public event EventDelegate Event;
public delegate void CompleteDelegate(AnimationState state, int trackIndex, int loopCount);
public event CompleteDelegate Complete;
public AnimationState (AnimationStateData data) {
if (data == null) throw new ArgumentNullException("data cannot be null.");
this.data = data;
}
public void Update (float delta) {
delta *= timeScale;
for (int i = 0; i < tracks.Count; i++) {
TrackEntry current = tracks.Items[i];
if (current == null) continue;
float trackDelta = delta * current.timeScale;
float time = current.time + trackDelta;
float endTime = current.endTime;
current.time = time;
if (current.previous != null) {
current.previous.time += trackDelta;
current.mixTime += trackDelta;
}
// Check if completed the animation or a loop iteration.
if (current.loop ? (current.lastTime % endTime > time % endTime) : (current.lastTime < endTime && time >= endTime)) {
int count = (int)(time / endTime);
current.OnComplete(this, i, count);
if (Complete != null) Complete(this, i, count);
}
TrackEntry next = current.next;
if (next != null) {
next.time = current.lastTime - next.delay;
if (next.time >= 0) SetCurrent(i, next);
} else {
// End non-looping animation when it reaches its end time and there is no next entry.
if (!current.loop && current.lastTime >= current.endTime) ClearTrack(i);
}
}
}
public void Apply (Skeleton skeleton) {
ExposedList<Event> events = this.events;
for (int i = 0; i < tracks.Count; i++) {
TrackEntry current = tracks.Items[i];
if (current == null) continue;
events.Clear();
float time = current.time;
bool loop = current.loop;
if (!loop && time > current.endTime) time = current.endTime;
TrackEntry previous = current.previous;
if (previous == null) {
if (current.mix == 1)
current.animation.Apply(skeleton, current.lastTime, time, loop, events);
else
current.animation.Mix(skeleton, current.lastTime, time, loop, events, current.mix);
} else {
float previousTime = previous.time;
if (!previous.loop && previousTime > previous.endTime) previousTime = previous.endTime;
previous.animation.Apply(skeleton, previousTime, previousTime, previous.loop, null);
float alpha = current.mixTime / current.mixDuration * current.mix;
if (alpha >= 1) {
alpha = 1;
current.previous = null;
}
current.animation.Mix(skeleton, current.lastTime, time, loop, events, alpha);
}
for (int ii = 0, nn = events.Count; ii < nn; ii++) {
Event e = events.Items[ii];
current.OnEvent(this, i, e);
if (Event != null) Event(this, i, e);
}
current.lastTime = current.time;
}
}
public void ClearTracks () {
for (int i = 0, n = tracks.Count; i < n; i++)
ClearTrack(i);
tracks.Clear();
}
public void ClearTrack (int trackIndex) {
if (trackIndex >= tracks.Count) return;
TrackEntry current = tracks.Items[trackIndex];
if (current == null) return;
current.OnEnd(this, trackIndex);
if (End != null) End(this, trackIndex);
tracks.Items[trackIndex] = null;
}
private TrackEntry ExpandToIndex (int index) {
if (index < tracks.Count) return tracks.Items[index];
while (index >= tracks.Count)
tracks.Add(null);
return null;
}
private void SetCurrent (int index, TrackEntry entry) {
TrackEntry current = ExpandToIndex(index);
if (current != null) {
TrackEntry previous = current.previous;
current.previous = null;
current.OnEnd(this, index);
if (End != null) End(this, index);
entry.mixDuration = data.GetMix(current.animation, entry.animation);
if (entry.mixDuration > 0) {
entry.mixTime = 0;
// If a mix is in progress, mix from the closest animation.
if (previous != null && current.mixTime / current.mixDuration < 0.5f)
entry.previous = previous;
else
entry.previous = current;
}
}
tracks.Items[index] = entry;
entry.OnStart(this, index);
if (Start != null) Start(this, index);
}
public TrackEntry SetAnimation (int trackIndex, String animationName, bool loop) {
Animation animation = data.skeletonData.FindAnimation(animationName);
if (animation == null) throw new ArgumentException("Animation not found: " + animationName);
return SetAnimation(trackIndex, animation, loop);
}
/// <summary>Set the current animation. Any queued animations are cleared.</summary>
public TrackEntry SetAnimation (int trackIndex, Animation animation, bool loop) {
if (animation == null) throw new ArgumentException("animation cannot be null.");
TrackEntry entry = new TrackEntry();
entry.animation = animation;
entry.loop = loop;
entry.time = 0;
entry.endTime = animation.Duration;
SetCurrent(trackIndex, entry);
return entry;
}
public TrackEntry AddAnimation (int trackIndex, String animationName, bool loop, float delay) {
Animation animation = data.skeletonData.FindAnimation(animationName);
if (animation == null) throw new ArgumentException("Animation not found: " + animationName);
return AddAnimation(trackIndex, animation, loop, delay);
}
/// <summary>Adds an animation to be played delay seconds after the current or last queued animation.</summary>
/// <param name="delay">May be <= 0 to use duration of previous animation minus any mix duration plus the negative delay.</param>
public TrackEntry AddAnimation (int trackIndex, Animation animation, bool loop, float delay) {
if (animation == null) throw new ArgumentException("animation cannot be null.");
TrackEntry entry = new TrackEntry();
entry.animation = animation;
entry.loop = loop;
entry.time = 0;
entry.endTime = animation.Duration;
TrackEntry last = ExpandToIndex(trackIndex);
if (last != null) {
while (last.next != null)
last = last.next;
last.next = entry;
} else
tracks.Items[trackIndex] = entry;
if (delay <= 0) {
if (last != null)
delay += last.endTime - data.GetMix(last.animation, animation);
else
delay = 0;
}
entry.delay = delay;
return entry;
}
/// <returns>May be null.</returns>
public TrackEntry GetCurrent (int trackIndex) {
if (trackIndex >= tracks.Count) return null;
return tracks.Items[trackIndex];
}
override public String ToString () {
StringBuilder buffer = new StringBuilder();
for (int i = 0, n = tracks.Count; i < n; i++) {
TrackEntry entry = tracks.Items[i];
if (entry == null) continue;
if (buffer.Length > 0) buffer.Append(", ");
buffer.Append(entry.ToString());
}
if (buffer.Length == 0) return "<none>";
return buffer.ToString();
}
}
public class TrackEntry {
internal TrackEntry next, previous;
internal Animation animation;
internal bool loop;
internal float delay, time, lastTime = -1, endTime, timeScale = 1;
internal float mixTime, mixDuration, mix = 1;
public Animation Animation { get { return animation; } }
public float Delay { get { return delay; } set { delay = value; } }
public float Time { get { return time; } set { time = value; } }
public float LastTime { get { return lastTime; } set { lastTime = value; } }
public float EndTime { get { return endTime; } set { endTime = value; } }
public float TimeScale { get { return timeScale; } set { timeScale = value; } }
public float Mix { get { return mix; } set { mix = value; } }
public bool Loop { get { return loop; } set { loop = value; } }
public event AnimationState.StartEndDelegate Start;
public event AnimationState.StartEndDelegate End;
public event AnimationState.EventDelegate Event;
public event AnimationState.CompleteDelegate Complete;
internal void OnStart (AnimationState state, int index) {
if (Start != null) Start(state, index);
}
internal void OnEnd (AnimationState state, int index) {
if (End != null) End(state, index);
}
internal void OnEvent (AnimationState state, int index, Event e) {
if (Event != null) Event(state, index, e);
}
internal void OnComplete (AnimationState state, int index, int loopCount) {
if (Complete != null) Complete(state, index, loopCount);
}
override public String ToString () {
return animation == null ? "<none>" : animation.name;
}
}
}
| |
using UnityEngine;
/// <summary>
/// Functionality common to both NGUI and 2D sprites brought out into a single common parent.
/// Mostly contains everything related to drawing the sprite.
/// </summary>
public abstract class UIBasicSprite : UIWidget
{
public enum Type
{
Simple,
Sliced,
Tiled,
Filled,
Advanced,
}
public enum FillDirection
{
Horizontal,
Vertical,
Radial90,
Radial180,
Radial360,
}
public enum AdvancedType
{
Invisible,
Sliced,
Tiled,
}
public enum Flip
{
Nothing,
Horizontally,
Vertically,
Both,
}
[HideInInspector][SerializeField] protected Type mType = Type.Simple;
[HideInInspector][SerializeField] protected FillDirection mFillDirection = FillDirection.Radial360;
[Range(0f, 1f)]
[HideInInspector][SerializeField] protected float mFillAmount = 1.0f;
[HideInInspector][SerializeField] protected bool mInvert = false;
[HideInInspector][SerializeField] protected Flip mFlip = Flip.Nothing;
// Cached to avoid allocations
Rect mInnerUV = new Rect();
Rect mOuterUV = new Rect();
/// <summary>
/// When the sprite type is advanced, this determines whether the center is tiled or sliced.
/// </summary>
public AdvancedType centerType = AdvancedType.Sliced;
/// <summary>
/// When the sprite type is advanced, this determines whether the left edge is tiled or sliced.
/// </summary>
public AdvancedType leftType = AdvancedType.Sliced;
/// <summary>
/// When the sprite type is advanced, this determines whether the right edge is tiled or sliced.
/// </summary>
public AdvancedType rightType = AdvancedType.Sliced;
/// <summary>
/// When the sprite type is advanced, this determines whether the bottom edge is tiled or sliced.
/// </summary>
public AdvancedType bottomType = AdvancedType.Sliced;
/// <summary>
/// When the sprite type is advanced, this determines whether the top edge is tiled or sliced.
/// </summary>
public AdvancedType topType = AdvancedType.Sliced;
/// <summary>
/// How the sprite is drawn. It's virtual for legacy reasons (UISlicedSprite, UITiledSprite, UIFilledSprite).
/// </summary>
public virtual Type type
{
get
{
return mType;
}
set
{
if (mType != value)
{
mType = value;
MarkAsChanged();
}
}
}
/// <summary>
/// Sprite flip setting.
/// </summary>
public Flip flip
{
get
{
return mFlip;
}
set
{
if (mFlip != value)
{
mFlip = value;
MarkAsChanged();
}
}
}
/// <summary>
/// Direction of the cut procedure.
/// </summary>
public FillDirection fillDirection
{
get
{
return mFillDirection;
}
set
{
if (mFillDirection != value)
{
mFillDirection = value;
mChanged = true;
}
}
}
/// <summary>
/// Amount of the sprite shown. 0-1 range with 0 being nothing shown, and 1 being the full sprite.
/// </summary>
public float fillAmount
{
get
{
return mFillAmount;
}
set
{
float val = Mathf.Clamp01(value);
if (mFillAmount != val)
{
mFillAmount = val;
mChanged = true;
}
}
}
/// <summary>
/// Minimum allowed width for this widget.
/// </summary>
override public int minWidth
{
get
{
if (type == Type.Sliced || type == Type.Advanced)
{
Vector4 b = border * pixelSize;
int min = Mathf.RoundToInt(b.x + b.z);
return Mathf.Max(base.minWidth, ((min & 1) == 1) ? min + 1 : min);
}
return base.minWidth;
}
}
/// <summary>
/// Minimum allowed height for this widget.
/// </summary>
override public int minHeight
{
get
{
if (type == Type.Sliced || type == Type.Advanced)
{
Vector4 b = border * pixelSize;
int min = Mathf.RoundToInt(b.y + b.w);
return Mathf.Max(base.minHeight, ((min & 1) == 1) ? min + 1 : min);
}
return base.minHeight;
}
}
/// <summary>
/// Whether the sprite should be filled in the opposite direction.
/// </summary>
public bool invert
{
get
{
return mInvert;
}
set
{
if (mInvert != value)
{
mInvert = value;
mChanged = true;
}
}
}
/// <summary>
/// Whether the widget has a border for 9-slicing.
/// </summary>
public bool hasBorder
{
get
{
Vector4 br = border;
return (br.x != 0f || br.y != 0f || br.z != 0f || br.w != 0f);
}
}
/// <summary>
/// Whether the sprite's material is using a pre-multiplied alpha shader.
/// </summary>
public virtual bool premultipliedAlpha { get { return false; } }
/// <summary>
/// Size of the pixel. Overwritten in the NGUI sprite to pull a value from the atlas.
/// </summary>
public virtual float pixelSize { get { return 1f; } }
#if UNITY_EDITOR
/// <summary>
/// Keep sane values.
/// </summary>
protected override void OnValidate ()
{
base.OnValidate();
mFillAmount = Mathf.Clamp01(mFillAmount);
}
#endif
#region Fill Functions
// Static variables to reduce garbage collection
static protected Vector2[] mTempPos = new Vector2[4];
static protected Vector2[] mTempUVs = new Vector2[4];
/// <summary>
/// Convenience function that returns the drawn UVs after flipping gets considered.
/// X = left, Y = bottom, Z = right, W = top.
/// </summary>
Vector4 drawingUVs
{
get
{
switch (mFlip)
{
case Flip.Horizontally: return new Vector4(mOuterUV.xMax, mOuterUV.yMin, mOuterUV.xMin, mOuterUV.yMax);
case Flip.Vertically: return new Vector4(mOuterUV.xMin, mOuterUV.yMax, mOuterUV.xMax, mOuterUV.yMin);
case Flip.Both: return new Vector4(mOuterUV.xMax, mOuterUV.yMax, mOuterUV.xMin, mOuterUV.yMin);
default: return new Vector4(mOuterUV.xMin, mOuterUV.yMin, mOuterUV.xMax, mOuterUV.yMax);
}
}
}
/// <summary>
/// Final widget's color passed to the draw buffer.
/// </summary>
Color32 drawingColor
{
get
{
Color colF = color;
colF.a = finalAlpha;
return premultipliedAlpha ? NGUITools.ApplyPMA(colF) : colF;
}
}
/// <summary>
/// Fill the draw buffers.
/// </summary>
protected void Fill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols, Rect outer, Rect inner)
{
mOuterUV = outer;
mInnerUV = inner;
switch (type)
{
case Type.Simple:
SimpleFill(verts, uvs, cols);
break;
case Type.Sliced:
SlicedFill(verts, uvs, cols);
break;
case Type.Filled:
FilledFill(verts, uvs, cols);
break;
case Type.Tiled:
TiledFill(verts, uvs, cols);
break;
case Type.Advanced:
AdvancedFill(verts, uvs, cols);
break;
}
}
/// <summary>
/// Regular sprite fill function is quite simple.
/// </summary>
void SimpleFill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols)
{
Vector4 v = drawingDimensions;
Vector4 u = drawingUVs;
Color32 c = drawingColor;
verts.Add(new Vector3(v.x, v.y));
verts.Add(new Vector3(v.x, v.w));
verts.Add(new Vector3(v.z, v.w));
verts.Add(new Vector3(v.z, v.y));
uvs.Add(new Vector2(u.x, u.y));
uvs.Add(new Vector2(u.x, u.w));
uvs.Add(new Vector2(u.z, u.w));
uvs.Add(new Vector2(u.z, u.y));
cols.Add(c);
cols.Add(c);
cols.Add(c);
cols.Add(c);
}
/// <summary>
/// Sliced sprite fill function is more complicated as it generates 9 quads instead of 1.
/// </summary>
void SlicedFill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols)
{
Vector4 br = border * pixelSize;
if (br.x == 0f && br.y == 0f && br.z == 0f && br.w == 0f)
{
SimpleFill(verts, uvs, cols);
return;
}
Color32 c = drawingColor;
Vector4 v = drawingDimensions;
mTempPos[0].x = v.x;
mTempPos[0].y = v.y;
mTempPos[3].x = v.z;
mTempPos[3].y = v.w;
if (mFlip == Flip.Horizontally || mFlip == Flip.Both)
{
mTempPos[1].x = mTempPos[0].x + br.z;
mTempPos[2].x = mTempPos[3].x - br.x;
mTempUVs[3].x = mOuterUV.xMin;
mTempUVs[2].x = mInnerUV.xMin;
mTempUVs[1].x = mInnerUV.xMax;
mTempUVs[0].x = mOuterUV.xMax;
}
else
{
mTempPos[1].x = mTempPos[0].x + br.x;
mTempPos[2].x = mTempPos[3].x - br.z;
mTempUVs[0].x = mOuterUV.xMin;
mTempUVs[1].x = mInnerUV.xMin;
mTempUVs[2].x = mInnerUV.xMax;
mTempUVs[3].x = mOuterUV.xMax;
}
if (mFlip == Flip.Vertically || mFlip == Flip.Both)
{
mTempPos[1].y = mTempPos[0].y + br.w;
mTempPos[2].y = mTempPos[3].y - br.y;
mTempUVs[3].y = mOuterUV.yMin;
mTempUVs[2].y = mInnerUV.yMin;
mTempUVs[1].y = mInnerUV.yMax;
mTempUVs[0].y = mOuterUV.yMax;
}
else
{
mTempPos[1].y = mTempPos[0].y + br.y;
mTempPos[2].y = mTempPos[3].y - br.w;
mTempUVs[0].y = mOuterUV.yMin;
mTempUVs[1].y = mInnerUV.yMin;
mTempUVs[2].y = mInnerUV.yMax;
mTempUVs[3].y = mOuterUV.yMax;
}
for (int x = 0; x < 3; ++x)
{
int x2 = x + 1;
for (int y = 0; y < 3; ++y)
{
if (centerType == AdvancedType.Invisible && x == 1 && y == 1) continue;
int y2 = y + 1;
verts.Add(new Vector3(mTempPos[x].x, mTempPos[y].y));
verts.Add(new Vector3(mTempPos[x].x, mTempPos[y2].y));
verts.Add(new Vector3(mTempPos[x2].x, mTempPos[y2].y));
verts.Add(new Vector3(mTempPos[x2].x, mTempPos[y].y));
uvs.Add(new Vector2(mTempUVs[x].x, mTempUVs[y].y));
uvs.Add(new Vector2(mTempUVs[x].x, mTempUVs[y2].y));
uvs.Add(new Vector2(mTempUVs[x2].x, mTempUVs[y2].y));
uvs.Add(new Vector2(mTempUVs[x2].x, mTempUVs[y].y));
cols.Add(c);
cols.Add(c);
cols.Add(c);
cols.Add(c);
}
}
}
/// <summary>
/// Tiled sprite fill function.
/// </summary>
void TiledFill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols)
{
Texture tex = mainTexture;
if (tex == null) return;
Vector2 size = new Vector2(mInnerUV.width * tex.width, mInnerUV.height * tex.height);
size *= pixelSize;
if (tex == null || size.x < 2f || size.y < 2f) return;
Color32 c = drawingColor;
Vector4 v = drawingDimensions;
Vector4 u;
if (mFlip == Flip.Horizontally || mFlip == Flip.Both)
{
u.x = mInnerUV.xMax;
u.z = mInnerUV.xMin;
}
else
{
u.x = mInnerUV.xMin;
u.z = mInnerUV.xMax;
}
if (mFlip == Flip.Vertically || mFlip == Flip.Both)
{
u.y = mInnerUV.yMax;
u.w = mInnerUV.yMin;
}
else
{
u.y = mInnerUV.yMin;
u.w = mInnerUV.yMax;
}
float x0 = v.x;
float y0 = v.y;
float u0 = u.x;
float v0 = u.y;
while (y0 < v.w)
{
x0 = v.x;
float y1 = y0 + size.y;
float v1 = u.w;
if (y1 > v.w)
{
v1 = Mathf.Lerp(u.y, u.w, (v.w - y0) / size.y);
y1 = v.w;
}
while (x0 < v.z)
{
float x1 = x0 + size.x;
float u1 = u.z;
if (x1 > v.z)
{
u1 = Mathf.Lerp(u.x, u.z, (v.z - x0) / size.x);
x1 = v.z;
}
verts.Add(new Vector3(x0, y0));
verts.Add(new Vector3(x0, y1));
verts.Add(new Vector3(x1, y1));
verts.Add(new Vector3(x1, y0));
uvs.Add(new Vector2(u0, v0));
uvs.Add(new Vector2(u0, v1));
uvs.Add(new Vector2(u1, v1));
uvs.Add(new Vector2(u1, v0));
cols.Add(c);
cols.Add(c);
cols.Add(c);
cols.Add(c);
x0 += size.x;
}
y0 += size.y;
}
}
/// <summary>
/// Filled sprite fill function.
/// </summary>
void FilledFill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols)
{
if (mFillAmount < 0.001f) return;
Vector4 v = drawingDimensions;
Vector4 u = drawingUVs;
Color32 c = drawingColor;
// Horizontal and vertical filled sprites are simple -- just end the sprite prematurely
if (mFillDirection == FillDirection.Horizontal || mFillDirection == FillDirection.Vertical)
{
if (mFillDirection == FillDirection.Horizontal)
{
float fill = (u.z - u.x) * mFillAmount;
if (mInvert)
{
v.x = v.z - (v.z - v.x) * mFillAmount;
u.x = u.z - fill;
}
else
{
v.z = v.x + (v.z - v.x) * mFillAmount;
u.z = u.x + fill;
}
}
else if (mFillDirection == FillDirection.Vertical)
{
float fill = (u.w - u.y) * mFillAmount;
if (mInvert)
{
v.y = v.w - (v.w - v.y) * mFillAmount;
u.y = u.w - fill;
}
else
{
v.w = v.y + (v.w - v.y) * mFillAmount;
u.w = u.y + fill;
}
}
}
mTempPos[0] = new Vector2(v.x, v.y);
mTempPos[1] = new Vector2(v.x, v.w);
mTempPos[2] = new Vector2(v.z, v.w);
mTempPos[3] = new Vector2(v.z, v.y);
mTempUVs[0] = new Vector2(u.x, u.y);
mTempUVs[1] = new Vector2(u.x, u.w);
mTempUVs[2] = new Vector2(u.z, u.w);
mTempUVs[3] = new Vector2(u.z, u.y);
if (mFillAmount < 1f)
{
if (mFillDirection == FillDirection.Radial90)
{
if (RadialCut(mTempPos, mTempUVs, mFillAmount, mInvert, 0))
{
for (int i = 0; i < 4; ++i)
{
verts.Add(mTempPos[i]);
uvs.Add(mTempUVs[i]);
cols.Add(c);
}
}
return;
}
if (mFillDirection == FillDirection.Radial180)
{
for (int side = 0; side < 2; ++side)
{
float fx0, fx1, fy0, fy1;
fy0 = 0f;
fy1 = 1f;
if (side == 0) { fx0 = 0f; fx1 = 0.5f; }
else { fx0 = 0.5f; fx1 = 1f; }
mTempPos[0].x = Mathf.Lerp(v.x, v.z, fx0);
mTempPos[1].x = mTempPos[0].x;
mTempPos[2].x = Mathf.Lerp(v.x, v.z, fx1);
mTempPos[3].x = mTempPos[2].x;
mTempPos[0].y = Mathf.Lerp(v.y, v.w, fy0);
mTempPos[1].y = Mathf.Lerp(v.y, v.w, fy1);
mTempPos[2].y = mTempPos[1].y;
mTempPos[3].y = mTempPos[0].y;
mTempUVs[0].x = Mathf.Lerp(u.x, u.z, fx0);
mTempUVs[1].x = mTempUVs[0].x;
mTempUVs[2].x = Mathf.Lerp(u.x, u.z, fx1);
mTempUVs[3].x = mTempUVs[2].x;
mTempUVs[0].y = Mathf.Lerp(u.y, u.w, fy0);
mTempUVs[1].y = Mathf.Lerp(u.y, u.w, fy1);
mTempUVs[2].y = mTempUVs[1].y;
mTempUVs[3].y = mTempUVs[0].y;
float val = !mInvert ? fillAmount * 2f - side : mFillAmount * 2f - (1 - side);
if (RadialCut(mTempPos, mTempUVs, Mathf.Clamp01(val), !mInvert, NGUIMath.RepeatIndex(side + 3, 4)))
{
for (int i = 0; i < 4; ++i)
{
verts.Add(mTempPos[i]);
uvs.Add(mTempUVs[i]);
cols.Add(c);
}
}
}
return;
}
if (mFillDirection == FillDirection.Radial360)
{
for (int corner = 0; corner < 4; ++corner)
{
float fx0, fx1, fy0, fy1;
if (corner < 2) { fx0 = 0f; fx1 = 0.5f; }
else { fx0 = 0.5f; fx1 = 1f; }
if (corner == 0 || corner == 3) { fy0 = 0f; fy1 = 0.5f; }
else { fy0 = 0.5f; fy1 = 1f; }
mTempPos[0].x = Mathf.Lerp(v.x, v.z, fx0);
mTempPos[1].x = mTempPos[0].x;
mTempPos[2].x = Mathf.Lerp(v.x, v.z, fx1);
mTempPos[3].x = mTempPos[2].x;
mTempPos[0].y = Mathf.Lerp(v.y, v.w, fy0);
mTempPos[1].y = Mathf.Lerp(v.y, v.w, fy1);
mTempPos[2].y = mTempPos[1].y;
mTempPos[3].y = mTempPos[0].y;
mTempUVs[0].x = Mathf.Lerp(u.x, u.z, fx0);
mTempUVs[1].x = mTempUVs[0].x;
mTempUVs[2].x = Mathf.Lerp(u.x, u.z, fx1);
mTempUVs[3].x = mTempUVs[2].x;
mTempUVs[0].y = Mathf.Lerp(u.y, u.w, fy0);
mTempUVs[1].y = Mathf.Lerp(u.y, u.w, fy1);
mTempUVs[2].y = mTempUVs[1].y;
mTempUVs[3].y = mTempUVs[0].y;
float val = mInvert ?
mFillAmount * 4f - NGUIMath.RepeatIndex(corner + 2, 4) :
mFillAmount * 4f - (3 - NGUIMath.RepeatIndex(corner + 2, 4));
if (RadialCut(mTempPos, mTempUVs, Mathf.Clamp01(val), mInvert, NGUIMath.RepeatIndex(corner + 2, 4)))
{
for (int i = 0; i < 4; ++i)
{
verts.Add(mTempPos[i]);
uvs.Add(mTempUVs[i]);
cols.Add(c);
}
}
}
return;
}
}
// Fill the buffer with the quad for the sprite
for (int i = 0; i < 4; ++i)
{
verts.Add(mTempPos[i]);
uvs.Add(mTempUVs[i]);
cols.Add(c);
}
}
/// <summary>
/// Advanced sprite fill function. Contributed by Nicki Hansen.
/// </summary>
void AdvancedFill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols)
{
Texture tex = mainTexture;
if (tex == null) return;
Vector4 br = border * pixelSize;
if (br.x == 0f && br.y == 0f && br.z == 0f && br.w == 0f)
{
SimpleFill(verts, uvs, cols);
return;
}
Color32 c = drawingColor;
Vector4 v = drawingDimensions;
Vector2 tileSize = new Vector2(mInnerUV.width * tex.width, mInnerUV.height * tex.height);
tileSize *= pixelSize;
if (tileSize.x < 1f) tileSize.x = 1f;
if (tileSize.y < 1f) tileSize.y = 1f;
mTempPos[0].x = v.x;
mTempPos[0].y = v.y;
mTempPos[3].x = v.z;
mTempPos[3].y = v.w;
if (mFlip == Flip.Horizontally || mFlip == Flip.Both)
{
mTempPos[1].x = mTempPos[0].x + br.z;
mTempPos[2].x = mTempPos[3].x - br.x;
mTempUVs[3].x = mOuterUV.xMin;
mTempUVs[2].x = mInnerUV.xMin;
mTempUVs[1].x = mInnerUV.xMax;
mTempUVs[0].x = mOuterUV.xMax;
}
else
{
mTempPos[1].x = mTempPos[0].x + br.x;
mTempPos[2].x = mTempPos[3].x - br.z;
mTempUVs[0].x = mOuterUV.xMin;
mTempUVs[1].x = mInnerUV.xMin;
mTempUVs[2].x = mInnerUV.xMax;
mTempUVs[3].x = mOuterUV.xMax;
}
if (mFlip == Flip.Vertically || mFlip == Flip.Both)
{
mTempPos[1].y = mTempPos[0].y + br.w;
mTempPos[2].y = mTempPos[3].y - br.y;
mTempUVs[3].y = mOuterUV.yMin;
mTempUVs[2].y = mInnerUV.yMin;
mTempUVs[1].y = mInnerUV.yMax;
mTempUVs[0].y = mOuterUV.yMax;
}
else
{
mTempPos[1].y = mTempPos[0].y + br.y;
mTempPos[2].y = mTempPos[3].y - br.w;
mTempUVs[0].y = mOuterUV.yMin;
mTempUVs[1].y = mInnerUV.yMin;
mTempUVs[2].y = mInnerUV.yMax;
mTempUVs[3].y = mOuterUV.yMax;
}
for (int x = 0; x < 3; ++x)
{
int x2 = x + 1;
for (int y = 0; y < 3; ++y)
{
if (centerType == AdvancedType.Invisible && x == 1 && y == 1) continue;
int y2 = y + 1;
if (x == 1 && y == 1) // Center
{
if (centerType == AdvancedType.Tiled)
{
float startPositionX = mTempPos[x].x;
float endPositionX = mTempPos[x2].x;
float startPositionY = mTempPos[y].y;
float endPositionY = mTempPos[y2].y;
float textureStartX = mTempUVs[x].x;
float textureStartY = mTempUVs[y].y;
float tileStartY = startPositionY;
while (tileStartY < endPositionY)
{
float tileStartX = startPositionX;
float textureEndY = mTempUVs[y2].y;
float tileEndY = tileStartY + tileSize.y;
if (tileEndY > endPositionY)
{
textureEndY = Mathf.Lerp(textureStartY, textureEndY, (endPositionY - tileStartY) / tileSize.y);
tileEndY = endPositionY;
}
while (tileStartX < endPositionX)
{
float tileEndX = tileStartX + tileSize.x;
float textureEndX = mTempUVs[x2].x;
if (tileEndX > endPositionX)
{
textureEndX = Mathf.Lerp(textureStartX, textureEndX, (endPositionX - tileStartX) / tileSize.x);
tileEndX = endPositionX;
}
Fill(verts, uvs, cols,
tileStartX, tileEndX,
tileStartY, tileEndY,
textureStartX, textureEndX,
textureStartY, textureEndY, c);
tileStartX += tileSize.x;
}
tileStartY += tileSize.y;
}
}
else if (centerType == AdvancedType.Sliced)
{
Fill(verts, uvs, cols,
mTempPos[x].x, mTempPos[x2].x,
mTempPos[y].y, mTempPos[y2].y,
mTempUVs[x].x, mTempUVs[x2].x,
mTempUVs[y].y, mTempUVs[y2].y, c);
}
}
else if (x == 1) // Top or bottom
{
if ((y == 0 && bottomType == AdvancedType.Tiled) || (y == 2 && topType == AdvancedType.Tiled))
{
float startPositionX = mTempPos[x].x;
float endPositionX = mTempPos[x2].x;
float startPositionY = mTempPos[y].y;
float endPositionY = mTempPos[y2].y;
float textureStartX = mTempUVs[x].x;
float textureStartY = mTempUVs[y].y;
float textureEndY = mTempUVs[y2].y;
float tileStartX = startPositionX;
while (tileStartX < endPositionX)
{
float tileEndX = tileStartX + tileSize.x;
float textureEndX = mTempUVs[x2].x;
if (tileEndX > endPositionX)
{
textureEndX = Mathf.Lerp(textureStartX, textureEndX, (endPositionX - tileStartX) / tileSize.x);
tileEndX = endPositionX;
}
Fill(verts, uvs, cols,
tileStartX, tileEndX,
startPositionY, endPositionY,
textureStartX, textureEndX,
textureStartY, textureEndY, c);
tileStartX += tileSize.x;
}
}
else if ((y == 0 && bottomType == AdvancedType.Sliced) || (y == 2 && topType == AdvancedType.Sliced))
{
Fill(verts, uvs, cols,
mTempPos[x].x, mTempPos[x2].x,
mTempPos[y].y, mTempPos[y2].y,
mTempUVs[x].x, mTempUVs[x2].x,
mTempUVs[y].y, mTempUVs[y2].y, c);
}
}
else if (y == 1) // Left or right
{
if ((x == 0 && leftType == AdvancedType.Tiled) || (x == 2 && rightType == AdvancedType.Tiled))
{
float startPositionX = mTempPos[x].x;
float endPositionX = mTempPos[x2].x;
float startPositionY = mTempPos[y].y;
float endPositionY = mTempPos[y2].y;
float textureStartX = mTempUVs[x].x;
float textureEndX = mTempUVs[x2].x;
float textureStartY = mTempUVs[y].y;
float tileStartY = startPositionY;
while (tileStartY < endPositionY)
{
float textureEndY = mTempUVs[y2].y;
float tileEndY = tileStartY + tileSize.y;
if (tileEndY > endPositionY)
{
textureEndY = Mathf.Lerp(textureStartY, textureEndY, (endPositionY - tileStartY) / tileSize.y);
tileEndY = endPositionY;
}
Fill(verts, uvs, cols,
startPositionX, endPositionX,
tileStartY, tileEndY,
textureStartX, textureEndX,
textureStartY, textureEndY, c);
tileStartY += tileSize.y;
}
}
else if ((x == 0 && leftType == AdvancedType.Sliced) || (x == 2 && rightType == AdvancedType.Sliced))
{
Fill(verts, uvs, cols,
mTempPos[x].x, mTempPos[x2].x,
mTempPos[y].y, mTempPos[y2].y,
mTempUVs[x].x, mTempUVs[x2].x,
mTempUVs[y].y, mTempUVs[y2].y, c);
}
}
else // Corner
{
Fill(verts, uvs, cols,
mTempPos[x].x, mTempPos[x2].x,
mTempPos[y].y, mTempPos[y2].y,
mTempUVs[x].x, mTempUVs[x2].x,
mTempUVs[y].y, mTempUVs[y2].y, c);
}
}
}
}
/// <summary>
/// Adjust the specified quad, making it be radially filled instead.
/// </summary>
static bool RadialCut (Vector2[] xy, Vector2[] uv, float fill, bool invert, int corner)
{
// Nothing to fill
if (fill < 0.001f) return false;
// Even corners invert the fill direction
if ((corner & 1) == 1) invert = !invert;
// Nothing to adjust
if (!invert && fill > 0.999f) return true;
// Convert 0-1 value into 0 to 90 degrees angle in radians
float angle = Mathf.Clamp01(fill);
if (invert) angle = 1f - angle;
angle *= 90f * Mathf.Deg2Rad;
// Calculate the effective X and Y factors
float cos = Mathf.Cos(angle);
float sin = Mathf.Sin(angle);
RadialCut(xy, cos, sin, invert, corner);
RadialCut(uv, cos, sin, invert, corner);
return true;
}
/// <summary>
/// Adjust the specified quad, making it be radially filled instead.
/// </summary>
static void RadialCut (Vector2[] xy, float cos, float sin, bool invert, int corner)
{
int i0 = corner;
int i1 = NGUIMath.RepeatIndex(corner + 1, 4);
int i2 = NGUIMath.RepeatIndex(corner + 2, 4);
int i3 = NGUIMath.RepeatIndex(corner + 3, 4);
if ((corner & 1) == 1)
{
if (sin > cos)
{
cos /= sin;
sin = 1f;
if (invert)
{
xy[i1].x = Mathf.Lerp(xy[i0].x, xy[i2].x, cos);
xy[i2].x = xy[i1].x;
}
}
else if (cos > sin)
{
sin /= cos;
cos = 1f;
if (!invert)
{
xy[i2].y = Mathf.Lerp(xy[i0].y, xy[i2].y, sin);
xy[i3].y = xy[i2].y;
}
}
else
{
cos = 1f;
sin = 1f;
}
if (!invert) xy[i3].x = Mathf.Lerp(xy[i0].x, xy[i2].x, cos);
else xy[i1].y = Mathf.Lerp(xy[i0].y, xy[i2].y, sin);
}
else
{
if (cos > sin)
{
sin /= cos;
cos = 1f;
if (!invert)
{
xy[i1].y = Mathf.Lerp(xy[i0].y, xy[i2].y, sin);
xy[i2].y = xy[i1].y;
}
}
else if (sin > cos)
{
cos /= sin;
sin = 1f;
if (invert)
{
xy[i2].x = Mathf.Lerp(xy[i0].x, xy[i2].x, cos);
xy[i3].x = xy[i2].x;
}
}
else
{
cos = 1f;
sin = 1f;
}
if (invert) xy[i3].y = Mathf.Lerp(xy[i0].y, xy[i2].y, sin);
else xy[i1].x = Mathf.Lerp(xy[i0].x, xy[i2].x, cos);
}
}
/// <summary>
/// Helper function that adds the specified values to the buffers.
/// </summary>
static void Fill (BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols,
float v0x, float v1x, float v0y, float v1y, float u0x, float u1x, float u0y, float u1y, Color col)
{
verts.Add(new Vector3(v0x, v0y));
verts.Add(new Vector3(v0x, v1y));
verts.Add(new Vector3(v1x, v1y));
verts.Add(new Vector3(v1x, v0y));
uvs.Add(new Vector2(u0x, u0y));
uvs.Add(new Vector2(u0x, u1y));
uvs.Add(new Vector2(u1x, u1y));
uvs.Add(new Vector2(u1x, u0y));
cols.Add(col);
cols.Add(col);
cols.Add(col);
cols.Add(col);
}
#endregion // Fill functions
}
| |
using System;
using Avalonia.Controls.Metadata;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace Avalonia.Controls
{
public enum Location
{
Left,
Right
}
/// <summary>
/// Represents a spinner control that includes two Buttons.
/// </summary>
[PseudoClasses(":left", ":right")]
public class ButtonSpinner : Spinner
{
/// <summary>
/// Defines the <see cref="AllowSpin"/> property.
/// </summary>
public static readonly StyledProperty<bool> AllowSpinProperty =
AvaloniaProperty.Register<ButtonSpinner, bool>(nameof(AllowSpin), true);
/// <summary>
/// Defines the <see cref="ShowButtonSpinner"/> property.
/// </summary>
public static readonly StyledProperty<bool> ShowButtonSpinnerProperty =
AvaloniaProperty.Register<ButtonSpinner, bool>(nameof(ShowButtonSpinner), true);
/// <summary>
/// Defines the <see cref="ButtonSpinnerLocation"/> property.
/// </summary>
public static readonly StyledProperty<Location> ButtonSpinnerLocationProperty =
AvaloniaProperty.Register<ButtonSpinner, Location>(nameof(ButtonSpinnerLocation), Location.Right);
public ButtonSpinner()
{
UpdatePseudoClasses(ButtonSpinnerLocation);
}
private Button? _decreaseButton;
/// <summary>
/// Gets or sets the DecreaseButton template part.
/// </summary>
private Button? DecreaseButton
{
get { return _decreaseButton; }
set
{
if (_decreaseButton != null)
{
_decreaseButton.Click -= OnButtonClick;
}
_decreaseButton = value;
if (_decreaseButton != null)
{
_decreaseButton.Click += OnButtonClick;
}
}
}
private Button? _increaseButton;
/// <summary>
/// Gets or sets the IncreaseButton template part.
/// </summary>
private Button? IncreaseButton
{
get
{
return _increaseButton;
}
set
{
if (_increaseButton != null)
{
_increaseButton.Click -= OnButtonClick;
}
_increaseButton = value;
if (_increaseButton != null)
{
_increaseButton.Click += OnButtonClick;
}
}
}
/// <summary>
/// Initializes static members of the <see cref="ButtonSpinner"/> class.
/// </summary>
static ButtonSpinner()
{
AllowSpinProperty.Changed.Subscribe(AllowSpinChanged);
}
/// <summary>
/// Gets or sets a value indicating whether the <see cref="ButtonSpinner"/> should allow to spin.
/// </summary>
public bool AllowSpin
{
get { return GetValue(AllowSpinProperty); }
set { SetValue(AllowSpinProperty, value); }
}
/// <summary>
/// Gets or sets a value indicating whether the spin buttons should be shown.
/// </summary>
public bool ShowButtonSpinner
{
get { return GetValue(ShowButtonSpinnerProperty); }
set { SetValue(ShowButtonSpinnerProperty, value); }
}
/// <summary>
/// Gets or sets current location of the <see cref="ButtonSpinner"/>.
/// </summary>
public Location ButtonSpinnerLocation
{
get { return GetValue(ButtonSpinnerLocationProperty); }
set { SetValue(ButtonSpinnerLocationProperty, value); }
}
/// <inheritdoc />
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
IncreaseButton = e.NameScope.Find<Button>("PART_IncreaseButton");
DecreaseButton = e.NameScope.Find<Button>("PART_DecreaseButton");
SetButtonUsage();
}
/// <inheritdoc />
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
base.OnPointerReleased(e);
Point mousePosition;
if (IncreaseButton != null && IncreaseButton.IsEnabled == false)
{
mousePosition = e.GetPosition(IncreaseButton);
if (mousePosition.X > 0 && mousePosition.X < IncreaseButton.Width &&
mousePosition.Y > 0 && mousePosition.Y < IncreaseButton.Height)
{
e.Handled = true;
}
}
if (DecreaseButton != null && DecreaseButton.IsEnabled == false)
{
mousePosition = e.GetPosition(DecreaseButton);
if (mousePosition.X > 0 && mousePosition.X < DecreaseButton.Width &&
mousePosition.Y > 0 && mousePosition.Y < DecreaseButton.Height)
{
e.Handled = true;
}
}
}
/// <inheritdoc />
protected override void OnKeyDown(KeyEventArgs e)
{
switch (e.Key)
{
case Key.Up:
{
if (AllowSpin)
{
OnSpin(new SpinEventArgs(SpinEvent, SpinDirection.Increase));
e.Handled = true;
}
break;
}
case Key.Down:
{
if (AllowSpin)
{
OnSpin(new SpinEventArgs(SpinEvent, SpinDirection.Decrease));
e.Handled = true;
}
break;
}
case Key.Enter:
{
//Do not Spin on enter Key when spinners have focus
if (((IncreaseButton != null) && (IncreaseButton.IsFocused))
|| ((DecreaseButton != null) && DecreaseButton.IsFocused))
{
e.Handled = true;
}
break;
}
}
}
/// <inheritdoc />
protected override void OnPointerWheelChanged(PointerWheelEventArgs e)
{
base.OnPointerWheelChanged(e);
if (AllowSpin && IsKeyboardFocusWithin)
{
if (e.Delta.Y != 0)
{
var spinnerEventArgs = new SpinEventArgs(SpinEvent, (e.Delta.Y < 0) ? SpinDirection.Decrease : SpinDirection.Increase, true);
OnSpin(spinnerEventArgs);
e.Handled = true;
}
}
}
protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change)
{
base.OnPropertyChanged(change);
if (change.Property == ButtonSpinnerLocationProperty)
{
UpdatePseudoClasses(change.NewValue.GetValueOrDefault<Location>());
}
}
protected override void OnValidSpinDirectionChanged(ValidSpinDirections oldValue, ValidSpinDirections newValue)
{
SetButtonUsage();
}
/// <summary>
/// Called when the <see cref="AllowSpin"/> property value changed.
/// </summary>
/// <param name="oldValue">The old value.</param>
/// <param name="newValue">The new value.</param>
protected virtual void OnAllowSpinChanged(bool oldValue, bool newValue)
{
SetButtonUsage();
}
/// <summary>
/// Called when the <see cref="AllowSpin"/> property value changed.
/// </summary>
/// <param name="e">The event args.</param>
private static void AllowSpinChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is ButtonSpinner spinner)
{
var oldValue = (bool)e.OldValue!;
var newValue = (bool)e.NewValue!;
spinner.OnAllowSpinChanged(oldValue, newValue);
}
}
/// <summary>
/// Disables or enables the buttons based on the valid spin direction.
/// </summary>
private void SetButtonUsage()
{
if (IncreaseButton != null)
{
IncreaseButton.IsEnabled = AllowSpin && ((ValidSpinDirection & ValidSpinDirections.Increase) == ValidSpinDirections.Increase);
}
if (DecreaseButton != null)
{
DecreaseButton.IsEnabled = AllowSpin && ((ValidSpinDirection & ValidSpinDirections.Decrease) == ValidSpinDirections.Decrease);
}
}
/// <summary>
/// Called when user clicks one of the spin buttons.
/// </summary>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event args.</param>
private void OnButtonClick(object? sender, RoutedEventArgs e)
{
if (AllowSpin)
{
var direction = sender == IncreaseButton ? SpinDirection.Increase : SpinDirection.Decrease;
OnSpin(new SpinEventArgs(SpinEvent, direction));
}
}
private void UpdatePseudoClasses(Location location)
{
PseudoClasses.Set(":left", location == Location.Left);
PseudoClasses.Set(":right", location == Location.Right);
}
}
}
| |
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Tencent is pleased to support the open source community by making behaviac available.
//
// Copyright (C) 2015-2017 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at http://opensource.org/licenses/BSD-3-Clause
//
// 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;
namespace behaviac
{
public enum ERefType
{
/**by default, a class is a ref type while a struct is a value type
*
* a ref type in designer will be displayed as a 'pointer, which is not expanded so that its members can't be configured individually
**/
ERT_Undefined,
//forced to be a value type
ERT_ValueType
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum, AllowMultiple = false, Inherited = false)]
public class TypeMetaInfoAttribute : Attribute
{
public TypeMetaInfoAttribute(string displayName, string description)
{
this.displayName_ = displayName;
this.desc_ = description;
}
public TypeMetaInfoAttribute(string displayName, string description, ERefType refType)
{
this.displayName_ = displayName;
this.desc_ = description;
this.refType_ = refType;
}
public TypeMetaInfoAttribute()
{
}
public TypeMetaInfoAttribute(ERefType refType)
{
this.refType_ = refType;
}
private string displayName_;
private string desc_;
public string DisplayName
{
get
{
return this.displayName_;
}
}
public string Description
{
get
{
return this.desc_;
}
}
//0, by default, class is reftype while struct is value type
//1, even it is a class, it is still as a value type in designer
private ERefType refType_ = ERefType.ERT_Undefined;
public ERefType RefType
{
get
{
return refType_;
}
}
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum, AllowMultiple = false, Inherited = false)]
public class GeneratedTypeMetaInfoAttribute : Attribute
{
public GeneratedTypeMetaInfoAttribute()
{
}
}
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class MemberMetaInfoAttribute : TypeMetaInfoAttribute
{
public MemberMetaInfoAttribute(string displayName, string description, bool bReadOnly) :
this(displayName, description)
{
m_bIsReadonly = bReadOnly;
}
public MemberMetaInfoAttribute(string displayName, string description)
: this(displayName, description, 1.0f)
{
}
public MemberMetaInfoAttribute(string displayName, string description, float range)
: base(displayName, description)
{
m_range = range;
}
public MemberMetaInfoAttribute()
{
}
public MemberMetaInfoAttribute(bool bReadonly)
: this()
{
this.m_bIsReadonly = bReadonly;
}
private bool m_bIsReadonly = false;
public bool IsReadonly
{
get
{
return this.m_bIsReadonly;
}
}
private static string getEnumName(object obj)
{
if (obj == null)
{
return string.Empty;
}
Type type = obj.GetType();
if (!type.IsEnum)
{
return string.Empty;
}
string enumName = Enum.GetName(type, obj);
if (string.IsNullOrEmpty(enumName))
{
return string.Empty;
}
return enumName;
}
public static string GetEnumDisplayName(object obj)
{
if (obj == null)
{
return string.Empty;
}
string enumName = getEnumName(obj);
System.Reflection.FieldInfo fi = obj.GetType().GetField(obj.ToString());
Attribute[] attributes = (Attribute[])fi.GetCustomAttributes(typeof(MemberMetaInfoAttribute), false);
if (attributes.Length > 0)
{
enumName = ((MemberMetaInfoAttribute)attributes[0]).DisplayName;
}
return enumName;
}
public static string GetEnumDescription(object obj)
{
if (obj == null)
{
return string.Empty;
}
string enumName = getEnumName(obj);
System.Reflection.FieldInfo fi = obj.GetType().GetField(obj.ToString());
Attribute[] attributes = (Attribute[])fi.GetCustomAttributes(typeof(MemberMetaInfoAttribute), false);
if (attributes.Length > 0)
{
enumName = ((MemberMetaInfoAttribute)attributes[0]).Description;
}
return enumName;
}
private float m_range = 1.0f;
public float Range
{
get
{
return this.m_range;
}
}
}
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public class MethodMetaInfoAttribute : TypeMetaInfoAttribute
{
public MethodMetaInfoAttribute(string displayName, string description)
: base(displayName, description)
{
}
public MethodMetaInfoAttribute()
{
}
}
[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
public class ParamMetaInfoAttribute : TypeMetaInfoAttribute
{
public ParamMetaInfoAttribute()
{
}
public ParamMetaInfoAttribute(string displayName, string description, string defaultValue)
: base(displayName, description)
{
defaultValue_ = defaultValue;
rangeMin_ = float.MinValue;
rangeMax_ = float.MaxValue;
}
public ParamMetaInfoAttribute(string displayName, string description, string defaultValue, float rangeMin, float rangeMax)
: base(displayName, description)
{
defaultValue_ = defaultValue;
rangeMin_ = rangeMin;
rangeMax_ = rangeMax;
}
private string defaultValue_;
public string DefaultValue
{
get
{
return defaultValue_;
}
}
private float rangeMin_ = float.MinValue;
public float RangeMin
{
get
{
return rangeMin_;
}
}
private float rangeMax_ = float.MaxValue;
public float RangeMax
{
get
{
return rangeMax_;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Linq;
using Bloom.Api;
using Bloom.Book;
using Bloom.ImageProcessing;
using Bloom.Properties;
using Bloom.Publish.Android.file;
using SIL.Windows.Forms.Miscellaneous;
#if !__MonoCS__
using Bloom.Publish.Android.usb;
#endif
using Bloom.Publish.Android.wifi;
using Bloom.web;
using DesktopAnalytics;
using SIL.IO;
namespace Bloom.Publish.Android
{
/// <summary>
/// Handles api request dealing with the publishing of books to an Android device
/// </summary>
public class PublishToAndroidApi
{
private const string kApiUrlPart = "publish/android/";
private const string kWebsocketStateId = "publish/android/state";
private readonly WiFiPublisher _wifiPublisher;
#if !__MonoCS__
private readonly UsbPublisher _usbPublisher;
#endif
private readonly BloomWebSocketServer _webSocketServer;
private readonly BookServer _bookServer;
private readonly WebSocketProgress _progress;
private Color _thumbnailBackgroundColor = Color.Transparent; // can't be actual book cover color <--- why not?
private Book.Book _coverColorSourceBook;
private RuntimeImageProcessor _imageProcessor;
public PublishToAndroidApi(BloomWebSocketServer bloomWebSocketServer, BookServer bookServer, RuntimeImageProcessor imageProcessor)
{
_webSocketServer = bloomWebSocketServer;
_bookServer = bookServer;
_imageProcessor = imageProcessor;
_progress = new WebSocketProgress(_webSocketServer);
_wifiPublisher = new WiFiPublisher(_progress, _bookServer);
#if !__MonoCS__
_usbPublisher = new UsbPublisher(_progress, _bookServer)
{
Stopped = () => SetState("stopped")
};
#endif
}
private static string ToCssColorString(System.Drawing.Color c)
{
return "#" + c.R.ToString("X2") + c.G.ToString("X2") + c.B.ToString("X2");
}
private static bool TryCssColorFromString(string input, out Color result)
{
result = Color.White; // some default in case of error.
if (!input.StartsWith("#") || input.Length != 7)
return false; // arbitrary failure
try
{
result = ColorTranslator.FromHtml(input);
}
catch (Exception e)
{
return false;
}
return true;
}
public void RegisterWithServer(EnhancedImageServer server)
{
// This is just for storing the user preference of method
// If we had a couple of these, we could just have a generic preferences api
// that browser-side code could use.
server.RegisterEndpointHandler(kApiUrlPart + "method", request =>
{
if(request.HttpMethod == HttpMethods.Get)
{
var method = Settings.Default.PublishAndroidMethod;
if(!new string[]{"wifi", "usb", "file"}.Contains(method))
{
method = "wifi";
}
request.ReplyWithText(method);
}
else // post
{
Settings.Default.PublishAndroidMethod = request.RequiredPostString();
#if __MonoCS__
if (Settings.Default.PublishAndroidMethod == "usb")
{
_progress.MessageWithoutLocalizing("Sorry, this method is not available on Linux yet.");
}
#endif
request.PostSucceeded();
}
}, true);
server.RegisterEndpointHandler(kApiUrlPart + "backColor", request =>
{
if (request.HttpMethod == HttpMethods.Get)
{
if (request.CurrentBook != _coverColorSourceBook)
{
_coverColorSourceBook = request.CurrentBook;
TryCssColorFromString(request.CurrentBook?.GetCoverColor()??"", out _thumbnailBackgroundColor);
}
request.ReplyWithText(ToCssColorString(_thumbnailBackgroundColor));
}
else // post
{
// ignore invalid colors (very common while user is editing hex)
Color newColor;
var newColorAsString = request.RequiredPostString();
if (TryCssColorFromString(newColorAsString, out newColor))
{
_thumbnailBackgroundColor = newColor;
request.CurrentBook.SetCoverColor(newColorAsString);
}
request.PostSucceeded();
}
}, true);
server.RegisterEndpointHandler(kApiUrlPart + "photoStoryMode", request =>
{
if (request.HttpMethod == HttpMethods.Get)
{
// this is temporary, just trying to get support for full screen pan & zoom out quickly in 4.2
request.ReplyWithText(request.CurrentBook.UsePhotoStoryModeInBloomReader.ToString()
.ToLowerInvariant()); // "false", not "False"
}
else // post
{
request.CurrentBook.UsePhotoStoryModeInBloomReader = bool.Parse(request.RequiredPostString());
request.PostSucceeded();
}
}, true);
server.RegisterEndpointHandler(kApiUrlPart + "thumbnail", request =>
{
var coverImage = request.CurrentBook.GetCoverImagePath();
if (coverImage == null)
request.Failed("no cover image");
else
{
// We don't care as much about making it resized as making its background transparent.
using(var thumbnail = TempFile.CreateAndGetPathButDontMakeTheFile())
{
if(_thumbnailBackgroundColor == Color.Transparent)
{
TryCssColorFromString(request.CurrentBook?.GetCoverColor(), out _thumbnailBackgroundColor);
}
RuntimeImageProcessor.GenerateEBookThumbnail(coverImage, thumbnail.Path, 256, 256, _thumbnailBackgroundColor);
request.ReplyWithImage( thumbnail.Path);
}
}
}, true);
server.RegisterEndpointHandler(kApiUrlPart + "usb/start", request =>
{
#if !__MonoCS__
SetState("UsbStarted");
_usbPublisher.Connect(request.CurrentBook, _thumbnailBackgroundColor);
#endif
request.PostSucceeded();
}, true);
server.RegisterEndpointHandler(kApiUrlPart + "usb/stop", request =>
{
#if !__MonoCS__
_usbPublisher.Stop();
SetState("stopped");
#endif
request.PostSucceeded();
}, true);
server.RegisterEndpointHandler(kApiUrlPart + "wifi/start", request =>
{
_wifiPublisher.Start(request.CurrentBook, request.CurrentCollectionSettings, _thumbnailBackgroundColor);
SetState("ServingOnWifi");
request.PostSucceeded();
}, true);
server.RegisterEndpointHandler(kApiUrlPart + "wifi/stop", request =>
{
_wifiPublisher.Stop();
SetState("stopped");
request.PostSucceeded();
}, true);
server.RegisterEndpointHandler(kApiUrlPart + "file/save", request =>
{
FilePublisher.Save(request.CurrentBook, _bookServer, _thumbnailBackgroundColor, _progress);
SetState("stopped");
request.PostSucceeded();
}, true);
server.RegisterEndpointHandler(kApiUrlPart + "cleanup", request =>
{
Stop();
request.PostSucceeded();
}, true);
server.RegisterEndpointHandler(kApiUrlPart + "textToClipboard", request =>
{
PortableClipboard.SetText(request.RequiredPostString());
request.PostSucceeded();
}, true);
}
public void Stop()
{
#if !__MonoCS__
_usbPublisher.Stop();
#endif
_wifiPublisher.Stop();
SetState("stopped");
}
private void SetState(string state)
{
_webSocketServer.Send(kWebsocketStateId, state);
}
public static void ReportAnalytics(string mode, Book.Book book)
{
Analytics.Track("Publish Android", new Dictionary<string, string>() {{"mode", mode}, {"BookId", book.ID}, { "Country", book.CollectionSettings.Country}, {"Language", book.CollectionSettings.Language1Iso639Code}});
}
/// <summary>
/// This is the core of sending a book to a device. We need a book and a bookServer in order to come up
/// with the .bloomd file.
/// We are either simply saving the .bloomd to destFileName, or else we will make a temporary .bloomd file and
/// actually send it using sendAction.
/// We report important progress on the progress control. This includes reporting that we are starting
/// the actual transmission using startingMessageAction, which is passed the safe file name (for checking pre-existence
/// in UsbPublisher) and the book title (typically inserted into the message).
/// If a confirmAction is passed (currently only by UsbPublisher), we use it check for a successful transfer
/// before reporting completion (except for file save, where the current message is inappropriate).
/// This is an awkward case where the three ways of publishing are similar enough that
/// it's annoying and dangerous to have three entirely separate methods but somewhat awkward to combine them.
/// Possibly we could eventually make them more similar, e.g., it would simplify things if they all said
/// "Sending X to Y", though I'm not sure that would be good i18n if Y is sometimes a device name
/// and sometimes a path.
/// </summary>
/// <param name="book"></param>
/// <param name="destFileName"></param>
/// <param name="sendAction"></param>
/// <param name="progress"></param>
/// <param name="bookServer"></param>
/// <param name="startingMessageFunction"></param>
public static void SendBook(Book.Book book, BookServer bookServer, string destFileName, Action<string, string> sendAction, WebSocketProgress progress, Func<string, string, string> startingMessageFunction,
Func<string, bool> confirmFunction, Color backColor)
{
var bookTitle = book.Title;
progress.MessageUsingTitle("PackagingBook", "Packaging \"{0}\" for use with Bloom Reader...", bookTitle);
// compress audio if needed, with progress message
if (AudioProcessor.IsAnyCompressedAudioMissing(book.FolderPath, book.RawDom))
{
progress.Message("CompressingAudio", "Compressing audio files");
AudioProcessor.TryCompressingAudioAsNeeded(book.FolderPath, book.RawDom);
}
var publishedFileName = BookStorage.SanitizeNameForFileSystem(bookTitle) + BookCompressor.ExtensionForDeviceBloomBook;
if (startingMessageFunction != null)
progress.MessageWithoutLocalizing(startingMessageFunction(publishedFileName, bookTitle));
if (destFileName == null)
{
// wifi or usb...make the .bloomd in a temp folder.
using (var bloomdTempFile = TempFile.WithFilenameInTempFolder(publishedFileName))
{
BookCompressor.CompressBookForDevice(bloomdTempFile.Path, book, bookServer, backColor, progress);
sendAction(publishedFileName, bloomdTempFile.Path);
if (confirmFunction != null && !confirmFunction(publishedFileName))
throw new ApplicationException("Book does not exist after write operation.");
progress.MessageUsingTitle("BookSent", "You can now read \"{0}\" in Bloom Reader!", bookTitle);
}
} else
{
// save file...user has supplied name, there is no further action.
Debug.Assert(sendAction == null, "further actions are not supported when passing a path name");
BookCompressor.CompressBookForDevice(destFileName, book, bookServer, backColor, progress);
}
}
}
}
| |
/*
* 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.Data;
using OpenSim.Framework;
using OpenSim.Services.Interfaces;
namespace OpenSim.Services.InventoryService
{
/// <summary>
/// The Inventory service reference implementation
/// </summary>
public class InventoryService : InventoryServiceBase, IInventoryService
{
private static readonly ILog m_log
= LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public InventoryService(IConfigSource config) : base(config)
{
m_log.Debug("[INVENTORY SERVICE]: Initialized.");
}
#region IInventoryServices methods
public string Host
{
get { return "default"; }
}
public List<InventoryFolderBase> GetInventorySkeleton(UUID userId)
{
m_log.DebugFormat("[INVENTORY SERVICE]: Getting inventory skeleton for {0}", userId);
InventoryFolderBase rootFolder = GetRootFolder(userId);
// Agent has no inventory structure yet.
if (null == rootFolder)
{
m_log.DebugFormat("[INVENTORY SERVICE]: No root folder");
return null;
}
List<InventoryFolderBase> userFolders = new List<InventoryFolderBase>();
userFolders.Add(rootFolder);
IList<InventoryFolderBase> folders = m_Database.getFolderHierarchy(rootFolder.ID);
userFolders.AddRange(folders);
// m_log.DebugFormat("[INVENTORY SERVICE]: Got folder {0} {1}", folder.name, folder.folderID);
return userFolders;
}
public virtual bool HasInventoryForUser(UUID userID)
{
return false;
}
// See IInventoryServices
public virtual InventoryFolderBase GetRootFolder(UUID userID)
{
//m_log.DebugFormat("[INVENTORY SERVICE]: Getting root folder for {0}", userID);
// Retrieve the first root folder we get from the DB.
InventoryFolderBase rootFolder = m_Database.getUserRootFolder(userID);
if (rootFolder != null)
return rootFolder;
// Return nothing if the plugin was unable to supply a root folder
return null;
}
// See IInventoryServices
public bool CreateUserInventory(UUID user)
{
InventoryFolderBase existingRootFolder;
try
{
existingRootFolder = GetRootFolder(user);
}
catch /*(Exception e)*/
{
// Munch the exception, it has already been reported
//
return false;
}
if (null != existingRootFolder)
{
m_log.WarnFormat(
"[INVENTORY SERVICE]: Did not create a new inventory for user {0} since they already have "
+ "a root inventory folder with id {1}",
user, existingRootFolder.ID);
}
else
{
UsersInventory inven = new UsersInventory();
inven.CreateNewInventorySet(user);
AddNewInventorySet(inven);
return true;
}
return false;
}
// See IInventoryServices
/// <summary>
/// Return a user's entire inventory synchronously
/// </summary>
/// <param name="rawUserID"></param>
/// <returns>The user's inventory. If an inventory cannot be found then an empty collection is returned.</returns>
public InventoryCollection GetUserInventory(UUID userID)
{
m_log.InfoFormat("[INVENTORY SERVICE]: Processing request for inventory of {0}", userID);
// Uncomment me to simulate a slow responding inventory server
//Thread.Sleep(16000);
InventoryCollection invCollection = new InventoryCollection();
List<InventoryFolderBase> allFolders = GetInventorySkeleton(userID);
if (null == allFolders)
{
m_log.WarnFormat("[INVENTORY SERVICE]: No inventory found for user {0}", userID);
return invCollection;
}
List<InventoryItemBase> allItems = new List<InventoryItemBase>();
foreach (InventoryFolderBase folder in allFolders)
{
List<InventoryItemBase> items = GetFolderItems(userID, folder.ID);
if (items != null)
{
allItems.InsertRange(0, items);
}
}
invCollection.UserID = userID;
invCollection.Folders = allFolders;
invCollection.Items = allItems;
// foreach (InventoryFolderBase folder in invCollection.Folders)
// {
// m_log.DebugFormat("[GRID INVENTORY SERVICE]: Sending back folder {0} {1}", folder.Name, folder.ID);
// }
//
// foreach (InventoryItemBase item in invCollection.Items)
// {
// m_log.DebugFormat("[GRID INVENTORY SERVICE]: Sending back item {0} {1}, folder {2}", item.Name, item.ID, item.Folder);
// }
m_log.InfoFormat(
"[INVENTORY SERVICE]: Sending back inventory response to user {0} containing {1} folders and {2} items",
invCollection.UserID, invCollection.Folders.Count, invCollection.Items.Count);
return invCollection;
}
/// <summary>
/// Asynchronous inventory fetch.
/// </summary>
/// <param name="userID"></param>
/// <param name="callback"></param>
public void GetUserInventory(UUID userID, InventoryReceiptCallback callback)
{
m_log.InfoFormat("[INVENTORY SERVICE]: Requesting inventory for user {0}", userID);
List<InventoryFolderImpl> folders = new List<InventoryFolderImpl>();
List<InventoryItemBase> items = new List<InventoryItemBase>();
List<InventoryFolderBase> skeletonFolders = GetInventorySkeleton(userID);
if (skeletonFolders != null)
{
InventoryFolderImpl rootFolder = null;
// Need to retrieve the root folder on the first pass
foreach (InventoryFolderBase folder in skeletonFolders)
{
if (folder.ParentID == UUID.Zero)
{
rootFolder = new InventoryFolderImpl(folder);
folders.Add(rootFolder);
items.AddRange(GetFolderItems(userID, rootFolder.ID));
break; // Only 1 root folder per user
}
}
if (rootFolder != null)
{
foreach (InventoryFolderBase folder in skeletonFolders)
{
if (folder.ID != rootFolder.ID)
{
folders.Add(new InventoryFolderImpl(folder));
items.AddRange(GetFolderItems(userID, folder.ID));
}
}
}
m_log.InfoFormat(
"[INVENTORY SERVICE]: Received inventory response for user {0} containing {1} folders and {2} items",
userID, folders.Count, items.Count);
}
else
{
m_log.WarnFormat("[INVENTORY SERVICE]: User {0} inventory not available", userID);
}
Util.FireAndForget(delegate { callback(folders, items); });
}
public InventoryCollection GetFolderContent(UUID userID, UUID folderID)
{
// Uncomment me to simulate a slow responding inventory server
//Thread.Sleep(16000);
InventoryCollection invCollection = new InventoryCollection();
List<InventoryItemBase> items = GetFolderItems(userID, folderID);
List<InventoryFolderBase> folders = RequestSubFolders(folderID);
invCollection.UserID = userID;
invCollection.Folders = folders;
invCollection.Items = items;
m_log.DebugFormat("[INVENTORY SERVICE]: Found {0} items and {1} folders in folder {2}", items.Count, folders.Count, folderID);
return invCollection;
}
public InventoryFolderBase GetFolderForType(UUID userID, AssetType type)
{
// m_log.DebugFormat("[INVENTORY SERVICE]: Looking for folder type {0} for user {1}", type, userID);
InventoryFolderBase root = m_Database.getUserRootFolder(userID);
if (root != null)
{
List<InventoryFolderBase> folders = RequestSubFolders(root.ID);
foreach (InventoryFolderBase folder in folders)
{
if (folder.Type == (short)type)
{
// m_log.DebugFormat(
// "[INVENTORY SERVICE]: Found folder {0} type {1}", folder.Name, (AssetType)folder.Type);
return folder;
}
}
}
// we didn't find any folder of that type. Return the root folder
// hopefully the root folder is not null. If it is, too bad
return root;
}
public Dictionary<AssetType, InventoryFolderBase> GetSystemFolders(UUID userID)
{
InventoryFolderBase root = GetRootFolder(userID);
if (root != null)
{
InventoryCollection content = GetFolderContent(userID, root.ID);
if (content != null)
{
Dictionary<AssetType, InventoryFolderBase> folders = new Dictionary<AssetType, InventoryFolderBase>();
foreach (InventoryFolderBase folder in content.Folders)
{
if ((folder.Type != (short)AssetType.Folder) && (folder.Type != (short)AssetType.Unknown))
folders[(AssetType)folder.Type] = folder;
}
m_log.DebugFormat("[INVENTORY SERVICE]: Got {0} system folders for {1}", folders.Count, userID);
return folders;
}
}
m_log.WarnFormat("[INVENTORY SERVICE]: System folders for {0} not found", userID);
return new Dictionary<AssetType, InventoryFolderBase>();
}
public List<InventoryItemBase> GetActiveGestures(UUID userId)
{
List<InventoryItemBase> activeGestures = new List<InventoryItemBase>();
activeGestures.AddRange(m_Database.fetchActiveGestures(userId));
return activeGestures;
}
#endregion
#region Methods used by GridInventoryService
public List<InventoryFolderBase> RequestSubFolders(UUID parentFolderID)
{
List<InventoryFolderBase> inventoryList = new List<InventoryFolderBase>();
inventoryList.AddRange(m_Database.getInventoryFolders(parentFolderID));
return inventoryList;
}
public List<InventoryItemBase> GetFolderItems(UUID userID, UUID folderID)
{
List<InventoryItemBase> itemsList = new List<InventoryItemBase>();
itemsList.AddRange(m_Database.getInventoryInFolder(folderID));
return itemsList;
}
#endregion
// See IInventoryServices
public virtual bool AddFolder(InventoryFolderBase folder)
{
m_log.DebugFormat(
"[INVENTORY SERVICE]: Adding folder {0} {1} to folder {2}", folder.Name, folder.ID, folder.ParentID);
m_Database.addInventoryFolder(folder);
// FIXME: Should return false on failure
return true;
}
// See IInventoryServices
public virtual bool UpdateFolder(InventoryFolderBase folder)
{
m_log.DebugFormat(
"[INVENTORY SERVICE]: Updating folder {0} {1} to folder {2}", folder.Name, folder.ID, folder.ParentID);
m_Database.updateInventoryFolder(folder);
// FIXME: Should return false on failure
return true;
}
// See IInventoryServices
public virtual bool MoveFolder(InventoryFolderBase folder)
{
m_log.DebugFormat(
"[INVENTORY SERVICE]: Moving folder {0} {1} to folder {2}", folder.Name, folder.ID, folder.ParentID);
m_Database.moveInventoryFolder(folder);
// FIXME: Should return false on failure
return true;
}
// See IInventoryServices
public virtual bool AddItem(InventoryItemBase item)
{
m_log.DebugFormat(
"[INVENTORY SERVICE]: Adding item {0} {1} to folder {2}", item.Name, item.ID, item.Folder);
m_Database.addInventoryItem(item);
// FIXME: Should return false on failure
return true;
}
// See IInventoryServices
public virtual bool UpdateItem(InventoryItemBase item)
{
m_log.InfoFormat(
"[INVENTORY SERVICE]: Updating item {0} {1} in folder {2}", item.Name, item.ID, item.Folder);
m_Database.updateInventoryItem(item);
// FIXME: Should return false on failure
return true;
}
public virtual bool MoveItems(UUID ownerID, List<InventoryItemBase> items)
{
m_log.InfoFormat(
"[INVENTORY SERVICE]: Moving {0} items from user {1}", items.Count, ownerID);
InventoryItemBase itm = null;
foreach (InventoryItemBase item in items)
{
itm = GetInventoryItem(item.ID);
itm.Folder = item.Folder;
if ((item.Name != null) && !item.Name.Equals(string.Empty))
itm.Name = item.Name;
m_Database.updateInventoryItem(itm);
}
return true;
}
// See IInventoryServices
public virtual bool DeleteItems(UUID owner, List<UUID> itemIDs)
{
m_log.InfoFormat(
"[INVENTORY SERVICE]: Deleting {0} items from user {1}", itemIDs.Count, owner);
// uhh.....
foreach (UUID uuid in itemIDs)
m_Database.deleteInventoryItem(uuid);
// FIXME: Should return false on failure
return true;
}
public virtual InventoryItemBase GetItem(InventoryItemBase item)
{
InventoryItemBase result = m_Database.getInventoryItem(item.ID);
if (result != null)
return result;
m_log.DebugFormat("[INVENTORY SERVICE]: GetItem failed to find item {0}", item.ID);
return null;
}
public virtual InventoryFolderBase GetFolder(InventoryFolderBase folder)
{
InventoryFolderBase result = m_Database.getInventoryFolder(folder.ID);
if (result != null)
return result;
m_log.DebugFormat("[INVENTORY SERVICE]: GetFolder failed to find folder {0}", folder.ID);
return null;
}
public virtual bool DeleteFolders(UUID ownerID, List<UUID> folderIDs)
{
m_log.InfoFormat("[INVENTORY SERVICE]: Deleting {0} folders from user {1}", folderIDs.Count, ownerID);
foreach (UUID id in folderIDs)
{
InventoryFolderBase folder = new InventoryFolderBase(id, ownerID);
PurgeFolder(folder);
m_Database.deleteInventoryFolder(id);
}
return true;
}
/// <summary>
/// Purge a folder of all items items and subfolders.
///
/// FIXME: Really nasty in a sense, because we have to query the database to get information we may
/// already know... Needs heavy refactoring.
/// </summary>
/// <param name="folder"></param>
public virtual bool PurgeFolder(InventoryFolderBase folder)
{
m_log.DebugFormat(
"[INVENTORY SERVICE]: Purging folder {0} {1} of its contents", folder.Name, folder.ID);
List<InventoryFolderBase> subFolders = RequestSubFolders(folder.ID);
foreach (InventoryFolderBase subFolder in subFolders)
{
// m_log.DebugFormat("[INVENTORY SERVICE]: Deleting folder {0} {1}", subFolder.Name, subFolder.ID);
m_Database.deleteInventoryFolder(subFolder.ID);
}
List<InventoryItemBase> items = GetFolderItems(folder.Owner, folder.ID);
List<UUID> uuids = new List<UUID>();
foreach (InventoryItemBase item in items)
{
uuids.Add(item.ID);
}
DeleteItems(folder.Owner, uuids);
// FIXME: Should return false on failure
return true;
}
private void AddNewInventorySet(UsersInventory inventory)
{
foreach (InventoryFolderBase folder in inventory.Folders.Values)
{
AddFolder(folder);
}
}
public InventoryItemBase GetInventoryItem(UUID itemID)
{
InventoryItemBase item = m_Database.getInventoryItem(itemID);
if (item != null)
return item;
return null;
}
public int GetAssetPermissions(UUID userID, UUID assetID)
{
InventoryFolderBase parent = GetRootFolder(userID);
return FindAssetPerms(parent, assetID);
}
private int FindAssetPerms(InventoryFolderBase folder, UUID assetID)
{
InventoryCollection contents = GetFolderContent(folder.Owner, folder.ID);
int perms = 0;
foreach (InventoryItemBase item in contents.Items)
{
if (item.AssetID == assetID)
perms = (int)item.CurrentPermissions | perms;
}
foreach (InventoryFolderBase subfolder in contents.Folders)
perms = perms | FindAssetPerms(subfolder, assetID);
return perms;
}
/// <summary>
/// Used to create a new user inventory.
/// </summary>
private class UsersInventory
{
public Dictionary<UUID, InventoryFolderBase> Folders = new Dictionary<UUID, InventoryFolderBase>();
public Dictionary<UUID, InventoryItemBase> Items = new Dictionary<UUID, InventoryItemBase>();
public virtual void CreateNewInventorySet(UUID user)
{
InventoryFolderBase folder = new InventoryFolderBase();
folder.ParentID = UUID.Zero;
folder.Owner = user;
folder.ID = UUID.Random();
folder.Name = "My Inventory";
folder.Type = (short)AssetType.Folder;
folder.Version = 1;
Folders.Add(folder.ID, folder);
UUID rootFolder = folder.ID;
folder = new InventoryFolderBase();
folder.ParentID = rootFolder;
folder.Owner = user;
folder.ID = UUID.Random();
folder.Name = "Animations";
folder.Type = (short)AssetType.Animation;
folder.Version = 1;
Folders.Add(folder.ID, folder);
folder = new InventoryFolderBase();
folder.ParentID = rootFolder;
folder.Owner = user;
folder.ID = UUID.Random();
folder.Name = "Body Parts";
folder.Type = (short)AssetType.Bodypart;
folder.Version = 1;
Folders.Add(folder.ID, folder);
folder = new InventoryFolderBase();
folder.ParentID = rootFolder;
folder.Owner = user;
folder.ID = UUID.Random();
folder.Name = "Calling Cards";
folder.Type = (short)AssetType.CallingCard;
folder.Version = 1;
Folders.Add(folder.ID, folder);
folder = new InventoryFolderBase();
folder.ParentID = rootFolder;
folder.Owner = user;
folder.ID = UUID.Random();
folder.Name = "Clothing";
folder.Type = (short)AssetType.Clothing;
folder.Version = 1;
Folders.Add(folder.ID, folder);
folder = new InventoryFolderBase();
folder.ParentID = rootFolder;
folder.Owner = user;
folder.ID = UUID.Random();
folder.Name = "Gestures";
folder.Type = (short)AssetType.Gesture;
folder.Version = 1;
Folders.Add(folder.ID, folder);
folder = new InventoryFolderBase();
folder.ParentID = rootFolder;
folder.Owner = user;
folder.ID = UUID.Random();
folder.Name = "Landmarks";
folder.Type = (short)AssetType.Landmark;
folder.Version = 1;
Folders.Add(folder.ID, folder);
folder = new InventoryFolderBase();
folder.ParentID = rootFolder;
folder.Owner = user;
folder.ID = UUID.Random();
folder.Name = "Lost And Found";
folder.Type = (short)AssetType.LostAndFoundFolder;
folder.Version = 1;
Folders.Add(folder.ID, folder);
folder = new InventoryFolderBase();
folder.ParentID = rootFolder;
folder.Owner = user;
folder.ID = UUID.Random();
folder.Name = "Notecards";
folder.Type = (short)AssetType.Notecard;
folder.Version = 1;
Folders.Add(folder.ID, folder);
folder = new InventoryFolderBase();
folder.ParentID = rootFolder;
folder.Owner = user;
folder.ID = UUID.Random();
folder.Name = "Objects";
folder.Type = (short)AssetType.Object;
folder.Version = 1;
Folders.Add(folder.ID, folder);
folder = new InventoryFolderBase();
folder.ParentID = rootFolder;
folder.Owner = user;
folder.ID = UUID.Random();
folder.Name = "Photo Album";
folder.Type = (short)AssetType.SnapshotFolder;
folder.Version = 1;
Folders.Add(folder.ID, folder);
folder = new InventoryFolderBase();
folder.ParentID = rootFolder;
folder.Owner = user;
folder.ID = UUID.Random();
folder.Name = "Scripts";
folder.Type = (short)AssetType.LSLText;
folder.Version = 1;
Folders.Add(folder.ID, folder);
folder = new InventoryFolderBase();
folder.ParentID = rootFolder;
folder.Owner = user;
folder.ID = UUID.Random();
folder.Name = "Sounds";
folder.Type = (short)AssetType.Sound;
folder.Version = 1;
Folders.Add(folder.ID, folder);
folder = new InventoryFolderBase();
folder.ParentID = rootFolder;
folder.Owner = user;
folder.ID = UUID.Random();
folder.Name = "Textures";
folder.Type = (short)AssetType.Texture;
folder.Version = 1;
Folders.Add(folder.ID, folder);
folder = new InventoryFolderBase();
folder.ParentID = rootFolder;
folder.Owner = user;
folder.ID = UUID.Random();
folder.Name = "Trash";
folder.Type = (short)AssetType.TrashFolder;
folder.Version = 1;
Folders.Add(folder.ID, folder);
}
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using NodaTime;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Securities;
using QuantConnect.Securities.Option;
namespace QuantConnect.Lean.Engine.DataFeeds
{
/// <summary>
/// Represents a grouping of data emitted at a certain time.
/// </summary>
public class TimeSlice
{
/// <summary>
/// Gets the count of data points in this <see cref="TimeSlice"/>
/// </summary>
public int DataPointCount { get; private set; }
/// <summary>
/// Gets the time this data was emitted
/// </summary>
public DateTime Time { get; private set; }
/// <summary>
/// Gets the data in the time slice
/// </summary>
public List<DataFeedPacket> Data { get; private set; }
/// <summary>
/// Gets the <see cref="Slice"/> that will be used as input for the algorithm
/// </summary>
public Slice Slice { get; private set; }
/// <summary>
/// Gets the data used to update securities
/// </summary>
public List<UpdateData<Security>> SecuritiesUpdateData { get; private set; }
/// <summary>
/// Gets the data used to update the consolidators
/// </summary>
public List<UpdateData<SubscriptionDataConfig>> ConsolidatorUpdateData { get; private set; }
/// <summary>
/// Gets all the custom data in this <see cref="TimeSlice"/>
/// </summary>
public List<UpdateData<Security>> CustomData { get; private set; }
/// <summary>
/// Gets the changes to the data subscriptions as a result of universe selection
/// </summary>
public SecurityChanges SecurityChanges { get; set; }
/// <summary>
/// Initializes a new <see cref="TimeSlice"/> containing the specified data
/// </summary>
public TimeSlice(DateTime time,
int dataPointCount,
Slice slice,
List<DataFeedPacket> data,
List<UpdateData<Security>> securitiesUpdateData,
List<UpdateData<SubscriptionDataConfig>> consolidatorUpdateData,
List<UpdateData<Security>> customData,
SecurityChanges securityChanges)
{
Time = time;
Data = data;
Slice = slice;
CustomData = customData;
DataPointCount = dataPointCount;
SecuritiesUpdateData = securitiesUpdateData;
ConsolidatorUpdateData = consolidatorUpdateData;
SecurityChanges = securityChanges;
}
/// <summary>
/// Creates a new <see cref="TimeSlice"/> for the specified time using the specified data
/// </summary>
/// <param name="utcDateTime">The UTC frontier date time</param>
/// <param name="algorithmTimeZone">The algorithm's time zone, required for computing algorithm and slice time</param>
/// <param name="cashBook">The algorithm's cash book, required for generating cash update pairs</param>
/// <param name="data">The data in this <see cref="TimeSlice"/></param>
/// <param name="changes">The new changes that are seen in this time slice as a result of universe selection</param>
/// <returns>A new <see cref="TimeSlice"/> containing the specified data</returns>
public static TimeSlice Create(DateTime utcDateTime, DateTimeZone algorithmTimeZone, CashBook cashBook, List<DataFeedPacket> data, SecurityChanges changes)
{
int count = 0;
var security = new List<UpdateData<Security>>();
var custom = new List<UpdateData<Security>>();
var consolidator = new List<UpdateData<SubscriptionDataConfig>>();
var allDataForAlgorithm = new List<BaseData>(data.Count);
var optionUnderlyingUpdates = new Dictionary<Symbol, BaseData>();
Split split;
Dividend dividend;
Delisting delisting;
SymbolChangedEvent symbolChange;
// we need to be able to reference the slice being created in order to define the
// evaluation of option price models, so we define a 'future' that can be referenced
// in the option price model evaluation delegates for each contract
Slice slice = null;
var sliceFuture = new Lazy<Slice>(() => slice);
var algorithmTime = utcDateTime.ConvertFromUtc(algorithmTimeZone);
var tradeBars = new TradeBars(algorithmTime);
var quoteBars = new QuoteBars(algorithmTime);
var ticks = new Ticks(algorithmTime);
var splits = new Splits(algorithmTime);
var dividends = new Dividends(algorithmTime);
var delistings = new Delistings(algorithmTime);
var optionChains = new OptionChains(algorithmTime);
var futuresChains = new FuturesChains(algorithmTime);
var symbolChanges = new SymbolChangedEvents(algorithmTime);
// ensure we read equity data before option data, so we can set the current underlying price
foreach (var packet in data)
{
var list = packet.Data;
var symbol = packet.Security.Symbol;
if (list.Count == 0) continue;
// keep count of all data points
if (list.Count == 1 && list[0] is BaseDataCollection)
{
var baseDataCollectionCount = ((BaseDataCollection)list[0]).Data.Count;
if (baseDataCollectionCount == 0)
{
continue;
}
count += baseDataCollectionCount;
}
else
{
count += list.Count;
}
if (!packet.Configuration.IsInternalFeed && packet.Configuration.IsCustomData)
{
// This is all the custom data
custom.Add(new UpdateData<Security>(packet.Security, packet.Configuration.Type, list));
}
var securityUpdate = new List<BaseData>(list.Count);
var consolidatorUpdate = new List<BaseData>(list.Count);
for (int i = 0; i < list.Count; i++)
{
var baseData = list[i];
if (!packet.Configuration.IsInternalFeed)
{
// this is all the data that goes into the algorithm
allDataForAlgorithm.Add(baseData);
}
// don't add internal feed data to ticks/bars objects
if (baseData.DataType != MarketDataType.Auxiliary)
{
if (!packet.Configuration.IsInternalFeed)
{
PopulateDataDictionaries(baseData, ticks, tradeBars, quoteBars, optionChains, futuresChains);
// special handling of options data to build the option chain
if (packet.Security.Type == SecurityType.Option)
{
if (baseData.DataType == MarketDataType.OptionChain)
{
optionChains[baseData.Symbol] = (OptionChain) baseData;
}
else if (!HandleOptionData(algorithmTime, baseData, optionChains, packet.Security, sliceFuture, optionUnderlyingUpdates))
{
continue;
}
}
// special handling of futures data to build the futures chain
if (packet.Security.Type == SecurityType.Future)
{
if (baseData.DataType == MarketDataType.FuturesChain)
{
futuresChains[baseData.Symbol] = (FuturesChain)baseData;
}
else if (!HandleFuturesData(algorithmTime, baseData, futuresChains, packet.Security))
{
continue;
}
}
// this is data used to update consolidators
consolidatorUpdate.Add(baseData);
}
// this is the data used set market prices
// do not add it if it is a Suspicious tick
var tick = baseData as Tick;
if (tick != null && tick.Suspicious) continue;
securityUpdate.Add(baseData);
// option underlying security update
if (packet.Security.Symbol.SecurityType == SecurityType.Equity)
{
optionUnderlyingUpdates[packet.Security.Symbol] = baseData;
}
}
// include checks for various aux types so we don't have to construct the dictionaries in Slice
else if ((delisting = baseData as Delisting) != null)
{
delistings[symbol] = delisting;
}
else if ((dividend = baseData as Dividend) != null)
{
dividends[symbol] = dividend;
}
else if ((split = baseData as Split) != null)
{
splits[symbol] = split;
}
else if ((symbolChange = baseData as SymbolChangedEvent) != null)
{
// symbol changes is keyed by the requested symbol
symbolChanges[packet.Configuration.Symbol] = symbolChange;
}
}
if (securityUpdate.Count > 0)
{
security.Add(new UpdateData<Security>(packet.Security, packet.Configuration.Type, securityUpdate));
}
if (consolidatorUpdate.Count > 0)
{
consolidator.Add(new UpdateData<SubscriptionDataConfig>(packet.Configuration, packet.Configuration.Type, consolidatorUpdate));
}
}
slice = new Slice(algorithmTime, allDataForAlgorithm, tradeBars, quoteBars, ticks, optionChains, futuresChains, splits, dividends, delistings, symbolChanges, allDataForAlgorithm.Count > 0);
return new TimeSlice(utcDateTime, count, slice, data, security, consolidator, custom, changes);
}
/// <summary>
/// Adds the specified <see cref="BaseData"/> instance to the appropriate <see cref="DataDictionary{T}"/>
/// </summary>
private static void PopulateDataDictionaries(BaseData baseData, Ticks ticks, TradeBars tradeBars, QuoteBars quoteBars, OptionChains optionChains, FuturesChains futuresChains)
{
var symbol = baseData.Symbol;
// populate data dictionaries
switch (baseData.DataType)
{
case MarketDataType.Tick:
ticks.Add(symbol, (Tick)baseData);
break;
case MarketDataType.TradeBar:
tradeBars[symbol] = (TradeBar) baseData;
break;
case MarketDataType.QuoteBar:
quoteBars[symbol] = (QuoteBar) baseData;
break;
case MarketDataType.OptionChain:
optionChains[symbol] = (OptionChain) baseData;
break;
case MarketDataType.FuturesChain:
futuresChains[symbol] = (FuturesChain)baseData;
break;
}
}
private static bool HandleOptionData(DateTime algorithmTime, BaseData baseData, OptionChains optionChains, Security security, Lazy<Slice> sliceFuture, IReadOnlyDictionary<Symbol, BaseData> optionUnderlyingUpdates)
{
var symbol = baseData.Symbol;
OptionChain chain;
var canonical = Symbol.CreateOption(symbol.Underlying, symbol.ID.Market, default(OptionStyle), default(OptionRight), 0, SecurityIdentifier.DefaultDate);
if (!optionChains.TryGetValue(canonical, out chain))
{
chain = new OptionChain(canonical, algorithmTime);
optionChains[canonical] = chain;
}
// set the underlying current data point in the option chain
var option = security as Option;
if (option != null)
{
var underlyingData = option.Underlying.GetLastData();
BaseData underlyingUpdate;
if (optionUnderlyingUpdates.TryGetValue(option.Underlying.Symbol, out underlyingUpdate))
{
underlyingData = underlyingUpdate;
}
chain.Underlying = underlyingData;
}
var universeData = baseData as OptionChainUniverseDataCollection;
if (universeData != null)
{
if (universeData.Underlying != null)
{
foreach(var addedContract in chain.Contracts)
{
addedContract.Value.UnderlyingLastPrice = chain.Underlying.Price;
}
}
foreach (var contractSymbol in universeData.FilteredContracts)
{
chain.FilteredContracts.Add(contractSymbol);
}
return false;
}
OptionContract contract;
if (!chain.Contracts.TryGetValue(baseData.Symbol, out contract))
{
var underlyingSymbol = baseData.Symbol.Underlying;
contract = new OptionContract(baseData.Symbol, underlyingSymbol)
{
Time = baseData.EndTime,
LastPrice = security.Close,
Volume = (long)security.Volume,
BidPrice = security.BidPrice,
BidSize = (long)security.BidSize,
AskPrice = security.AskPrice,
AskSize = (long)security.AskSize,
OpenInterest = security.OpenInterest,
UnderlyingLastPrice = chain.Underlying.Price
};
chain.Contracts[baseData.Symbol] = contract;
if (option != null)
{
contract.SetOptionPriceModel(() => option.PriceModel.Evaluate(option, sliceFuture.Value, contract));
}
}
// populate ticks and tradebars dictionaries with no aux data
switch (baseData.DataType)
{
case MarketDataType.Tick:
var tick = (Tick)baseData;
chain.Ticks.Add(tick.Symbol, tick);
UpdateContract(contract, tick);
break;
case MarketDataType.TradeBar:
var tradeBar = (TradeBar)baseData;
chain.TradeBars[symbol] = tradeBar;
UpdateContract(contract, tradeBar);
break;
case MarketDataType.QuoteBar:
var quote = (QuoteBar)baseData;
chain.QuoteBars[symbol] = quote;
UpdateContract(contract, quote);
break;
case MarketDataType.Base:
chain.AddAuxData(baseData);
break;
}
return true;
}
private static bool HandleFuturesData(DateTime algorithmTime, BaseData baseData, FuturesChains futuresChains, Security security)
{
var symbol = baseData.Symbol;
FuturesChain chain;
var canonical = Symbol.Create(symbol.ID.Symbol, SecurityType.Future, symbol.ID.Market);
if (!futuresChains.TryGetValue(canonical, out chain))
{
chain = new FuturesChain(canonical, algorithmTime);
futuresChains[canonical] = chain;
}
var universeData = baseData as FuturesChainUniverseDataCollection;
if (universeData != null)
{
foreach (var contractSymbol in universeData.FilteredContracts)
{
chain.FilteredContracts.Add(contractSymbol);
}
return false;
}
FuturesContract contract;
if (!chain.Contracts.TryGetValue(baseData.Symbol, out contract))
{
var underlyingSymbol = baseData.Symbol.Underlying;
contract = new FuturesContract(baseData.Symbol, underlyingSymbol)
{
Time = baseData.EndTime,
LastPrice = security.Close,
Volume = (long)security.Volume,
BidPrice = security.BidPrice,
BidSize = (long)security.BidSize,
AskPrice = security.AskPrice,
AskSize = (long)security.AskSize,
OpenInterest = security.OpenInterest
};
chain.Contracts[baseData.Symbol] = contract;
}
// populate ticks and tradebars dictionaries with no aux data
switch (baseData.DataType)
{
case MarketDataType.Tick:
var tick = (Tick)baseData;
chain.Ticks.Add(tick.Symbol, tick);
UpdateContract(contract, tick);
break;
case MarketDataType.TradeBar:
var tradeBar = (TradeBar)baseData;
chain.TradeBars[symbol] = tradeBar;
UpdateContract(contract, tradeBar);
break;
case MarketDataType.QuoteBar:
var quote = (QuoteBar)baseData;
chain.QuoteBars[symbol] = quote;
UpdateContract(contract, quote);
break;
case MarketDataType.Base:
chain.AddAuxData(baseData);
break;
}
return true;
}
private static void UpdateContract(OptionContract contract, QuoteBar quote)
{
if (quote.Ask != null && quote.Ask.Close != 0m)
{
contract.AskPrice = quote.Ask.Close;
contract.AskSize = (long)quote.LastAskSize;
}
if (quote.Bid != null && quote.Bid.Close != 0m)
{
contract.BidPrice = quote.Bid.Close;
contract.BidSize = (long)quote.LastBidSize;
}
}
private static void UpdateContract(OptionContract contract, Tick tick)
{
if (tick.TickType == TickType.Trade)
{
contract.LastPrice = tick.Price;
}
else if (tick.TickType == TickType.Quote)
{
if (tick.AskPrice != 0m)
{
contract.AskPrice = tick.AskPrice;
contract.AskSize = (long)tick.AskSize;
}
if (tick.BidPrice != 0m)
{
contract.BidPrice = tick.BidPrice;
contract.BidSize = (long)tick.BidSize;
}
}
else if (tick.TickType == TickType.OpenInterest)
{
if (tick.Value != 0m)
{
contract.OpenInterest = tick.Value;
}
}
}
private static void UpdateContract(OptionContract contract, TradeBar tradeBar)
{
if (tradeBar.Close == 0m) return;
contract.LastPrice = tradeBar.Close;
contract.Volume = (long)tradeBar.Volume;
}
private static void UpdateContract(FuturesContract contract, QuoteBar quote)
{
if (quote.Ask != null && quote.Ask.Close != 0m)
{
contract.AskPrice = quote.Ask.Close;
contract.AskSize = (long)quote.LastAskSize;
}
if (quote.Bid != null && quote.Bid.Close != 0m)
{
contract.BidPrice = quote.Bid.Close;
contract.BidSize = (long)quote.LastBidSize;
}
}
private static void UpdateContract(FuturesContract contract, Tick tick)
{
if (tick.TickType == TickType.Trade)
{
contract.LastPrice = tick.Price;
}
else if (tick.TickType == TickType.Quote)
{
if (tick.AskPrice != 0m)
{
contract.AskPrice = tick.AskPrice;
contract.AskSize = (long)tick.AskSize;
}
if (tick.BidPrice != 0m)
{
contract.BidPrice = tick.BidPrice;
contract.BidSize = (long)tick.BidSize;
}
}
else if (tick.TickType == TickType.OpenInterest)
{
if (tick.Value != 0m)
{
contract.OpenInterest = tick.Value;
}
}
}
private static void UpdateContract(FuturesContract contract, TradeBar tradeBar)
{
if (tradeBar.Close == 0m) return;
contract.LastPrice = tradeBar.Close;
contract.Volume = (long)tradeBar.Volume;
}
}
}
| |
// Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors.
// All rights reserved. Licensed under the BSD 3-Clause License; see License.txt.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.Serialization;
using System.Security;
using System.Text;
using Moq.Language;
using Moq.Properties;
namespace Moq
{
/// <summary>
/// Exception thrown by mocks when they are not properly set up,
/// when setups are not matched, when verification fails, etc.
/// </summary>
/// <remarks>
/// A distinct exception type is provided so that exceptions
/// thrown by a mock can be distinguished from other exceptions
/// that might be thrown in tests.
/// <para>
/// Moq does not provide a richer hierarchy of exception types, as
/// tests typically should <em>not</em> catch or expect exceptions
/// from mocks. These are typically the result of changes
/// in the tested class or its collaborators' implementation, and
/// result in fixes in the mock setup so that they disappear and
/// allow the test to pass.
/// </para>
/// </remarks>
[SuppressMessage("Microsoft.Design", "CA1032:ImplementStandardExceptionConstructors", Justification = "It's only initialized internally.")]
[Serializable]
public class MockException : Exception
{
/// <summary>
/// Returns the exception to be thrown when a setup limited by <see cref="IOccurrence.AtMostOnce()"/> is matched more often than once.
/// </summary>
internal static MockException MoreThanOneCall(MethodCall setup, int invocationCount)
{
var message = new StringBuilder();
message.AppendLine(setup.FailMessage ?? "")
.Append(Times.AtMostOnce().GetExceptionMessage(invocationCount))
.AppendLine(setup.Expression.ToStringFixed());
return new MockException(MockExceptionReasons.MoreThanOneCall, message.ToString());
}
/// <summary>
/// Returns the exception to be thrown when a setup limited by <see cref="IOccurrence.AtMost(int)"/> is matched more often than the specified maximum number of times.
/// </summary>
internal static MockException MoreThanNCalls(MethodCall setup, int maxInvocationCount, int invocationCount)
{
var message = new StringBuilder();
message.AppendLine(setup.FailMessage ?? "")
.Append(Times.AtMost(maxInvocationCount).GetExceptionMessage(invocationCount))
.AppendLine(setup.Expression.ToStringFixed());
return new MockException(MockExceptionReasons.MoreThanNCalls, message.ToString());
}
/// <summary>
/// Returns the exception to be thrown when <see cref="Mock.Verify"/> finds no invocations (or the wrong number of invocations) that match the specified expectation.
/// </summary>
internal static MockException NoMatchingCalls(
Mock rootMock,
LambdaExpression expression,
string failMessage,
Times times,
int callCount)
{
var message = new StringBuilder();
message.AppendLine(failMessage ?? "")
.Append(times.GetExceptionMessage(callCount))
.AppendLine(expression.PartialMatcherAwareEval().ToStringFixed())
.AppendLine()
.AppendLine(Resources.PerformedInvocations)
.AppendLine();
var visitedMocks = new HashSet<Mock>();
var mocks = new Queue<Mock>();
mocks.Enqueue(rootMock);
while (mocks.Any())
{
var mock = mocks.Dequeue();
if (visitedMocks.Contains(mock)) continue;
visitedMocks.Add(mock);
message.AppendLine(mock == rootMock ? $" {mock} ({expression.Parameters[0].Name}):"
: $" {mock}:");
var invocations = mock.MutableInvocations.ToArray();
if (invocations.Any())
{
message.AppendLine();
foreach (var invocation in invocations)
{
message.Append($" {invocation}");
if (invocation.Method.ReturnType != typeof(void) && Unwrap.ResultIfCompletedTask(invocation.ReturnValue) is IMocked mocked)
{
var innerMock = mocked.Mock;
mocks.Enqueue(innerMock);
message.Append($" => {innerMock}");
}
message.AppendLine();
}
}
else
{
message.AppendLine($" {Resources.NoInvocationsPerformed}");
}
message.AppendLine();
}
return new MockException(MockExceptionReasons.NoMatchingCalls, message.TrimEnd().AppendLine().ToString());
}
/// <summary>
/// Returns the exception to be thrown when a strict mock has no setup corresponding to the specified invocation.
/// </summary>
internal static MockException NoSetup(Invocation invocation)
{
return new MockException(
MockExceptionReasons.NoSetup,
string.Format(
CultureInfo.CurrentCulture,
Resources.MockExceptionMessage,
invocation.ToString(),
MockBehavior.Strict,
Resources.NoSetup));
}
/// <summary>
/// Returns the exception to be thrown when a strict mock has no setup that provides a return value for the specified invocation.
/// </summary>
internal static MockException ReturnValueRequired(Invocation invocation)
{
return new MockException(
MockExceptionReasons.ReturnValueRequired,
string.Format(
CultureInfo.CurrentCulture,
Resources.MockExceptionMessage,
invocation.ToString(),
MockBehavior.Strict,
Resources.ReturnValueRequired));
}
/// <summary>
/// Returns the exception to be thrown when a setup was not matched.
/// </summary>
internal static MockException UnmatchedSetup(Setup setup)
{
return new MockException(
MockExceptionReasons.UnmatchedSetup,
string.Format(
CultureInfo.CurrentCulture,
Resources.UnmatchedSetup,
setup));
}
internal static MockException FromInnerMockOf(ISetup setup, MockException error)
{
var message = new StringBuilder();
message.AppendLine(string.Format(CultureInfo.CurrentCulture, Resources.VerificationErrorsOfInnerMock, setup)).TrimEnd().AppendLine()
.AppendLine();
message.AppendIndented(error.Message, count: 3);
return new MockException(error.Reasons, message.ToString());
}
/// <summary>
/// Returns an exception whose message is the concatenation of the given <paramref name="errors"/>' messages
/// and whose reason(s) is the combination of the given <paramref name="errors"/>' reason(s).
/// Used by <see cref="MockFactory.VerifyMocks(Action{Mock})"/> when it finds one or more mocks with verification errors.
/// </summary>
internal static MockException Combined(IEnumerable<MockException> errors, string preamble)
{
Debug.Assert(errors != null);
Debug.Assert(errors.Any());
var reasons = default(MockExceptionReasons);
var message = new StringBuilder();
if (preamble != null)
{
message.Append(preamble).TrimEnd().AppendLine()
.AppendLine();
}
foreach (var error in errors)
{
reasons |= error.Reasons;
message.AppendIndented(error.Message, count: 3).TrimEnd().AppendLine()
.AppendLine();
}
return new MockException(reasons, message.TrimEnd().ToString());
}
/// <summary>
/// Returns the exception to be thrown when <see cref="Mock.VerifyNoOtherCalls(Mock)"/> finds invocations that have not been verified.
/// </summary>
internal static MockException UnverifiedInvocations(Mock mock, IEnumerable<Invocation> invocations)
{
var message = new StringBuilder();
message.AppendLine(string.Format(CultureInfo.CurrentCulture, Resources.UnverifiedInvocations, mock)).TrimEnd().AppendLine()
.AppendLine();
foreach (var invocation in invocations)
{
message.AppendIndented(invocation.ToString(), count: 3).TrimEnd().AppendLine();
}
return new MockException(MockExceptionReasons.UnverifiedInvocations, message.TrimEnd().ToString());
}
private readonly MockExceptionReasons reasons;
private MockException(MockExceptionReasons reasons, string message)
: base(message)
{
this.reasons = reasons;
}
internal MockExceptionReasons Reasons => this.reasons;
/// <summary>
/// Indicates whether this exception is a verification fault raised by Verify()
/// </summary>
public bool IsVerificationError
{
get
{
const MockExceptionReasons verificationErrorMask = MockExceptionReasons.NoMatchingCalls
| MockExceptionReasons.UnmatchedSetup
| MockExceptionReasons.UnverifiedInvocations;
return (this.reasons & verificationErrorMask) != 0;
}
}
/// <summary>
/// Supports the serialization infrastructure.
/// </summary>
/// <param name="info">Serialization information.</param>
/// <param name="context">Streaming context.</param>
protected MockException(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
this.reasons = (MockExceptionReasons)info.GetValue(nameof(this.reasons), typeof(MockExceptionReasons));
}
/// <summary>
/// Supports the serialization infrastructure.
/// </summary>
/// <param name="info">Serialization information.</param>
/// <param name="context">Streaming context.</param>
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue(nameof(this.reasons), this.reasons);
}
}
}
| |
using System;
namespace NBitcoin.BouncyCastle.Asn1.Pkcs
{
public abstract class PkcsObjectIdentifiers
{
//
// pkcs-1 OBJECT IDENTIFIER ::= {
// iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 1 }
//
public const string Pkcs1 = "1.2.840.113549.1.1";
public static readonly DerObjectIdentifier RsaEncryption = new DerObjectIdentifier(Pkcs1 + ".1");
public static readonly DerObjectIdentifier MD2WithRsaEncryption = new DerObjectIdentifier(Pkcs1 + ".2");
public static readonly DerObjectIdentifier MD4WithRsaEncryption = new DerObjectIdentifier(Pkcs1 + ".3");
public static readonly DerObjectIdentifier MD5WithRsaEncryption = new DerObjectIdentifier(Pkcs1 + ".4");
public static readonly DerObjectIdentifier Sha1WithRsaEncryption = new DerObjectIdentifier(Pkcs1 + ".5");
public static readonly DerObjectIdentifier SrsaOaepEncryptionSet = new DerObjectIdentifier(Pkcs1 + ".6");
public static readonly DerObjectIdentifier IdRsaesOaep = new DerObjectIdentifier(Pkcs1 + ".7");
public static readonly DerObjectIdentifier IdMgf1 = new DerObjectIdentifier(Pkcs1 + ".8");
public static readonly DerObjectIdentifier IdPSpecified = new DerObjectIdentifier(Pkcs1 + ".9");
public static readonly DerObjectIdentifier IdRsassaPss = new DerObjectIdentifier(Pkcs1 + ".10");
public static readonly DerObjectIdentifier Sha256WithRsaEncryption = new DerObjectIdentifier(Pkcs1 + ".11");
public static readonly DerObjectIdentifier Sha384WithRsaEncryption = new DerObjectIdentifier(Pkcs1 + ".12");
public static readonly DerObjectIdentifier Sha512WithRsaEncryption = new DerObjectIdentifier(Pkcs1 + ".13");
public static readonly DerObjectIdentifier Sha224WithRsaEncryption = new DerObjectIdentifier(Pkcs1 + ".14");
//
// pkcs-3 OBJECT IDENTIFIER ::= {
// iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 3 }
//
public const string Pkcs3 = "1.2.840.113549.1.3";
public static readonly DerObjectIdentifier DhKeyAgreement = new DerObjectIdentifier(Pkcs3 + ".1");
//
// pkcs-5 OBJECT IDENTIFIER ::= {
// iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 5 }
//
public const string Pkcs5 = "1.2.840.113549.1.5";
public static readonly DerObjectIdentifier PbeWithMD2AndDesCbc = new DerObjectIdentifier(Pkcs5 + ".1");
public static readonly DerObjectIdentifier PbeWithMD2AndRC2Cbc = new DerObjectIdentifier(Pkcs5 + ".4");
public static readonly DerObjectIdentifier PbeWithMD5AndDesCbc = new DerObjectIdentifier(Pkcs5 + ".3");
public static readonly DerObjectIdentifier PbeWithMD5AndRC2Cbc = new DerObjectIdentifier(Pkcs5 + ".6");
public static readonly DerObjectIdentifier PbeWithSha1AndDesCbc = new DerObjectIdentifier(Pkcs5 + ".10");
public static readonly DerObjectIdentifier PbeWithSha1AndRC2Cbc = new DerObjectIdentifier(Pkcs5 + ".11");
public static readonly DerObjectIdentifier IdPbeS2 = new DerObjectIdentifier(Pkcs5 + ".13");
public static readonly DerObjectIdentifier IdPbkdf2 = new DerObjectIdentifier(Pkcs5 + ".12");
//
// encryptionAlgorithm OBJECT IDENTIFIER ::= {
// iso(1) member-body(2) us(840) rsadsi(113549) 3 }
//
public const string EncryptionAlgorithm = "1.2.840.113549.3";
public static readonly DerObjectIdentifier DesEde3Cbc = new DerObjectIdentifier(EncryptionAlgorithm + ".7");
public static readonly DerObjectIdentifier RC2Cbc = new DerObjectIdentifier(EncryptionAlgorithm + ".2");
//
// object identifiers for digests
//
public const string DigestAlgorithm = "1.2.840.113549.2";
//
// md2 OBJECT IDENTIFIER ::=
// {iso(1) member-body(2) US(840) rsadsi(113549) DigestAlgorithm(2) 2}
//
public static readonly DerObjectIdentifier MD2 = new DerObjectIdentifier(DigestAlgorithm + ".2");
//
// md4 OBJECT IDENTIFIER ::=
// {iso(1) member-body(2) US(840) rsadsi(113549) DigestAlgorithm(2) 4}
//
public static readonly DerObjectIdentifier MD4 = new DerObjectIdentifier(DigestAlgorithm + ".4");
//
// md5 OBJECT IDENTIFIER ::=
// {iso(1) member-body(2) US(840) rsadsi(113549) DigestAlgorithm(2) 5}
//
public static readonly DerObjectIdentifier MD5 = new DerObjectIdentifier(DigestAlgorithm + ".5");
public static readonly DerObjectIdentifier IdHmacWithSha1 = new DerObjectIdentifier(DigestAlgorithm + ".7");
public static readonly DerObjectIdentifier IdHmacWithSha224 = new DerObjectIdentifier(DigestAlgorithm + ".8");
public static readonly DerObjectIdentifier IdHmacWithSha256 = new DerObjectIdentifier(DigestAlgorithm + ".9");
public static readonly DerObjectIdentifier IdHmacWithSha384 = new DerObjectIdentifier(DigestAlgorithm + ".10");
public static readonly DerObjectIdentifier IdHmacWithSha512 = new DerObjectIdentifier(DigestAlgorithm + ".11");
//
// pkcs-7 OBJECT IDENTIFIER ::= {
// iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 7 }
//
public const string Pkcs7 = "1.2.840.113549.1.7";
public static readonly DerObjectIdentifier Data = new DerObjectIdentifier(Pkcs7 + ".1");
public static readonly DerObjectIdentifier SignedData = new DerObjectIdentifier(Pkcs7 + ".2");
public static readonly DerObjectIdentifier EnvelopedData = new DerObjectIdentifier(Pkcs7 + ".3");
public static readonly DerObjectIdentifier SignedAndEnvelopedData = new DerObjectIdentifier(Pkcs7 + ".4");
public static readonly DerObjectIdentifier DigestedData = new DerObjectIdentifier(Pkcs7 + ".5");
public static readonly DerObjectIdentifier EncryptedData = new DerObjectIdentifier(Pkcs7 + ".6");
//
// pkcs-9 OBJECT IDENTIFIER ::= {
// iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 9 }
//
public const string Pkcs9 = "1.2.840.113549.1.9";
public static readonly DerObjectIdentifier Pkcs9AtEmailAddress = new DerObjectIdentifier(Pkcs9 + ".1");
public static readonly DerObjectIdentifier Pkcs9AtUnstructuredName = new DerObjectIdentifier(Pkcs9 + ".2");
public static readonly DerObjectIdentifier Pkcs9AtContentType = new DerObjectIdentifier(Pkcs9 + ".3");
public static readonly DerObjectIdentifier Pkcs9AtMessageDigest = new DerObjectIdentifier(Pkcs9 + ".4");
public static readonly DerObjectIdentifier Pkcs9AtSigningTime = new DerObjectIdentifier(Pkcs9 + ".5");
public static readonly DerObjectIdentifier Pkcs9AtCounterSignature = new DerObjectIdentifier(Pkcs9 + ".6");
public static readonly DerObjectIdentifier Pkcs9AtChallengePassword = new DerObjectIdentifier(Pkcs9 + ".7");
public static readonly DerObjectIdentifier Pkcs9AtUnstructuredAddress = new DerObjectIdentifier(Pkcs9 + ".8");
public static readonly DerObjectIdentifier Pkcs9AtExtendedCertificateAttributes = new DerObjectIdentifier(Pkcs9 + ".9");
public static readonly DerObjectIdentifier Pkcs9AtSigningDescription = new DerObjectIdentifier(Pkcs9 + ".13");
public static readonly DerObjectIdentifier Pkcs9AtExtensionRequest = new DerObjectIdentifier(Pkcs9 + ".14");
public static readonly DerObjectIdentifier Pkcs9AtSmimeCapabilities = new DerObjectIdentifier(Pkcs9 + ".15");
public static readonly DerObjectIdentifier Pkcs9AtFriendlyName = new DerObjectIdentifier(Pkcs9 + ".20");
public static readonly DerObjectIdentifier Pkcs9AtLocalKeyID = new DerObjectIdentifier(Pkcs9 + ".21");
[Obsolete("Use X509Certificate instead")]
public static readonly DerObjectIdentifier X509CertType = new DerObjectIdentifier(Pkcs9 + ".22.1");
public const string CertTypes = Pkcs9 + ".22";
public static readonly DerObjectIdentifier X509Certificate = new DerObjectIdentifier(CertTypes + ".1");
public static readonly DerObjectIdentifier SdsiCertificate = new DerObjectIdentifier(CertTypes + ".2");
public const string CrlTypes = Pkcs9 + ".23";
public static readonly DerObjectIdentifier X509Crl = new DerObjectIdentifier(CrlTypes + ".1");
public static readonly DerObjectIdentifier IdAlgPwriKek = new DerObjectIdentifier(Pkcs9 + ".16.3.9");
//
// SMIME capability sub oids.
//
public static readonly DerObjectIdentifier PreferSignedData = new DerObjectIdentifier(Pkcs9 + ".15.1");
public static readonly DerObjectIdentifier CannotDecryptAny = new DerObjectIdentifier(Pkcs9 + ".15.2");
public static readonly DerObjectIdentifier SmimeCapabilitiesVersions = new DerObjectIdentifier(Pkcs9 + ".15.3");
//
// other SMIME attributes
//
public static readonly DerObjectIdentifier IdAAReceiptRequest = new DerObjectIdentifier(Pkcs9 + ".16.2.1");
//
// id-ct OBJECT IDENTIFIER ::= {iso(1) member-body(2) usa(840)
// rsadsi(113549) pkcs(1) pkcs-9(9) smime(16) ct(1)}
//
public const string IdCT = "1.2.840.113549.1.9.16.1";
public static readonly DerObjectIdentifier IdCTAuthData = new DerObjectIdentifier(IdCT + ".2");
public static readonly DerObjectIdentifier IdCTTstInfo = new DerObjectIdentifier(IdCT + ".4");
public static readonly DerObjectIdentifier IdCTCompressedData = new DerObjectIdentifier(IdCT + ".9");
public static readonly DerObjectIdentifier IdCTAuthEnvelopedData = new DerObjectIdentifier(IdCT + ".23");
public static readonly DerObjectIdentifier IdCTTimestampedData = new DerObjectIdentifier(IdCT + ".31");
//
// id-cti OBJECT IDENTIFIER ::= {iso(1) member-body(2) usa(840)
// rsadsi(113549) pkcs(1) pkcs-9(9) smime(16) cti(6)}
//
public const string IdCti = "1.2.840.113549.1.9.16.6";
public static readonly DerObjectIdentifier IdCtiEtsProofOfOrigin = new DerObjectIdentifier(IdCti + ".1");
public static readonly DerObjectIdentifier IdCtiEtsProofOfReceipt = new DerObjectIdentifier(IdCti + ".2");
public static readonly DerObjectIdentifier IdCtiEtsProofOfDelivery = new DerObjectIdentifier(IdCti + ".3");
public static readonly DerObjectIdentifier IdCtiEtsProofOfSender = new DerObjectIdentifier(IdCti + ".4");
public static readonly DerObjectIdentifier IdCtiEtsProofOfApproval = new DerObjectIdentifier(IdCti + ".5");
public static readonly DerObjectIdentifier IdCtiEtsProofOfCreation = new DerObjectIdentifier(IdCti + ".6");
//
// id-aa OBJECT IDENTIFIER ::= {iso(1) member-body(2) usa(840)
// rsadsi(113549) pkcs(1) pkcs-9(9) smime(16) attributes(2)}
//
public const string IdAA = "1.2.840.113549.1.9.16.2";
public static readonly DerObjectIdentifier IdAAContentHint = new DerObjectIdentifier(IdAA + ".4"); // See RFC 2634
public static readonly DerObjectIdentifier IdAAMsgSigDigest = new DerObjectIdentifier(IdAA + ".5");
public static readonly DerObjectIdentifier IdAAContentReference = new DerObjectIdentifier(IdAA + ".10");
/*
* id-aa-encrypKeyPref OBJECT IDENTIFIER ::= {id-aa 11}
*
*/
public static readonly DerObjectIdentifier IdAAEncrypKeyPref = new DerObjectIdentifier(IdAA + ".11");
public static readonly DerObjectIdentifier IdAASigningCertificate = new DerObjectIdentifier(IdAA + ".12");
public static readonly DerObjectIdentifier IdAASigningCertificateV2 = new DerObjectIdentifier(IdAA + ".47");
public static readonly DerObjectIdentifier IdAAContentIdentifier = new DerObjectIdentifier(IdAA + ".7"); // See RFC 2634
/*
* RFC 3126
*/
public static readonly DerObjectIdentifier IdAASignatureTimeStampToken = new DerObjectIdentifier(IdAA + ".14");
public static readonly DerObjectIdentifier IdAAEtsSigPolicyID = new DerObjectIdentifier(IdAA + ".15");
public static readonly DerObjectIdentifier IdAAEtsCommitmentType = new DerObjectIdentifier(IdAA + ".16");
public static readonly DerObjectIdentifier IdAAEtsSignerLocation = new DerObjectIdentifier(IdAA + ".17");
public static readonly DerObjectIdentifier IdAAEtsSignerAttr = new DerObjectIdentifier(IdAA + ".18");
public static readonly DerObjectIdentifier IdAAEtsOtherSigCert = new DerObjectIdentifier(IdAA + ".19");
public static readonly DerObjectIdentifier IdAAEtsContentTimestamp = new DerObjectIdentifier(IdAA + ".20");
public static readonly DerObjectIdentifier IdAAEtsCertificateRefs = new DerObjectIdentifier(IdAA + ".21");
public static readonly DerObjectIdentifier IdAAEtsRevocationRefs = new DerObjectIdentifier(IdAA + ".22");
public static readonly DerObjectIdentifier IdAAEtsCertValues = new DerObjectIdentifier(IdAA + ".23");
public static readonly DerObjectIdentifier IdAAEtsRevocationValues = new DerObjectIdentifier(IdAA + ".24");
public static readonly DerObjectIdentifier IdAAEtsEscTimeStamp = new DerObjectIdentifier(IdAA + ".25");
public static readonly DerObjectIdentifier IdAAEtsCertCrlTimestamp = new DerObjectIdentifier(IdAA + ".26");
public static readonly DerObjectIdentifier IdAAEtsArchiveTimestamp = new DerObjectIdentifier(IdAA + ".27");
[Obsolete("Use 'IdAAEtsSigPolicyID' instead")]
public static readonly DerObjectIdentifier IdAASigPolicyID = IdAAEtsSigPolicyID;
[Obsolete("Use 'IdAAEtsCommitmentType' instead")]
public static readonly DerObjectIdentifier IdAACommitmentType = IdAAEtsCommitmentType;
[Obsolete("Use 'IdAAEtsSignerLocation' instead")]
public static readonly DerObjectIdentifier IdAASignerLocation = IdAAEtsSignerLocation;
[Obsolete("Use 'IdAAEtsOtherSigCert' instead")]
public static readonly DerObjectIdentifier IdAAOtherSigCert = IdAAEtsOtherSigCert;
//
// id-spq OBJECT IDENTIFIER ::= {iso(1) member-body(2) usa(840)
// rsadsi(113549) pkcs(1) pkcs-9(9) smime(16) id-spq(5)}
//
public const string IdSpq = "1.2.840.113549.1.9.16.5";
public static readonly DerObjectIdentifier IdSpqEtsUri = new DerObjectIdentifier(IdSpq + ".1");
public static readonly DerObjectIdentifier IdSpqEtsUNotice = new DerObjectIdentifier(IdSpq + ".2");
//
// pkcs-12 OBJECT IDENTIFIER ::= {
// iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 12 }
//
public const string Pkcs12 = "1.2.840.113549.1.12";
public const string BagTypes = Pkcs12 + ".10.1";
public static readonly DerObjectIdentifier KeyBag = new DerObjectIdentifier(BagTypes + ".1");
public static readonly DerObjectIdentifier Pkcs8ShroudedKeyBag = new DerObjectIdentifier(BagTypes + ".2");
public static readonly DerObjectIdentifier CertBag = new DerObjectIdentifier(BagTypes + ".3");
public static readonly DerObjectIdentifier CrlBag = new DerObjectIdentifier(BagTypes + ".4");
public static readonly DerObjectIdentifier SecretBag = new DerObjectIdentifier(BagTypes + ".5");
public static readonly DerObjectIdentifier SafeContentsBag = new DerObjectIdentifier(BagTypes + ".6");
public const string Pkcs12PbeIds = Pkcs12 + ".1";
public static readonly DerObjectIdentifier PbeWithShaAnd128BitRC4 = new DerObjectIdentifier(Pkcs12PbeIds + ".1");
public static readonly DerObjectIdentifier PbeWithShaAnd40BitRC4 = new DerObjectIdentifier(Pkcs12PbeIds + ".2");
public static readonly DerObjectIdentifier PbeWithShaAnd3KeyTripleDesCbc = new DerObjectIdentifier(Pkcs12PbeIds + ".3");
public static readonly DerObjectIdentifier PbeWithShaAnd2KeyTripleDesCbc = new DerObjectIdentifier(Pkcs12PbeIds + ".4");
public static readonly DerObjectIdentifier PbeWithShaAnd128BitRC2Cbc = new DerObjectIdentifier(Pkcs12PbeIds + ".5");
public static readonly DerObjectIdentifier PbewithShaAnd40BitRC2Cbc = new DerObjectIdentifier(Pkcs12PbeIds + ".6");
public static readonly DerObjectIdentifier IdAlgCms3DesWrap = new DerObjectIdentifier("1.2.840.113549.1.9.16.3.6");
public static readonly DerObjectIdentifier IdAlgCmsRC2Wrap = new DerObjectIdentifier("1.2.840.113549.1.9.16.3.7");
}
}
| |
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel
//
// 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.Threading;
using System.Windows.Forms;
namespace SharpDX.DirectInput
{
public partial class Device
{
private DeviceProperties _properties;
/// <summary>
/// Initializes a new instance of the <see cref="Device"/> class based on a given globally unique identifier (Guid).
/// </summary>
/// <param name="directInput">The direct input.</param>
/// <param name="deviceGuid">The device GUID.</param>
protected Device(DirectInput directInput, Guid deviceGuid)
{
IntPtr temp;
directInput.CreateDevice(deviceGuid, out temp, null);
NativePointer = temp;
}
/// <summary>
/// Gets the device properties.
/// </summary>
/// <value>The device properties.</value>
public DeviceProperties Properties
{
get
{
if (_properties == null)
_properties = new DeviceProperties(this);
return _properties;
}
}
/// <summary>
/// Sends a hardware-specific command to the force-feedback driver.
/// </summary>
/// <param name="command">Driver-specific command number. Consult the driver documentation for a list of valid commands. </param>
/// <param name="inData">Buffer containing the data required to perform the operation. </param>
/// <param name="outData">Buffer in which the operation's output data is returned. </param>
/// <returns>Number of bytes written to the output buffer</returns>
/// <remarks>
/// Because each driver implements different escapes, it is the application's responsibility to ensure that it is sending the escape to the correct driver by comparing the value of the guidFFDriver member of the <see cref="DeviceInstance"/> structure against the value the application is expecting.
/// </remarks>
public int Escape(int command, byte[] inData, byte[] outData)
{
var effectEscape = new EffectEscape();
unsafe
{
fixed (void* pInData = &inData[0])
fixed (void* pOutData = &outData[0])
{
effectEscape.Size = sizeof (EffectEscape);
effectEscape.Command = command;
effectEscape.InBufferPointer = (IntPtr) pInData;
effectEscape.InBufferSize = inData.Length;
effectEscape.OutBufferPointer = (IntPtr) pOutData;
effectEscape.OutBufferSize = outData.Length;
Escape(ref effectEscape);
return effectEscape.OutBufferSize;
}
}
}
/// <summary>
/// Gets information about a device image for use in a configuration property sheet.
/// </summary>
/// <returns>A structure that receives information about the device image.</returns>
public DeviceImageHeader GetDeviceImages()
{
var imageHeader = new DeviceImageHeader();
GetImageInfo(imageHeader);
if (imageHeader.BufferUsed > 0)
{
unsafe
{
imageHeader.BufferSize = imageHeader.BufferUsed;
var pImages = stackalloc DeviceImage.__Native[imageHeader.BufferSize/sizeof (DeviceImage.__Native)];
imageHeader.ImageInfoArrayPointer = (IntPtr)pImages;
}
GetImageInfo(imageHeader);
}
return imageHeader;
}
/// <summary>
/// Gets all effects.
/// </summary>
/// <returns>A collection of <see cref="EffectInfo"/></returns>
public IList<EffectInfo> GetEffects()
{
return GetEffects(EffectType.All);
}
/// <summary>
/// Gets the effects for a particular <see cref="EffectType"/>.
/// </summary>
/// <param name="effectType">Effect type.</param>
/// <returns>A collection of <see cref="EffectInfo"/></returns>
public IList<EffectInfo> GetEffects(EffectType effectType)
{
var enumEffectsCallback = new EnumEffectsCallback();
EnumEffects(enumEffectsCallback.NativePointer, IntPtr.Zero, effectType);
return enumEffectsCallback.EffectInfos;
}
/// <summary>
/// Gets the effects stored in a RIFF Force Feedback file.
/// </summary>
/// <param name="fileName">Name of the file.</param>
/// <returns>A collection of <see cref="EffectFile"/></returns>
public IList<EffectFile> GetEffectsInFile(string fileName)
{
return GetEffectsInFile(fileName, EffectFileFlags.None);
}
/// <summary>
/// Gets the effects stored in a RIFF Force Feedback file.
/// </summary>
/// <param name="fileName">Name of the file.</param>
/// <param name="effectFileFlags">Flags used to filter effects.</param>
/// <returns>A collection of <see cref="EffectFile"/></returns>
public IList<EffectFile> GetEffectsInFile(string fileName, EffectFileFlags effectFileFlags)
{
var enumEffectsInFileCallback = new EnumEffectsInFileCallback();
EnumEffectsInFile(fileName, enumEffectsInFileCallback.NativePointer, IntPtr.Zero, effectFileFlags);
return enumEffectsInFileCallback.EffectsInFile;
}
/// <summary>
/// Gets information about a device object, such as a button or axis.
/// </summary>
/// <param name="objectId">The object type/instance identifier. This identifier is returned in the <see cref="DeviceObjectInstance.ObjectId"/> member of the <see cref="DeviceObjectInstance"/> structure returned from a previous call to the <see cref="GetObjects()"/> method.</param>
/// <returns>A <see cref="DeviceObjectInstance"/> information</returns>
public DeviceObjectInstance GetObjectInfoById(DeviceObjectId objectId)
{
return GetObjectInfo((int)objectId, PropertyHowType.Byid);
}
/// <summary>
/// Gets information about a device object, such as a button or axis.
/// </summary>
/// <param name="usageCode">the HID Usage Page and Usage values.</param>
/// <returns>A <see cref="DeviceObjectInstance"/> information</returns>
public DeviceObjectInstance GetObjectInfoByUsage(int usageCode)
{
return GetObjectInfo(usageCode, PropertyHowType.Byusage);
}
/// <summary>
/// Gets the properties about a device object, such as a button or axis.
/// </summary>
/// <param name="objectId">The object type/instance identifier. This identifier is returned in the <see cref="DeviceObjectInstance.Type"/> member of the <see cref="DeviceObjectInstance"/> structure returned from a previous call to the <see cref="GetObjects()"/> method.</param>
/// <returns>an ObjectProperties</returns>
public ObjectProperties GetObjectPropertiesById(DeviceObjectId objectId)
{
return new ObjectProperties(this, (int)objectId, PropertyHowType.Byid);
}
/// <summary>
/// Gets the properties about a device object, such as a button or axis.
/// </summary>
/// <param name="usageCode">the HID Usage Page and Usage values.</param>
/// <returns>an ObjectProperties</returns>
public ObjectProperties GetObjectPropertiesByUsage(int usageCode)
{
return new ObjectProperties(this, usageCode, PropertyHowType.Byusage);
}
/// <summary>
/// Retrieves a collection of objects on the device.
/// </summary>
/// <returns>A collection of all device objects on the device.</returns>
public IList<DeviceObjectInstance> GetObjects()
{
return GetObjects(DeviceObjectTypeFlags.All);
}
/// <summary>
/// Retrieves a collection of objects on the device.
/// </summary>
/// <param name="deviceObjectTypeFlag">A filter for the returned device objects collection.</param>
/// <returns>A collection of device objects matching the specified filter.</returns>
public IList<DeviceObjectInstance> GetObjects(DeviceObjectTypeFlags deviceObjectTypeFlag)
{
var enumEffectsInFileCallback = new EnumObjectsCallback();
EnumObjects(enumEffectsInFileCallback.NativePointer, IntPtr.Zero, (int)deviceObjectTypeFlag);
return enumEffectsInFileCallback.Objects;
}
/// <summary>
/// Runs the DirectInput control panel associated with this device. If the device does not have a control panel associated with it, the default device control panel is launched.
/// </summary>
/// <returns>A <see cref = "T:SharpDX.Result" /> object describing the result of the operation.</returns>
public void RunControlPanel()
{
RunControlPanel(IntPtr.Zero, 0);
}
/// <summary>
/// Runs the DirectInput control panel associated with this device. If the device does not have a control panel associated with it, the default device control panel is launched.
/// </summary>
/// <param name="parent">The parent control.</param>
/// <returns>A <see cref = "T:SharpDX.Result" /> object describing the result of the operation.</returns>
public void RunControlPanel(Control parent)
{
RunControlPanel(parent.Handle, 0);
}
// Disabled as it seems to be not used anymore
///// <summary>
///// Sends data to a device that accepts output. Applications should not use this method. Force Feedback is the recommended way to send data to a device. If you want to send other data to a device, such as changing LED or internal device states, the HID application programming interface (API) is the recommended way.
///// </summary>
///// <param name="data">An array of object data.</param>
///// <param name="overlay">if set to <c>true</c> the device data sent is overlaid on the previously sent device data..</param>
///// <returns>A <see cref = "T:SharpDX.Result" /> object describing the result of the operation.</returns>
//public Result SendData(ObjectData[] data, bool overlay)
//{
// unsafe
// {
// int count = data==null?0:data.Length;
// return SendDeviceData(sizeof (ObjectData), data, ref count, overlay ? 1 : 0);
// }
//}
/// <summary>
/// Requests the cooperative level for this instance of the input device. The cooperative level determines how this instance of the device interacts with other instances of the device and the rest of the system.
/// </summary>
/// <param name="control">Window control to be associated with the device. This parameter must be a valid top-level window handle that belongs to the process. The window associated with the device must not be destroyed while it is still active in a DirectInput device.</param>
/// <param name="level">Flags that specify the cooperative level to associate with the input device.</param>
/// <returns>If the method succeeds, the return value is <see cref="SharpDX.DirectInput.ResultCode.Ok"/>. If the method fails, a <see cref="SharpDXException"/> is raised with the following error code values: <see cref="SharpDX.DirectInput.ResultCode.InvalidParam"/>, <see cref="SharpDX.DirectInput.ResultCode.NotInitialized"/>, <see cref="Result.Handle"/>.</returns>
/// <remarks>
/// <para>Applications cannot specify <see cref="SharpDX.DirectInput.CooperativeLevel.Foreground"/> and <see cref="SharpDX.DirectInput.CooperativeLevel.Background"/> at the same time. This apply as well to <see cref="SharpDX.DirectInput.CooperativeLevel.Exclusive"/> and <see cref="SharpDX.DirectInput.CooperativeLevel.NonExclusive"/>.</para>
/// <para>When the mouse is acquired with exclusive access, the mouse pointer is removed from the screen until the device is unacquired.</para>
/// <para>Applications that select the background exclusive mode cooperative level are not guaranteed to retain access to the device if another application requests exclusive access. When a background exclusive mode application loses access, calls to DirectInput device methods will fail and return <see cref="SharpDX.DirectInput.ResultCode.NotAcquired"/>. The application can regain access to the device by manually unacquiring the device and reacquiring it.</para>
/// <para>Applications must call this method before acquiring the device by using the <see cref="SharpDX.DirectInput.Device"/> method.</para>
/// </remarks>
/// <unmanaged>HRESULT IDirectInputDevice8W::SetCooperativeLevel([In] HWND arg0,[In] DISCL arg1)</unmanaged>
public void SetCooperativeLevel(Control control, CooperativeLevel level)
{
SetCooperativeLevel(control.Handle, level);
}
/// <summary>
/// Specifies an event that is to be set when the device state changes. It is also used to turn off event notification.
/// </summary>
/// <param name="eventHandle">Handle to the event that is to be set when the device state changes. DirectInput uses the Microsoft Win32 SetEvent function on the handle when the state of the device changes. If the eventHandle parameter is null, notification is disabled.</param>
/// <returns>A <see cref = "T:SharpDX.Result" /> object describing the result of the operation.</returns>
public void SetNotification(WaitHandle eventHandle)
{
SetEventNotification(eventHandle!=null?eventHandle.SafeWaitHandle.DangerousGetHandle():IntPtr.Zero);
}
/// <summary>
/// Writes the effects to a file.
/// </summary>
/// <param name="fileName">Name of the file.</param>
/// <param name="effects">The effects.</param>
/// <returns>A <see cref = "T:SharpDX.Result" /> object describing the result of the operation.</returns>
public void WriteEffectsToFile(string fileName, EffectFile[] effects)
{
WriteEffectsToFile(fileName, effects, false);
}
/// <summary>
/// Writes the effects to file.
/// </summary>
/// <param name="fileName">Name of the file.</param>
/// <param name="effects">The effects.</param>
/// <param name="includeNonstandardEffects">if set to <c>true</c> [include nonstandard effects].</param>
/// <returns>A <see cref = "T:SharpDX.Result" /> object describing the result of the operation.</returns>
public void WriteEffectsToFile(string fileName, EffectFile[] effects, bool includeNonstandardEffects)
{
WriteEffectToFile(fileName, effects.Length, effects, (int)(includeNonstandardEffects?EffectFileFlags.IncludeNonStandard:0));
}
/// <summary>
/// Gets the created effects.
/// </summary>
/// <value>The created effects.</value>
public IList<Effect> CreatedEffects
{
get
{
var enumCreatedEffectsCallback = new EnumCreatedEffectsCallback();
EnumCreatedEffectObjects(enumCreatedEffectsCallback.NativePointer, IntPtr.Zero, 0);
return enumCreatedEffectsCallback.Effects;
}
}
}
}
| |
/*
* Copyright 2012-2015 Aerospike, Inc.
*
* Portions may be licensed to Aerospike, Inc. under one or more contributor
* license agreements.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
using System;
using System.IO;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace Aerospike.Client
{
public sealed class Util
{
public static void Sleep(int millis)
{
try
{
Thread.Sleep(millis);
}
catch (ThreadInterruptedException)
{
}
}
public static string GetErrorMessage(Exception e)
{
// Find initial cause of exception
Exception cause = e;
while (cause.InnerException != null)
{
cause = e.InnerException;
}
// Connection error messages don't need a stacktrace.
if (cause is SocketException || cause is AerospikeException.Connection)
{
return e.Message;
}
// Inner exception stack traces identify the real problem.
return e.Message + Environment.NewLine + cause.StackTrace;
}
public static string ReadFileEncodeBase64(string path)
{
try
{
byte[] bytes = File.ReadAllBytes(path);
return Convert.ToBase64String(bytes);
}
catch (Exception e)
{
throw new AerospikeException("Failed to read " + path, e);
}
}
public static string MapToString(Dictionary<object,object> map)
{
StringBuilder sb = new StringBuilder(200);
MapToString(sb, map);
return sb.ToString();
}
private static void MapToString(StringBuilder sb, Dictionary<object, object> map)
{
sb.Append('[');
int i = 0;
foreach (KeyValuePair<object, object> pair in map)
{
if (i > 0)
{
sb.Append(", ");
}
sb.Append('{');
ObjectToString(sb, pair.Key);
sb.Append(",");
ObjectToString(sb, pair.Value);
sb.Append('}');
i++;
}
sb.Append(']');
}
public static string ListToString(List<object> list)
{
StringBuilder sb = new StringBuilder(200);
ListToString(sb, list);
return sb.ToString();
}
private static void ListToString(StringBuilder sb, List<object> list)
{
sb.Append('[');
for (int i = 0; i < list.Count; i++)
{
if (i > 0)
{
sb.Append(", ");
}
ObjectToString(sb, list[i]);
}
sb.Append(']');
}
public static string ArrayToString(object[] list)
{
StringBuilder sb = new StringBuilder(200);
ArrayToString(sb, list);
return sb.ToString();
}
private static void ArrayToString(StringBuilder sb, object[] list)
{
sb.Append('[');
for (int i = 0; i < list.Length; i++)
{
if (i > 0)
{
sb.Append(", ");
}
ObjectToString(sb, list[i]);
}
sb.Append(']');
}
public static string BytesToString(byte[] bytes)
{
StringBuilder sb = new StringBuilder(200);
sb.Append('[');
for (int i = 0; i < bytes.Length; i++)
{
if (i > 0)
{
sb.Append(", ");
}
sb.Append(bytes[i]);
}
sb.Append(']');
return sb.ToString();
}
public static string ObjectToString(object obj)
{
StringBuilder sb = new StringBuilder(200);
ObjectToString(sb, obj);
return sb.ToString();
}
/// <summary>
/// String conversion for objects containing List, Dictionary and array.
/// </summary>
private static void ObjectToString(StringBuilder sb, object obj)
{
if (obj is object[])
{
ArrayToString(sb, (object[])obj);
return;
}
if (obj is List<object>)
{
ListToString(sb, (List<object>)obj);
return;
}
if (obj is Dictionary<object, object>)
{
MapToString(sb, (Dictionary<object, object>)obj);
return;
}
sb.Append(obj);
}
#if (AS_OPTIMIZE_WINDOWS)
[DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl)]
static extern int memcmp(byte[] b1, byte[] b2, long count);
public static bool ByteArrayEquals(byte[] b1, byte[] b2)
{
return b1.Length == b2.Length && memcmp(b1, b2, b1.Length) == 0;
}
#else
public static bool ByteArrayEquals(byte[] b1, byte[] b2)
{
if (b1.Length != b2.Length)
{
return false;
}
for (int i = 0; i < b1.Length; i++)
{
if (b1[i] != b2[i])
{
return false;
}
}
return true;
}
#endif
}
}
| |
// ==========================================================
// FreeImage 3 .NET wrapper
// Original FreeImage 3 functions and .NET compatible derived functions
//
// Design and implementation by
// - Jean-Philippe Goerke (jpgoerke@users.sourceforge.net)
// - Carsten Klein (cklein05@users.sourceforge.net)
//
// Contributors:
// - David Boland (davidboland@vodafone.ie)
//
// Main reference : MSDN Knowlede Base
//
// This file is part of FreeImage 3
//
// COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES
// THAT THE COVERED CODE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE
// OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED
// CODE IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT
// THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY
// SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL
// PART OF THIS LICENSE. NO USE OF ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER
// THIS DISCLAIMER.
//
// Use at your own risk!
// ==========================================================
// ==========================================================
// CVS
// $Revision: 1.4 $
// $Date: 2008/06/16 15:17:37 $
// $Id: BITMAPINFOHEADER.cs,v 1.4 2008/06/16 15:17:37 cklein05 Exp $
// ==========================================================
using System;
using System.Runtime.InteropServices;
namespace FreeImageAPI
{
/// <summary>
/// This structure contains information about the dimensions and color format
/// of a device-independent bitmap (DIB).
/// </summary>
/// <remarks>
/// The <see cref="FreeImageAPI.BITMAPINFO"/> structure combines the
/// <b>BITMAPINFOHEADER</b> structure and a color table to provide a complete
/// definition of the dimensions and colors of a DIB.
/// </remarks>
[Serializable, StructLayout(LayoutKind.Sequential)]
public struct BITMAPINFOHEADER : IEquatable<BITMAPINFOHEADER>
{
/// <summary>
/// Specifies the size of the structure, in bytes.
/// </summary>
public uint biSize;
/// <summary>
/// Specifies the width of the bitmap, in pixels.
/// <para/>
/// <b>Windows 98/Me, Windows 2000/XP:</b> If <b>biCompression</b> is BI_JPEG or BI_PNG,
/// the <b>biWidth</b> member specifies the width of the decompressed JPEG or PNG image file,
/// respectively.
/// </summary>
public int biWidth;
/// <summary>
/// Specifies the height of the bitmap, in pixels. If <b>biHeight</b> is positive, the bitmap
/// is a bottom-up DIB and its origin is the lower-left corner. If <b>biHeight</b> is negative,
/// the bitmap is a top-down DIB and its origin is the upper-left corner.
/// <para/>
/// If <b>biHeight</b> is negative, indicating a top-down DIB, <b>biCompression</b> must be
/// either BI_RGB or BI_BITFIELDS. Top-down DIBs cannot be compressed.
/// <para/>
/// <b>Windows 98/Me, Windows 2000/XP:</b> If <b>biCompression</b> is BI_JPEG or BI_PNG,
/// the <b>biHeight</b> member specifies the height of the decompressed JPEG or PNG image file,
/// respectively.
/// </summary>
public int biHeight;
/// <summary>
/// Specifies the number of planes for the target device. This value must be set to 1.
/// </summary>
public ushort biPlanes;
/// <summary>
/// Specifies the number of bits per pixel.The biBitCount member of the <b>BITMAPINFOHEADER</b>
/// structure determines the number of bits that define each pixel and the maximum number of
/// colors in the bitmap. This member must be one of the following values.
/// <para/>
///
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <description>Meaning</description>
/// </listheader>
///
/// <item>
/// <term>0</term>
/// <description>
/// <b>Windows 98/Me, Windows 2000/XP:</b> The number of bits-per-pixel is specified
/// or is implied by the JPEG or PNG format.
/// </description>
/// </item>
///
/// <item>
/// <term>1</term>
/// <description>
/// The bitmap is monochrome, and the bmiColors member of <see cref="FreeImageAPI.BITMAPINFO"/>
/// contains two entries. Each bit in the bitmap array represents a pixel. If the bit is clear,
/// the pixel is displayed with the color of the first entry in the bmiColors table; if the bit
/// is set, the pixel has the color of the second entry in the table.
/// </description>
/// </item>
///
/// <item>
/// <term>4</term>
/// <description>
/// The bitmap has a maximum of 16 colors, and the <b>bmiColors</b> member of <b>BITMAPINFO</b>
/// contains up to 16 entries. Each pixel in the bitmap is represented by a 4-bit index into the
/// color table. For example, if the first byte in the bitmap is 0x1F, the byte represents two
/// pixels. The first pixel contains the color in the second table entry, and the second pixel
/// contains the color in the sixteenth table entry.</description>
/// </item>
///
/// <item>
/// <term>8</term>
/// <description>
/// The bitmap has a maximum of 256 colors, and the <b>bmiColors</b> member of <b>BITMAPINFO</b>
/// contains up to 256 entries. In this case, each byte in the array represents a single pixel.
/// </description>
/// </item>
///
/// <item>
/// <term>16</term>
/// <description>
/// The bitmap has a maximum of 2^16 colors. If the <b>biCompression</b> member of the
/// <b>BITMAPINFOHEADER</b> is BI_RGB, the <b>bmiColors</b> member of <b>BITMAPINFO</b> is NULL.
/// Each <b>WORD</b> in the bitmap array represents a single pixel. The relative intensities
/// of red, green, and blue are represented with five bits for each color component.
/// The value for blue is in the least significant five bits, followed by five bits each for
/// green and red. The most significant bit is not used. The <b>bmiColors</b> color table is used
/// for optimizing colors used on palette-based devices, and must contain the number of entries
/// specified by the <b>biClrUsed</b> member of the <b>BITMAPINFOHEADER</b>.
/// <para/>
/// If the <b>biCompression</b> member of the <b>BITMAPINFOHEADER</b> is BI_BITFIELDS, the
/// <b>bmiColors</b> member contains three <b>DWORD</b> color masks that specify the red, green,
/// and blue components, respectively, of each pixel. Each <b>WORD</b> in the bitmap array represents
/// a single pixel.
/// <para/>
/// <b>Windows NT/Windows 2000/XP:</b> When the <b>biCompression</b> member is BI_BITFIELDS,
/// bits set in each <b>DWORD</b> mask must be contiguous and should not overlap the bits
/// of another mask. All the bits in the pixel do not have to be used.
/// <para/>
/// <b>Windows 95/98/Me:</b> When the <b>biCompression</b> member is BI_BITFIELDS, the system
/// supports only the following 16bpp color masks: A 5-5-5 16-bit image, where the blue mask is
/// 0x001F, the green mask is 0x03E0, and the red mask is 0x7C00; and a 5-6-5 16-bit image,
/// where the blue mask is 0x001F, the green mask is 0x07E0, and the red mask is 0xF800.
/// </description>
/// </item>
///
/// <item>
/// <term>24</term>
/// <description>
/// The bitmap has a maximum of 2^24 colors, and the <b>bmiColors</b> member of <b>BITMAPINFO</b>
/// is NULL. Each 3-byte triplet in the bitmap array represents the relative intensities of blue,
/// green, and red, respectively, for a pixel. The <b>bmiColors</b> color table is used for
/// optimizing colors used on palette-based devices, and must contain the number of entries
/// specified by the <b>biClrUsed</b> member of the <b>BITMAPINFOHEADER</b>.
/// </description>
/// </item>
///
/// <item>
/// <term>32</term>
/// <description>
/// The bitmap has a maximum of 2^32 colors. If the <b>biCompression</b> member of the
/// <b>BITMAPINFOHEADER</b> is BI_RGB, the <b>bmiColors</b> member of <b>BITMAPINFO</b> is NULL.
/// Each <b>DWORD</b> in the bitmap array represents the relative intensities of blue, green, and red,
/// respectively, for a pixel. The high byte in each <b>DWORD</b> is not used. The <b>bmiColors</b>
/// color table is used for optimizing colors used on palette-based devices, and must contain the
/// number of entries specified by the <b>biClrUsed</b> member of the <b>BITMAPINFOHEADER</b>.
/// <para/>
/// If the <b>biCompression</b> member of the <b>BITMAPINFOHEADER</b> is BI_BITFIELDS,
/// the <b>bmiColors</b> member contains three <b>DWORD</b> color masks that specify the red, green,
/// and blue components, respectively, of each pixel. Each <b>DWORD</b> in the bitmap array represents
/// a single pixel.
/// <para/>
/// <b>Windows NT/ 2000:</b> When the <b>biCompression</b> member is BI_BITFIELDS, bits set in each
/// <b>DWORD</b> mask must be contiguous and should not overlap the bits of another mask. All the
/// bits in the pixel do not need to be used.
/// <para/>
/// <b>Windows 95/98/Me:</b> When the <b>biCompression</b> member is BI_BITFIELDS, the system
/// supports only the following 32-bpp color mask: The blue mask is 0x000000FF, the green mask is
/// 0x0000FF00, and the red mask is 0x00FF0000.
/// </description>
/// </item>
/// </list>
/// </summary>
public ushort biBitCount;
/// <summary>
/// Specifies the type of compression for a compressed bottom-up bitmap (top-down DIBs cannot be
/// compressed).
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <description>Meaning</description>
/// </listheader>
///
/// <item>
/// <term>BI_RGB</term>
/// <description>An uncompressed format.</description>
/// </item>
///
/// <item>
/// <term>BI_RLE8</term>
/// <description>A run-length encoded (RLE) format for bitmaps with 8 bpp. The compression format
/// is a 2-byte format consisting of a count byte followed by a byte containing a color index.
/// </description>
/// </item>
///
/// <item>
/// <term>BI_RLE4</term>
/// <description>An RLE format for bitmaps with 4 bpp. The compression format is a 2-byte format
/// consisting of a count byte followed by two word-length color indexes.</description>
/// </item>
///
/// <item>
/// <term>BI_BITFIELDS</term>
/// <description>Specifies that the bitmap is not compressed and that the color table consists
/// of three <b>DWORD</b> color masks that specify the red, green, and blue components, respectively,
/// of each pixel. This is valid when used with 16- and 32-bpp bitmaps.</description>
/// </item>
///
/// <item>
/// <term>BI_JPEG</term>
/// <description><b>Windows 98/Me, Windows 2000/XP:</b> Indicates that the image is a JPEG image.
/// </description>
/// </item>
///
/// <item>
/// <term>BI_PNG</term>
/// <description><b>Windows 98/Me, Windows 2000/XP:</b> Indicates that the image is a PNG image.
/// </description>
/// </item>
///
/// </list>
/// </summary>
public uint biCompression;
/// <summary>
/// Specifies the size, in bytes, of the image. This may be set to zero for BI_RGB bitmaps.
/// <para/>
/// <b>Windows 98/Me, Windows 2000/XP:</b> If <b>biCompression</b> is BI_JPEG or BI_PNG,
/// <b>biSizeImage</b> indicates the size of the JPEG or PNG image buffer, respectively.
/// </summary>
public uint biSizeImage;
/// <summary>
/// Specifies the horizontal resolution, in pixels-per-meter, of the target device for the bitmap.
/// An application can use this value to select a bitmap from a resource group that best matches
/// the characteristics of the current device.
/// </summary>
public int biXPelsPerMeter;
/// <summary>
/// Specifies the vertical resolution, in pixels-per-meter, of the target device for the bitmap.
/// </summary>
public int biYPelsPerMeter;
/// <summary>
/// Specifies the number of color indexes in the color table that are actually used by the bitmap.
/// If this value is zero, the bitmap uses the maximum number of colors corresponding to the value
/// of the biBitCount member for the compression mode specified by <b>biCompression</b>.
/// <para/>
/// If <b>iClrUsed</b> is nonzero and the <b>biBitCount</b> member is less than 16, the <b>biClrUsed</b>
/// member specifies the actual number of colors the graphics engine or device driver accesses.
/// If <b>biBitCount</b> is 16 or greater, the <b>biClrUsed</b> member specifies the size of the color
/// table used to optimize performance of the system color palettes. If <b>biBitCount</b> equals 16 or 32,
/// the optimal color palette starts immediately following the three <b>DWORD</b> masks.
/// <para/>
/// When the bitmap array immediately follows the <see cref="BITMAPINFO"/> structure, it is a packed bitmap.
/// Packed bitmaps are referenced by a single pointer. Packed bitmaps require that the
/// <b>biClrUsed</b> member must be either zero or the actual size of the color table.
/// </summary>
public uint biClrUsed;
/// <summary>
/// Specifies the number of color indexes that are required for displaying the bitmap. If this value
/// is zero, all colors are required.
/// </summary>
public uint biClrImportant;
/// <summary>
/// Tests whether two specified <see cref="BITMAPINFOHEADER"/> structures are equivalent.
/// </summary>
/// <param name="left">The <see cref="BITMAPINFOHEADER"/> that is to the left of the equality operator.</param>
/// <param name="right">The <see cref="BITMAPINFOHEADER"/> that is to the right of the equality operator.</param>
/// <returns>
/// <b>true</b> if the two <see cref="BITMAPINFOHEADER"/> structures are equal; otherwise, <b>false</b>.
/// </returns>
public static bool operator ==(BITMAPINFOHEADER left, BITMAPINFOHEADER right)
{
return ((left.biSize == right.biSize) &&
(left.biWidth == right.biWidth) &&
(left.biHeight == right.biHeight) &&
(left.biPlanes == right.biPlanes) &&
(left.biBitCount == right.biBitCount) &&
(left.biCompression == right.biCompression) &&
(left.biSizeImage == right.biSizeImage) &&
(left.biXPelsPerMeter == right.biXPelsPerMeter) &&
(left.biYPelsPerMeter == right.biYPelsPerMeter) &&
(left.biClrUsed == right.biClrUsed) &&
(left.biClrImportant == right.biClrImportant));
}
/// <summary>
/// Tests whether two specified <see cref="BITMAPINFOHEADER"/> structures are different.
/// </summary>
/// <param name="left">The <see cref="BITMAPINFOHEADER"/> that is to the left of the inequality operator.</param>
/// <param name="right">The <see cref="BITMAPINFOHEADER"/> that is to the right of the inequality operator.</param>
/// <returns>
/// <b>true</b> if the two <see cref="BITMAPINFOHEADER"/> structures are different; otherwise, <b>false</b>.
/// </returns>
public static bool operator !=(BITMAPINFOHEADER left, BITMAPINFOHEADER right)
{
return !(left == right);
}
/// <summary>
/// Tests whether the specified <see cref="BITMAPINFOHEADER"/> structure is equivalent to this <see cref="BITMAPINFOHEADER"/> structure.
/// </summary>
/// <param name="other">A <see cref="BITMAPINFOHEADER"/> structure to compare to this instance.</param>
/// <returns><b>true</b> if <paramref name="obj"/> is a <see cref="BITMAPINFOHEADER"/> structure
/// equivalent to this <see cref="BITMAPINFOHEADER"/> structure; otherwise, <b>false</b>.</returns>
public bool Equals(BITMAPINFOHEADER other)
{
return (this == other);
}
/// <summary>
/// Tests whether the specified object is a <see cref="BITMAPINFOHEADER"/> structure
/// and is equivalent to this <see cref="BITMAPINFOHEADER"/> structure.
/// </summary>
/// <param name="obj">The object to test.</param>
/// <returns><b>true</b> if <paramref name="obj"/> is a <see cref="BITMAPINFOHEADER"/> structure
/// equivalent to this <see cref="BITMAPINFOHEADER"/> structure; otherwise, <b>false</b>.</returns>
public override bool Equals(object obj)
{
return ((obj is BITMAPINFOHEADER) && (this == (BITMAPINFOHEADER)obj));
}
/// <summary>
/// Returns a hash code for this <see cref="BITMAPINFOHEADER"/> structure.
/// </summary>
/// <returns>An integer value that specifies the hash code for this <see cref="BITMAPINFOHEADER"/>.</returns>
public override int GetHashCode()
{
return base.GetHashCode();
}
}
}
| |
// 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;
public class TestEmptyClass
{
}
public abstract class TestAbstractClass
{
public TestAbstractClass()
{
x = 1;
x--;
}
public abstract void TestAbstractMethod();
private int x;
}
public class TestClass : TestAbstractClass
{
public override void TestAbstractMethod()
{
}
public void TestMethod()
{
}
}
public struct TestStruct1
{
public TestStruct1(int value)
{
m_value = value;
}
int m_value;
}
public struct TestStruct2
{
public TestStruct2(int value)
{
m_value = value;
}
int m_value;
}
public enum TestEnum1
{
DEFAULT
}
public enum TestEnum2
{
DEFAULT
}
/// <summary>
/// Equals(System.Object)
/// </summary>
public class RuntimeTypeHandleEquals
{
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: Equals should return true when comparing with itself");
try
{
RuntimeTypeHandle handle = typeof(TestEmptyClass).TypeHandle;
if (!handle.Equals(handle))
{
TestLibrary.TestFramework.LogError("001.1", "Equals returns false when comparing with itself");
retVal = false;
}
handle = typeof(TestStruct1).TypeHandle;
if (!handle.Equals(handle))
{
TestLibrary.TestFramework.LogError("001.2", "Equals returns false when comparing with itself");
retVal = false;
}
handle = typeof(TestEnum1).TypeHandle;
if (!handle.Equals(handle))
{
TestLibrary.TestFramework.LogError("001.3", "Equals returns false when comparing with itself");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001.4", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: Equals should return true when comparing with instance of same classes");
try
{
TestEmptyClass ec1 = new TestEmptyClass();
TestEmptyClass ec2 = new TestEmptyClass();
RuntimeTypeHandle handle1 = ec1.GetType().TypeHandle;
RuntimeTypeHandle handle2 = ec2.GetType().TypeHandle;
if (!handle1.Equals(handle2))
{
TestLibrary.TestFramework.LogError("002.1", "Equals returns false when comparing with instance of same classe");
retVal = false;
}
TestStruct1 ts1 = new TestStruct1();
TestStruct1 ts2 = new TestStruct1();
handle1 = ts1.GetType().TypeHandle;
handle2 = ts2.GetType().TypeHandle;
if (!handle1.Equals(handle2))
{
TestLibrary.TestFramework.LogError("002.2", "Equals returns false when comparing with instance of same structs");
retVal = false;
}
TestEnum1 te1 = TestEnum1.DEFAULT;
TestEnum1 te2 = TestEnum1.DEFAULT;
handle1 = te1.GetType().TypeHandle;
handle2 = te2.GetType().TypeHandle;
if (!handle1.Equals(handle2))
{
TestLibrary.TestFramework.LogError("002.3", "Equals returns false when comparing with instance of same enums");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002.4", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: Equals should return false when comparing with instance of different classes");
try
{
TestEmptyClass classInstance1 = new TestEmptyClass();
TestClass classInstance2 = new TestClass();
RuntimeTypeHandle classInstanceHandle1 = classInstance1.GetType().TypeHandle;
RuntimeTypeHandle classInstanceHandle2 = classInstance2.GetType().TypeHandle;
if (classInstanceHandle1.Equals(classInstanceHandle2))
{
TestLibrary.TestFramework.LogError("003.1", "Equals returns true when comparing with instance of different classe");
retVal = false;
}
TestStruct1 ts1 = new TestStruct1();
TestStruct2 ts2 = new TestStruct2();
RuntimeTypeHandle structHandle1 = ts1.GetType().TypeHandle;
RuntimeTypeHandle structHandle2 = ts2.GetType().TypeHandle;
if (structHandle1.Equals(structHandle2))
{
TestLibrary.TestFramework.LogError("003.2", "Equals returns false when comparing with instance of different structs");
retVal = false;
}
TestEnum1 te1 = TestEnum1.DEFAULT;
TestEnum2 te2 = TestEnum2.DEFAULT;
RuntimeTypeHandle enumHandle1 = te1.GetType().TypeHandle;
RuntimeTypeHandle enumHandle2 = te2.GetType().TypeHandle;
if (enumHandle1.Equals(enumHandle2))
{
TestLibrary.TestFramework.LogError("003.3", "Equals returns false when comparing with instance of different enums");
retVal = false;
}
if (classInstanceHandle1.Equals(structHandle1))
{
TestLibrary.TestFramework.LogError("003.4", "Equals returns false when comparing a instance of struct with a instance of class");
retVal = false;
}
if (classInstanceHandle1.Equals(enumHandle1))
{
TestLibrary.TestFramework.LogError("003.5", "Equals returns false when comparing a instance of enum with a instance of class");
retVal = false;
}
if (structHandle1.Equals(enumHandle1))
{
TestLibrary.TestFramework.LogError("003.6", "Equals returns false when comparing a instance of struct with a instance of enum");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("003.7", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4: Equals should return false when comparing with a invalid value");
try
{
RuntimeTypeHandle handle = typeof(TestClass).TypeHandle;
if (handle.Equals(null))
{
TestLibrary.TestFramework.LogError("004.1", "Equals returns true when comparing with a null");
retVal = false;
}
if (handle.Equals(new Object()))
{
TestLibrary.TestFramework.LogError("004.2", "Equals returns true when comparing with a instance of object");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004.3", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest5: Equals should return false when comparing with RuntimeTypeHandle of base class");
try
{
RuntimeTypeHandle handle1 = typeof(TestClass).TypeHandle;
RuntimeTypeHandle handle2 = typeof(Object).TypeHandle;
if (handle1.Equals(handle2))
{
TestLibrary.TestFramework.LogError("005.1", "Equals returns true when comparing with RuntimeTypeHandle of base class");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("005.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
RuntimeTypeHandleEquals test = new RuntimeTypeHandleEquals();
TestLibrary.TestFramework.BeginTestCase("RuntimeTypeHandleEquals");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using Avalonia.Data;
#nullable enable
namespace Avalonia.Animation
{
/// <summary>
/// Base class for all animatable objects.
/// </summary>
public class Animatable : AvaloniaObject
{
/// <summary>
/// Defines the <see cref="Clock"/> property.
/// </summary>
public static readonly StyledProperty<IClock> ClockProperty =
AvaloniaProperty.Register<Animatable, IClock>(nameof(Clock), inherits: true);
/// <summary>
/// Defines the <see cref="Transitions"/> property.
/// </summary>
public static readonly StyledProperty<Transitions?> TransitionsProperty =
AvaloniaProperty.Register<Animatable, Transitions?>(nameof(Transitions));
private bool _transitionsEnabled = true;
private Dictionary<ITransition, TransitionState>? _transitionState;
/// <summary>
/// Gets or sets the clock which controls the animations on the control.
/// </summary>
public IClock Clock
{
get => GetValue(ClockProperty);
set => SetValue(ClockProperty, value);
}
/// <summary>
/// Gets or sets the property transitions for the control.
/// </summary>
public Transitions? Transitions
{
get => GetValue(TransitionsProperty);
set => SetValue(TransitionsProperty, value);
}
/// <summary>
/// Enables transitions for the control.
/// </summary>
/// <remarks>
/// This method should not be called from user code, it will be called automatically by the framework
/// when a control is added to the visual tree.
/// </remarks>
protected void EnableTransitions()
{
if (!_transitionsEnabled)
{
_transitionsEnabled = true;
if (Transitions is object)
{
AddTransitions(Transitions);
}
}
}
/// <summary>
/// Disables transitions for the control.
/// </summary>
/// <remarks>
/// This method should not be called from user code, it will be called automatically by the framework
/// when a control is added to the visual tree.
/// </remarks>
protected void DisableTransitions()
{
if (_transitionsEnabled)
{
_transitionsEnabled = false;
if (Transitions is object)
{
RemoveTransitions(Transitions);
}
}
}
protected sealed override void OnPropertyChangedCore<T>(AvaloniaPropertyChangedEventArgs<T> change)
{
if (change.Property == TransitionsProperty && change.IsEffectiveValueChange)
{
var oldTransitions = change.OldValue.GetValueOrDefault<Transitions>();
var newTransitions = change.NewValue.GetValueOrDefault<Transitions>();
// When transitions are replaced, we add the new transitions before removing the old
// transitions, so that when the old transition being disposed causes the value to
// change, there is a corresponding entry in `_transitionStates`. This means that we
// need to account for any transitions present in both the old and new transitions
// collections.
if (newTransitions is object)
{
var toAdd = (IList)newTransitions;
if (newTransitions.Count > 0 && oldTransitions?.Count > 0)
{
toAdd = newTransitions.Except(oldTransitions).ToList();
}
newTransitions.CollectionChanged += TransitionsCollectionChanged;
AddTransitions(toAdd);
}
if (oldTransitions is object)
{
var toRemove = (IList)oldTransitions;
if (oldTransitions.Count > 0 && newTransitions?.Count > 0)
{
toRemove = oldTransitions.Except(newTransitions).ToList();
}
oldTransitions.CollectionChanged -= TransitionsCollectionChanged;
RemoveTransitions(toRemove);
}
}
else if (_transitionsEnabled &&
Transitions is object &&
_transitionState is object &&
!change.Property.IsDirect &&
change.Priority > BindingPriority.Animation)
{
for (var i = Transitions.Count -1; i >= 0; --i)
{
var transition = Transitions[i];
if (transition.Property == change.Property &&
_transitionState.TryGetValue(transition, out var state))
{
var oldValue = state.BaseValue;
var newValue = GetAnimationBaseValue(transition.Property);
if (!Equals(oldValue, newValue))
{
state.BaseValue = newValue;
// We need to transition from the current animated value if present,
// instead of the old base value.
var animatedValue = GetValue(transition.Property);
if (!Equals(newValue, animatedValue))
{
oldValue = animatedValue;
}
state.Instance?.Dispose();
state.Instance = transition.Apply(
this,
Clock ?? AvaloniaLocator.Current.GetRequiredService<IGlobalClock>(),
oldValue,
newValue);
return;
}
}
}
}
base.OnPropertyChangedCore(change);
}
private void TransitionsCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e)
{
if (!_transitionsEnabled)
{
return;
}
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
AddTransitions(e.NewItems!);
break;
case NotifyCollectionChangedAction.Remove:
RemoveTransitions(e.OldItems!);
break;
case NotifyCollectionChangedAction.Replace:
RemoveTransitions(e.OldItems!);
AddTransitions(e.NewItems!);
break;
case NotifyCollectionChangedAction.Reset:
throw new NotSupportedException("Transitions collection cannot be reset.");
}
}
private void AddTransitions(IList items)
{
if (!_transitionsEnabled)
{
return;
}
_transitionState ??= new Dictionary<ITransition, TransitionState>();
for (var i = 0; i < items.Count; ++i)
{
var t = (ITransition)items[i]!;
_transitionState.Add(t, new TransitionState
{
BaseValue = GetAnimationBaseValue(t.Property),
});
}
}
private void RemoveTransitions(IList items)
{
if (_transitionState is null)
{
return;
}
for (var i = 0; i < items.Count; ++i)
{
var t = (ITransition)items[i]!;
if (_transitionState.TryGetValue(t, out var state))
{
state.Instance?.Dispose();
_transitionState.Remove(t);
}
}
}
private object? GetAnimationBaseValue(AvaloniaProperty property)
{
var value = this.GetBaseValue(property, BindingPriority.LocalValue);
if (value == AvaloniaProperty.UnsetValue)
{
value = GetValue(property);
}
return value;
}
private class TransitionState
{
public IDisposable? Instance { get; set; }
public object? BaseValue { get; set; }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading.Tasks;
using Abp.Extensions;
using Abp.MultiTenancy;
using Abp.Runtime.Session;
namespace Abp.Domain.Uow
{
/// <summary>
/// Base for all Unit Of Work classes.
/// </summary>
public abstract class UnitOfWorkBase : IUnitOfWork
{
public string Id { get; private set; }
public IUnitOfWork Outer { get; set; }
/// <inheritdoc/>
public event EventHandler Completed;
/// <inheritdoc/>
public event EventHandler<UnitOfWorkFailedEventArgs> Failed;
/// <inheritdoc/>
public event EventHandler Disposed;
/// <inheritdoc/>
public UnitOfWorkOptions Options { get; private set; }
/// <inheritdoc/>
public IReadOnlyList<DataFilterConfiguration> Filters
{
get { return _filters.ToImmutableList(); }
}
private readonly List<DataFilterConfiguration> _filters;
/// <summary>
/// Gets a value indicates that this unit of work is disposed or not.
/// </summary>
public bool IsDisposed { get; private set; }
/// <summary>
/// Reference to current ABP session.
/// </summary>
public IAbpSession AbpSession { private get; set; }
/// <summary>
/// Is <see cref="Begin"/> method called before?
/// </summary>
private bool _isBeginCalledBefore;
/// <summary>
/// Is <see cref="Complete"/> method called before?
/// </summary>
private bool _isCompleteCalledBefore;
/// <summary>
/// Is this unit of work successfully completed.
/// </summary>
private bool _succeed;
/// <summary>
/// A reference to the exception if this unit of work failed.
/// </summary>
private Exception _exception;
/// <summary>
/// Constructor.
/// </summary>
protected UnitOfWorkBase(IUnitOfWorkDefaultOptions defaultOptions)
{
Id = Guid.NewGuid().ToString("N");
_filters = defaultOptions.Filters.ToList();
AbpSession = NullAbpSession.Instance;
}
/// <inheritdoc/>
public void Begin(UnitOfWorkOptions options)
{
if (options == null)
{
throw new ArgumentNullException("options");
}
PreventMultipleBegin();
Options = options; //TODO: Do not set options like that!
SetFilters(options.FilterOverrides);
BeginUow();
}
/// <inheritdoc/>
public abstract void SaveChanges();
/// <inheritdoc/>
public abstract Task SaveChangesAsync();
/// <inheritdoc/>
public IDisposable DisableFilter(params string[] filterNames)
{
//TODO: Check if filters exists?
var disabledFilters = new List<string>();
foreach (var filterName in filterNames)
{
var filterIndex = GetFilterIndex(filterName);
if (_filters[filterIndex].IsEnabled)
{
disabledFilters.Add(filterName);
_filters[filterIndex] = new DataFilterConfiguration(filterName, false);
}
}
disabledFilters.ForEach(ApplyDisableFilter);
return new DisposeAction(() => EnableFilter(disabledFilters.ToArray()));
}
/// <inheritdoc/>
public IDisposable EnableFilter(params string[] filterNames)
{
//TODO: Check if filters exists?
var enabledFilters = new List<string>();
foreach (var filterName in filterNames)
{
var filterIndex = GetFilterIndex(filterName);
if (!_filters[filterIndex].IsEnabled)
{
enabledFilters.Add(filterName);
_filters[filterIndex] = new DataFilterConfiguration(filterName, true);
}
}
enabledFilters.ForEach(ApplyEnableFilter);
return new DisposeAction(() => DisableFilter(enabledFilters.ToArray()));
}
/// <inheritdoc/>
public bool IsFilterEnabled(string filterName)
{
return GetFilter(filterName).IsEnabled;
}
/// <inheritdoc/>
public void SetFilterParameter(string filterName, string parameterName, object value)
{
var filterIndex = GetFilterIndex(filterName);
var newfilter = new DataFilterConfiguration(_filters[filterIndex]);
newfilter.FilterParameters[parameterName] = value;
_filters[filterIndex] = newfilter;
ApplyFilterParameterValue(filterName, parameterName, value);
}
/// <inheritdoc/>
public void Complete()
{
PreventMultipleComplete();
try
{
CompleteUow();
_succeed = true;
OnCompleted();
}
catch (Exception ex)
{
_exception = ex;
throw;
}
}
/// <inheritdoc/>
public async Task CompleteAsync()
{
PreventMultipleComplete();
try
{
await CompleteUowAsync();
_succeed = true;
OnCompleted();
}
catch (Exception ex)
{
_exception = ex;
throw;
}
}
/// <inheritdoc/>
public void Dispose()
{
if (IsDisposed)
{
return;
}
IsDisposed = true;
if (!_succeed)
{
OnFailed(_exception);
}
DisposeUow();
OnDisposed();
}
/// <summary>
/// Should be implemented by derived classes to start UOW.
/// </summary>
protected abstract void BeginUow();
/// <summary>
/// Should be implemented by derived classes to complete UOW.
/// </summary>
protected abstract void CompleteUow();
/// <summary>
/// Should be implemented by derived classes to complete UOW.
/// </summary>
protected abstract Task CompleteUowAsync();
/// <summary>
/// Should be implemented by derived classes to dispose UOW.
/// </summary>
protected abstract void DisposeUow();
/// <summary>
/// Concrete Unit of work classes should implement this
/// method in order to disable a filter.
/// Should not call base method since it throws <see cref="NotImplementedException"/>.
/// </summary>
/// <param name="filterName">Filter name</param>
protected virtual void ApplyDisableFilter(string filterName)
{
throw new NotImplementedException("DisableFilter is not implemented for " + GetType().FullName);
}
/// <summary>
/// Concrete Unit of work classes should implement this
/// method in order to enable a filter.
/// Should not call base method since it throws <see cref="NotImplementedException"/>.
/// </summary>
/// <param name="filterName">Filter name</param>
protected virtual void ApplyEnableFilter(string filterName)
{
throw new NotImplementedException("EnableFilter is not implemented for " + GetType().FullName);
}
/// <summary>
/// Concrete Unit of work classes should implement this
/// method in order to set a parameter's value.
/// Should not call base method since it throws <see cref="NotImplementedException"/>.
/// </summary>
/// <param name="filterName">Filter name</param>
protected virtual void ApplyFilterParameterValue(string filterName, string parameterName, object value)
{
throw new NotImplementedException("SetFilterParameterValue is not implemented for " + GetType().FullName);
}
/// <summary>
/// Called to trigger <see cref="Completed"/> event.
/// </summary>
protected virtual void OnCompleted()
{
Completed.InvokeSafely(this);
}
/// <summary>
/// Called to trigger <see cref="Failed"/> event.
/// </summary>
/// <param name="exception">Exception that cause failure</param>
protected virtual void OnFailed(Exception exception)
{
Failed.InvokeSafely(this, new UnitOfWorkFailedEventArgs(exception));
}
/// <summary>
/// Called to trigger <see cref="Disposed"/> event.
/// </summary>
protected virtual void OnDisposed()
{
Disposed.InvokeSafely(this);
}
private void PreventMultipleBegin()
{
if (_isBeginCalledBefore)
{
throw new AbpException("This unit of work has started before. Can not call Start method more than once.");
}
_isBeginCalledBefore = true;
}
private void PreventMultipleComplete()
{
if (_isCompleteCalledBefore)
{
throw new AbpException("Complete is called before!");
}
_isCompleteCalledBefore = true;
}
private void SetFilters(List<DataFilterConfiguration> filterOverrides)
{
for (var i = 0; i < _filters.Count; i++)
{
var filterOverride = filterOverrides.FirstOrDefault(f => f.FilterName == _filters[i].FilterName);
if (filterOverride != null)
{
_filters[i] = filterOverride;
}
}
if (!AbpSession.UserId.HasValue || AbpSession.MultiTenancySide == MultiTenancySides.Host)
{
ChangeFilterIsEnabledIfNotOverrided(filterOverrides, AbpDataFilters.MustHaveTenant, false);
}
}
private void ChangeFilterIsEnabledIfNotOverrided(List<DataFilterConfiguration> filterOverrides, string filterName, bool isEnabled)
{
if (filterOverrides.Any(f => f.FilterName == filterName))
{
return;
}
var index = _filters.FindIndex(f => f.FilterName == filterName);
if (index < 0)
{
return;
}
if (_filters[index].IsEnabled == isEnabled)
{
return;
}
_filters[index] = new DataFilterConfiguration(filterName, isEnabled);
}
private DataFilterConfiguration GetFilter(string filterName)
{
var filter = _filters.FirstOrDefault(f => f.FilterName == filterName);
if (filter == null)
{
throw new AbpException("Unknown filter name: " + filterName + ". Be sure this filter is registered before.");
}
return filter;
}
private int GetFilterIndex(string filterName)
{
var filterIndex = _filters.FindIndex(f => f.FilterName == filterName);
if (filterIndex < 0)
{
throw new AbpException("Unknown filter name: " + filterName + ". Be sure this filter is registered before.");
}
return filterIndex;
}
}
}
| |
// 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.Xml.Linq;
using Xunit;
namespace CoreXml.Test.XLinq
{
public partial class ImplicitConversionsElem
{
// these tests are duplication of the
// valid cases
// - direct value
// - concat value
// - concat of text
// - text & CData
// - concat from children
// - removing, adding and modifying nodes sanity
// invalid cases (sanity, pri2)
[Theory]
[InlineData("<A>text</A>", "text")]
[InlineData("<A>text1<B/>text2</A>", "text1text2")]
[InlineData("<A>text1<B/><![CDATA[text2]]></A>", "text1text2")]
[InlineData("<A><B>text1<D><![CDATA[text2]]></D></B><C>text3</C></A>", "text1text2text3")]
[InlineData("<A><B><D></D></B><C></C></A>", "")]
[InlineData("<A><B><D><![CDATA[]]></D></B><C></C></A>", "")]
public void StringConvert(string xml, string expected)
{
XElement elem = XElement.Parse(xml);
Assert.Equal(expected, (string)elem);
}
[Theory]
[InlineData("<A>true</A>", true)]
[InlineData("<A>1</A>", true)]
[InlineData("<A>false</A>", false)]
[InlineData("<A>0</A>", false)]
[InlineData("<A>tr<B/>ue</A>", true)]
[InlineData("<A>f<B/>alse</A>", false)]
[InlineData("<A>tru<B/><![CDATA[e]]></A>", true)]
[InlineData("<A>fal<B/><![CDATA[se]]></A>", false)]
[InlineData("<A><B>t<D><![CDATA[ru]]></D></B><C>e</C></A>", true)]
[InlineData("<A> <B><D><![CDATA[1]]></D></B><C> </C></A>", true)]
[InlineData("<A><B>fa<D><![CDATA[l]]></D></B><C>se</C></A>", false)]
[InlineData("<A><B> <D><![CDATA[ ]]></D></B><C>0</C></A>", false)]
public void BoolConvert(string xml, bool expected)
{
XElement elem = XElement.Parse(xml);
Assert.Equal(expected, (bool)elem);
}
[Theory]
[InlineData("<A></A>")]
[InlineData("<A>2</A>")]
public void BoolConvertInvalid(string xml)
{
XElement elem = XElement.Parse(xml);
Assert.Throws<FormatException>(() => (bool)elem);
}
[Theory]
[InlineData("<A>true</A>", true)]
[InlineData("<A>1</A>", true)]
[InlineData("<A>false</A>", false)]
[InlineData("<A>0</A>", false)]
[InlineData("<A>tr<B/>ue</A>", true)]
[InlineData("<A>f<B/>alse</A>", false)]
[InlineData("<A>tru<B/><![CDATA[e]]></A>", true)]
[InlineData("<A>fal<B/><![CDATA[se]]></A>", false)]
[InlineData("<A><B>t<D><![CDATA[ru]]></D></B><C>e</C></A>", true)]
[InlineData("<A> <B><D><![CDATA[1]]></D></B><C> </C></A>", true)]
[InlineData("<A><B>fa<D><![CDATA[l]]></D></B><C>se</C></A>", false)]
[InlineData("<A><B> <D><![CDATA[ ]]></D></B><C>0</C></A>", false)]
public void BoolQConvert(string xml, bool? expected)
{
XElement elem = XElement.Parse(xml);
Assert.Equal(expected, (bool?)elem);
}
[Theory]
[InlineData("<A a='1'></A>")]
[InlineData("<A a='1'>tr<B/> ue</A>")]
[InlineData("<A a='1'>2</A>")]
public void BoolQConvertInvalid(string xml)
{
XElement elem = XElement.Parse(xml);
Assert.Throws<FormatException>(() => (bool?)elem);
}
[Fact]
public void BoolQConvertNull()
{
XElement elem = null;
Assert.Null((bool?)elem);
}
[Theory]
[InlineData("<A a='1'>10</A>", 10)]
[InlineData("<A a='1'>1<B/>7</A>", 17)]
[InlineData("<A a='1'>-<B/><![CDATA[21]]></A>", -21)]
[InlineData("<A a='1'><B>-<D><![CDATA[12]]></D></B><C>0</C></A>", -120)]
public void IntConvert(string xml, int expected)
{
XElement elem = XElement.Parse(xml);
Assert.Equal(expected, (int)elem);
}
[Theory]
[InlineData("<A a='1'></A>")]
[InlineData("<A a='1'>2<B/> 1</A>")]
[InlineData("<A a='1'>X</A>")]
public void IntConvertInvalid(string xml)
{
XElement elem = XElement.Parse(xml);
Assert.Throws<FormatException>(() => (int)elem);
}
[Theory]
[InlineData("<A a='1'>10</A>", 10)]
[InlineData("<A a='1'>1<B/>7</A>", 17)]
[InlineData("<A a='1'>-<B/><![CDATA[21]]></A>", -21)]
[InlineData("<A a='1'><B>-<D><![CDATA[12]]></D></B><C>0</C></A>", -120)]
public void IntQConvert(string xml, int? expected)
{
XElement elem = XElement.Parse(xml);
Assert.Equal(expected, (int?)elem);
}
[Theory]
[InlineData("<A a='1'></A>")]
[InlineData("<A a='1'>2<B/> 1</A>")]
[InlineData("<A a='1'>X</A>")]
public void IntQConvertInvalid(string xml)
{
XElement elem = XElement.Parse(xml);
Assert.Throws<FormatException>(() => (int?)elem);
}
[Fact]
public void IntQConvertNull()
{
XElement elem = null;
Assert.Null((int?)elem);
}
[Theory]
[InlineData("<A a='1'>10</A>", 10)]
[InlineData("<A a='1'>1<B/>7</A>", 17)]
[InlineData("<A a='1'><B/><![CDATA[21]]></A>", 21)]
[InlineData("<A a='1'><B><D><![CDATA[12]]></D></B><C>0</C></A>", 120)]
public void UIntConvert(string xml, uint expected)
{
XElement elem = XElement.Parse(xml);
Assert.Equal(expected, (uint)elem);
}
[Theory]
[InlineData("<A a='1'></A>")]
[InlineData("<A a='1'>2<B/> 1</A>")]
[InlineData("<A a='1'>-<B/>1</A>")]
[InlineData("<A a='1'>X</A>")]
public void UIntConvertInvalid(string xml)
{
XElement elem = XElement.Parse(xml);
Assert.Throws<FormatException>(() => (uint)elem);
}
[Theory]
[InlineData("<A a='1'>10</A>", 10u)]
[InlineData("<A a='1'>1<B/>7</A>", 17u)]
[InlineData("<A a='1'><B/><![CDATA[21]]></A>", 21u)]
[InlineData("<A a='1'><B><D><![CDATA[12]]></D></B><C>0</C></A>", 120u)]
public void UIntQConvert(string xml, uint? expected)
{
XElement elem = XElement.Parse(xml);
Assert.Equal(expected, (uint?)elem);
}
[Theory]
[InlineData("<A a='1'></A>")]
[InlineData("<A a='1'>2<B/> 1</A>")]
[InlineData("<A a='1'>-<B/>1</A>")]
[InlineData("<A a='1'>X</A>")]
public void UIntQConvertInvalid(string xml)
{
XElement elem = XElement.Parse(xml);
Assert.Throws<FormatException>(() => (uint?)elem);
}
[Fact]
public void UIntQConvertNull()
{
XElement elem = null;
Assert.Null((uint?)elem);
}
}
}
| |
// 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.
/*============================================================
**
**
**
** Purpose: Capture execution context for a thread
**
**
===========================================================*/
namespace System.Threading
{
using System;
using System.Security;
using System.Runtime.Remoting;
using System.Security.Principal;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.ExceptionServices;
using System.Runtime.Serialization;
using System.Security.Permissions;
#if FEATURE_REMOTING
using System.Runtime.Remoting.Messaging;
#endif // FEATURE_REMOTING
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Diagnostics.Contracts;
using System.Diagnostics.CodeAnalysis;
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
[System.Runtime.InteropServices.ComVisible(true)]
public delegate void ContextCallback(Object state);
#if FEATURE_CORECLR
[SecurityCritical]
internal struct ExecutionContextSwitcher
{
internal ExecutionContext m_ec;
internal SynchronizationContext m_sc;
internal void Undo()
{
SynchronizationContext.SetSynchronizationContext(m_sc);
ExecutionContext.Restore(m_ec);
}
}
public sealed class ExecutionContext : IDisposable
{
private static readonly ExecutionContext Default = new ExecutionContext();
[ThreadStatic]
[SecurityCritical]
static ExecutionContext t_currentMaybeNull;
private readonly Dictionary<IAsyncLocal, object> m_localValues;
private readonly IAsyncLocal[] m_localChangeNotifications;
private ExecutionContext()
{
m_localValues = new Dictionary<IAsyncLocal, object>();
m_localChangeNotifications = Array.Empty<IAsyncLocal>();
}
private ExecutionContext(Dictionary<IAsyncLocal, object> localValues, IAsyncLocal[] localChangeNotifications)
{
m_localValues = localValues;
m_localChangeNotifications = localChangeNotifications;
}
[SecuritySafeCritical]
public static ExecutionContext Capture()
{
return t_currentMaybeNull ?? ExecutionContext.Default;
}
[SecurityCritical]
[HandleProcessCorruptedStateExceptions]
public static void Run(ExecutionContext executionContext, ContextCallback callback, Object state)
{
ExecutionContextSwitcher ecsw = default(ExecutionContextSwitcher);
try
{
EstablishCopyOnWriteScope(ref ecsw);
ExecutionContext.Restore(executionContext);
callback(state);
}
catch
{
// Note: we have a "catch" rather than a "finally" because we want
// to stop the first pass of EH here. That way we can restore the previous
// context before any of our callers' EH filters run. That means we need to
// end the scope separately in the non-exceptional case below.
ecsw.Undo();
throw;
}
ecsw.Undo();
}
[SecurityCritical]
internal static void Restore(ExecutionContext executionContext)
{
if (executionContext == null)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NullContext"));
ExecutionContext previous = t_currentMaybeNull ?? Default;
t_currentMaybeNull = executionContext;
if (previous != executionContext)
OnContextChanged(previous, executionContext);
}
[SecurityCritical]
static internal void EstablishCopyOnWriteScope(ref ExecutionContextSwitcher ecsw)
{
ecsw.m_ec = Capture();
ecsw.m_sc = SynchronizationContext.CurrentNoFlow;
}
[SecurityCritical]
[HandleProcessCorruptedStateExceptions]
private static void OnContextChanged(ExecutionContext previous, ExecutionContext current)
{
previous = previous ?? Default;
foreach (IAsyncLocal local in previous.m_localChangeNotifications)
{
object previousValue;
object currentValue;
previous.m_localValues.TryGetValue(local, out previousValue);
current.m_localValues.TryGetValue(local, out currentValue);
if (previousValue != currentValue)
local.OnValueChanged(previousValue, currentValue, true);
}
if (current.m_localChangeNotifications != previous.m_localChangeNotifications)
{
try
{
foreach (IAsyncLocal local in current.m_localChangeNotifications)
{
// If the local has a value in the previous context, we already fired the event for that local
// in the code above.
object previousValue;
if (!previous.m_localValues.TryGetValue(local, out previousValue))
{
object currentValue;
current.m_localValues.TryGetValue(local, out currentValue);
if (previousValue != currentValue)
local.OnValueChanged(previousValue, currentValue, true);
}
}
}
catch (Exception ex)
{
Environment.FailFast(
Environment.GetResourceString("ExecutionContext_ExceptionInAsyncLocalNotification"),
ex);
}
}
}
[SecurityCritical]
internal static object GetLocalValue(IAsyncLocal local)
{
ExecutionContext current = t_currentMaybeNull;
if (current == null)
return null;
object value;
current.m_localValues.TryGetValue(local, out value);
return value;
}
[SecurityCritical]
internal static void SetLocalValue(IAsyncLocal local, object newValue, bool needChangeNotifications)
{
ExecutionContext current = t_currentMaybeNull ?? ExecutionContext.Default;
object previousValue;
bool hadPreviousValue = current.m_localValues.TryGetValue(local, out previousValue);
if (previousValue == newValue)
return;
//
// Allocate a new Dictionary containing a copy of the old values, plus the new value. We have to do this manually to
// minimize allocations of IEnumerators, etc.
//
Dictionary<IAsyncLocal, object> newValues = new Dictionary<IAsyncLocal, object>(current.m_localValues.Count + (hadPreviousValue ? 0 : 1));
foreach (KeyValuePair<IAsyncLocal, object> pair in current.m_localValues)
newValues.Add(pair.Key, pair.Value);
newValues[local] = newValue;
//
// Either copy the change notification array, or create a new one, depending on whether we need to add a new item.
//
IAsyncLocal[] newChangeNotifications = current.m_localChangeNotifications;
if (needChangeNotifications)
{
if (hadPreviousValue)
{
Contract.Assert(Array.IndexOf(newChangeNotifications, local) >= 0);
}
else
{
int newNotificationIndex = newChangeNotifications.Length;
Array.Resize(ref newChangeNotifications, newNotificationIndex + 1);
newChangeNotifications[newNotificationIndex] = local;
}
}
t_currentMaybeNull = new ExecutionContext(newValues, newChangeNotifications);
if (needChangeNotifications)
{
local.OnValueChanged(previousValue, newValue, false);
}
}
#region Wrappers for CLR compat, to avoid ifdefs all over the BCL
[Flags]
internal enum CaptureOptions
{
None = 0x00,
IgnoreSyncCtx = 0x01,
OptimizeDefaultCase = 0x02,
}
[SecurityCritical]
internal static ExecutionContext Capture(ref StackCrawlMark stackMark, CaptureOptions captureOptions)
{
return Capture();
}
[SecuritySafeCritical]
[FriendAccessAllowed]
internal static ExecutionContext FastCapture()
{
return Capture();
}
[SecurityCritical]
[FriendAccessAllowed]
internal static void Run(ExecutionContext executionContext, ContextCallback callback, Object state, bool preserveSyncCtx)
{
Run(executionContext, callback, state);
}
[SecurityCritical]
internal bool IsDefaultFTContext(bool ignoreSyncCtx)
{
return this == Default;
}
[SecuritySafeCritical]
public ExecutionContext CreateCopy()
{
return this; // since CoreCLR's ExecutionContext is immutable, we don't need to create copies.
}
public void Dispose()
{
// For CLR compat only
}
public static bool IsFlowSuppressed()
{
return false;
}
internal static ExecutionContext PreAllocatedDefault
{
[SecuritySafeCritical]
get { return ExecutionContext.Default; }
}
internal bool IsPreAllocatedDefault
{
get { return this == ExecutionContext.Default; }
}
#endregion
}
#else // FEATURE_CORECLR
// Legacy desktop ExecutionContext implementation
internal struct ExecutionContextSwitcher
{
internal ExecutionContext.Reader outerEC; // previous EC we need to restore on Undo
internal bool outerECBelongsToScope;
#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
internal SecurityContextSwitcher scsw;
#endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
internal Object hecsw;
#if FEATURE_IMPERSONATION
internal WindowsIdentity wi;
internal bool cachedAlwaysFlowImpersonationPolicy;
internal bool wiIsValid;
#endif
internal Thread thread;
[System.Security.SecurityCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
#if FEATURE_CORRUPTING_EXCEPTIONS
[HandleProcessCorruptedStateExceptions]
#endif // FEATURE_CORRUPTING_EXCEPTIONS
internal bool UndoNoThrow()
{
try
{
Undo();
}
catch
{
return false;
}
return true;
}
[System.Security.SecurityCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal void Undo()
{
//
// Don't use an uninitialized switcher, or one that's already been used.
//
if (thread == null)
return; // Don't do anything
Contract.Assert(Thread.CurrentThread == this.thread);
Thread currentThread = this.thread;
//
// Restore the HostExecutionContext before restoring the ExecutionContext.
//
#if FEATURE_CAS_POLICY
if (hecsw != null)
HostExecutionContextSwitcher.Undo(hecsw);
#endif // FEATURE_CAS_POLICY
//
// restore the saved Execution Context. Note that this will also restore the
// SynchronizationContext, Logical/IllogicalCallContext, etc.
//
ExecutionContext.Reader innerEC = currentThread.GetExecutionContextReader();
currentThread.SetExecutionContext(outerEC, outerECBelongsToScope);
#if DEBUG
try
{
currentThread.ForbidExecutionContextMutation = true;
#endif
//
// Tell the SecurityContext to do the side-effects of restoration.
//
#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
if (scsw.currSC != null)
{
// Any critical failure inside scsw will cause FailFast
scsw.Undo();
}
#endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
#if FEATURE_IMPERSONATION
if (wiIsValid)
SecurityContext.RestoreCurrentWI(outerEC, innerEC, wi, cachedAlwaysFlowImpersonationPolicy);
#endif
thread = null; // this will prevent the switcher object being used again
#if DEBUG
}
finally
{
currentThread.ForbidExecutionContextMutation = false;
}
#endif
ExecutionContext.OnAsyncLocalContextChanged(innerEC.DangerousGetRawExecutionContext(), outerEC.DangerousGetRawExecutionContext());
}
}
public struct AsyncFlowControl: IDisposable
{
private bool useEC;
private ExecutionContext _ec;
#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
private SecurityContext _sc;
#endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
private Thread _thread;
#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
[SecurityCritical]
internal void Setup(SecurityContextDisableFlow flags)
{
useEC = false;
Thread currentThread = Thread.CurrentThread;
_sc = currentThread.GetMutableExecutionContext().SecurityContext;
_sc._disableFlow = flags;
_thread = currentThread;
}
#endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
[SecurityCritical]
internal void Setup()
{
useEC = true;
Thread currentThread = Thread.CurrentThread;
_ec = currentThread.GetMutableExecutionContext();
_ec.isFlowSuppressed = true;
_thread = currentThread;
}
public void Dispose()
{
Undo();
}
[SecuritySafeCritical]
public void Undo()
{
if (_thread == null)
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotUseAFCMultiple"));
}
if (_thread != Thread.CurrentThread)
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotUseAFCOtherThread"));
}
if (useEC)
{
if (Thread.CurrentThread.GetMutableExecutionContext() != _ec)
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_AsyncFlowCtrlCtxMismatch"));
}
ExecutionContext.RestoreFlow();
}
#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
else
{
if (!Thread.CurrentThread.GetExecutionContextReader().SecurityContext.IsSame(_sc))
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_AsyncFlowCtrlCtxMismatch"));
}
SecurityContext.RestoreFlow();
}
#endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
_thread = null;
}
public override int GetHashCode()
{
return _thread == null ? ToString().GetHashCode() : _thread.GetHashCode();
}
public override bool Equals(Object obj)
{
if (obj is AsyncFlowControl)
return Equals((AsyncFlowControl)obj);
else
return false;
}
public bool Equals(AsyncFlowControl obj)
{
return obj.useEC == useEC && obj._ec == _ec &&
#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
obj._sc == _sc &&
#endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
obj._thread == _thread;
}
public static bool operator ==(AsyncFlowControl a, AsyncFlowControl b)
{
return a.Equals(b);
}
public static bool operator !=(AsyncFlowControl a, AsyncFlowControl b)
{
return !(a == b);
}
}
[Serializable]
public sealed class ExecutionContext : IDisposable, ISerializable
{
/*=========================================================================
** Data accessed from managed code that needs to be defined in
** ExecutionContextObject to maintain alignment between the two classes.
** DON'T CHANGE THESE UNLESS YOU MODIFY ExecutionContextObject in vm\object.h
=========================================================================*/
#if FEATURE_CAS_POLICY
private HostExecutionContext _hostExecutionContext;
#endif // FEATURE_CAS_POLICY
private SynchronizationContext _syncContext;
private SynchronizationContext _syncContextNoFlow;
#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
private SecurityContext _securityContext;
#endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
#if FEATURE_REMOTING
[System.Security.SecurityCritical] // auto-generated
private LogicalCallContext _logicalCallContext;
private IllogicalCallContext _illogicalCallContext; // this call context follows the physical thread
#endif // #if FEATURE_REMOTING
enum Flags
{
None = 0x0,
IsNewCapture = 0x1,
IsFlowSuppressed = 0x2,
IsPreAllocatedDefault = 0x4
}
private Flags _flags;
private Dictionary<IAsyncLocal, object> _localValues;
private List<IAsyncLocal> _localChangeNotifications;
internal bool isNewCapture
{
get
{
return (_flags & (Flags.IsNewCapture | Flags.IsPreAllocatedDefault)) != Flags.None;
}
set
{
Contract.Assert(!IsPreAllocatedDefault);
if (value)
_flags |= Flags.IsNewCapture;
else
_flags &= ~Flags.IsNewCapture;
}
}
internal bool isFlowSuppressed
{
get
{
return (_flags & Flags.IsFlowSuppressed) != Flags.None;
}
set
{
Contract.Assert(!IsPreAllocatedDefault);
if (value)
_flags |= Flags.IsFlowSuppressed;
else
_flags &= ~Flags.IsFlowSuppressed;
}
}
private static readonly ExecutionContext s_dummyDefaultEC = new ExecutionContext(isPreAllocatedDefault: true);
static internal ExecutionContext PreAllocatedDefault
{
[SecuritySafeCritical]
get { return s_dummyDefaultEC; }
}
internal bool IsPreAllocatedDefault
{
get
{
// we use _flags instead of a direct comparison w/ s_dummyDefaultEC to avoid the static access on
// hot code paths.
if ((_flags & Flags.IsPreAllocatedDefault) != Flags.None)
{
Contract.Assert(this == s_dummyDefaultEC);
return true;
}
else
{
return false;
}
}
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal ExecutionContext()
{
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal ExecutionContext(bool isPreAllocatedDefault)
{
if (isPreAllocatedDefault)
_flags = Flags.IsPreAllocatedDefault;
}
// Read-only wrapper around ExecutionContext. This enables safe reading of an ExecutionContext without accidentally modifying it.
internal struct Reader
{
ExecutionContext m_ec;
public Reader(ExecutionContext ec) { m_ec = ec; }
public ExecutionContext DangerousGetRawExecutionContext() { return m_ec; }
public bool IsNull { get { return m_ec == null; } }
[SecurityCritical]
public bool IsDefaultFTContext(bool ignoreSyncCtx) { return m_ec.IsDefaultFTContext(ignoreSyncCtx); }
public bool IsFlowSuppressed
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return IsNull ? false : m_ec.isFlowSuppressed; }
}
//public Thread Thread { get { return m_ec._thread; } }
public bool IsSame(ExecutionContext.Reader other) { return m_ec == other.m_ec; }
public SynchronizationContext SynchronizationContext { get { return IsNull ? null : m_ec.SynchronizationContext; } }
public SynchronizationContext SynchronizationContextNoFlow { get { return IsNull ? null : m_ec.SynchronizationContextNoFlow; } }
#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
public SecurityContext.Reader SecurityContext
{
[SecurityCritical]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return new SecurityContext.Reader(IsNull ? null : m_ec.SecurityContext); }
}
#endif
#if FEATURE_REMOTING
public LogicalCallContext.Reader LogicalCallContext
{
[SecurityCritical]
get { return new LogicalCallContext.Reader(IsNull ? null : m_ec.LogicalCallContext); }
}
public IllogicalCallContext.Reader IllogicalCallContext
{
[SecurityCritical]
get { return new IllogicalCallContext.Reader(IsNull ? null : m_ec.IllogicalCallContext); }
}
#endif
[SecurityCritical]
public object GetLocalValue(IAsyncLocal local)
{
if (IsNull)
return null;
if (m_ec._localValues == null)
return null;
object value;
m_ec._localValues.TryGetValue(local, out value);
return value;
}
[SecurityCritical]
public bool HasSameLocalValues(ExecutionContext other)
{
var thisLocalValues = IsNull ? null : m_ec._localValues;
var otherLocalValues = other == null ? null : other._localValues;
return thisLocalValues == otherLocalValues;
}
[SecurityCritical]
public bool HasLocalValues()
{
return !this.IsNull && m_ec._localValues != null;
}
}
[SecurityCritical]
internal static object GetLocalValue(IAsyncLocal local)
{
return Thread.CurrentThread.GetExecutionContextReader().GetLocalValue(local);
}
[SecurityCritical]
internal static void SetLocalValue(IAsyncLocal local, object newValue, bool needChangeNotifications)
{
ExecutionContext current = Thread.CurrentThread.GetMutableExecutionContext();
object previousValue = null;
bool hadPreviousValue = current._localValues != null && current._localValues.TryGetValue(local, out previousValue);
if (previousValue == newValue)
return;
if (current._localValues == null)
current._localValues = new Dictionary<IAsyncLocal, object>();
else
current._localValues = new Dictionary<IAsyncLocal, object>(current._localValues);
current._localValues[local] = newValue;
if (needChangeNotifications)
{
if (hadPreviousValue)
{
Contract.Assert(current._localChangeNotifications != null);
Contract.Assert(current._localChangeNotifications.Contains(local));
}
else
{
if (current._localChangeNotifications == null)
current._localChangeNotifications = new List<IAsyncLocal>();
else
current._localChangeNotifications = new List<IAsyncLocal>(current._localChangeNotifications);
current._localChangeNotifications.Add(local);
}
local.OnValueChanged(previousValue, newValue, false);
}
}
[SecurityCritical]
[HandleProcessCorruptedStateExceptions]
internal static void OnAsyncLocalContextChanged(ExecutionContext previous, ExecutionContext current)
{
List<IAsyncLocal> previousLocalChangeNotifications = (previous == null) ? null : previous._localChangeNotifications;
if (previousLocalChangeNotifications != null)
{
foreach (IAsyncLocal local in previousLocalChangeNotifications)
{
object previousValue = null;
if (previous != null && previous._localValues != null)
previous._localValues.TryGetValue(local, out previousValue);
object currentValue = null;
if (current != null && current._localValues != null)
current._localValues.TryGetValue(local, out currentValue);
if (previousValue != currentValue)
local.OnValueChanged(previousValue, currentValue, true);
}
}
List<IAsyncLocal> currentLocalChangeNotifications = (current == null) ? null : current._localChangeNotifications;
if (currentLocalChangeNotifications != null && currentLocalChangeNotifications != previousLocalChangeNotifications)
{
try
{
foreach (IAsyncLocal local in currentLocalChangeNotifications)
{
// If the local has a value in the previous context, we already fired the event for that local
// in the code above.
object previousValue = null;
if (previous == null ||
previous._localValues == null ||
!previous._localValues.TryGetValue(local, out previousValue))
{
object currentValue = null;
if (current != null && current._localValues != null)
current._localValues.TryGetValue(local, out currentValue);
if (previousValue != currentValue)
local.OnValueChanged(previousValue, currentValue, true);
}
}
}
catch (Exception ex)
{
Environment.FailFast(
Environment.GetResourceString("ExecutionContext_ExceptionInAsyncLocalNotification"),
ex);
}
}
}
#if FEATURE_REMOTING
internal LogicalCallContext LogicalCallContext
{
[System.Security.SecurityCritical] // auto-generated
get
{
if (_logicalCallContext == null)
{
_logicalCallContext = new LogicalCallContext();
}
return _logicalCallContext;
}
[System.Security.SecurityCritical] // auto-generated
set
{
Contract.Assert(this != s_dummyDefaultEC);
_logicalCallContext = value;
}
}
internal IllogicalCallContext IllogicalCallContext
{
get
{
if (_illogicalCallContext == null)
{
_illogicalCallContext = new IllogicalCallContext();
}
return _illogicalCallContext;
}
set
{
Contract.Assert(this != s_dummyDefaultEC);
_illogicalCallContext = value;
}
}
#endif // #if FEATURE_REMOTING
internal SynchronizationContext SynchronizationContext
{
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
get
{
return _syncContext;
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
set
{
Contract.Assert(this != s_dummyDefaultEC);
_syncContext = value;
}
}
internal SynchronizationContext SynchronizationContextNoFlow
{
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
get
{
return _syncContextNoFlow;
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
set
{
Contract.Assert(this != s_dummyDefaultEC);
_syncContextNoFlow = value;
}
}
#if FEATURE_CAS_POLICY
internal HostExecutionContext HostExecutionContext
{
get
{
return _hostExecutionContext;
}
set
{
Contract.Assert(this != s_dummyDefaultEC);
_hostExecutionContext = value;
}
}
#endif // FEATURE_CAS_POLICY
#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
internal SecurityContext SecurityContext
{
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
get
{
return _securityContext;
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
set
{
Contract.Assert(this != s_dummyDefaultEC);
// store the new security context
_securityContext = value;
// perform the reverse link too
if (value != null)
_securityContext.ExecutionContext = this;
}
}
#endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
public void Dispose()
{
if(this.IsPreAllocatedDefault)
return; //Do nothing if this is the default context
#if FEATURE_CAS_POLICY
if (_hostExecutionContext != null)
_hostExecutionContext.Dispose();
#endif // FEATURE_CAS_POLICY
#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
if (_securityContext != null)
_securityContext.Dispose();
#endif //FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
}
[DynamicSecurityMethod]
[System.Security.SecurityCritical] // auto-generated_required
public static void Run(ExecutionContext executionContext, ContextCallback callback, Object state)
{
if (executionContext == null)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NullContext"));
if (!executionContext.isNewCapture)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotNewCaptureContext"));
Run(executionContext, callback, state, false);
}
// This method is special from a security perspective - the VM will not allow a stack walk to
// continue past the call to ExecutionContext.Run. If you change the signature to this method, make
// sure to update SecurityStackWalk::IsSpecialRunFrame in the VM to search for the new signature.
[DynamicSecurityMethod]
[SecurityCritical]
[FriendAccessAllowed]
internal static void Run(ExecutionContext executionContext, ContextCallback callback, Object state, bool preserveSyncCtx)
{
RunInternal(executionContext, callback, state, preserveSyncCtx);
}
// Actual implementation of Run is here, in a non-DynamicSecurityMethod, because the JIT seems to refuse to inline callees into
// a DynamicSecurityMethod.
[SecurityCritical]
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread safety")]
[HandleProcessCorruptedStateExceptions]
internal static void RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, bool preserveSyncCtx)
{
Contract.Assert(executionContext != null);
if (executionContext.IsPreAllocatedDefault)
{
Contract.Assert(executionContext.IsDefaultFTContext(preserveSyncCtx));
}
else
{
Contract.Assert(executionContext.isNewCapture);
executionContext.isNewCapture = false;
}
Thread currentThread = Thread.CurrentThread;
ExecutionContextSwitcher ecsw = default(ExecutionContextSwitcher);
RuntimeHelpers.PrepareConstrainedRegions();
try
{
ExecutionContext.Reader ec = currentThread.GetExecutionContextReader();
if ( (ec.IsNull || ec.IsDefaultFTContext(preserveSyncCtx)) &&
#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
SecurityContext.CurrentlyInDefaultFTSecurityContext(ec) &&
#endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
executionContext.IsDefaultFTContext(preserveSyncCtx) &&
ec.HasSameLocalValues(executionContext)
)
{
// Neither context is interesting, so we don't need to set the context.
// We do need to reset any changes made by the user's callback,
// so here we establish a "copy-on-write scope". Any changes will
// result in a copy of the context being made, preserving the original
// context.
EstablishCopyOnWriteScope(currentThread, true, ref ecsw);
}
else
{
if (executionContext.IsPreAllocatedDefault)
executionContext = new ExecutionContext();
ecsw = SetExecutionContext(executionContext, preserveSyncCtx);
}
//
// Call the user's callback
//
callback(state);
}
finally
{
ecsw.Undo();
}
}
[SecurityCritical]
static internal void EstablishCopyOnWriteScope(ref ExecutionContextSwitcher ecsw)
{
EstablishCopyOnWriteScope(Thread.CurrentThread, false, ref ecsw);
}
[SecurityCritical]
static private void EstablishCopyOnWriteScope(Thread currentThread, bool knownNullWindowsIdentity, ref ExecutionContextSwitcher ecsw)
{
Contract.Assert(currentThread == Thread.CurrentThread);
ecsw.outerEC = currentThread.GetExecutionContextReader();
ecsw.outerECBelongsToScope = currentThread.ExecutionContextBelongsToCurrentScope;
#if FEATURE_IMPERSONATION
ecsw.cachedAlwaysFlowImpersonationPolicy = SecurityContext.AlwaysFlowImpersonationPolicy;
if (knownNullWindowsIdentity)
Contract.Assert(SecurityContext.GetCurrentWI(ecsw.outerEC, ecsw.cachedAlwaysFlowImpersonationPolicy) == null);
else
ecsw.wi = SecurityContext.GetCurrentWI(ecsw.outerEC, ecsw.cachedAlwaysFlowImpersonationPolicy);
ecsw.wiIsValid = true;
#endif
currentThread.ExecutionContextBelongsToCurrentScope = false;
ecsw.thread = currentThread;
}
// Sets the given execution context object on the thread.
// Returns the previous one.
[System.Security.SecurityCritical] // auto-generated
[DynamicSecurityMethodAttribute()]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
#if FEATURE_CORRUPTING_EXCEPTIONS
[HandleProcessCorruptedStateExceptions]
#endif // FEATURE_CORRUPTING_EXCEPTIONS
internal static ExecutionContextSwitcher SetExecutionContext(ExecutionContext executionContext, bool preserveSyncCtx)
{
#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
#endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
Contract.Assert(executionContext != null);
Contract.Assert(executionContext != s_dummyDefaultEC);
// Set up the switcher object to return;
ExecutionContextSwitcher ecsw = new ExecutionContextSwitcher();
Thread currentThread = Thread.CurrentThread;
ExecutionContext.Reader outerEC = currentThread.GetExecutionContextReader();
ecsw.thread = currentThread;
ecsw.outerEC = outerEC;
ecsw.outerECBelongsToScope = currentThread.ExecutionContextBelongsToCurrentScope;
if (preserveSyncCtx)
executionContext.SynchronizationContext = outerEC.SynchronizationContext;
executionContext.SynchronizationContextNoFlow = outerEC.SynchronizationContextNoFlow;
currentThread.SetExecutionContext(executionContext, belongsToCurrentScope: true);
RuntimeHelpers.PrepareConstrainedRegions();
try
{
OnAsyncLocalContextChanged(outerEC.DangerousGetRawExecutionContext(), executionContext);
#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
//set the security context
SecurityContext sc = executionContext.SecurityContext;
if (sc != null)
{
// non-null SC: needs to be set
SecurityContext.Reader prevSeC = outerEC.SecurityContext;
ecsw.scsw = SecurityContext.SetSecurityContext(sc, prevSeC, false, ref stackMark);
}
else if (!SecurityContext.CurrentlyInDefaultFTSecurityContext(ecsw.outerEC))
{
// null incoming SC, but we're currently not in FT: use static FTSC to set
SecurityContext.Reader prevSeC = outerEC.SecurityContext;
ecsw.scsw = SecurityContext.SetSecurityContext(SecurityContext.FullTrustSecurityContext, prevSeC, false, ref stackMark);
}
#endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
#if FEATURE_CAS_POLICY
// set the Host Context
HostExecutionContext hostContext = executionContext.HostExecutionContext;
if (hostContext != null)
{
ecsw.hecsw = HostExecutionContextManager.SetHostExecutionContextInternal(hostContext);
}
#endif // FEATURE_CAS_POLICY
}
catch
{
ecsw.UndoNoThrow();
throw;
}
return ecsw;
}
//
// Public CreateCopy. Used to copy captured ExecutionContexts so they can be reused multiple times.
// This should only copy the portion of the context that we actually capture.
//
[SecuritySafeCritical]
public ExecutionContext CreateCopy()
{
if (!isNewCapture)
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotCopyUsedContext"));
}
ExecutionContext ec = new ExecutionContext();
ec.isNewCapture = true;
ec._syncContext = _syncContext == null ? null : _syncContext.CreateCopy();
ec._localValues = _localValues;
ec._localChangeNotifications = _localChangeNotifications;
#if FEATURE_CAS_POLICY
// capture the host execution context
ec._hostExecutionContext = _hostExecutionContext == null ? null : _hostExecutionContext.CreateCopy();
#endif // FEATURE_CAS_POLICY
#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
if (_securityContext != null)
{
ec._securityContext = _securityContext.CreateCopy();
ec._securityContext.ExecutionContext = ec;
}
#endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
#if FEATURE_REMOTING
if (this._logicalCallContext != null)
ec.LogicalCallContext = (LogicalCallContext)this.LogicalCallContext.Clone();
Contract.Assert(this._illogicalCallContext == null);
#endif // #if FEATURE_REMOTING
return ec;
}
//
// Creates a complete copy, used for copy-on-write.
//
[SecuritySafeCritical]
internal ExecutionContext CreateMutableCopy()
{
Contract.Assert(!this.isNewCapture);
ExecutionContext ec = new ExecutionContext();
// We don't deep-copy the SyncCtx, since we're still in the same context after copy-on-write.
ec._syncContext = this._syncContext;
ec._syncContextNoFlow = this._syncContextNoFlow;
#if FEATURE_CAS_POLICY
// capture the host execution context
ec._hostExecutionContext = this._hostExecutionContext == null ? null : _hostExecutionContext.CreateCopy();
#endif // FEATURE_CAS_POLICY
#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
if (_securityContext != null)
{
ec._securityContext = this._securityContext.CreateMutableCopy();
ec._securityContext.ExecutionContext = ec;
}
#endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
#if FEATURE_REMOTING
if (this._logicalCallContext != null)
ec.LogicalCallContext = (LogicalCallContext)this.LogicalCallContext.Clone();
if (this._illogicalCallContext != null)
ec.IllogicalCallContext = (IllogicalCallContext)this.IllogicalCallContext.CreateCopy();
#endif // #if FEATURE_REMOTING
ec._localValues = this._localValues;
ec._localChangeNotifications = this._localChangeNotifications;
ec.isFlowSuppressed = this.isFlowSuppressed;
return ec;
}
[System.Security.SecurityCritical] // auto-generated_required
public static AsyncFlowControl SuppressFlow()
{
if (IsFlowSuppressed())
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotSupressFlowMultipleTimes"));
}
Contract.EndContractBlock();
AsyncFlowControl afc = new AsyncFlowControl();
afc.Setup();
return afc;
}
[SecuritySafeCritical]
public static void RestoreFlow()
{
ExecutionContext ec = Thread.CurrentThread.GetMutableExecutionContext();
if (!ec.isFlowSuppressed)
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotRestoreUnsupressedFlow"));
}
ec.isFlowSuppressed = false;
}
[Pure]
public static bool IsFlowSuppressed()
{
return Thread.CurrentThread.GetExecutionContextReader().IsFlowSuppressed;
}
[System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public static ExecutionContext Capture()
{
// set up a stack mark for finding the caller
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return ExecutionContext.Capture(ref stackMark, CaptureOptions.None);
}
//
// Captures an ExecutionContext with optimization for the "default" case, and captures a "null" synchronization context.
// When calling ExecutionContext.Run on the returned context, specify ignoreSyncCtx = true
//
[System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
[FriendAccessAllowed]
internal static ExecutionContext FastCapture()
{
// set up a stack mark for finding the caller
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return ExecutionContext.Capture(ref stackMark, CaptureOptions.IgnoreSyncCtx | CaptureOptions.OptimizeDefaultCase);
}
[Flags]
internal enum CaptureOptions
{
None = 0x00,
IgnoreSyncCtx = 0x01, //Don't flow SynchronizationContext
OptimizeDefaultCase = 0x02, //Faster in the typical case, but can't show the result to users
// because they could modify the shared default EC.
// Use this only if you won't be exposing the captured EC to users.
}
// internal helper to capture the current execution context using a passed in stack mark
[System.Security.SecurityCritical] // auto-generated
static internal ExecutionContext Capture(ref StackCrawlMark stackMark, CaptureOptions options)
{
ExecutionContext.Reader ecCurrent = Thread.CurrentThread.GetExecutionContextReader();
// check to see if Flow is suppressed
if (ecCurrent.IsFlowSuppressed)
return null;
//
// Attempt to capture context. There may be nothing to capture...
//
#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
// capture the security context
SecurityContext secCtxNew = SecurityContext.Capture(ecCurrent, ref stackMark);
#endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
#if FEATURE_CAS_POLICY
// capture the host execution context
HostExecutionContext hostCtxNew = HostExecutionContextManager.CaptureHostExecutionContext();
#endif // FEATURE_CAS_POLICY
SynchronizationContext syncCtxNew = null;
#if FEATURE_REMOTING
LogicalCallContext logCtxNew = null;
#endif
if (!ecCurrent.IsNull)
{
// capture the sync context
if (0 == (options & CaptureOptions.IgnoreSyncCtx))
syncCtxNew = (ecCurrent.SynchronizationContext == null) ? null : ecCurrent.SynchronizationContext.CreateCopy();
#if FEATURE_REMOTING
// copy over the Logical Call Context
if (ecCurrent.LogicalCallContext.HasInfo)
logCtxNew = ecCurrent.LogicalCallContext.Clone();
#endif // #if FEATURE_REMOTING
}
Dictionary<IAsyncLocal, object> localValues = null;
List<IAsyncLocal> localChangeNotifications = null;
if (!ecCurrent.IsNull)
{
localValues = ecCurrent.DangerousGetRawExecutionContext()._localValues;
localChangeNotifications = ecCurrent.DangerousGetRawExecutionContext()._localChangeNotifications;
}
//
// If we didn't get anything but defaults, and we're allowed to return the
// dummy default EC, don't bother allocating a new context.
//
if (0 != (options & CaptureOptions.OptimizeDefaultCase) &&
#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
secCtxNew == null &&
#endif
#if FEATURE_CAS_POLICY
hostCtxNew == null &&
#endif // FEATURE_CAS_POLICY
syncCtxNew == null &&
#if FEATURE_REMOTING
(logCtxNew == null || !logCtxNew.HasInfo) &&
#endif // #if FEATURE_REMOTING
localValues == null &&
localChangeNotifications == null
)
{
return s_dummyDefaultEC;
}
//
// Allocate the new context, and fill it in.
//
ExecutionContext ecNew = new ExecutionContext();
#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
ecNew.SecurityContext = secCtxNew;
if (ecNew.SecurityContext != null)
ecNew.SecurityContext.ExecutionContext = ecNew;
#endif
#if FEATURE_CAS_POLICY
ecNew._hostExecutionContext = hostCtxNew;
#endif // FEATURE_CAS_POLICY
ecNew._syncContext = syncCtxNew;
#if FEATURE_REMOTING
ecNew.LogicalCallContext = logCtxNew;
#endif // #if FEATURE_REMOTING
ecNew._localValues = localValues;
ecNew._localChangeNotifications = localChangeNotifications;
ecNew.isNewCapture = true;
return ecNew;
}
//
// Implementation of ISerializable
//
[System.Security.SecurityCritical] // auto-generated_required
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info==null)
throw new ArgumentNullException("info");
Contract.EndContractBlock();
#if FEATURE_REMOTING
if (_logicalCallContext != null)
{
info.AddValue("LogicalCallContext", _logicalCallContext, typeof(LogicalCallContext));
}
#endif // #if FEATURE_REMOTING
}
[System.Security.SecurityCritical] // auto-generated
private ExecutionContext(SerializationInfo info, StreamingContext context)
{
SerializationInfoEnumerator e = info.GetEnumerator();
while (e.MoveNext())
{
#if FEATURE_REMOTING
if (e.Name.Equals("LogicalCallContext"))
{
_logicalCallContext = (LogicalCallContext) e.Value;
}
#endif // #if FEATURE_REMOTING
}
} // ObjRef .ctor
[System.Security.SecurityCritical] // auto-generated
internal bool IsDefaultFTContext(bool ignoreSyncCtx)
{
#if FEATURE_CAS_POLICY
if (_hostExecutionContext != null)
return false;
#endif // FEATURE_CAS_POLICY
if (!ignoreSyncCtx && _syncContext != null)
return false;
#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
if (_securityContext != null && !_securityContext.IsDefaultFTSecurityContext())
return false;
#endif //#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
#if FEATURE_REMOTING
if (_logicalCallContext != null && _logicalCallContext.HasInfo)
return false;
if (_illogicalCallContext != null && _illogicalCallContext.HasUserData)
return false;
#endif //#if FEATURE_REMOTING
return true;
}
} // class ExecutionContext
#endif //FEATURE_CORECLR
}
| |
//
// 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.Collections.Generic;
using System.Globalization;
using System.IO;
using DiscUtils.Streams;
namespace DiscUtils.Ntfs
{
internal class NtfsAttribute : IDiagnosticTraceable
{
private IBuffer _cachedRawBuffer;
protected FileRecordReference _containingFile;
protected Dictionary<AttributeReference, AttributeRecord> _extents;
protected File _file;
protected AttributeRecord _primaryRecord;
protected NtfsAttribute(File file, FileRecordReference containingFile, AttributeRecord record)
{
_file = file;
_containingFile = containingFile;
_primaryRecord = record;
_extents = new Dictionary<AttributeReference, AttributeRecord>();
_extents.Add(new AttributeReference(containingFile, record.AttributeId), _primaryRecord);
}
protected string AttributeTypeName
{
get
{
switch (_primaryRecord.AttributeType)
{
case AttributeType.StandardInformation:
return "STANDARD INFORMATION";
case AttributeType.FileName:
return "FILE NAME";
case AttributeType.SecurityDescriptor:
return "SECURITY DESCRIPTOR";
case AttributeType.Data:
return "DATA";
case AttributeType.Bitmap:
return "BITMAP";
case AttributeType.VolumeName:
return "VOLUME NAME";
case AttributeType.VolumeInformation:
return "VOLUME INFORMATION";
case AttributeType.IndexRoot:
return "INDEX ROOT";
case AttributeType.IndexAllocation:
return "INDEX ALLOCATION";
case AttributeType.ObjectId:
return "OBJECT ID";
case AttributeType.ReparsePoint:
return "REPARSE POINT";
case AttributeType.AttributeList:
return "ATTRIBUTE LIST";
default:
return "UNKNOWN";
}
}
}
public long CompressedDataSize
{
get
{
NonResidentAttributeRecord firstExtent = FirstExtent as NonResidentAttributeRecord;
if (firstExtent == null)
{
return FirstExtent.AllocatedLength;
}
return firstExtent.CompressedDataSize;
}
set
{
NonResidentAttributeRecord firstExtent = FirstExtent as NonResidentAttributeRecord;
if (firstExtent != null)
{
firstExtent.CompressedDataSize = value;
}
}
}
public int CompressionUnitSize
{
get
{
NonResidentAttributeRecord firstExtent = FirstExtent as NonResidentAttributeRecord;
if (firstExtent == null)
{
return 0;
}
return firstExtent.CompressionUnitSize;
}
set
{
NonResidentAttributeRecord firstExtent = FirstExtent as NonResidentAttributeRecord;
if (firstExtent != null)
{
firstExtent.CompressionUnitSize = value;
}
}
}
public IDictionary<AttributeReference, AttributeRecord> Extents
{
get { return _extents; }
}
public AttributeRecord FirstExtent
{
get
{
if (_extents != null)
{
foreach (KeyValuePair<AttributeReference, AttributeRecord> extent in _extents)
{
NonResidentAttributeRecord nonResident = extent.Value as NonResidentAttributeRecord;
if (nonResident == null)
{
// Resident attribute, so there can only be one...
return extent.Value;
}
if (nonResident.StartVcn == 0)
{
return extent.Value;
}
}
}
throw new InvalidDataException("Attribute with no initial extent");
}
}
public AttributeFlags Flags
{
get { return _primaryRecord.Flags; }
set
{
_primaryRecord.Flags = value;
_cachedRawBuffer = null;
}
}
public ushort Id
{
get { return _primaryRecord.AttributeId; }
}
public bool IsNonResident
{
get { return _primaryRecord.IsNonResident; }
}
public AttributeRecord LastExtent
{
get
{
AttributeRecord last = null;
if (_extents != null)
{
long lastVcn = 0;
foreach (KeyValuePair<AttributeReference, AttributeRecord> extent in _extents)
{
NonResidentAttributeRecord nonResident = extent.Value as NonResidentAttributeRecord;
if (nonResident == null)
{
// Resident attribute, so there can only be one...
return extent.Value;
}
if (nonResident.LastVcn >= lastVcn)
{
last = extent.Value;
lastVcn = nonResident.LastVcn;
}
}
}
return last;
}
}
public long Length
{
get { return _primaryRecord.DataLength; }
}
public string Name
{
get { return _primaryRecord.Name; }
}
public AttributeRecord PrimaryRecord
{
get { return _primaryRecord; }
}
public IBuffer RawBuffer
{
get
{
if (_cachedRawBuffer == null)
{
if (_primaryRecord.IsNonResident)
{
_cachedRawBuffer = new NonResidentAttributeBuffer(_file, this);
}
else
{
_cachedRawBuffer = ((ResidentAttributeRecord)_primaryRecord).DataBuffer;
}
}
return _cachedRawBuffer;
}
}
public List<AttributeRecord> Records
{
get
{
List<AttributeRecord> records = new List<AttributeRecord>(_extents.Values);
records.Sort(AttributeRecord.CompareStartVcns);
return records;
}
}
public AttributeReference Reference
{
get { return new AttributeReference(_containingFile, _primaryRecord.AttributeId); }
}
public AttributeType Type
{
get { return _primaryRecord.AttributeType; }
}
public virtual void Dump(TextWriter writer, string indent)
{
writer.WriteLine(indent + AttributeTypeName + " ATTRIBUTE (" + (Name == null ? "No Name" : Name) + ")");
writer.WriteLine(indent + " Length: " + _primaryRecord.DataLength + " bytes");
if (_primaryRecord.DataLength == 0)
{
writer.WriteLine(indent + " Data: <none>");
}
else
{
try
{
using (Stream s = Open(FileAccess.Read))
{
string hex = string.Empty;
byte[] buffer = new byte[32];
int numBytes = s.Read(buffer, 0, buffer.Length);
for (int i = 0; i < numBytes; ++i)
{
hex = hex + string.Format(CultureInfo.InvariantCulture, " {0:X2}", buffer[i]);
}
writer.WriteLine(indent + " Data: " + hex + (numBytes < s.Length ? "..." : string.Empty));
}
}
catch
{
writer.WriteLine(indent + " Data: <can't read>");
}
}
_primaryRecord.Dump(writer, indent + " ");
}
public static NtfsAttribute FromRecord(File file, FileRecordReference recordFile, AttributeRecord record)
{
switch (record.AttributeType)
{
case AttributeType.StandardInformation:
return new StructuredNtfsAttribute<StandardInformation>(file, recordFile, record);
case AttributeType.FileName:
return new StructuredNtfsAttribute<FileNameRecord>(file, recordFile, record);
case AttributeType.SecurityDescriptor:
return new StructuredNtfsAttribute<SecurityDescriptor>(file, recordFile, record);
case AttributeType.Data:
return new NtfsAttribute(file, recordFile, record);
case AttributeType.Bitmap:
return new NtfsAttribute(file, recordFile, record);
case AttributeType.VolumeName:
return new StructuredNtfsAttribute<VolumeName>(file, recordFile, record);
case AttributeType.VolumeInformation:
return new StructuredNtfsAttribute<VolumeInformation>(file, recordFile, record);
case AttributeType.IndexRoot:
return new NtfsAttribute(file, recordFile, record);
case AttributeType.IndexAllocation:
return new NtfsAttribute(file, recordFile, record);
case AttributeType.ObjectId:
return new StructuredNtfsAttribute<ObjectId>(file, recordFile, record);
case AttributeType.ReparsePoint:
return new StructuredNtfsAttribute<ReparsePointRecord>(file, recordFile, record);
case AttributeType.AttributeList:
return new StructuredNtfsAttribute<AttributeList>(file, recordFile, record);
default:
return new NtfsAttribute(file, recordFile, record);
}
}
public void SetExtent(FileRecordReference containingFile, AttributeRecord record)
{
_cachedRawBuffer = null;
_containingFile = containingFile;
_primaryRecord = record;
_extents.Clear();
_extents.Add(new AttributeReference(containingFile, record.AttributeId), record);
}
public void AddExtent(FileRecordReference containingFile, AttributeRecord record)
{
_cachedRawBuffer = null;
_extents.Add(new AttributeReference(containingFile, record.AttributeId), record);
}
public void RemoveExtentCacheSafe(AttributeReference reference)
{
_extents.Remove(reference);
}
public bool ReplaceExtent(AttributeReference oldRef, AttributeReference newRef, AttributeRecord record)
{
_cachedRawBuffer = null;
if (!_extents.Remove(oldRef))
{
return false;
}
if (oldRef.Equals(Reference) || _extents.Count == 0)
{
_primaryRecord = record;
_containingFile = newRef.File;
}
_extents.Add(newRef, record);
return true;
}
public Range<long, long>[] GetClusters()
{
List<Range<long, long>> result = new List<Range<long, long>>();
foreach (KeyValuePair<AttributeReference, AttributeRecord> extent in _extents)
{
result.AddRange(extent.Value.GetClusters());
}
return result.ToArray();
}
internal SparseStream Open(FileAccess access)
{
return new BufferStream(GetDataBuffer(), access);
}
internal IMappedBuffer GetDataBuffer()
{
return new NtfsAttributeBuffer(_file, this);
}
internal long OffsetToAbsolutePos(long offset)
{
return GetDataBuffer().MapPosition(offset);
}
}
}
| |
#pragma warning disable 162,108,618
using Casanova.Prelude;
using System.Linq;
using System;
using System.Collections.Generic;
using UnityEngine;
namespace Game {public class World : MonoBehaviour{
public static int frame;
void Update () { Update(Time.deltaTime, this);
frame++; }
public bool JustEntered = true;
static public int WorldCounter;
static public int ElemCounter;
static public Dictionary<int, Tuple<World, RuleTable>> WorldWithActiveRules;
static public Dictionary<int, Tuple<Elem, RuleTable>> ElemWithActiveRules;
static public List<int> WorldWithActiveRulesToRemove;
static public List<int> ElemWithActiveRulesToRemove;
static public Dictionary<int, List<World>> NotifySlotWorldElemsWorld1;
static public Dictionary<int, List<Elem>> NotifySlotElemCounterElem0;
static public Dictionary<int, List<Elem>> NotifySlotElemVElem3;
int ID = 0;
public void Start()
{
WorldCounter = 0;
ElemCounter = 0;
NotifySlotWorldElemsWorld1 = new Dictionary<int, List<World>>();
NotifySlotElemCounterElem0 = new Dictionary<int, List<Elem>>();
NotifySlotElemVElem3 = new Dictionary<int, List<Elem>>();
NotifySlotWorldElemsWorld1.Add(ID, new List<World>());
NotifySlotWorldElemsWorld1[ID].Add(this);
WorldWithActiveRules = new Dictionary<int, Tuple<World, RuleTable>>();
ElemWithActiveRules = new Dictionary<int, Tuple<Elem, RuleTable>>();
WorldWithActiveRulesToRemove = new List<int>();
ElemWithActiveRulesToRemove = new List<int>();
System.Random ___seed00;
___seed00 = new System.Random(0);
List<Elem> ___elems00;
___elems00 = (
(Enumerable.Range(0,(1) + ((10000) - (0))).ToList<System.Int32>()).Select(__ContextSymbol0 => new { ___i01 = __ContextSymbol0 })
.Select(__ContextSymbol1 => new Elem(___seed00))
.ToList<Elem>()).ToList<Elem>();
Seed = ___seed00;
Elems = ___elems00;
World1 = new List<Elem>(Elems);
List<Elem> q;
q = (
(Elems).Select(__ContextSymbol2 => new { ___e10 = __ContextSymbol2 })
.Where(__ContextSymbol3 => !(__ContextSymbol3.___e10.Counter))
.Select(__ContextSymbol4 => __ContextSymbol4.___e10)
.ToList<Elem>()).ToList<Elem>();
World1 = q;
}
public void Init() { System.Random ___seed00;
___seed00 = new System.Random(0);
List<Elem> ___elems00;
___elems00 = (
(Enumerable.Range(0,(1) + ((10000) - (0))).ToList<System.Int32>()).Select(__ContextSymbol5 => new { ___i01 = __ContextSymbol5 })
.Select(__ContextSymbol6 => new Elem(___seed00))
.ToList<Elem>()).ToList<Elem>();
Seed = ___seed00;
Elems = ___elems00;
World1 = new List<Elem>(Elems);
List<Elem> q;
q = (
(Elems).Select(__ContextSymbol7 => new { ___e10 = __ContextSymbol7 })
.Where(__ContextSymbol8 => !(__ContextSymbol8.___e10.Counter))
.Select(__ContextSymbol9 => __ContextSymbol9.___e10)
.ToList<Elem>()).ToList<Elem>();
World1 = q;
}
public List<Elem> _Elems;
public System.Random Seed;
public List<Elem> __World1;
public List<Elem> World1{ get { return __World1; }
set{ __World1 = value;
Elems= __World1;
foreach(var e in value){if(e.JustEntered){ e.JustEntered = false;
World.NotifySlotElemCounterElem0[e.ID].Add(e);
World.NotifySlotElemVElem3[e.ID].Add(e);
}
} }
}
public System.Single count_down1;
public List<Elem> __Elems1;
public System.Boolean q_temp1;
public Elem ___s1;
public System.Int32 counter31;
public RuleTable ActiveRules = new RuleTable(1);
public List<Elem> Elems{
get { return _Elems; }
set {
_Elems = value;
q_temp1 = true;
for(int i = 0; i < World.NotifySlotWorldElemsWorld1[ID].Count; i++) {
var entity = World.NotifySlotWorldElemsWorld1[ID][i];
if(!World.WorldWithActiveRules.ContainsKey(entity.ID))
World.WorldWithActiveRules.Add(entity.ID,new Tuple<World, RuleTable>(entity, new RuleTable(2)));World.WorldWithActiveRules[entity.ID].Item2.Add(1);
}
}
}
System.DateTime init_time = System.DateTime.Now;
public void Update(float dt, World world) {
var t = System.DateTime.Now;
for(int x0 = 0; x0 < Elems.Count; x0++) {
Elems[x0].Update(dt, world);
}
this.Rule0(dt, world);
if(WorldWithActiveRules.Count > 0){
foreach(var x in WorldWithActiveRules)
x.Value.Item1.UpdateSuspendedRules(dt, this, WorldWithActiveRulesToRemove, x.Value.Item2);
if(WorldWithActiveRulesToRemove.Count > 0){
for(int i = 0; i < WorldWithActiveRulesToRemove.Count; i++)
WorldWithActiveRules.Remove(WorldWithActiveRulesToRemove[i]);
WorldWithActiveRulesToRemove.Clear();
}
}
if(ElemWithActiveRules.Count > 0){
foreach(var x in ElemWithActiveRules)
x.Value.Item1.UpdateSuspendedRules(dt, this, ElemWithActiveRulesToRemove, x.Value.Item2);
if(ElemWithActiveRulesToRemove.Count > 0){
for(int i = 0; i < ElemWithActiveRulesToRemove.Count; i++)
ElemWithActiveRules.Remove(ElemWithActiveRulesToRemove[i]);
ElemWithActiveRulesToRemove.Clear();
}
}
}
public void UpdateSuspendedRules(float dt, World world, List<int> toRemove, RuleTable ActiveRules) { if (ActiveRules.ActiveIndices.Top > 0)
{
for (int i = 0; i < ActiveRules.ActiveIndices.Top; i++)
{
var x = ActiveRules.ActiveIndices.Elements[i];
switch (x)
{case 1:
if (this.Rule1(dt, world) == RuleResult.Done)
{
ActiveRules.ActiveSlots[i] = false;
ActiveRules.ActiveIndices.Top--;
}
else{
ActiveRules.SupportSlots[1] = true;
ActiveRules.SupportStack.Push(x);
}
break;
default:
break;
}
}
ActiveRules.ActiveIndices.Clear();
ActiveRules.Clear();
var tmp = ActiveRules.SupportStack;
var tmp1 = ActiveRules.SupportSlots;
ActiveRules.SupportStack = ActiveRules.ActiveIndices;
ActiveRules.SupportSlots = ActiveRules.ActiveSlots;
ActiveRules.ActiveIndices = tmp;
ActiveRules.ActiveSlots = tmp1;
if (ActiveRules.ActiveIndices.Top == 0)
toRemove.Add(ID);
} }
int s0=-1;
public void Rule0(float dt, World world){
switch (s0)
{
case -1:
count_down1 = 5f;
goto case 2;
case 2:
if(((count_down1) > (0f)))
{
count_down1 = ((count_down1) - (dt));
s0 = 2;
return; }else
{
goto case 0; }
case 0:
__Elems1 = (
(Enumerable.Range(0,(1) + ((1000) - (0))).ToList<System.Int32>()).Select(__ContextSymbol10 => new { ___i00 = __ContextSymbol10 })
.Select(__ContextSymbol11 => new Elem(Seed))
.ToList<Elem>()).ToList<Elem>();
for(int i = 0; ((__Elems1.Count) > (i)); i++){
{
((__Elems1)[i])._World = this;
Elems.Add(__Elems1[i]); }
}
s0 = -1;
return;
default: return;}}
int s1=-1;
public RuleResult Rule1(float dt, World world){
switch (s1)
{
case -1:
goto case 14;
case 14:
if(!(q_temp1))
{
s1 = 14;
return RuleResult.Done; }else
{
goto case 13; }
case 13:
q_temp1 = false;
if(((World1) == (Elems)))
{
goto case 11; }else
{
goto case 9; }
case 11:
_Elems = new List<Elem>(Elems);
goto case 9;
case 9:
World1.Clear();
counter31 = -1;
if((((Elems).Count) == (0)))
{
goto case 1; }else
{
___s1 = (Elems)[0];
goto case 3; }
case 3:
counter31 = ((counter31) + (1));
if((((((Elems).Count) == (counter31))) || (((counter31) > ((Elems).Count)))))
{
goto case 1; }else
{
___s1 = (Elems)[counter31];
goto case 4; }
case 4:
if(!(___s1.Counter))
{
goto case 6; }else
{
goto case 3; }
case 6:
___s1._World = this;
World1.Add(___s1);
goto case 3;
case 1:
q_temp1 = false;
Elems = World1;
s1 = -1;
return RuleResult.Working;
default: return RuleResult.Done;}}
}
public class Elem{
public int frame;
public bool JustEntered = true;
private System.Random Seed;
public int ID;
public Elem(System.Random Seed)
{JustEntered = false;
frame = World.frame;
this.ID = World.ElemCounter++;
World.NotifySlotElemCounterElem0.Add(ID, new List<Elem>());
World.NotifySlotElemVElem3.Add(ID, new List<Elem>());
World.NotifySlotElemCounterElem0[ID].Add(this);
World.NotifySlotElemVElem3[ID].Add(this);
Velocity = Vector3.zero;
V = -1;
UnityCube = UnityCube.Instantiate(new UnityEngine.Vector3(((((System.Single)Seed.NextDouble())) * (500)) - (250f),((((System.Single)Seed.NextDouble())) * (300)) - (150f),0f));
Counter = false;
}
public void Init() { Velocity = Vector3.zero;
V = -1;
UnityCube = UnityCube.Instantiate(new UnityEngine.Vector3(((((System.Single)Seed.NextDouble())) * (500)) - (250f),((((System.Single)Seed.NextDouble())) * (300)) - (150f),0f));
Counter = false;
}
public System.Boolean _Counter;
public System.Boolean Destroyed{ get { return UnityCube.Destroyed; }
set{UnityCube.Destroyed = value; }
}
public UnityEngine.Vector3 Position{ get { return UnityCube.Position; }
set{UnityCube.Position = value; }
}
public UnityCube UnityCube;
public System.Int32 _V;
public UnityEngine.Vector3 Velocity;
public System.Boolean enabled{ get { return UnityCube.enabled; }
set{UnityCube.enabled = value; }
}
public UnityEngine.GameObject gameObject{ get { return UnityCube.gameObject; }
}
public UnityEngine.HideFlags hideFlags{ get { return UnityCube.hideFlags; }
set{UnityCube.hideFlags = value; }
}
public System.Boolean isActiveAndEnabled{ get { return UnityCube.isActiveAndEnabled; }
}
public System.String name{ get { return UnityCube.name; }
set{UnityCube.name = value; }
}
public System.String tag{ get { return UnityCube.tag; }
set{UnityCube.tag = value; }
}
public UnityEngine.Transform transform{ get { return UnityCube.transform; }
}
public System.Boolean useGUILayout{ get { return UnityCube.useGUILayout; }
set{UnityCube.useGUILayout = value; }
}
public World _World;
public System.Boolean _cond01;
public System.Single count_down2;
public System.Single count_down3;
public RuleTable ActiveRules = new RuleTable(2);
public System.Boolean Counter{
get { return _Counter; }
set {
_Counter = value;
for(int i = 0; i < World.NotifySlotElemCounterElem0[ID].Count; i++) {
var entity = World.NotifySlotElemCounterElem0[ID][i];
if (entity.frame == World.frame){ if(!World.ElemWithActiveRules.ContainsKey(entity.ID))
World.ElemWithActiveRules.Add(entity.ID,new Tuple<Elem, RuleTable>(entity, new RuleTable(4)));World.ElemWithActiveRules[entity.ID].Item2.Add(0);
}else{ entity.JustEntered = true;
World.NotifySlotElemCounterElem0.Remove(entity.ID);
World.NotifySlotElemVElem3.Remove(entity.ID);
}}
}
}
public System.Int32 V{
get { return _V; }
set {
_V = value;
for(int i = 0; i < World.NotifySlotElemVElem3[ID].Count; i++) {
var entity = World.NotifySlotElemVElem3[ID][i];
if (entity.frame == World.frame){ if(!World.ElemWithActiveRules.ContainsKey(entity.ID))
World.ElemWithActiveRules.Add(entity.ID,new Tuple<Elem, RuleTable>(entity, new RuleTable(4)));World.ElemWithActiveRules[entity.ID].Item2.Add(3);
}else{ entity.JustEntered = true;
World.NotifySlotElemCounterElem0.Remove(entity.ID);
World.NotifySlotElemVElem3.Remove(entity.ID);
}}
}
}
public void Update(float dt, World world) {
frame = World.frame; this.Rule2(dt, world);
this.Rule1(dt, world);
}
public void UpdateSuspendedRules(float dt, World world, List<int> toRemove, RuleTable ActiveRules) { if (ActiveRules.ActiveIndices.Top > 0 && frame == World.frame)
{
for (int i = 0; i < ActiveRules.ActiveIndices.Top; i++)
{
var x = ActiveRules.ActiveIndices.Elements[i];
switch (x)
{case 0:
if (this.Rule0(dt, world) == RuleResult.Done)
{
ActiveRules.ActiveSlots[i] = false;
ActiveRules.ActiveIndices.Top--;
}
else{
ActiveRules.SupportSlots[0] = true;
ActiveRules.SupportStack.Push(x);
}
break;
case 3:
if (this.Rule3(dt, world) == RuleResult.Done)
{
ActiveRules.ActiveSlots[i] = false;
ActiveRules.ActiveIndices.Top--;
}
else{
ActiveRules.SupportSlots[3] = true;
ActiveRules.SupportStack.Push(x);
}
break;
default:
break;
}
}
ActiveRules.ActiveIndices.Clear();
ActiveRules.Clear();
var tmp = ActiveRules.SupportStack;
var tmp1 = ActiveRules.SupportSlots;
ActiveRules.SupportStack = ActiveRules.ActiveIndices;
ActiveRules.SupportSlots = ActiveRules.ActiveSlots;
ActiveRules.ActiveIndices = tmp;
ActiveRules.ActiveSlots = tmp1;
if (ActiveRules.ActiveIndices.Top == 0)
toRemove.Add(ID);
}else
{
if (this.frame != World.frame)
toRemove.Add(ID);
} }
public void Rule2(float dt, World world)
{
Position = (Position) + ((Velocity) * (dt));
}
int s1=-1;
public void Rule1(float dt, World world){
switch (s1)
{
case -1:
count_down2 = ((((((System.Single)world.Seed.NextDouble())) * (6))) + (8f));
goto case 2;
case 2:
if(((count_down2) > (0f)))
{
count_down2 = ((count_down2) - (dt));
s1 = 2;
return; }else
{
goto case 0; }
case 0:
Velocity = new UnityEngine.Vector3(((((System.Single)world.Seed.NextDouble())) * (10f)) - (5f),((((System.Single)world.Seed.NextDouble())) * (10f)) - (5f),0f);
V = 0;
s1 = -1;
return;
default: return;}}
int s0=-1;
public RuleResult Rule0(float dt, World world){
switch (s0)
{
case -1:
_cond01 = Counter;
goto case 11;
case 11:
if(!(((!(((_cond01) == (Counter)))) || (false))))
{
s0 = 11;
return RuleResult.Done; }else
{
goto case 2; }
case 2:
if(!(Counter))
{
goto case 0; }else
{
goto case 1; }
case 0:
if(!(_World.World1.Contains(this)))
{
goto case 3; }else
{
goto case 4; }
case 3:
_World.World1.Add(this);
goto case -1;
case 4:
goto case -1;
case 1:
_World.World1.Remove(this);
goto case -1;
default: return RuleResult.Done;}}
int s3=-1;
public RuleResult Rule3(float dt, World world){
switch (s3)
{
case -1:
if(!(((V) == (0))))
{
s3 = -1;
return RuleResult.Done; }else
{
goto case 3; }
case 3:
Counter = false;
Destroyed = false;
s3 = 1;
return RuleResult.Working;
case 1:
count_down3 = ((((((System.Single)world.Seed.NextDouble())) * (2f))) + (5f));
goto case 2;
case 2:
if(((count_down3) > (0f)))
{
count_down3 = ((count_down3) - (dt));
s3 = 2;
return RuleResult.Working; }else
{
goto case 0; }
case 0:
Counter = true;
Destroyed = true;
s3 = -1;
return RuleResult.Working;
default: return RuleResult.Done;}}
}
}
| |
//
// 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
{
using System;
using System.Linq;
using NLog.Internal;
/// <summary>
/// Async version of <see cref="NestedDiagnosticsContext" /> - a logical context structure that keeps a stack
/// Allows for maintaining scope across asynchronous tasks and call contexts.
/// </summary>
[Obsolete("Replaced by ScopeContext.PushNestedState or Logger.PushScopeNested using ${scopenested}. Marked obsolete on NLog 5.0")]
public static class NestedDiagnosticsLogicalContext
{
/// <summary>
/// Pushes the specified value on current stack
/// </summary>
/// <param name="value">The value to be pushed.</param>
/// <returns>An instance of the object that implements IDisposable that returns the stack to the previous level when IDisposable.Dispose() is called. To be used with C# using() statement.</returns>
[Obsolete("Replaced by ScopeContext.PushNestedState or Logger.PushScopeNested using ${scopenested}. Marked obsolete on NLog 5.0")]
public static IDisposable Push<T>(T value)
{
return ScopeContext.PushNestedState(value);
}
/// <summary>
/// Pushes the specified value on current stack
/// </summary>
/// <param name="value">The value to be pushed.</param>
/// <returns>An instance of the object that implements IDisposable that returns the stack to the previous level when IDisposable.Dispose() is called. To be used with C# using() statement.</returns>
[Obsolete("Replaced by ScopeContext.PushNestedState or Logger.PushScopeNested using ${scopenested}. Marked obsolete on NLog 5.0")]
public static IDisposable PushObject(object value)
{
return Push(value);
}
/// <summary>
/// Pops the top message off the NDLC stack.
/// </summary>
/// <returns>The top message which is no longer on the stack.</returns>
/// <remarks>this methods returns a object instead of string, this because of backwards-compatibility</remarks>
[Obsolete("Replaced by dispose of return value from ScopeContext.PushNestedState or Logger.PushScopeNested. Marked obsolete on NLog 5.0")]
public static object Pop()
{
return PopObject();
}
/// <summary>
/// Pops the top message from the NDLC stack.
/// </summary>
/// <param name="formatProvider">The <see cref="IFormatProvider"/> to use when converting the value to a string.</param>
/// <returns>The top message, which is removed from the stack, as a string value.</returns>
[Obsolete("Replaced by dispose of return value from ScopeContext.PushNestedState or Logger.PushScopeNested. Marked obsolete on NLog 5.0")]
public static string Pop(IFormatProvider formatProvider)
{
return FormatHelper.ConvertToString(PopObject() ?? string.Empty, formatProvider);
}
/// <summary>
/// Pops the top message off the current NDLC stack
/// </summary>
/// <returns>The object from the top of the NDLC stack, if defined; otherwise <c>null</c>.</returns>
[Obsolete("Replaced by dispose of return value from ScopeContext.PushNestedState or Logger.PushScopeNested. Marked obsolete on NLog 5.0")]
public static object PopObject()
{
return ScopeContext.PopNestedContextLegacy();
}
/// <summary>
/// Peeks the top object on the current NDLC stack
/// </summary>
/// <returns>The object from the top of the NDLC stack, if defined; otherwise <c>null</c>.</returns>
[Obsolete("Replaced by ScopeContext.PeekNestedState. Marked obsolete on NLog 5.0")]
public static object PeekObject()
{
return ScopeContext.PeekNestedState();
}
/// <summary>
/// Clears current stack.
/// </summary>
[Obsolete("Replaced by ScopeContext.Clear. Marked obsolete on NLog 5.0")]
public static void Clear()
{
ScopeContext.ClearNestedContextLegacy();
}
/// <summary>
/// Gets all messages on the stack.
/// </summary>
/// <returns>Array of strings on the stack.</returns>
[Obsolete("Replaced by ScopeContext.GetAllNestedStates. Marked obsolete on NLog 5.0")]
public static string[] GetAllMessages()
{
return GetAllMessages(null);
}
/// <summary>
/// Gets all messages from the stack, without removing them.
/// </summary>
/// <param name="formatProvider">The <see cref="IFormatProvider"/> to use when converting a value to a string.</param>
/// <returns>Array of strings.</returns>
[Obsolete("Replaced by ScopeContext.GetAllNestedStates. Marked obsolete on NLog 5.0")]
public static string[] GetAllMessages(IFormatProvider formatProvider)
{
return GetAllObjects().Select((o) => FormatHelper.ConvertToString(o, formatProvider)).ToArray();
}
/// <summary>
/// Gets all objects on the stack. The objects are not removed from the stack.
/// </summary>
/// <returns>Array of objects on the stack.</returns>
[Obsolete("Replaced by ScopeContext.GetAllNestedStates. Marked obsolete on NLog 5.0")]
public static object[] GetAllObjects()
{
return ScopeContext.GetAllNestedStates();
}
[Obsolete("Required to be compatible with legacy NLog versions, when using remoting. Marked obsolete on NLog 5.0")]
interface INestedContext : IDisposable
{
INestedContext Parent { get; }
int FrameLevel { get; }
object Value { get; }
long CreatedTimeUtcTicks { get; }
}
#if !NETSTANDARD1_3 && !NETSTANDARD1_5
[Serializable]
#endif
[Obsolete("Required to be compatible with legacy NLog versions, when using remoting. Marked obsolete on NLog 5.0")]
sealed class NestedContext<T> : INestedContext
{
public INestedContext Parent { get; }
public T Value { get; }
public long CreatedTimeUtcTicks { get; }
public int FrameLevel { get; }
private int _disposed;
object INestedContext.Value
{
get
{
object value = Value;
#if NET35 || NET40 || NET45
if (value is ObjectHandleSerializer objectHandle)
{
return objectHandle.Unwrap();
}
#endif
return value;
}
}
public NestedContext(INestedContext parent, T value)
{
Parent = parent;
Value = value;
CreatedTimeUtcTicks = DateTime.UtcNow.Ticks; // Low time resolution, but okay fast
FrameLevel = parent?.FrameLevel + 1 ?? 1;
}
void IDisposable.Dispose()
{
if (System.Threading.Interlocked.Exchange(ref _disposed, 1) != 1)
{
PopObject();
}
}
public override string ToString()
{
object value = Value;
return value?.ToString() ?? "null";
}
}
}
}
| |
/*
* 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.Collections.Generic;
using System.Globalization;
using System.Linq;
using MindTouch.Deki.Data;
using MindTouch.Xml;
namespace MindTouch.Deki.Logic {
public static class NavBL {
//--- Constants ---
internal const int NEW_PAGE_ID = 1000000000;
//--- Types ---
internal enum NavDocStage {
None,
Ancestors,
SiblingPre,
ChildrenPre,
ChildrenPost,
SiblingPost
}
public class ExpandableNavPage {
//--- Fields ---
public List<ExpandableNavPage> Children = new List<ExpandableNavPage>();
public bool IsHomepage;
public ExpandableNavPage Parent;
public bool LastParent;
internal NavBE NavPage;
private bool _isAncestor;
private bool _isSelected;
//--- Constructors ---
public ExpandableNavPage(NavBE navPage) {
this.NavPage = navPage;
}
//--- Properties ---
public bool IsAncestor {
get { return _isAncestor; }
set {
_isAncestor = value;
if(value && Parent != null && Parent.NavPage.Id != DekiContext.Current.Instance.HomePageId) {
Parent.IsAncestor = true;
}
}
}
public bool IsSelected {
get { return _isSelected; }
set {
_isSelected = value;
if(value && Parent != null) {
Parent.IsAncestor = true;
}
}
}
}
//--- Class Methods ---
public static IList<NavBE> QueryNavTreeData(PageBE page, CultureInfo culture, bool includeAllChildren) {
IList<NavBE> navPages = DbUtils.CurrentSession.Nav_GetTree(page, includeAllChildren);
navPages = FilterDisallowedNavRecords(navPages, page);
navPages = SortNavRecords(navPages, culture);
return navPages;
}
public static IList<NavBE> QueryNavSiblingsData(PageBE page, CultureInfo culture) {
IList<NavBE> navPages = DbUtils.CurrentSession.Nav_GetSiblings(page);
navPages = FilterDisallowedNavRecords(navPages);
navPages = SortNavRecords(navPages, culture);
return navPages;
}
public static IList<NavBE> QueryNavChildrenData(PageBE page, CultureInfo culture) {
IList<NavBE> navPages = DbUtils.CurrentSession.Nav_GetChildren(page);
navPages = FilterDisallowedNavRecords(navPages);
navPages = SortNavRecords(navPages, culture);
return navPages;
}
public static IList<NavBE> QueryNavSiblingsAndChildrenData(PageBE page, CultureInfo culture) {
IList<NavBE> navPages = DbUtils.CurrentSession.Nav_GetSiblingsAndChildren(page);
navPages = FilterDisallowedNavRecords(navPages);
navPages = SortNavRecords(navPages, culture);
return navPages;
}
public static XDoc ConvertNavPageListToDoc(IList<NavBE> navPages) {
XDoc ret = new XDoc("pages");
foreach(NavBE np in navPages) {
ret.Start("page")
.Start("page_id").Value(np.Id).End()
.Start("page_namespace").Value(np.NameSpace).End()
.Start("page_title").Value(np.Title).End()
.Start("page_parent").Value(np.ParentId).End()
.Start("page_children").Value(np.ChildCount).End()
.End();
}
return ret;
}
public static XDoc ComputeExpandableNavigationDocument(IList<NavBE> list, PageBE page, uint splitSibling, uint splitChildren, bool hidden) {
return CreateExpandableTree(list, page);
}
public static XDoc ComputeNavigationDocument(IList<NavBE> list, PageBE page, uint splitSibling, uint splitChildren, bool hidden, int max_width) {
XDoc result = new XDoc("tree");
List<string> css = new List<string>();
List<string> fetchedChildren = new List<string>();
List<NavBE> childrenNodes = new List<NavBE>();
ulong homepageId = DekiContext.Current.Instance.HomePageId;
NavDocStage stage = NavDocStage.None;
if (splitSibling > 0) {
stage = NavDocStage.SiblingPre;
result.Start("siblings-pre");
} else if (splitChildren > 0) {
stage = NavDocStage.ChildrenPre;
result.Start("siblings-pre").End();
result.Start("children-pre");
}
int splitSiblingIndex = 0;
int splitChildrenIndex = 0;
// fix page_parent_id: it's stored as zero for home and children of home
ulong page_parent_id = page.ParentID;
if ((page_parent_id == 0) && (page.ID != homepageId)) {
page_parent_id = homepageId;
}
int page_index = 0;
// iterate over result set
int siblingIndex = 0;
int childIndex = 0;
foreach(NavBE node in list) {
// retrieve page values
uint node_id = node.Id;
ulong node_parent_id = node.ParentId;
bool virtual_node = (node_id >= NEW_PAGE_ID);
// fix parent_id: it's stored as zero for home and children of home
if ((node_parent_id == 0) && (node_id != homepageId)) {
node_parent_id = homepageId;
}
// set node index (if possible)
if (node_id == page.ID) {
page_index = siblingIndex;
}
// check if we need to split the output
if (node_id == splitSibling) {
splitSiblingIndex = siblingIndex;
stage = NavDocStage.ChildrenPre;
result.End().Start("children-pre");
if (splitChildren == 0) {
stage = NavDocStage.ChildrenPost;
result.End().Start("children-post");
}
continue;
}
if (node_id == splitChildren) {
splitChildrenIndex = childIndex;
stage = NavDocStage.ChildrenPost;
result.End().Start("children-post");
continue;
}
if (((stage == NavDocStage.ChildrenPre) || (stage == NavDocStage.ChildrenPost)) && (splitSibling > 0) && (node_parent_id != splitSibling)) {
if (stage == NavDocStage.ChildrenPre) {
result.End().Start("children-post");
}
stage = NavDocStage.SiblingPost;
result.End().Start("siblings-post");
}
// check if this node is part of the result set (only include ancestors, siblings, and children of selected node)
bool ancestor = false;
Title nodeTitle = Title.FromDbPath((NS)node.NameSpace, node.Title, node.DisplayName);
if ((node_id != page.ID /* selected */) && (node_parent_id != page_parent_id /* sibling */) && (node_parent_id != page.ID /* child */)) {
ancestor = (node_id == page_parent_id /* immediate parent */) || (node_id == homepageId) || nodeTitle.IsParentOf(page.Title);
if (!ancestor) {
continue;
}
}
// don't include siblings root user pages
if (((page.Title.IsUser) || (page.Title.IsSpecial) || (page.Title.IsTemplate)) && (page_parent_id == homepageId) && (node_parent_id == homepageId) && (node_id != page.ID)) {
continue;
}
// 'div' element
result.Start("div");
// 'class' attribute
css.Clear();
css.Add("node");
if (hidden) {
css.Add("closedNode");
}
// 'c' (children) attribute
fetchedChildren.Clear();
childrenNodes.Clear();
uint parentId = (node_id == homepageId) ? 0 : node_id;
for(int i =0 ; i < list.Count;++i) {
NavBE child = list[i];
if((child.ParentId == parentId) & (child.Id != homepageId)) {
Title childTitle = Title.FromDbPath((NS)child.NameSpace, child.Title, child.DisplayName);
// skip children if they are siblings of the top User: or Template: page
if(((page.Title.IsUser) || (page.Title.IsSpecial) || (page.Title.IsTemplate)) && (node_id == homepageId) && !childTitle.IsParentOf(page.Title)) {
continue;
}
childrenNodes.Add(child);
fetchedChildren.Add("n" + child.Id);
}
}
int totalChildrenCount = node.ChildCount ?? fetchedChildren.Count;
// 'p' (parent) attribute
string p = null;
if (node_id != homepageId) {
p = "n" + node_parent_id;
}
// 'cd' (child-data) and 'sd' (sibling-data) attribute
string cd = null;
string sd;
if (node_id == page.ID) {
// active node
if (node_id == homepageId) {
css.Add("dockedNode");
css.Add("homeNode");
css.Add("parentClosed");
css.Add("homeSelected");
} else {
css.Add("childNode");
if (!hidden) {
css.Add("sibling");
}
if (totalChildrenCount > 0) {
css.Add("parentOpen");
}
}
css.Add("selected");
// we have all the child data
cd = "1";
sd = "1";
} else if (node_parent_id == page_parent_id) {
// sibling of active node
css.Add("childNode");
if (!hidden) {
css.Add("sibling");
}
if (totalChildrenCount > 0) {
css.Add("parentClosed");
}
// if no children exist, then we have all the child data
cd = ((totalChildrenCount > 0) ? "0" : "1");
sd = "1";
} else if (node_parent_id == page.ID) {
// child of active node
css.Add("childNode");
if ((node_parent_id == homepageId) && !hidden) {
css.Add("sibling");
}
if ((page.ID != homepageId) && !hidden) {
css.Add("selectedChild");
}
if (totalChildrenCount > 0) {
css.Add("parentClosed");
}
// if no children exist, then we have all the child data
cd = ((totalChildrenCount > 0) ? "0" : "1");
sd = "1";
} else if (ancestor) {
// ancestor of active node (parent and above)
css.Add("dockedNode");
if (node_id == homepageId) {
css.Add("homeNode");
}
if(node_id == page_parent_id) {
css.Add("lastDocked");
}
css.Add("parentClosed");
// check if we are the last docked node or have more than one child
if ((node_id == page_parent_id) || (totalChildrenCount == 1)) {
cd = "1";
} else {
// find the child node that is actually included in the tree
foreach(NavBE child in childrenNodes) {
Title childTitle = Title.FromDbPath((NS)child.NameSpace, child.Title, child.DisplayName);
if (childTitle.IsParentOf(page.Title)) {
cd = "n" + child.Id;
break;
}
}
if (cd == null) {
#if DEBUG
throw new Exception("unexpected [expected to find child nodes]");
#else
cd = "1";
#endif
}
}
// check if parent of this node has more than one child
if ((node_id == homepageId) || (result[string.Format("div[@id='{0}']/@cd", "n" + node_parent_id)].Contents == "1")) {
sd = "1";
} else {
sd = "0";
}
} else {
throw new Exception("unexpected");
}
// attributes
result.Attr("class", string.Join(" ", css.ToArray()));
result.Attr("id", "n" + node_id.ToString());
if (fetchedChildren.Count > 0) {
result.Attr("c", string.Join(",", fetchedChildren.ToArray()));
}
if (p != null) {
result.Attr("p", p);
}
// NOTE (steveb): this is used by the JS in the browser to correlate nodes in the pane (it's never used by anything else; hence the different format)
string safe_path = nodeTitle.AsPrefixedDbPath().Replace("//", "%2f");
result.Attr("path", (safe_path.Length == 0) ? string.Empty : (safe_path + "/"));
// root page always has all children if they belong to User:, Template:, or Special: namespace
if ((cd != "1") && !virtual_node && ((page.Title.IsMain) || (((page.Title.IsTemplate) || (page.Title.IsUser) || (page.Title.IsSpecial)) && (node_id != homepageId)))) {
result.Attr("cd", cd);
}
// children of root page always have all siblings if they belong to User:, Template:, or Special: namespace
if ((sd != "1") && !virtual_node && ((page.Title.IsMain) || (((page.Title.IsTemplate) || (page.Title.IsUser) || (page.Title.IsSpecial)) && (node_parent_id != homepageId)))) {
result.Attr("sd", "0");
}
if (virtual_node || ((node_id == homepageId) && (!page.Title.IsMain))) {
result.Attr("reload", "1");
}
// div contents
result.Start("a");
// set page title
string name = nodeTitle.AsUserFriendlyName();
result.Attr("href", Utils.AsPublicUiUri(nodeTitle));
result.Attr("title", name);
result.Elem("span", DekiWikiService.ScreenFont.Truncate(name, max_width));
result.End();
result.End();
if (node_parent_id == page_parent_id) {
++siblingIndex;
} else if (node_parent_id == page.ID) {
++childIndex;
}
}
// post-process created list
if ((splitSibling > 0) || (splitChildren > 0)) {
if (stage == NavDocStage.SiblingPre) {
result.End().Start("siblings-post");
result.End().Start("children-pre");
result.End().Start("children-post");
} else if (stage == NavDocStage.ChildrenPre) {
result.End().Start("children-post");
result.End().Start("siblings-post");
} else if (stage == NavDocStage.ChildrenPost) {
result.End().Start("siblings-post");
}
result.End();
// truncate siblings and children
TruncateList(result["siblings-pre/div | siblings-post/div"], ~splitSiblingIndex, hidden);
TruncateList(result["children-pre/div | children-post/div"], ~splitChildrenIndex, hidden);
} else if (hidden) {
// truncate full list
TruncateList(result["div"], 0, hidden);
} else {
// truncate children of selected node
TruncateList(result[string.Format("div[@p='n{0}']", page.ID)], 0, hidden);
// truncate siblings of selected node
TruncateList(result[string.Format("div[@p='n{0}']", page_parent_id)], page_index, hidden);
}
return result;
}
private static void TruncateList(XDoc list, int selectedIndex, bool hidden) {
int count = list.ListLength;
// check if the selected node is a phantom node (i.e. it's not in the list, but must be accounted for)
bool phantom = false;
if (selectedIndex < 0) {
phantom = true;
++count;
selectedIndex = ~selectedIndex;
}
int max_list_count = DekiContext.Current.Instance.NavMaxItems;
int firstVisible;
int lastVisible;
if (max_list_count <= 0) {
firstVisible = 0;
lastVisible = count - 1;
} else {
firstVisible = Math.Max(0, selectedIndex - max_list_count / 2);
lastVisible = Math.Min(count - 1, selectedIndex + max_list_count / 2);
firstVisible = Math.Max(0, Math.Min(firstVisible, lastVisible - max_list_count + 1));
lastVisible = Math.Min(count - 1, firstVisible + max_list_count - 1);
}
if (firstVisible == 1) {
firstVisible = 0;
}
if (lastVisible == (count - 2)) {
lastVisible = count - 1;
}
// set nodes as hidden
List<string> firstClosed = new List<string>();
List<string> lastClosed = new List<string>();
XDoc first = null;
XDoc last = null;
int counter = 0;
foreach (XDoc current in list) {
if (!phantom || (counter != selectedIndex)) {
if (counter < firstVisible) {
XDoc css = current["@class"];
if (first == null) {
first = current;
} else {
css.ReplaceValue(css.Contents + (hidden ? " hiddenNode" : " closedNode hiddenNode"));
firstClosed.Add(current["@id"].Contents);
}
} else if (counter > lastVisible) {
XDoc css = current["@class"];
if (last == null) {
last = current;
} else {
css.ReplaceValue(css.Contents + (hidden ? " hiddenNode" : " closedNode hiddenNode"));
lastClosed.Add(current["@id"].Contents);
}
}
}
++counter;
}
// convert first and last node into '...' nodes
if (first != null) {
first["@class"].ReplaceValue(first["@class"].Contents + " moreNodes");
XDoc address = first["a"];
first.Attr("content", address.AsXmlNode.InnerText);
first.Attr("contentTitle", address["@title"].Contents);
first.Attr("hiddenNodes", string.Join(",", firstClosed.ToArray()));
address.ReplaceValue(string.Empty);
address["span"].Remove();
address.Start("span").Attr("class", "more").Value("...").End();
address["@title"].ReplaceValue(DekiResources.MORE_DOT_DOT_DOT);
}
if (last != null) {
last["@class"].ReplaceValue(last["@class"].Contents + " moreNodes");
XDoc address = last["a"];
last.Attr("content", address.AsXmlNode.InnerText);
last.Attr("contentTitle", address["@title"].Contents);
last.Attr("hiddenNodes", string.Join(",", lastClosed.ToArray()));
address.ReplaceValue(string.Empty);
address["span"].Remove();
address.Start("span").Attr("class", "more").Value("...").End();
address["@title"].ReplaceValue(DekiResources.MORE_DOT_DOT_DOT);
}
}
private static IList<NavBE> FilterDisallowedNavRecords(IList<NavBE> navPages, PageBE page) {
Dictionary<ulong, NavBE> navLookup = new Dictionary<ulong, NavBE>();
// NOTE (steveb): we collect the given page and its parent pages into a separate collection since these
// will need to be shown regardless in the nav pane.
List<NavBE> parents = new List<NavBE>();
foreach(NavBE nav in navPages) {
navLookup.Add(nav.Id, nav);
}
ulong homepageId = DekiContext.Current.Instance.HomePageId;
NavBE current;
ulong id = page.ID;
do {
if(!navLookup.TryGetValue(id, out current)) {
break;
}
parents.Add(current);
navLookup.Remove(id);
id = ((current.ParentId == 0) && current.Id != homepageId) ? homepageId : current.ParentId;
} while(current.Id != homepageId);
// filter non-parent pages from nav pane
IList<NavBE> allowed = FilterDisallowedNavRecords(new List<NavBE>(navLookup.Values));
// add parent page back
allowed.AddRange(parents);
return allowed;
}
private static IList<NavBE> FilterDisallowedNavRecords(IList<NavBE> navPages) {
Dictionary<ulong,NavBE> pagesToCheck = new Dictionary<ulong, NavBE>();
List<NavBE> allowedPages = new List<NavBE>(navPages.Count);
Permissions userPermissions = PermissionsBL.GetUserPermissions(DekiContext.Current.User);
foreach (NavBE np in navPages) {
ulong effectivePageRights = PermissionsBL.CalculateEffectivePageRights(new PermissionStruct((ulong)userPermissions, np.RestrictionFlags ?? ulong.MaxValue, 0));
if(!PermissionsBL.IsActionAllowed(effectivePageRights, false, Permissions.BROWSE)) {
pagesToCheck.Add(np.Id,np);
} else {
allowedPages.Add(np);
}
}
if(pagesToCheck.Count > 0) {
ulong[] filteredOutPages;
var allowedIds = PermissionsBL.FilterDisallowed(DekiContext.Current.User, pagesToCheck.Keys.ToArray(), false, out filteredOutPages, Permissions.BROWSE);
foreach (ulong allowedId in allowedIds) {
allowedPages.Add(pagesToCheck[allowedId]);
}
return allowedPages;
} else {
//No changes made..
return navPages;
}
}
private static IList<NavBE> SortNavRecords(IList<NavBE> navPages, CultureInfo culture) {
List<NavBE> navPagesList = new List<NavBE>(navPages);
navPagesList.Sort(delegate(NavBE left, NavBE right) {
int compare = left.NameSpace - right.NameSpace;
if (compare != 0) {
return compare;
}
return string.Compare(left.SortableTitle, right.SortableTitle, true, culture);
});
return navPagesList;
}
private static XDoc CreateExpandableTree(IList<NavBE> list, PageBE page) {
List<ExpandableNavPage> tree = new List<ExpandableNavPage>();
bool onlyChildren = list.Count(s => s.ParentId == 0 || s.ParentId == DekiContext.Current.Instance.HomePageId) == 0;
foreach(NavBE node in list) {
uint node_id = node.Id;
ulong homepageId = DekiContext.Current.Instance.HomePageId;
uint parentId = (node_id == homepageId) ? 0 : node_id;
ulong node_parent_id = node.ParentId;
// fix parent_id: it's stored as zero for home and children of home
if((node_parent_id == 0) && (node_id != homepageId)) {
node_parent_id = homepageId;
}
// fix page_parent_id: it's stored as zero for home and children of home
ulong page_parent_id = (ulong)page.ParentID;
if((page_parent_id == 0) && (page.ID != homepageId)) {
page_parent_id = homepageId;
}
// don't include siblings root user pages
if(((page.Title.IsUser) || (page.Title.IsSpecial) || (page.Title.IsTemplate)) && (page_parent_id == homepageId) && (node_parent_id == homepageId) && (node_id != page.ID)) {
continue;
}
var sNode = new ExpandableNavPage(node);
BuildExpandableTree(list, sNode, page);
if(onlyChildren || (node.ParentId == 0 || node.ParentId == DekiContext.Current.Instance.HomePageId)) {
tree.Add(sNode);
}
}
tree[tree.Count - 1].LastParent = true;
XDoc result = new XDoc("tree");
return CreateExpandableTreeDoc(ref result, tree);
}
private static void BuildExpandableTree(IList<NavBE> list, ExpandableNavPage node, PageBE page) {
uint node_id = node.NavPage.Id;
ulong homepageId = DekiContext.Current.Instance.HomePageId;
uint parentId = (node_id == homepageId) ? 0 : node_id;
foreach(NavBE child in list) {
if((child.ParentId == parentId) & (child.Id != homepageId)) {
Title childTitle = Title.FromDbPath((NS)child.NameSpace, child.Title, child.DisplayName);
// skip children if they are siblings of the top User: or Template: page
if(((page.Title.IsUser) || (page.Title.IsSpecial) || (page.Title.IsTemplate)) && (node_id == homepageId) && !childTitle.IsParentOf(page.Title)) {
continue;
}
var sChild = new ExpandableNavPage(child);
sChild.Parent = node;
node.Children.Add(sChild);
///recursive.
BuildExpandableTree(list, sChild, page);
}
}
if(node_id == page.ID) {
node.IsSelected = true;
}
if(node_id == homepageId) {
node.IsHomepage = true;
}
}
private static XDoc CreateExpandableTreeDoc(ref XDoc result, List<ExpandableNavPage> tree) {
foreach(ExpandableNavPage branch in tree) {
CreateExpandableTreeChildrenDoc(ref result, branch);
}
return result;
}
private static void CreateExpandableTreeChildrenDoc(ref XDoc result, ExpandableNavPage branch) {
uint nodeID = branch.NavPage.Id;
// fix page_parent_id: it's stored as zero for home and children of home
Title nodeTitle = Title.FromDbPath((NS)branch.NavPage.NameSpace, branch.NavPage.Title, branch.NavPage.DisplayName);
string name = nodeTitle.AsUserFriendlyName();
List<string> css = new List<string>();
result.Start("ul");
if(branch.Parent != null && branch.Parent.Children[branch.Parent.Children.Count - 1] == branch) {
css.Add("lastNode");
} else if(branch.LastParent) {
css.Add("lastNode");
}
if(branch.IsHomepage) {
css.Add("homepage");
}
result.Attr("class", String.Join(" ", css.ToArray()));
css.Clear();
result.Start("li");
result.Attr("id", "n" + nodeID);
bool isChild = false;
css.Add("node");
if(branch.IsAncestor) {
css.Add("ancestor");
}
if(branch.IsSelected) {
css.Add("selected");
}
if(branch.IsHomepage) {
css.Add("homeNode");
} else {
if(branch.Children.Count > 0 || branch.NavPage.ChildCount > 0) {
css.Add(branch.IsAncestor || branch.IsSelected ? "parentOpen" : "parentClosed");
} else {
css.Add("child");
isChild = true;
}
}
result.Attr("class", String.Join(" ", css.ToArray()));
///Icon Spacer
result.Start("div");
result.Attr("class", "icon");
if(!isChild) {
result.Attr("onclick", "DekiExpandableNav.Toggle(this,event);");
}
///Link.
result.Start("a").Value(name);
const string stopBubbelingScript = @"if (!event) var event = window.event; event.cancelBubble = true; if (event.stopPropagation) event.stopPropagation();";
result.Attr("onclick", stopBubbelingScript);
if(css.Contains("selected")) {
result.Attr("class", "selected");
} else if(css.Contains("ancestor")) {
result.Attr("class", "ancestor");
} else if(branch.IsHomepage) {
result.Attr("class", "homepage");
}
result.Attr("title", name);
result.Attr("href", Utils.AsPublicUiUri(nodeTitle));
result.End();
result.End();
if(branch.Children.Count > 0 && branch.NavPage.Id != DekiContext.Current.Instance.HomePageId) {
foreach(ExpandableNavPage cBranch in branch.Children) {
CreateExpandableTreeChildrenDoc(ref result, cBranch);
}
}
result.End();
result.End();
}
}
}
| |
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
using System.Threading;
using Mono.Collections.Generic;
namespace Mono.Cecil.Cil {
public sealed class MethodBody {
readonly internal MethodDefinition method;
internal ParameterDefinition this_parameter;
internal int max_stack_size;
internal int code_size;
internal bool init_locals;
internal MetadataToken local_var_token;
internal Collection<Instruction> instructions;
internal Collection<ExceptionHandler> exceptions;
internal Collection<VariableDefinition> variables;
public MethodDefinition Method {
get { return method; }
}
public int MaxStackSize {
get { return max_stack_size; }
set { max_stack_size = value; }
}
public int CodeSize {
get { return code_size; }
// HACK - Reflexil - Setter
set { code_size = value; }
}
public bool InitLocals {
get { return init_locals; }
set { init_locals = value; }
}
public MetadataToken LocalVarToken {
get { return local_var_token; }
set { local_var_token = value; }
}
public Collection<Instruction> Instructions {
get { return instructions ?? (instructions = new InstructionCollection (method)); }
}
public bool HasExceptionHandlers {
get { return !exceptions.IsNullOrEmpty (); }
}
public Collection<ExceptionHandler> ExceptionHandlers {
get { return exceptions ?? (exceptions = new Collection<ExceptionHandler> ()); }
}
public bool HasVariables {
get { return !variables.IsNullOrEmpty (); }
}
public Collection<VariableDefinition> Variables {
get { return variables ?? (variables = new VariableDefinitionCollection ()); }
}
public ParameterDefinition ThisParameter {
get {
if (method == null || method.DeclaringType == null)
throw new NotSupportedException ();
if (!method.HasThis)
return null;
if (this_parameter == null)
Interlocked.CompareExchange (ref this_parameter, CreateThisParameter (method), null);
return this_parameter;
}
}
static ParameterDefinition CreateThisParameter (MethodDefinition method)
{
var parameter_type = method.DeclaringType as TypeReference;
if (parameter_type.HasGenericParameters) {
var instance = new GenericInstanceType (parameter_type);
for (int i = 0; i < parameter_type.GenericParameters.Count; i++)
instance.GenericArguments.Add (parameter_type.GenericParameters [i]);
parameter_type = instance;
}
if (parameter_type.IsValueType || parameter_type.IsPrimitive)
parameter_type = new ByReferenceType (parameter_type);
return new ParameterDefinition (parameter_type, method);
}
public MethodBody (MethodDefinition method)
{
this.method = method;
}
public ILProcessor GetILProcessor ()
{
return new ILProcessor (this);
}
}
sealed class VariableDefinitionCollection : Collection<VariableDefinition> {
internal VariableDefinitionCollection ()
{
}
internal VariableDefinitionCollection (int capacity)
: base (capacity)
{
}
protected override void OnAdd (VariableDefinition item, int index)
{
item.index = index;
}
protected override void OnInsert (VariableDefinition item, int index)
{
item.index = index;
for (int i = index; i < size; i++)
items [i].index = i + 1;
}
protected override void OnSet (VariableDefinition item, int index)
{
item.index = index;
}
protected override void OnRemove (VariableDefinition item, int index)
{
item.index = -1;
for (int i = index + 1; i < size; i++)
items [i].index = i - 1;
}
}
class InstructionCollection : Collection<Instruction> {
readonly MethodDefinition method;
internal InstructionCollection (MethodDefinition method)
{
this.method = method;
}
internal InstructionCollection (MethodDefinition method, int capacity)
: base (capacity)
{
this.method = method;
}
protected override void OnAdd (Instruction item, int index)
{
if (index == 0)
return;
var previous = items [index - 1];
previous.next = item;
item.previous = previous;
}
protected override void OnInsert (Instruction item, int index)
{
if (size == 0)
return;
var current = items [index];
if (current == null) {
var last = items [index - 1];
last.next = item;
item.previous = last;
return;
}
var previous = current.previous;
if (previous != null) {
previous.next = item;
item.previous = previous;
}
current.previous = item;
item.next = current;
}
protected override void OnSet (Instruction item, int index)
{
var current = items [index];
item.previous = current.previous;
item.next = current.next;
current.previous = null;
current.next = null;
}
protected override void OnRemove (Instruction item, int index)
{
var previous = item.previous;
if (previous != null)
previous.next = item.next;
var next = item.next;
if (next != null)
next.previous = item.previous;
RemoveSequencePoint (item);
item.previous = null;
item.next = null;
}
void RemoveSequencePoint (Instruction instruction)
{
var debug_info = method.debug_info;
if (debug_info == null || !debug_info.HasSequencePoints)
return;
var sequence_points = debug_info.sequence_points;
for (int i = 0; i < sequence_points.Count; i++) {
if (sequence_points [i].Offset == instruction.offset) {
sequence_points.RemoveAt (i);
return;
}
}
}
}
}
| |
// Inspired by Simple AES
// https://github.com/ArtisanCode/SimpleAesEncryption
// The MIT License (MIT)
// Copyright(c) 2014 Artisan code
using System;
using System.IO;
using System.Security.Cryptography;
namespace Dks.SimpleToken.Protectors
{
internal sealed class AESMessageHandler
{
public const string CYPHER_TEXT_IV_SEPERATOR = "??";
/// <summary>
/// Initializes a new instance of the <see cref="AESMessageHandler"/> class.
/// </summary>
/// <param name="config">The configuration.</param>
public AESMessageHandler(AESEncryptionConfiguration config)
{
Configuration = config ?? throw new ArgumentNullException(nameof(config));
}
/// <summary>
/// Gets or sets the configuration.
/// </summary>
/// <value>
/// The configuration.
/// </value>
public AESEncryptionConfiguration Configuration { get; set; }
/// <summary>
/// Configures the crypto container.
/// </summary>
/// <param name="cryptoContainer">The crypto container to configure.</param>
private void ConfigureCryptoContainer(SymmetricAlgorithm cryptoContainer)
{
cryptoContainer.Mode = Configuration.CipherMode;
cryptoContainer.Padding = Configuration.Padding;
cryptoContainer.KeySize = Configuration.KeySize;
cryptoContainer.Key = Convert.FromBase64String(Configuration.EncryptionKey);
// Generate a new Unique IV for this container and transaction (can be overridden later to decrypt messages where the IV is known)
cryptoContainer.GenerateIV();
}
/// <summary>
/// Encrypts the specified source.
/// </summary>
/// <param name="source">The source.</param>
/// <returns></returns>
public string Encrypt(string source)
{
// Short-circuit encryption for empty strings
if (string.IsNullOrEmpty(source))
{
return string.Empty;
}
// Encrypt the string to an array of bytes.
var output = EncryptStringToBytes(source);
// Return the Base64 encoded cypher-text along with the (plaintext) unique IV used for this encryption
return string.Format("{0}{1}{2}", Convert.ToBase64String(output.Item1), CYPHER_TEXT_IV_SEPERATOR, Convert.ToBase64String(output.Item2));
}
/// <summary>
/// Encrypts the string to bytes.
/// </summary>
/// <param name="plainText">The plain text.</param>
/// <remarks>
/// Original version: http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged.aspx
/// 20/05/2014 @ 20:05
/// </remarks>
/// <returns>
/// Item 1: The cyphertext that is generated from the plaintext input
/// Item 2: The IV used for the encryption algorithm
/// </returns>
public Tuple<byte[], byte[]> EncryptStringToBytes(string plainText)
{
Tuple<byte[], byte[]> output;
using (var cryptoContainer = Aes.Create())
{
ConfigureCryptoContainer(cryptoContainer);
// Create an encryptor to perform the stream transform.
var encryptor = cryptoContainer.CreateEncryptor(cryptoContainer.Key, cryptoContainer.IV);
// Create the streams used for encryption.
using (var msEncrypt = new MemoryStream())
{
using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (var swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
output = new Tuple<byte[], byte[]>(msEncrypt.ToArray(), cryptoContainer.IV);
}
}
}
// Return the encrypted bytes from the memory stream.
return output;
}
/// <summary>
/// Decrypts the specified cypherText.
/// </summary>
/// <param name="cypherText">The cypherText to decrypt.</param>
/// <returns>The plaintext decrypted version of the cypher text</returns>
/// <exception cref="System.ArgumentException">Invalid source string. Unable to determine the correct IV used for the encryption. Please ensure the source string is in the format 'Cypher Text' + CYPHER_TEXT_IV_SEPERATOR + 'IV';source</exception>
public string Decrypt(string cypherText)
{
// Short-circuit decryption for empty strings
if (string.IsNullOrEmpty(cypherText))
{
return string.Empty;
}
var primitives = cypherText.Split(new[] { CYPHER_TEXT_IV_SEPERATOR }, StringSplitOptions.RemoveEmptyEntries);
if (primitives.Length != 2)
{
throw new ArgumentException("Invalid cypherText. Unable to determine the correct IV used for the encryption. Please ensure the source string is in the format 'Cypher Text'" + CYPHER_TEXT_IV_SEPERATOR + "'IV'", "source");
}
var cypherTextPrimitave = Convert.FromBase64String(primitives[0]);
var iv = Convert.FromBase64String(primitives[1]);
return DecryptStringFromBytes(cypherTextPrimitave, iv);
}
/// <summary>
/// Decrypts the string from bytes.
/// </summary>
/// <param name="cipherText">The cipher text.</param>
/// <param name="Key">The key.</param>
/// <param name="IV">The iv.</param>
/// <returns></returns>
/// <remarks>
/// Original version: http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged.aspx
/// 20/05/2014 @ 20:05
/// </remarks>
/// <exception cref="System.ArgumentNullException">
/// cipherText
/// or
/// IV
/// </exception>
public string DecryptStringFromBytes(byte[] cipherText, byte[] IV)
{
// Check arguments.
if (cipherText == null || cipherText.Length <= 0)
{
throw new ArgumentNullException("cipherText");
}
if (IV == null || IV.Length <= 0)
{
throw new ArgumentNullException("IV");
}
// Declare the string used to hold
// the decrypted text.
string plaintext = null;
// Create an RijndaelManaged object
// with the specified key and IV.
using (var cryptoContainer = Aes.Create())
{
ConfigureCryptoContainer(cryptoContainer);
// Remember to set the IV to the correct value for decryption
cryptoContainer.IV = IV;
// Create a decrytor to perform the stream transform.
var decryptor = cryptoContainer.CreateDecryptor(cryptoContainer.Key, cryptoContainer.IV);
// Create the streams used for decryption.
using (var msDecrypt = new MemoryStream(cipherText))
{
using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (var srDecrypt = new StreamReader(csDecrypt))
{
// Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
return plaintext;
}
public static string GenerateKey(int keySize, CipherMode cipherMode)
{
using (var cryptoContainer = Aes.Create())
{
cryptoContainer.Mode = cipherMode;
cryptoContainer.KeySize = keySize;
cryptoContainer.GenerateKey();
return Convert.ToBase64String(cryptoContainer.Key);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace DrillTime.WebApi.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2009 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.
// ***********************************************************************
using System;
using System.Collections;
namespace NUnit.Framework.Constraints
{
/// <summary>
/// Helper class with properties and methods that supply
/// a number of constraints used in Asserts.
/// </summary>
public class ConstraintFactory
{
#region Not
/// <summary>
/// Returns a ConstraintExpression that negates any
/// following constraint.
/// </summary>
public ConstraintExpression Not
{
get { return Is.Not; }
}
/// <summary>
/// Returns a ConstraintExpression that negates any
/// following constraint.
/// </summary>
public ConstraintExpression No
{
get { return Has.No; }
}
#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 ConstraintExpression All
{
get { return Is.All; }
}
#endregion
#region Some
/// <summary>
/// Returns a ConstraintExpression, which will apply
/// the following constraint to all members of a collection,
/// succeeding if at least one of them succeeds.
/// </summary>
public ConstraintExpression Some
{
get { return Has.Some; }
}
#endregion
#region None
/// <summary>
/// Returns a ConstraintExpression, which will apply
/// the following constraint to all members of a collection,
/// succeeding if all of them fail.
/// </summary>
public ConstraintExpression None
{
get { return Has.None; }
}
#endregion
#region Exactly(n)
/// <summary>
/// Returns a ConstraintExpression, which will apply
/// the following constraint to all members of a collection,
/// succeeding only if a specified number of them succeed.
/// </summary>
public static ConstraintExpression Exactly(int expectedCount)
{
return Has.Exactly(expectedCount);
}
#endregion
#region Property
/// <summary>
/// Returns a new PropertyConstraintExpression, which will either
/// test for the existence of the named property on the object
/// being tested or apply any following constraint to that property.
/// </summary>
public ResolvableConstraintExpression Property(string name)
{
return Has.Property(name);
}
#endregion
#region Length
/// <summary>
/// Returns a new ConstraintExpression, which will apply the following
/// constraint to the Length property of the object being tested.
/// </summary>
public ResolvableConstraintExpression Length
{
get { return Has.Length; }
}
#endregion
#region Count
/// <summary>
/// Returns a new ConstraintExpression, which will apply the following
/// constraint to the Count property of the object being tested.
/// </summary>
public ResolvableConstraintExpression Count
{
get { return Has.Count; }
}
#endregion
#region Message
/// <summary>
/// Returns a new ConstraintExpression, which will apply the following
/// constraint to the Message property of the object being tested.
/// </summary>
public ResolvableConstraintExpression Message
{
get { return Has.Message; }
}
#endregion
#region InnerException
/// <summary>
/// Returns a new ConstraintExpression, which will apply the following
/// constraint to the InnerException property of the object being tested.
/// </summary>
public ResolvableConstraintExpression InnerException
{
get { return Has.InnerException; }
}
#endregion
#region Attribute
/// <summary>
/// Returns a new AttributeConstraint checking for the
/// presence of a particular attribute on an object.
/// </summary>
public ResolvableConstraintExpression Attribute(Type expectedType)
{
return Has.Attribute(expectedType);
}
#if true
/// <summary>
/// Returns a new AttributeConstraint checking for the
/// presence of a particular attribute on an object.
/// </summary>
public ResolvableConstraintExpression Attribute<T>()
{
return Attribute(typeof(T));
}
#endif
#endregion
#region Null
/// <summary>
/// Returns a constraint that tests for null
/// </summary>
public NullConstraint Null
{
get { return new NullConstraint(); }
}
#endregion
#region True
/// <summary>
/// Returns a constraint that tests for True
/// </summary>
public TrueConstraint True
{
get { return new TrueConstraint(); }
}
#endregion
#region False
/// <summary>
/// Returns a constraint that tests for False
/// </summary>
public FalseConstraint False
{
get { return new FalseConstraint(); }
}
#endregion
#region Positive
/// <summary>
/// Returns a constraint that tests for a positive value
/// </summary>
public GreaterThanConstraint Positive
{
get { return new GreaterThanConstraint(0); }
}
#endregion
#region Negative
/// <summary>
/// Returns a constraint that tests for a negative value
/// </summary>
public LessThanConstraint Negative
{
get { return new LessThanConstraint(0); }
}
#endregion
#region NaN
/// <summary>
/// Returns a constraint that tests for NaN
/// </summary>
public NaNConstraint NaN
{
get { return new NaNConstraint(); }
}
#endregion
#region Empty
/// <summary>
/// Returns a constraint that tests for empty
/// </summary>
public EmptyConstraint Empty
{
get { return new EmptyConstraint(); }
}
#endregion
#region Unique
/// <summary>
/// Returns a constraint that tests whether a collection
/// contains all unique items.
/// </summary>
public UniqueItemsConstraint Unique
{
get { return new UniqueItemsConstraint(); }
}
#endregion
#region BinarySerializable
#if !NETCF
/// <summary>
/// Returns a constraint that tests whether an object graph is serializable in binary format.
/// </summary>
public BinarySerializableConstraint BinarySerializable
{
get { return new BinarySerializableConstraint(); }
}
#endif
#endregion
#region XmlSerializable
#if !NETCF_1_0
/// <summary>
/// Returns a constraint that tests whether an object graph is serializable in xml format.
/// </summary>
public XmlSerializableConstraint XmlSerializable
{
get { return new XmlSerializableConstraint(); }
}
#endif
#endregion
#region EqualTo
/// <summary>
/// Returns a constraint that tests two items for equality
/// </summary>
public 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 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 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 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 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 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 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 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 ExactTypeConstraint TypeOf(Type expectedType)
{
return new ExactTypeConstraint(expectedType);
}
#if true
/// <summary>
/// Returns a constraint that tests whether the actual
/// value is of the exact type supplied as an argument.
/// </summary>
public 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 InstanceOfTypeConstraint InstanceOf(Type expectedType)
{
return new InstanceOfTypeConstraint(expectedType);
}
#if true
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is of the type supplied as an argument or a derived type.
/// </summary>
public InstanceOfTypeConstraint InstanceOf<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 AssignableFromConstraint AssignableFrom(Type expectedType)
{
return new AssignableFromConstraint(expectedType);
}
#if true
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is assignable from the type supplied as an argument.
/// </summary>
public 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 AssignableToConstraint AssignableTo(Type expectedType)
{
return new AssignableToConstraint(expectedType);
}
#if true
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is assignable from the type supplied as an argument.
/// </summary>
public 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 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 CollectionSubsetConstraint SubsetOf(IEnumerable expected)
{
return new CollectionSubsetConstraint(expected);
}
#endregion
#region Ordered
/// <summary>
/// Returns a constraint that tests whether a collection is ordered
/// </summary>
public CollectionOrderedConstraint Ordered
{
get { return new CollectionOrderedConstraint(); }
}
#endregion
#region Member
/// <summary>
/// Returns a new CollectionContainsConstraint checking for the
/// presence of a particular object in the collection.
/// </summary>
public CollectionContainsConstraint Member(object expected)
{
return new CollectionContainsConstraint(expected);
}
/// <summary>
/// Returns a new CollectionContainsConstraint checking for the
/// presence of a particular object in the collection.
/// </summary>
public CollectionContainsConstraint Contains(object expected)
{
return new CollectionContainsConstraint(expected);
}
#endregion
#region Contains
/// <summary>
/// Returns a new ContainsConstraint. This constraint
/// will, in turn, make use of the appropriate second-level
/// constraint, depending on the type of the actual argument.
/// This overload is only used if the item sought is a string,
/// since any other type implies that we are looking for a
/// collection member.
/// </summary>
public ContainsConstraint Contains(string expected)
{
return new ContainsConstraint(expected);
}
#endregion
#region StringContaining
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value contains the substring supplied as an argument.
/// </summary>
public SubstringConstraint StringContaining(string expected)
{
return new SubstringConstraint(expected);
}
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value contains the substring supplied as an argument.
/// </summary>
public SubstringConstraint ContainsSubstring(string expected)
{
return new SubstringConstraint(expected);
}
#endregion
#region DoesNotContain
/// <summary>
/// Returns a constraint that fails if the actual
/// value contains the substring supplied as an argument.
/// </summary>
public SubstringConstraint DoesNotContain(string expected)
{
return new ConstraintExpression().Not.ContainsSubstring(expected);
}
#endregion
#region StartsWith
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value starts with the substring supplied as an argument.
/// </summary>
public StartsWithConstraint StartsWith(string expected)
{
return new StartsWithConstraint(expected);
}
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value starts with the substring supplied as an argument.
/// </summary>
public StartsWithConstraint StringStarting(string expected)
{
return new StartsWithConstraint(expected);
}
#endregion
#region DoesNotStartWith
/// <summary>
/// Returns a constraint that fails if the actual
/// value starts with the substring supplied as an argument.
/// </summary>
public StartsWithConstraint DoesNotStartWith(string expected)
{
return new ConstraintExpression().Not.StartsWith(expected);
}
#endregion
#region EndsWith
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value ends with the substring supplied as an argument.
/// </summary>
public EndsWithConstraint EndsWith(string expected)
{
return new EndsWithConstraint(expected);
}
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value ends with the substring supplied as an argument.
/// </summary>
public EndsWithConstraint StringEnding(string expected)
{
return new EndsWithConstraint(expected);
}
#endregion
#region DoesNotEndWith
/// <summary>
/// Returns a constraint that fails if the actual
/// value ends with the substring supplied as an argument.
/// </summary>
public EndsWithConstraint DoesNotEndWith(string expected)
{
return new ConstraintExpression().Not.EndsWith(expected);
}
#endregion
#region Matches
#if !NETCF
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value matches the regular expression supplied as an argument.
/// </summary>
public RegexConstraint Matches(string pattern)
{
return new RegexConstraint(pattern);
}
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value matches the regular expression supplied as an argument.
/// </summary>
public RegexConstraint StringMatching(string pattern)
{
return new RegexConstraint(pattern);
}
#endif
#endregion
#region DoesNotMatch
#if !NETCF
/// <summary>
/// Returns a constraint that fails if the actual
/// value matches the pattern supplied as an argument.
/// </summary>
public RegexConstraint DoesNotMatch(string pattern)
{
return new ConstraintExpression().Not.Matches(pattern);
}
#endif
#endregion
#region SamePath
/// <summary>
/// Returns a constraint that tests whether the path provided
/// is the same as an expected path after canonicalization.
/// </summary>
public SamePathConstraint SamePath(string expected)
{
return new SamePathConstraint(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 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 RangeConstraint InRange(IComparable from, IComparable to)
{
return new RangeConstraint(from, to);
}
#endregion
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Activation
{
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Hosting;
using System.Web.Compilation;
using System.Web.RegularExpressions;
using System.ServiceModel.Activation.Diagnostics;
using System.Security;
using System.Runtime.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime;
/// <summary>
/// This class will parse the .svc file and maintains a list of useful information that the build
/// provider needs in order to compile the file. The parser creates a list of dependent assemblies,
/// understands the compiler that we need to use, fully parses all the supported directives etc.
/// </summary>
/// <remarks>
/// The class is not thread-safe.
/// </remarks>
#pragma warning disable 618 // have not moved to the v4 security model yet
[SecurityCritical(SecurityCriticalScope.Everything)]
#pragma warning restore 618
class ServiceParser
{
// the delimiter for the compiled custom string
const string Delimiter = ServiceHostingEnvironment.ServiceParserDelimiter;
// attribute names
const string DefaultDirectiveName = "ServiceHost";
const string FactoryAttributeName = "Factory";
const string ServiceAttributeName = "Service";
// regular exression for the directive
readonly static SimpleDirectiveRegex directiveRegex;
// the build provider we will work with
ServiceBuildProvider buildProvider;
// text for the file
string serviceText;
// the class attribute value
string factoryAttributeValue = string.Empty;
// the constructorstring
string serviceAttributeValue = string.Empty;
// the line number in file currently being parsed
int lineNumber;
// the column number in file currently being parsed
int startColumn;
// the main directive was found or not
bool foundMainDirective;
// the type of the compiler (i.e C#)
CompilerType compilerType;
// the string containing the code to be compiled,
// it will be null when all the code is "behind"
string sourceString;
// assemblies to be linked with, we need a unique list
// of them and we maintain a Dictionary for it.
HybridDictionary linkedAssemblies;
// the set of assemblies that the build system is
// telling us we will be linked with. There is no unique
// requirement for them.
ICollection referencedAssemblies;
// used to figure out where the new lines start
static char[] newlineChars = new char[] { '\r', '\n' };
// source file dependencies
HybridDictionary sourceDependencies;
// virtual path for the file that we are parsing
string virtualPath;
[SuppressMessage(FxCop.Category.Security, FxCop.Rule.AptcaMethodsShouldOnlyCallAptcaMethods, Justification = "Users cannot pass arbitrary data to this code.")]
static ServiceParser()
{
directiveRegex = new SimpleDirectiveRegex();
}
/// <summary>
/// The Contructor needs the path to the file that it will parse and a reference to
/// the build provider that we are using. This is necessary because there are things that
/// need to be set on the build provider directly as we are parsing...
/// </summary>
internal ServiceParser(string virtualPath, ServiceBuildProvider buildProvider)
{
if (DiagnosticUtility.ShouldTraceInformation)
{
TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.WebHostCompilation, SR.TraceCodeWebHostCompilation,
new StringTraceRecord("VirtualPath", virtualPath), this, (Exception)null);
}
this.virtualPath = virtualPath;
this.buildProvider = buildProvider;
}
/// <summary>
/// Constructor that is used when the whole svc file content is provided. This is the case
/// when the COM+ Admin tool calls into it.
/// </summary>
ServiceParser(string serviceText)
{
this.serviceText = serviceText;
this.buildProvider = new ServiceBuildProvider();
}
/// <summary>
/// Parsing the content of the service file and retrieve the serviceAttributeValue attribute for ComPlus.
/// </summary>
/// <param name="serviceText">The content of the service file.</param>
/// <returns>The "serviceAttributeValue" attribute of the Service directive. </returns>
/// <exception cref="System.Web.HttpParseException"/>
internal static IDictionary<string, string> ParseServiceDirective(string serviceText)
{
ServiceParser parser = new ServiceParser(serviceText);
parser.ParseString();
// the list of valid attributes for ComPlus for Service Directive
IDictionary<string, string> attributeTable = new Dictionary<string, string>(
StringComparer.OrdinalIgnoreCase);
if (!string.IsNullOrEmpty(parser.factoryAttributeValue))
attributeTable.Add(FactoryAttributeName, parser.factoryAttributeValue);
if (!string.IsNullOrEmpty(parser.serviceAttributeValue))
attributeTable.Add(ServiceAttributeName, parser.serviceAttributeValue);
return attributeTable;
}
/// <summary>
/// </summary>
// various getters for private objects that the build
// provider will need
//
internal CompilerType CompilerType
{
get
{
return compilerType;
}
}
internal ICollection AssemblyDependencies
{
get
{
if (linkedAssemblies == null)
{
return null;
}
return linkedAssemblies.Keys;
}
}
internal ICollection SourceDependencies
{
get
{
if (sourceDependencies == null)
{
return null;
}
return sourceDependencies.Keys;
}
}
internal bool HasInlineCode
{
get
{
return (sourceString != null);
}
}
/// <summary>
/// Parses the code file appropriately. This method is used by the
/// build provider.
/// </summary>
internal void Parse(ICollection referencedAssemblies)
{
if (referencedAssemblies == null)
{
throw FxTrace.Exception.ArgumentNull("referencedAssemblies");
}
this.referencedAssemblies = referencedAssemblies;
AddSourceDependency(virtualPath);
using (TextReader reader = buildProvider.OpenReaderInternal())
{
this.serviceText = reader.ReadToEnd();
ParseString();
}
}
/// <summary>
/// This method returns a code compile unit that will be added
/// to the other depdnecies in order to compile
/// </summary>
internal CodeCompileUnit GetCodeModel()
{
// Do we have something to compile?
//
if (sourceString == null || sourceString.Length == 0)
return null;
CodeSnippetCompileUnit snippetCompileUnit = new CodeSnippetCompileUnit(sourceString);
// Put in some context so that the file can be debugged.
//
string pragmaFile = HostingEnvironmentWrapper.MapPath(virtualPath);
snippetCompileUnit.LinePragma = new CodeLinePragma(pragmaFile, lineNumber);
return snippetCompileUnit;
}
Exception CreateParseException(string message, string sourceCode)
{
return CreateParseException(message, null, sourceCode);
}
Exception CreateParseException(Exception innerException, string sourceCode)
{
return CreateParseException(innerException.Message, innerException, sourceCode);
}
Exception CreateParseException(string message, Exception innerException, string sourceCode)
{
return new HttpParseException(message, innerException, this.virtualPath, sourceCode, this.lineNumber);
}
/// <summary>
/// This method returns the custom string that is to be passed to ServiceHostingEnvironment from BuildManager.
/// </summary>
/// <param name="compiledAssembly">The full name of the built assembly for inline code.</param>
internal string CreateParseString(Assembly compiledAssembly)
{
Type typeToPreserve = this.GetCompiledType(compiledAssembly);
string typeToPreserveName = string.Empty;
if (typeToPreserve != null)
typeToPreserveName = typeToPreserve.AssemblyQualifiedName;
System.Text.StringBuilder builder = new System.Text.StringBuilder();
if (compiledAssembly != null)
{
builder.Append(Delimiter);
builder.Append(compiledAssembly.FullName);
}
if (this.referencedAssemblies != null)
{
// CSDMain #192135
// Minimize code change by doing 2 passes to have assembly containing type at the top of the list.
// As a result, this assembly will get loaded first in ServiceHostFactory.CreateServiceHost.
// In the multi-targetting scenario this prevents the runtime from trying to load a newer CLR assembly
// and failing. In the happy case, duplicate assembly references may occur (no effect on runtime).
// Note that if the service type is contained in a framework assembly, this does not fix the problem.
// Future improvement is to write fully qualified type name and let CLR handle load/search.
if (!string.IsNullOrEmpty(serviceAttributeValue))
{
foreach (Assembly assembly in this.referencedAssemblies)
{
Type serviceType;
try
{
serviceType = assembly.GetType(serviceAttributeValue, false);
}
catch (Exception e)
{
if (System.Runtime.Fx.IsFatal(e))
{
throw;
}
// log exception, but do not rethrow
DiagnosticUtility.TraceHandledException(e, TraceEventType.Warning);
break;
}
if (serviceType != null)
{
builder.Append(Delimiter);
builder.Append(assembly.FullName);
break;
}
}
}
foreach (Assembly assembly in this.referencedAssemblies)
{
builder.Append(Delimiter);
builder.Append(assembly.FullName);
}
}
if (this.AssemblyDependencies != null)
{
foreach (Assembly assembly in this.AssemblyDependencies)
{
builder.Append(Delimiter);
builder.Append(assembly.FullName);
}
}
// use application relative virtualpath instead of the absolute path
// so that the compliedcustomstring is applicationame independent
return string.Concat(VirtualPathUtility.ToAppRelative(virtualPath), Delimiter,
typeToPreserveName, Delimiter,
serviceAttributeValue, builder.ToString());
}
void AddSourceDependency(string fileName)
{
if (sourceDependencies == null)
sourceDependencies = new HybridDictionary(true);
sourceDependencies.Add(fileName, fileName);
}
Type GetCompiledType(Assembly compiledAssembly)
{
if (string.IsNullOrEmpty(factoryAttributeValue))
{
return null;
}
Type type = null;
// First, try to get the type from the assembly that has been built (if any)
if (this.HasInlineCode && (compiledAssembly != null))
{
type = compiledAssembly.GetType(factoryAttributeValue);
}
// If not, try to get it from other assemblies
if (type == null)
{
type = GetType(factoryAttributeValue);
}
return type;
}
internal IDictionary GetLinePragmasTable()
{
LinePragmaCodeInfo info = new LinePragmaCodeInfo(this.lineNumber, this.startColumn, 1, -1, false);
IDictionary dictionary = new Hashtable();
dictionary[this.lineNumber] = info;
return dictionary;
}
/// <summary>
/// Parses the content of the svc file for each directive line
/// </summary>
void ParseString()
{
try
{
int textPos = 0;
Match match;
lineNumber = 1;
// Check for ending bracket first, MB 45013.
if (this.serviceText.IndexOf('>') == -1)
{
throw FxTrace.Exception.AsError(new HttpException(SR.Hosting_BuildProviderDirectiveEndBracketMissing(ServiceParser.DefaultDirectiveName)));
}
// First, parse all the <%@ ... %> directives
//
for (;;)
{
match = directiveRegex.Match(this.serviceText, textPos);
// Done with the directives?
//
if (!match.Success)
break;
lineNumber += ServiceParserUtilities.LineCount(this.serviceText, textPos, match.Index);
textPos = match.Index;
// Get all the directives into a bag
//
IDictionary directive = CollectionsUtil.CreateCaseInsensitiveSortedList();
string directiveName = ProcessAttributes(match, directive);
// Understand the directive
//
ProcessDirective(directiveName, directive);
lineNumber += ServiceParserUtilities.LineCount(this.serviceText, textPos, match.Index + match.Length);
textPos = match.Index + match.Length;
// Fixup line and column numbers to have meaninglful errors
//
int newlineIndex = this.serviceText.LastIndexOfAny(newlineChars, textPos - 1);
startColumn = textPos - newlineIndex;
}
if (!foundMainDirective)
{
throw FxTrace.Exception.AsError(new HttpException(SR.Hosting_BuildProviderDirectiveMissing(ServiceParser.DefaultDirectiveName)));
}
// skip the directives chunk
//
string remainingText = this.serviceText.Substring(textPos);
// If there is something else in the file, it needs to be compiled
//
if (!ServiceParserUtilities.IsWhiteSpaceString(remainingText))
{
sourceString = remainingText;
}
}
catch (HttpException e)
{
// the string is set in the internal exception, no need to set it again.
//
Exception parseException = CreateParseException(e, this.serviceText);
throw FxTrace.Exception.AsError(
new HttpCompileException(parseException.Message, parseException));
}
}
/// <summary>
/// Return the directive if it exists or an empty string
/// </summary>
string ProcessAttributes(Match match, IDictionary attribs)
{
// creates 3 parallel capture collections
// for the attribute names, the attribute values and the
// equal signs
//
string ret = String.Empty;
CaptureCollection attrnames = match.Groups["attrname"].Captures;
CaptureCollection attrvalues = match.Groups["attrval"].Captures;
CaptureCollection equalsign = match.Groups["equal"].Captures;
// Iterate through all of them and add then to
// the dictionary of attributes
//
for (int i = 0; i < attrnames.Count; i++)
{
string attribName = attrnames[i].ToString();
string attribValue = attrvalues[i].ToString();
// Check if there is an equal sign.
//
bool fHasEqual = (equalsign[i].ToString().Length > 0);
if (attribName != null)
{
// A <%@ %> block can have two formats:
// <%@ directive foo=1 bar=hello %>
// <%@ foo=1 bar=hello %>
// Check if we have the first format
//
if (!fHasEqual && i == 0)
{
// return the main directive
//
ret = attribName;
continue;
}
try
{
if (attribs != null)
attribs.Add(attribName, attribValue);
}
catch (ArgumentException)
{
throw FxTrace.Exception.AsError(new HttpException(SR.Hosting_BuildProviderDuplicateAttribute(attribName)));
}
}
}
return ret;
}
/// <summary>
/// This method understands the compilation parameters if any ...
/// </summary>
[SuppressMessage(FxCop.Category.Security, FxCop.Rule.DoNotIndirectlyExposeMethodsWithLinkDemands, Justification = "This method doesn't allow callers to access sensitive information, operations, or resources that can be used in a destructive manner.")]
void ProcessCompilationParams(IDictionary directive, CompilerParameters compilParams)
{
bool debug = false;
if (ServiceParserUtilities.GetAndRemoveBooleanAttribute(directive, "debug", ref debug))
{
compilParams.IncludeDebugInformation = debug;
}
int warningLevel = 0;
if (ServiceParserUtilities.GetAndRemoveNonNegativeIntegerAttribute(directive, "warninglevel", ref warningLevel))
{
compilParams.WarningLevel = warningLevel;
if (warningLevel > 0)
compilParams.TreatWarningsAsErrors = true;
}
string compilerOptions = ServiceParserUtilities.GetAndRemoveNonEmptyAttribute(directive, "compileroptions");
if (compilerOptions != null)
{
compilParams.CompilerOptions = compilerOptions;
}
}
/// <summary>
/// Processes a directive block
/// </summary>
void ProcessDirective(string directiveName, IDictionary directive)
{
// Throw on empy, no directive specified
//
if (directiveName.Length == 0)
{
throw FxTrace.Exception.AsError(new HttpException(SR.Hosting_BuildProviderDirectiveNameMissing));
}
// Check for the main directive
//
if (string.Compare(directiveName, ServiceParser.DefaultDirectiveName, StringComparison.OrdinalIgnoreCase) == 0)
{
// Make sure the main directive was not already specified
//
if (foundMainDirective)
{
throw FxTrace.Exception.AsError(new HttpException(SR.Hosting_BuildProviderDuplicateDirective(ServiceParser.DefaultDirectiveName)));
}
foundMainDirective = true;
// Ignore 'codebehind' attribute (ASURT 4591)
//
directive.Remove("codebehind");
string language = ServiceParserUtilities.GetAndRemoveNonEmptyAttribute(directive, "language");
// Get the compiler for the specified language (if any)
// or get the one from config
//
if (language != null)
{
compilerType = buildProvider.GetDefaultCompilerTypeForLanguageInternal(language);
}
else
{
compilerType = buildProvider.GetDefaultCompilerTypeInternal();
}
if (directive.Contains(FactoryAttributeName))
{
factoryAttributeValue = ServiceParserUtilities.GetAndRemoveNonEmptyAttribute(directive, FactoryAttributeName);
serviceAttributeValue = ServiceParserUtilities.GetAndRemoveNonEmptyAttribute(directive, ServiceAttributeName);
}
else if (directive.Contains(ServiceAttributeName))
{
serviceAttributeValue = ServiceParserUtilities.GetAndRemoveNonEmptyAttribute(directive, ServiceAttributeName);
}
else
{
throw FxTrace.Exception.AsError(new HttpException(SR.Hosting_BuildProviderMainAttributeMissing));
}
// parse the parameters that are related to the compiler
//
ProcessCompilationParams(directive, compilerType.CompilerParameters);
}
else if (string.Compare(directiveName, "assembly", StringComparison.OrdinalIgnoreCase) == 0)
{
if (directive.Contains("name") && directive.Contains("src"))
{
throw FxTrace.Exception.AsError(new HttpException(SR.Hosting_BuildProviderMutualExclusiveAttributes("src", "name")));
}
else if (directive.Contains("name"))
{
string assemblyName = ServiceParserUtilities.GetAndRemoveNonEmptyAttribute(directive, "name");
if (assemblyName != null)
{
AddAssemblyDependency(assemblyName);
}
else
throw FxTrace.Exception.AsError(new HttpException(SR.Hosting_BuildProviderAttributeEmpty("name")));
}
else if (directive.Contains("src"))
{
string srcPath = ServiceParserUtilities.GetAndRemoveNonEmptyAttribute(directive, "src");
if (srcPath != null)
{
ImportSourceFile(srcPath);
}
else
throw FxTrace.Exception.AsError(new HttpException(SR.Hosting_BuildProviderAttributeEmpty("src")));
}
else
{ // if (!directive.Contains("name") && !directive.Contains("src"))
throw FxTrace.Exception.AsError(new HttpException(SR.Hosting_BuildProviderRequiredAttributesMissing("src", "name")));
}
}
else
{
throw FxTrace.Exception.AsError(new HttpException(SR.Hosting_BuildProviderUnknownDirective(directiveName)));
}
// check if there are any directives that you did not process
//
if (directive.Count > 0)
throw FxTrace.Exception.AsError(new HttpException(SR.Hosting_BuildProviderUnknownAttribute(ServiceParserUtilities.FirstDictionaryKey(directive))));
}
void ImportSourceFile(string path)
{
// Get a full path to the source file, compile it to an assembly
// add the depedency to the assembly
//
string baseVirtualDir = VirtualPathUtility.GetDirectory(virtualPath);
string fullVirtualPath = VirtualPathUtility.Combine(baseVirtualDir, path);
AddSourceDependency(fullVirtualPath);
Assembly a = BuildManager.GetCompiledAssembly(fullVirtualPath);
AddAssemblyDependency(a);
}
void AddAssemblyDependency(string assemblyName)
{
// Load and keep track of the assembly
//
Assembly a = Assembly.Load(assemblyName);
AddAssemblyDependency(a);
}
void AddAssemblyDependency(Assembly assembly)
{
if (linkedAssemblies == null)
linkedAssemblies = new HybridDictionary(false);
linkedAssemblies.Add(assembly, null);
}
/// <summary>
/// Look for a type by name in the assemblies available to this page
/// </summary>
Type GetType(string typeName)
{
Type type;
// If it contains an assembly name, just call Type.GetType (ASURT 53589)
//
if (ServiceParserUtilities.TypeNameIncludesAssembly(typeName))
{
try
{
type = Type.GetType(typeName, true);
}
catch (ArgumentException e)
{
Exception parseException = CreateParseException(e, this.sourceString);
throw FxTrace.Exception.AsError(
new HttpCompileException(parseException.Message, parseException));
}
catch (TargetInvocationException e)
{
Exception parseException = CreateParseException(e, this.sourceString);
throw FxTrace.Exception.AsError(
new HttpCompileException(parseException.Message, parseException));
}
catch (TypeLoadException e)
{
Exception parseException = CreateParseException(SR.Hosting_BuildProviderCouldNotCreateType(typeName), e, this.sourceString);
throw FxTrace.Exception.AsError(
new HttpCompileException(parseException.Message, parseException));
}
return type;
}
try
{
type = ServiceParserUtilities.GetTypeFromAssemblies(referencedAssemblies, typeName, false /*ignoreCase*/);
if (type != null)
return type;
type = ServiceParserUtilities.GetTypeFromAssemblies(AssemblyDependencies, typeName, false /*ignoreCase*/);
if (type != null)
return type;
}
catch (HttpException e)
{
Exception parseException = CreateParseException(SR.Hosting_BuildProviderCouldNotCreateType(typeName), e, this.sourceString);
throw FxTrace.Exception.AsError(
new HttpCompileException(parseException.Message, parseException));
}
Exception exception = CreateParseException(SR.Hosting_BuildProviderCouldNotCreateType(typeName), this.sourceString);
throw FxTrace.Exception.AsError(
new HttpCompileException(exception.Message, exception));
}
/// <summary>
/// This class contains static methods that are necessary to manipulate the
/// structures that contain the directives. The logic assumes that the parser will
/// create a dictionary that contains all the directives and we can pull certain directives as
/// necessary while processing/compiling the page. The directives are strings.
///
/// </summary>
static class ServiceParserUtilities
{
/// <summary>
/// Return the first key of the dictionary as a string. Throws if it's
/// empty or if the key is not a string.
/// </summary>
internal static string FirstDictionaryKey(IDictionary dictionary)
{
// assume that the caller has checked the dictionary before calling
//
IDictionaryEnumerator e = dictionary.GetEnumerator();
e.MoveNext();
return (string)e.Key;
}
/// <summary>
/// Get a string value from a dictionary, and remove
/// it from the dictionary of attributes if it exists.
/// </summary>
/// <remarks>Returns null if the value was not there ...</remarks>
static string GetAndRemove(IDictionary dictionary, string key)
{
string val = (string)dictionary[key];
if (val != null)
{
dictionary.Remove(key);
val = val.Trim();
}
else
return string.Empty;
return val;
}
/// <summary>
/// Get a value from a dictionary, and remove it from the dictionary if
/// it exists. Throw an exception if the value is a whitespace string.
/// However, don't complain about null, which simply means the value is not
/// in the dictionary.
/// </summary>
internal static string GetAndRemoveNonEmptyAttribute(IDictionary directives, string key, bool required)
{
string val = ServiceParserUtilities.GetAndRemove(directives, key);
if (val.Length == 0)
{
if (required)
{
throw FxTrace.Exception.AsError(new HttpException(SR.Hosting_BuildProviderAttributeMissing(key)));
}
return null;
}
return val;
}
internal static string GetAndRemoveNonEmptyAttribute(IDictionary directives, string key)
{
return GetAndRemoveNonEmptyAttribute(directives, key, false /*required*/);
}
/// <summary>
/// Get a string value from a dictionary, and convert it to bool. Throw an
/// exception if it's not a valid bool string.
/// However, don't complain about null, which simply means the value is not
/// in the dictionary.
/// The value is returned through a REF param (unchanged if null)
/// </summary>
/// <returns>True if attrib exists, false otherwise</returns>
internal static bool GetAndRemoveBooleanAttribute(IDictionary directives, string key, ref bool val)
{
string s = ServiceParserUtilities.GetAndRemove(directives, key);
if (s.Length == 0)
return false;
try
{
val = bool.Parse(s);
}
catch (FormatException)
{
throw FxTrace.Exception.AsError(new HttpException(SR.Hosting_BuildProviderInvalidValueForBooleanAttribute(s, key)));
}
return true;
}
/// <summary>
/// Get a string value from a dictionary, and convert it to integer. Throw an
/// exception if it's not a valid positive integer string.
/// However, don't complain about null, which simply means the value is not
/// in the dictionary.
/// The value is returned through a REF param (unchanged if null)
/// </summary>
/// <returns>True if attrib exists, false otherwise</returns>
internal static bool GetAndRemoveNonNegativeIntegerAttribute(IDictionary directives, string key, ref int val)
{
string s = ServiceParserUtilities.GetAndRemove(directives, key);
if (s.Length == 0)
return false;
val = GetNonNegativeIntegerAttribute(key, s);
return true;
}
/// <summary>
/// Parse a string attribute into a non-negative integer
/// </summary>
/// <param name="name">Name of the attribute, used only for the error messages</param>
/// <param name="value">Value to convert to int</param>
static int GetNonNegativeIntegerAttribute(string name, string value)
{
int ret;
try
{
ret = int.Parse(value, CultureInfo.InvariantCulture);
}
catch (FormatException)
{
throw FxTrace.Exception.AsError(new HttpException(SR.Hosting_BuildProviderInvalidValueForNonNegativeIntegerAttribute(value, name)));
}
// Make sure it's not negative
//
if (ret < 0)
{
throw FxTrace.Exception.AsError(new HttpException(SR.Hosting_BuildProviderInvalidValueForNonNegativeIntegerAttribute(value, name)));
}
return ret;
}
internal static bool IsWhiteSpaceString(string s)
{
return (s.Trim().Length == 0);
}
/// <summary>
/// This method takes the code that will be compiled as a string and it
/// will count how many lines exist between the given offset and the final
/// offset.
/// </summary>
/// <param name="text">The text that contains the source code</param>
/// <param name="offset">Starting offset for lookup</param>
/// <param name="newoffset">Ending offset</param>
/// <returns>The number of lines</returns>
internal static int LineCount(string text, int offset, int newoffset)
{
int linecount = 0;
while (offset < newoffset)
{
if (text[offset] == '\r' || (text[offset] == '\n' && (offset == 0 || text[offset - 1] != '\r')))
linecount++;
offset++;
}
return linecount;
}
/// <summary>
/// Parses a string that contains a type trying to figure out if the assembly info is there.
/// </summary>
/// <param name="typeName">The string to search</param>
internal static bool TypeNameIncludesAssembly(string typeName)
{
return (typeName.IndexOf(",", StringComparison.Ordinal) >= 0);
}
/// <summary>
/// Loops through a list of assemblies that are already collected by the parser/provider and
/// looks for the specified type.
/// </summary>
/// <param name="assemblies">The collection of assemblies</param>
/// <param name="typeName">The type name</param>
/// <param name="ignoreCase">Case sensitivity knob</param>
/// <returns></returns>
internal static Type GetTypeFromAssemblies(ICollection assemblies, string typeName, bool ignoreCase)
{
if (assemblies == null)
return null;
Type type = null;
foreach (Assembly assembly in assemblies)
{
Type t = assembly.GetType(typeName, false /*throwOnError*/, ignoreCase);
if (t == null)
continue;
// If we had already found a different one, it's an ambiguous type reference
//
if (type != null && t != type)
{
throw FxTrace.Exception.AsError(new HttpException(
SR.Hosting_BuildProviderAmbiguousType(typeName, type.Assembly.FullName, t.Assembly.FullName)));
}
// Keep track of it
//
type = t;
}
return type;
}
}
}
}
| |
// GZipOutputStream.cs
//
// Copyright (C) 2001 Mike Krueger
//
// This file was translated from java, it was part of the GNU Classpath
// Copyright (C) 2001 Free Software Foundation, Inc.
//
// 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.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
using System;
using System.IO;
using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.Zip.Compression;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
namespace ICSharpCode.SharpZipLib.GZip
{
/// <summary>
/// This filter stream is used to compress a stream into a "GZIP" stream.
/// The "GZIP" format is described in RFC 1952.
///
/// author of the original java version : John Leuner
/// </summary>
/// <example> This sample shows how to gzip a file
/// <code>
/// using System;
/// using System.IO;
///
/// using ICSharpCode.SharpZipLib.GZip;
/// using ICSharpCode.SharpZipLib.Core;
///
/// class MainClass
/// {
/// public static void Main(string[] args)
/// {
/// using (Stream s = new GZipOutputStream(File.Create(args[0] + ".gz")))
/// using (FileStream fs = File.OpenRead(args[0])) {
/// byte[] writeData = new byte[4096];
/// Streamutils.Copy(s, fs, writeData);
/// }
/// }
/// }
/// }
/// </code>
/// </example>
public class GZipOutputStream : DeflaterOutputStream
{
enum OutputState
{
Header,
Footer,
Finished,
Closed,
};
#region Instance Fields
/// <summary>
/// CRC-32 value for uncompressed data
/// </summary>
protected Crc32 crc = new Crc32();
OutputState state_ = OutputState.Header;
#endregion
#region Constructors
/// <summary>
/// Creates a GzipOutputStream with the default buffer size
/// </summary>
/// <param name="baseOutputStream">
/// The stream to read data (to be compressed) from
/// </param>
public GZipOutputStream(Stream baseOutputStream)
: this(baseOutputStream, 4096)
{
}
/// <summary>
/// Creates a GZipOutputStream with the specified buffer size
/// </summary>
/// <param name="baseOutputStream">
/// The stream to read data (to be compressed) from
/// </param>
/// <param name="size">
/// Size of the buffer to use
/// </param>
public GZipOutputStream(Stream baseOutputStream, int size) : base(baseOutputStream, new Deflater(Deflater.DEFAULT_COMPRESSION, true), size)
{
}
#endregion
#region Public API
/// <summary>
/// Sets the active compression level (1-9). The new level will be activated
/// immediately.
/// </summary>
/// <param name="level">The compression level to set.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// Level specified is not supported.
/// </exception>
/// <see cref="Deflater"/>
public void SetLevel(int level)
{
if (level < Deflater.BEST_SPEED) {
throw new ArgumentOutOfRangeException("level");
}
deflater_.SetLevel(level);
}
/// <summary>
/// Get the current compression level.
/// </summary>
/// <returns>The current compression level.</returns>
public int GetLevel()
{
return deflater_.GetLevel();
}
#endregion
#region Stream overrides
/// <summary>
/// Write given buffer to output updating crc
/// </summary>
/// <param name="buffer">Buffer to write</param>
/// <param name="offset">Offset of first byte in buf to write</param>
/// <param name="count">Number of bytes to write</param>
public override void Write(byte[] buffer, int offset, int count)
{
if ( state_ == OutputState.Header ) {
WriteHeader();
}
if( state_!=OutputState.Footer )
{
throw new InvalidOperationException("Write not permitted in current state");
}
crc.Update(buffer, offset, count);
base.Write(buffer, offset, count);
}
/// <summary>
/// Writes remaining compressed output data to the output stream
/// and closes it.
/// </summary>
#if UNITY_METRO && !UNITY_EDITOR
public void Close()
#else
public override void Close()
#endif
{
try {
Finish();
}
finally {
if ( state_ != OutputState.Closed ) {
state_ = OutputState.Closed;
if( IsStreamOwner ) {
baseOutputStream_.Dispose();
}
}
}
}
#endregion
#region DeflaterOutputStream overrides
/// <summary>
/// Finish compression and write any footer information required to stream
/// </summary>
public override void Finish()
{
// If no data has been written a header should be added.
if ( state_ == OutputState.Header ) {
WriteHeader();
}
if( state_ == OutputState.Footer)
{
state_=OutputState.Finished;
base.Finish();
uint totalin=(uint)(deflater_.TotalIn&0xffffffff);
uint crcval=(uint)(crc.Value&0xffffffff);
byte[] gzipFooter;
unchecked
{
gzipFooter=new byte[] {
(byte) crcval, (byte) (crcval >> 8),
(byte) (crcval >> 16), (byte) (crcval >> 24),
(byte) totalin, (byte) (totalin >> 8),
(byte) (totalin >> 16), (byte) (totalin >> 24)
};
}
baseOutputStream_.Write(gzipFooter, 0, gzipFooter.Length);
}
}
#endregion
#region Support Routines
void WriteHeader()
{
if ( state_ == OutputState.Header )
{
state_=OutputState.Footer;
int mod_time = (int)((DateTime.Now.Ticks - new DateTime(1970, 1, 1).Ticks) / 10000000L); // Ticks give back 100ns intervals
byte[] gzipHeader = {
// The two magic bytes
(byte) (GZipConstants.GZIP_MAGIC >> 8), (byte) (GZipConstants.GZIP_MAGIC & 0xff),
// The compression type
(byte) Deflater.DEFLATED,
// The flags (not set)
0,
// The modification time
(byte) mod_time, (byte) (mod_time >> 8),
(byte) (mod_time >> 16), (byte) (mod_time >> 24),
// The extra flags
0,
// The OS type (unknown)
(byte) 255
};
baseOutputStream_.Write(gzipHeader, 0, gzipHeader.Length);
}
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Avalonia.Collections;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Selection;
using Avalonia.Controls.Templates;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.UnitTests;
using Xunit;
namespace Avalonia.Controls.UnitTests.Primitives
{
public class SelectingItemsControlTests_Multiple
{
private MouseTestHelper _helper = new MouseTestHelper();
[Fact]
public void Setting_SelectedIndex_Should_Add_To_SelectedItems()
{
var target = new TestSelector
{
Items = new[] { "foo", "bar" },
Template = Template(),
};
target.ApplyTemplate();
target.SelectedIndex = 1;
Assert.Equal(new[] { "bar" }, target.SelectedItems.Cast<object>().ToList());
}
[Fact]
public void Adding_SelectedItems_Should_Set_SelectedIndex()
{
var target = new TestSelector
{
Items = new[] { "foo", "bar" },
Template = Template(),
};
target.ApplyTemplate();
target.SelectedItems.Add("bar");
Assert.Equal(1, target.SelectedIndex);
}
[Fact]
public void Assigning_Single_SelectedItems_Should_Set_SelectedIndex()
{
var target = new TestSelector
{
Items = new[] { "foo", "bar" },
Template = Template(),
};
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
target.SelectedItems = new AvaloniaList<object>("bar");
Assert.Equal(1, target.SelectedIndex);
Assert.Equal(new[] { "bar" }, target.SelectedItems);
Assert.Equal(new[] { 1 }, SelectedContainers(target));
}
[Fact]
public void Assigning_Multiple_SelectedItems_Should_Set_SelectedIndex()
{
var target = new TestSelector
{
Items = new[] { "foo", "bar", "baz" },
Template = Template(),
};
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
target.SelectedItems = new AvaloniaList<string>("foo", "bar", "baz");
Assert.Equal(0, target.SelectedIndex);
Assert.Equal(new[] { "foo", "bar", "baz" }, target.SelectedItems);
Assert.Equal(new[] { 0, 1, 2 }, SelectedContainers(target));
}
[Fact]
public void Selected_Items_Should_Be_Marked_When_Panel_Created_After_SelectedItems_Is_Set()
{
// Issue #2565.
var target = new TestSelector
{
Items = new[] { "foo", "bar", "baz" },
Template = Template(),
};
target.ApplyTemplate();
target.SelectedItems = new AvaloniaList<string>("foo", "bar", "baz");
target.Presenter.ApplyTemplate();
Assert.Equal(0, target.SelectedIndex);
Assert.Equal(new[] { "foo", "bar", "baz" }, target.SelectedItems);
Assert.Equal(new[] { 0, 1, 2 }, SelectedContainers(target));
}
[Fact]
public void Reassigning_SelectedItems_Should_Clear_Selection()
{
var target = new TestSelector
{
Items = new[] { "foo", "bar" },
Template = Template(),
};
target.ApplyTemplate();
target.SelectedItems.Add("bar");
target.SelectedItems = new AvaloniaList<object>();
Assert.Equal(-1, target.SelectedIndex);
Assert.Null(target.SelectedItem);
}
[Fact]
public void Adding_First_SelectedItem_Should_Raise_SelectedIndex_SelectedItem_Changed()
{
var target = new TestSelector
{
Items = new[] { "foo", "bar" },
Template = Template(),
};
bool indexRaised = false;
bool itemRaised = false;
target.PropertyChanged += (s, e) =>
{
indexRaised |= e.Property.Name == "SelectedIndex" &&
(int)e.OldValue == -1 &&
(int)e.NewValue == 1;
itemRaised |= e.Property.Name == "SelectedItem" &&
(string)e.OldValue == null &&
(string)e.NewValue == "bar";
};
target.ApplyTemplate();
target.SelectedItems.Add("bar");
Assert.True(indexRaised);
Assert.True(itemRaised);
}
[Fact]
public void Adding_Subsequent_SelectedItems_Should_Not_Raise_SelectedIndex_SelectedItem_Changed()
{
var target = new TestSelector
{
Items = new[] { "foo", "bar" },
Template = Template(),
};
target.ApplyTemplate();
target.SelectedItems.Add("foo");
bool raised = false;
target.PropertyChanged += (s, e) =>
raised |= e.Property.Name == "SelectedIndex" ||
e.Property.Name == "SelectedItem";
target.SelectedItems.Add("bar");
Assert.False(raised);
}
[Fact]
public void Removing_Last_SelectedItem_Should_Raise_SelectedIndex_Changed()
{
var target = new TestSelector
{
Items = new[] { "foo", "bar" },
Template = Template(),
};
target.ApplyTemplate();
target.SelectedItems.Add("foo");
bool raised = false;
target.PropertyChanged += (s, e) =>
raised |= e.Property.Name == "SelectedIndex" &&
(int)e.OldValue == 0 &&
(int)e.NewValue == -1;
target.SelectedItems.RemoveAt(0);
Assert.True(raised);
}
[Fact]
public void Adding_SelectedItems_Should_Set_Item_IsSelected()
{
var items = new[]
{
new ListBoxItem(),
new ListBoxItem(),
new ListBoxItem(),
};
var target = new TestSelector
{
Items = items,
Template = Template(),
};
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
target.SelectedItems.Add(items[0]);
target.SelectedItems.Add(items[1]);
var foo = target.Presenter.Panel.Children[0];
Assert.True(items[0].IsSelected);
Assert.True(items[1].IsSelected);
Assert.False(items[2].IsSelected);
}
[Fact]
public void Assigning_SelectedItems_Should_Set_Item_IsSelected()
{
var items = new[]
{
new ListBoxItem(),
new ListBoxItem(),
new ListBoxItem(),
};
var target = new TestSelector
{
Items = items,
Template = Template(),
};
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
target.SelectedItems = new AvaloniaList<object> { items[0], items[1] };
Assert.True(items[0].IsSelected);
Assert.True(items[1].IsSelected);
Assert.False(items[2].IsSelected);
}
[Fact]
public void Removing_SelectedItems_Should_Clear_Item_IsSelected()
{
var items = new[]
{
new ListBoxItem(),
new ListBoxItem(),
new ListBoxItem(),
};
var target = new TestSelector
{
Items = items,
Template = Template(),
};
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
target.SelectedItems.Add(items[0]);
target.SelectedItems.Add(items[1]);
target.SelectedItems.Remove(items[1]);
Assert.True(items[0].IsSelected);
Assert.False(items[1].IsSelected);
}
[Fact]
public void Reassigning_SelectedItems_Should_Clear_Item_IsSelected()
{
var items = new[]
{
new ListBoxItem(),
new ListBoxItem(),
new ListBoxItem(),
};
var target = new TestSelector
{
Items = items,
Template = Template(),
};
target.ApplyTemplate();
target.SelectedItems.Add(items[0]);
target.SelectedItems.Add(items[1]);
target.SelectedItems = new AvaloniaList<object> { items[0], items[1] };
Assert.False(items[0].IsSelected);
Assert.False(items[1].IsSelected);
}
[Fact]
public void Setting_SelectedIndex_Should_Unmark_Previously_Selected_Containers()
{
var target = new TestSelector
{
Items = new[] { "foo", "bar", "baz" },
Template = Template(),
};
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
target.SelectedItems.Add("foo");
target.SelectedItems.Add("bar");
Assert.Equal(new[] { 0, 1 }, SelectedContainers(target));
target.SelectedIndex = 2;
Assert.Equal(new[] { 2 }, SelectedContainers(target));
}
[Fact]
public void Range_Select_Should_Select_Range()
{
var target = new TestSelector
{
Items = new[]
{
"foo",
"bar",
"baz",
"qux",
"qiz",
"lol",
},
Template = Template(),
};
target.ApplyTemplate();
target.SelectedIndex = 1;
target.SelectRange(3);
Assert.Equal(new[] { "bar", "baz", "qux" }, target.SelectedItems.Cast<object>().ToList());
}
[Fact]
public void Range_Select_Backwards_Should_Select_Range()
{
var target = new TestSelector
{
Items = new[]
{
"foo",
"bar",
"baz",
"qux",
"qiz",
"lol",
},
SelectionMode = SelectionMode.Multiple,
Template = Template(),
};
target.ApplyTemplate();
target.SelectedIndex = 3;
target.SelectRange(1);
Assert.Equal(new[] { "qux", "bar", "baz" }, target.SelectedItems.Cast<object>().ToList());
}
[Fact]
public void Second_Range_Select_Backwards_Should_Select_From_Original_Selection()
{
var target = new TestSelector
{
Items = new[]
{
"foo",
"bar",
"baz",
"qux",
"qiz",
"lol",
},
SelectionMode = SelectionMode.Multiple,
Template = Template(),
};
target.ApplyTemplate();
target.SelectedIndex = 2;
target.SelectRange(5);
target.SelectRange(4);
Assert.Equal(new[] { "baz", "qux", "qiz" }, target.SelectedItems.Cast<object>().ToList());
}
[Fact]
public void Setting_SelectedIndex_After_Range_Should_Unmark_Previously_Selected_Containers()
{
var target = new TestSelector
{
Items = new[] { "foo", "bar", "baz", "qux" },
Template = Template(),
SelectedIndex = 0,
SelectionMode = SelectionMode.Multiple,
};
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
target.SelectRange(2);
Assert.Equal(new[] { 0, 1, 2 }, SelectedContainers(target));
target.SelectedIndex = 3;
Assert.Equal(new[] { 3 }, SelectedContainers(target));
}
[Fact]
public void Toggling_Selection_After_Range_Should_Work()
{
var target = new TestSelector
{
Items = new[] { "foo", "bar", "baz", "foo", "bar", "baz" },
Template = Template(),
SelectedIndex = 0,
SelectionMode = SelectionMode.Multiple,
};
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
target.SelectRange(3);
Assert.Equal(new[] { 0, 1, 2, 3 }, SelectedContainers(target));
target.Toggle(4);
Assert.Equal(new[] { 0, 1, 2, 3, 4 }, SelectedContainers(target));
}
[Fact]
public void Suprious_SelectedIndex_Changes_Should_Not_Be_Triggered()
{
var target = new TestSelector
{
Items = new[] { "foo", "bar", "baz" },
Template = Template(),
};
target.ApplyTemplate();
var selectedIndexes = new List<int>();
target.GetObservable(TestSelector.SelectedIndexProperty).Subscribe(x => selectedIndexes.Add(x));
target.SelectedItems = new AvaloniaList<object> { "bar", "baz" };
target.SelectedItem = "foo";
Assert.Equal(0, target.SelectedIndex);
Assert.Equal(new[] { -1, 1, 0 }, selectedIndexes);
}
[Fact]
public void Can_Set_SelectedIndex_To_Another_Selected_Item()
{
var target = new TestSelector
{
Items = new[] { "foo", "bar", "baz" },
Template = Template(),
};
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
target.SelectedItems.Add("foo");
target.SelectedItems.Add("bar");
Assert.Equal(0, target.SelectedIndex);
Assert.Equal(new[] { "foo", "bar" }, target.SelectedItems);
Assert.Equal(new[] { 0, 1 }, SelectedContainers(target));
var raised = false;
target.SelectionChanged += (s, e) =>
{
raised = true;
Assert.Empty(e.AddedItems);
Assert.Equal(new[] { "foo" }, e.RemovedItems);
};
target.SelectedIndex = 1;
Assert.True(raised);
Assert.Equal(1, target.SelectedIndex);
Assert.Equal(new[] { "bar" }, target.SelectedItems);
Assert.Equal(new[] { 1 }, SelectedContainers(target));
}
/// <summary>
/// Tests a problem discovered with ListBox with selection.
/// </summary>
/// <remarks>
/// - Items is bound to DataContext first, followed by say SelectedIndex
/// - When the ListBox is removed from the visual tree, DataContext becomes null (as it's
/// inherited)
/// - This changes Items to null, which changes SelectedIndex to null as there are no
/// longer any items
/// - However, the news that DataContext is now null hasn't yet reached the SelectedItems
/// binding and so the unselection is sent back to the ViewModel
///
/// This is a similar problem to that tested by XamlBindingTest.Should_Not_Write_To_Old_DataContext.
/// However, that tests a general property binding problem: here we are writing directly
/// to the SelectedItems collection - not via a binding - so it's something that the
/// binding system cannot solve. Instead we solve it by not clearing SelectedItems when
/// DataContext is in the process of changing.
/// </remarks>
[Fact]
public void Should_Not_Write_SelectedItems_To_Old_DataContext()
{
var vm = new OldDataContextViewModel();
var target = new TestSelector();
var itemsBinding = new Binding
{
Path = "Items",
Mode = BindingMode.OneWay,
};
var selectedItemsBinding = new Binding
{
Path = "SelectedItems",
Mode = BindingMode.OneWay,
};
// Bind Items and SelectedItems to the VM.
target.Bind(TestSelector.ItemsProperty, itemsBinding);
target.Bind(TestSelector.SelectedItemsProperty, selectedItemsBinding);
// Set DataContext and SelectedIndex
target.DataContext = vm;
target.SelectedIndex = 1;
// Make sure SelectedItems are written back to VM.
Assert.Equal(new[] { "bar" }, vm.SelectedItems);
// Clear DataContext and ensure that SelectedItems is still set in the VM.
target.DataContext = null;
Assert.Equal(new[] { "bar" }, vm.SelectedItems);
// Ensure target's SelectedItems is now clear.
Assert.Empty(target.SelectedItems);
}
/// <summary>
/// See <see cref="Should_Not_Write_SelectedItems_To_Old_DataContext"/>.
/// </summary>
[Fact]
public void Should_Not_Write_SelectionModel_To_Old_DataContext()
{
var vm = new OldDataContextViewModel();
var target = new TestSelector();
var itemsBinding = new Binding
{
Path = "Items",
Mode = BindingMode.OneWay,
};
var selectionBinding = new Binding
{
Path = "Selection",
Mode = BindingMode.OneWay,
};
// Bind Items and Selection to the VM.
target.Bind(TestSelector.ItemsProperty, itemsBinding);
target.Bind(TestSelector.SelectionProperty, selectionBinding);
// Set DataContext and SelectedIndex
target.DataContext = vm;
target.SelectedIndex = 1;
// Make sure selection is written to selection model
Assert.Equal(1, vm.Selection.SelectedIndex);
// Clear DataContext and ensure that selection is still set in model.
target.DataContext = null;
Assert.Equal(1, vm.Selection.SelectedIndex);
// Ensure target's SelectedItems is now clear.
Assert.Empty(target.SelectedItems);
}
[Fact]
public void Unbound_SelectedItems_Should_Be_Cleared_When_DataContext_Cleared()
{
var data = new
{
Items = new[] { "foo", "bar", "baz" },
};
var target = new TestSelector
{
DataContext = data,
Template = Template(),
};
var itemsBinding = new Binding { Path = "Items" };
target.Bind(TestSelector.ItemsProperty, itemsBinding);
Assert.Same(data.Items, target.Items);
target.SelectedItems.Add("bar");
target.DataContext = null;
Assert.Empty(target.SelectedItems);
}
[Fact]
public void Adding_To_SelectedItems_Should_Raise_SelectionChanged()
{
var items = new[] { "foo", "bar", "baz" };
var target = new TestSelector
{
DataContext = items,
Template = Template(),
Items = items,
};
var called = false;
target.SelectionChanged += (s, e) =>
{
Assert.Equal(new[] { "bar" }, e.AddedItems.Cast<object>().ToList());
Assert.Empty(e.RemovedItems);
called = true;
};
target.SelectedItems.Add("bar");
Assert.True(called);
}
[Fact]
public void Removing_From_SelectedItems_Should_Raise_SelectionChanged()
{
var items = new[] { "foo", "bar", "baz" };
var target = new TestSelector
{
Items = items,
Template = Template(),
SelectedItem = "bar",
};
var called = false;
target.SelectionChanged += (s, e) =>
{
Assert.Equal(new[] { "bar" }, e.RemovedItems.Cast<object>().ToList());
Assert.Empty(e.AddedItems);
called = true;
};
target.SelectedItems.Remove("bar");
Assert.True(called);
}
[Fact]
public void Assigning_SelectedItems_Should_Raise_SelectionChanged()
{
var items = new[] { "foo", "bar", "baz" };
var target = new TestSelector
{
Items = items,
Template = Template(),
SelectedItem = "bar",
};
var called = false;
target.SelectionChanged += (s, e) =>
{
Assert.Equal(new[] { "foo", "baz" }, e.AddedItems.Cast<object>());
Assert.Equal(new[] { "bar" }, e.RemovedItems.Cast<object>());
called = true;
};
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
target.SelectedItems = new AvaloniaList<object>("foo", "baz");
Assert.True(called);
}
[Fact]
public void Shift_Selecting_From_No_Selection_Selects_From_Start()
{
var target = new ListBox
{
Template = Template(),
Items = new[] { "Foo", "Bar", "Baz" },
SelectionMode = SelectionMode.Multiple,
};
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
_helper.Click((Interactive)target.Presenter.Panel.Children[2], modifiers: KeyModifiers.Shift);
var panel = target.Presenter.Panel;
Assert.Equal(new[] { "Foo", "Bar", "Baz" }, target.SelectedItems);
Assert.Equal(new[] { 0, 1, 2 }, SelectedContainers(target));
}
[Fact]
public void Ctrl_Selecting_Raises_SelectionChanged_Events()
{
var target = new ListBox
{
Template = Template(),
Items = new[] { "Foo", "Bar", "Baz", "Qux" },
SelectionMode = SelectionMode.Multiple,
};
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
SelectionChangedEventArgs receivedArgs = null;
target.SelectionChanged += (_, args) => receivedArgs = args;
void VerifyAdded(string selection)
{
Assert.NotNull(receivedArgs);
Assert.Equal(new[] { selection }, receivedArgs.AddedItems);
Assert.Empty(receivedArgs.RemovedItems);
}
void VerifyRemoved(string selection)
{
Assert.NotNull(receivedArgs);
Assert.Equal(new[] { selection }, receivedArgs.RemovedItems);
Assert.Empty(receivedArgs.AddedItems);
}
_helper.Click((Interactive)target.Presenter.Panel.Children[1]);
VerifyAdded("Bar");
receivedArgs = null;
_helper.Click((Interactive)target.Presenter.Panel.Children[2], modifiers: KeyModifiers.Control);
VerifyAdded("Baz");
receivedArgs = null;
_helper.Click((Interactive)target.Presenter.Panel.Children[3], modifiers: KeyModifiers.Control);
VerifyAdded("Qux");
receivedArgs = null;
_helper.Click((Interactive)target.Presenter.Panel.Children[1], modifiers: KeyModifiers.Control);
VerifyRemoved("Bar");
}
[Fact]
public void Ctrl_Selecting_SelectedItem_With_Multiple_Selection_Active_Sets_SelectedItem_To_Next_Selection()
{
var target = new ListBox
{
Template = Template(),
Items = new[] { "Foo", "Bar", "Baz", "Qux" },
SelectionMode = SelectionMode.Multiple,
};
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
_helper.Click((Interactive)target.Presenter.Panel.Children[1]);
_helper.Click((Interactive)target.Presenter.Panel.Children[2], modifiers: KeyModifiers.Control);
_helper.Click((Interactive)target.Presenter.Panel.Children[3], modifiers: KeyModifiers.Control);
Assert.Equal(1, target.SelectedIndex);
Assert.Equal("Bar", target.SelectedItem);
Assert.Equal(new[] { "Bar", "Baz", "Qux" }, target.SelectedItems);
_helper.Click((Interactive)target.Presenter.Panel.Children[1], modifiers: KeyModifiers.Control);
Assert.Equal(2, target.SelectedIndex);
Assert.Equal("Baz", target.SelectedItem);
Assert.Equal(new[] { "Baz", "Qux" }, target.SelectedItems);
}
[Fact]
public void Ctrl_Selecting_Non_SelectedItem_With_Multiple_Selection_Active_Leaves_SelectedItem_The_Same()
{
var target = new ListBox
{
Template = Template(),
Items = new[] { "Foo", "Bar", "Baz" },
SelectionMode = SelectionMode.Multiple,
};
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
_helper.Click((Interactive)target.Presenter.Panel.Children[1]);
_helper.Click((Interactive)target.Presenter.Panel.Children[2], modifiers: KeyModifiers.Control);
Assert.Equal(1, target.SelectedIndex);
Assert.Equal("Bar", target.SelectedItem);
_helper.Click((Interactive)target.Presenter.Panel.Children[2], modifiers: KeyModifiers.Control);
Assert.Equal(1, target.SelectedIndex);
Assert.Equal("Bar", target.SelectedItem);
}
[Fact]
public void Should_Ctrl_Select_Correct_Item_When_Duplicate_Items_Are_Present()
{
var target = new ListBox
{
Template = Template(),
Items = new[] { "Foo", "Bar", "Baz", "Foo", "Bar", "Baz" },
SelectionMode = SelectionMode.Multiple,
};
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
_helper.Click((Interactive)target.Presenter.Panel.Children[3]);
_helper.Click((Interactive)target.Presenter.Panel.Children[4], modifiers: KeyModifiers.Control);
var panel = target.Presenter.Panel;
Assert.Equal(new[] { "Foo", "Bar" }, target.SelectedItems);
Assert.Equal(new[] { 3, 4 }, SelectedContainers(target));
}
[Fact]
public void Should_Shift_Select_Correct_Item_When_Duplicates_Are_Present()
{
var target = new ListBox
{
Template = Template(),
Items = new[] { "Foo", "Bar", "Baz", "Foo", "Bar", "Baz" },
SelectionMode = SelectionMode.Multiple,
};
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
_helper.Click((Interactive)target.Presenter.Panel.Children[3]);
_helper.Click((Interactive)target.Presenter.Panel.Children[5], modifiers: KeyModifiers.Shift);
var panel = target.Presenter.Panel;
Assert.Equal(new[] { "Foo", "Bar", "Baz" }, target.SelectedItems);
Assert.Equal(new[] { 3, 4, 5 }, SelectedContainers(target));
}
[Fact]
public void Can_Shift_Select_All_Items_When_Duplicates_Are_Present()
{
var target = new ListBox
{
Template = Template(),
Items = new[] { "Foo", "Bar", "Baz", "Foo", "Bar", "Baz" },
SelectionMode = SelectionMode.Multiple,
};
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
_helper.Click((Interactive)target.Presenter.Panel.Children[0]);
_helper.Click((Interactive)target.Presenter.Panel.Children[5], modifiers: KeyModifiers.Shift);
var panel = target.Presenter.Panel;
Assert.Equal(new[] { "Foo", "Bar", "Baz", "Foo", "Bar", "Baz" }, target.SelectedItems);
Assert.Equal(new[] { 0, 1, 2, 3, 4, 5 }, SelectedContainers(target));
}
[Fact]
public void Shift_Selecting_Raises_SelectionChanged_Events()
{
var target = new ListBox
{
Template = Template(),
Items = new[] { "Foo", "Bar", "Baz", "Qux" },
SelectionMode = SelectionMode.Multiple,
};
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
SelectionChangedEventArgs receivedArgs = null;
target.SelectionChanged += (_, args) => receivedArgs = args;
void VerifyAdded(params string[] selection)
{
Assert.NotNull(receivedArgs);
Assert.Equal(selection, receivedArgs.AddedItems);
Assert.Empty(receivedArgs.RemovedItems);
}
void VerifyRemoved(string selection)
{
Assert.NotNull(receivedArgs);
Assert.Equal(new[] { selection }, receivedArgs.RemovedItems);
Assert.Empty(receivedArgs.AddedItems);
}
_helper.Click((Interactive)target.Presenter.Panel.Children[1]);
VerifyAdded("Bar");
receivedArgs = null;
_helper.Click((Interactive)target.Presenter.Panel.Children[3], modifiers: KeyModifiers.Shift);
VerifyAdded("Baz" ,"Qux");
receivedArgs = null;
_helper.Click((Interactive)target.Presenter.Panel.Children[2], modifiers: KeyModifiers.Shift);
VerifyRemoved("Qux");
}
[Fact]
public void Duplicate_Items_Are_Added_To_SelectedItems_In_Order()
{
var target = new ListBox
{
Template = Template(),
Items = new[] { "Foo", "Bar", "Baz", "Foo", "Bar", "Baz" },
SelectionMode = SelectionMode.Multiple,
};
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
_helper.Click((Interactive)target.Presenter.Panel.Children[0]);
Assert.Equal(new[] { "Foo" }, target.SelectedItems);
_helper.Click((Interactive)target.Presenter.Panel.Children[4], modifiers: KeyModifiers.Control);
Assert.Equal(new[] { "Foo", "Bar" }, target.SelectedItems);
_helper.Click((Interactive)target.Presenter.Panel.Children[3], modifiers: KeyModifiers.Control);
Assert.Equal(new[] { "Foo", "Bar", "Foo" }, target.SelectedItems);
_helper.Click((Interactive)target.Presenter.Panel.Children[1], modifiers: KeyModifiers.Control);
Assert.Equal(new[] { "Foo", "Bar", "Foo", "Bar" }, target.SelectedItems);
}
[Fact]
public void SelectAll_Sets_SelectedIndex_And_SelectedItem()
{
var target = new TestSelector
{
Template = Template(),
Items = new[] { "Foo", "Bar", "Baz" },
SelectionMode = SelectionMode.Multiple,
};
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
target.SelectAll();
Assert.Equal(0, target.SelectedIndex);
Assert.Equal("Foo", target.SelectedItem);
}
[Fact]
public void SelectAll_Raises_SelectionChanged_Event()
{
var target = new TestSelector
{
Template = Template(),
Items = new[] { "Foo", "Bar", "Baz" },
SelectionMode = SelectionMode.Multiple,
};
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
SelectionChangedEventArgs receivedArgs = null;
target.SelectionChanged += (_, args) => receivedArgs = args;
target.SelectAll();
Assert.NotNull(receivedArgs);
Assert.Equal(target.Items, receivedArgs.AddedItems);
Assert.Empty(receivedArgs.RemovedItems);
}
[Fact]
public void UnselectAll_Clears_SelectedIndex_And_SelectedItem()
{
var target = new TestSelector
{
Template = Template(),
Items = new[] { "Foo", "Bar", "Baz" },
SelectionMode = SelectionMode.Multiple,
SelectedIndex = 0,
};
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
target.UnselectAll();
Assert.Equal(-1, target.SelectedIndex);
Assert.Equal(null, target.SelectedItem);
}
[Fact]
public void SelectAll_Handles_Duplicate_Items()
{
var target = new TestSelector
{
Template = Template(),
Items = new[] { "Foo", "Bar", "Baz", "Foo", "Bar", "Baz" },
SelectionMode = SelectionMode.Multiple,
};
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
target.SelectAll();
Assert.Equal(new[] { "Foo", "Bar", "Baz", "Foo", "Bar", "Baz" }, target.SelectedItems);
}
[Fact]
public void Adding_Item_Before_SelectedItems_Should_Update_Selection()
{
var items = new ObservableCollection<string>
{
"Foo",
"Bar",
"Baz"
};
var target = new ListBox
{
Template = Template(),
Items = items,
SelectionMode = SelectionMode.Multiple,
};
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
target.SelectAll();
items.Insert(0, "Qux");
Assert.Equal(1, target.SelectedIndex);
Assert.Equal("Foo", target.SelectedItem);
Assert.Equal(new[] { "Foo", "Bar", "Baz" }, target.SelectedItems);
Assert.Equal(new[] { 1, 2, 3 }, SelectedContainers(target));
}
[Fact]
public void Removing_Item_Before_SelectedItem_Should_Update_Selection()
{
var items = new ObservableCollection<string>
{
"Foo",
"Bar",
"Baz"
};
var target = new TestSelector
{
Template = Template(),
Items = items,
SelectionMode = SelectionMode.Multiple,
};
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
target.SelectedIndex = 1;
target.SelectRange(2);
Assert.Equal(new[] { "Bar", "Baz" }, target.SelectedItems);
items.RemoveAt(0);
Assert.Equal(0, target.SelectedIndex);
Assert.Equal("Bar", target.SelectedItem);
Assert.Equal(new[] { "Bar", "Baz" }, target.SelectedItems);
Assert.Equal(new[] { 0, 1 }, SelectedContainers(target));
}
[Fact]
public void Removing_SelectedItem_With_Multiple_Selection_Active_Should_Update_Selection()
{
var items = new ObservableCollection<string>
{
"Foo",
"Bar",
"Baz"
};
var target = new ListBox
{
Template = Template(),
Items = items,
SelectionMode = SelectionMode.Multiple,
};
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
target.SelectAll();
items.RemoveAt(0);
Assert.Equal(0, target.SelectedIndex);
Assert.Equal("Bar", target.SelectedItem);
Assert.Equal(new[] { "Bar", "Baz" }, target.SelectedItems);
Assert.Equal(new[] { 0, 1 }, SelectedContainers(target));
}
[Fact]
public void Replacing_Selected_Item_Should_Update_SelectedItems()
{
var items = new ObservableCollection<string>
{
"Foo",
"Bar",
"Baz"
};
var target = new ListBox
{
Template = Template(),
Items = items,
SelectionMode = SelectionMode.Multiple,
};
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
target.SelectAll();
items[1] = "Qux";
Assert.Equal(new[] { "Foo", "Baz" }, target.SelectedItems);
}
[Fact]
public void Left_Click_On_SelectedItem_Should_Clear_Existing_Selection()
{
var target = new ListBox
{
Template = Template(),
Items = new[] { "Foo", "Bar", "Baz" },
ItemTemplate = new FuncDataTemplate<string>((x, _) => new TextBlock { Width = 20, Height = 10 }),
SelectionMode = SelectionMode.Multiple,
};
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
target.SelectAll();
Assert.Equal(3, target.SelectedItems.Count);
_helper.Click((Interactive)target.Presenter.Panel.Children[0]);
Assert.Equal(1, target.SelectedItems.Count);
Assert.Equal(new[] { "Foo", }, target.SelectedItems);
Assert.Equal(new[] { 0 }, SelectedContainers(target));
}
[Fact]
public void Right_Click_On_SelectedItem_Should_Not_Clear_Existing_Selection()
{
var target = new ListBox
{
Template = Template(),
Items = new[] { "Foo", "Bar", "Baz" },
ItemTemplate = new FuncDataTemplate<string>((x, _) => new TextBlock { Width = 20, Height = 10 }),
SelectionMode = SelectionMode.Multiple,
};
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
target.SelectAll();
Assert.Equal(3, target.SelectedItems.Count);
_helper.Click((Interactive)target.Presenter.Panel.Children[0], MouseButton.Right);
Assert.Equal(3, target.SelectedItems.Count);
}
[Fact]
public void Right_Click_On_UnselectedItem_Should_Clear_Existing_Selection()
{
var target = new ListBox
{
Template = Template(),
Items = new[] { "Foo", "Bar", "Baz" },
ItemTemplate = new FuncDataTemplate<string>((x, _) => new TextBlock { Width = 20, Height = 10 }),
SelectionMode = SelectionMode.Multiple,
};
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
_helper.Click((Interactive)target.Presenter.Panel.Children[0]);
_helper.Click((Interactive)target.Presenter.Panel.Children[1], modifiers: KeyModifiers.Shift);
Assert.Equal(2, target.SelectedItems.Count);
_helper.Click((Interactive)target.Presenter.Panel.Children[2], MouseButton.Right);
Assert.Equal(1, target.SelectedItems.Count);
}
[Fact]
public void Adding_Selected_ItemContainers_Should_Update_Selection()
{
var items = new AvaloniaList<ItemContainer>(new[]
{
new ItemContainer(),
new ItemContainer(),
});
var target = new TestSelector
{
Items = items,
SelectionMode = SelectionMode.Multiple,
Template = Template(),
};
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
items.Add(new ItemContainer { IsSelected = true });
items.Add(new ItemContainer { IsSelected = true });
Assert.Equal(2, target.SelectedIndex);
Assert.Equal(items[2], target.SelectedItem);
Assert.Equal(new[] { items[2], items[3] }, target.SelectedItems);
}
[Fact]
public void Shift_Right_Click_Should_Not_Select_Multiple()
{
var target = new ListBox
{
Template = Template(),
Items = new[] { "Foo", "Bar", "Baz" },
ItemTemplate = new FuncDataTemplate<string>((x, _) => new TextBlock { Width = 20, Height = 10 }),
SelectionMode = SelectionMode.Multiple,
};
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
_helper.Click((Interactive)target.Presenter.Panel.Children[0]);
_helper.Click((Interactive)target.Presenter.Panel.Children[2], MouseButton.Right, modifiers: KeyModifiers.Shift);
Assert.Equal(1, target.SelectedItems.Count);
}
[Fact]
public void Ctrl_Right_Click_Should_Not_Select_Multiple()
{
var target = new ListBox
{
Template = Template(),
Items = new[] { "Foo", "Bar", "Baz" },
ItemTemplate = new FuncDataTemplate<string>((x, _) => new TextBlock { Width = 20, Height = 10 }),
SelectionMode = SelectionMode.Multiple,
};
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
_helper.Click((Interactive)target.Presenter.Panel.Children[0]);
_helper.Click((Interactive)target.Presenter.Panel.Children[2], MouseButton.Right, modifiers: KeyModifiers.Control);
Assert.Equal(1, target.SelectedItems.Count);
}
[Fact]
public void Adding_To_Selection_Should_Set_SelectedIndex()
{
var target = new TestSelector
{
Items = new[] { "foo", "bar" },
Template = Template(),
};
target.ApplyTemplate();
target.SelectedItems.Add("bar");
Assert.Equal(1, target.SelectedIndex);
}
[Fact]
public void Assigning_Null_To_Selection_Should_Create_New_SelectionModel()
{
var target = new TestSelector
{
Items = new[] { "foo", "bar" },
Template = Template(),
};
var oldSelection = target.Selection;
target.Selection = null;
Assert.NotNull(target.Selection);
Assert.NotSame(oldSelection, target.Selection);
}
[Fact]
public void Assigning_SelectionModel_With_Different_Source_To_Selection_Should_Fail()
{
var target = new TestSelector
{
Items = new[] { "foo", "bar" },
Template = Template(),
};
var selection = new SelectionModel<string> { Source = new[] { "baz" } };
Assert.Throws<ArgumentException>(() => target.Selection = selection);
}
[Fact]
public void Assigning_SelectionModel_With_Null_Source_To_Selection_Should_Set_Source()
{
var target = new TestSelector
{
Items = new[] { "foo", "bar" },
Template = Template(),
};
var selection = new SelectionModel<string>();
target.Selection = selection;
Assert.Same(target.Items, selection.Source);
}
[Fact]
public void Assigning_Single_Selected_Item_To_Selection_Should_Set_SelectedIndex()
{
var target = new TestSelector
{
Items = new[] { "foo", "bar" },
Template = Template(),
};
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
var selection = new SelectionModel<string> { SingleSelect = false };
selection.Select(1);
target.Selection = selection;
Assert.Equal(1, target.SelectedIndex);
Assert.Equal(new[] { "bar" }, target.Selection.SelectedItems);
Assert.Equal(new[] { 1 }, SelectedContainers(target));
}
[Fact]
public void Assigning_Multiple_Selected_Items_To_Selection_Should_Set_SelectedIndex()
{
var target = new TestSelector
{
Items = new[] { "foo", "bar", "baz" },
Template = Template(),
};
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
var selection = new SelectionModel<string> { SingleSelect = false };
selection.SelectRange(0, 2);
target.Selection = selection;
Assert.Equal(0, target.SelectedIndex);
Assert.Equal(new[] { "foo", "bar", "baz" }, target.Selection.SelectedItems);
Assert.Equal(new[] { 0, 1, 2 }, SelectedContainers(target));
}
[Fact]
public void Reassigning_Selection_Should_Clear_Selection()
{
var target = new TestSelector
{
Items = new[] { "foo", "bar" },
Template = Template(),
};
target.ApplyTemplate();
target.Selection.Select(1);
target.Selection = new SelectionModel<string>();
Assert.Equal(-1, target.SelectedIndex);
Assert.Null(target.SelectedItem);
}
[Fact]
public void Assigning_Selection_Should_Set_Item_IsSelected()
{
var items = new[]
{
new ListBoxItem(),
new ListBoxItem(),
new ListBoxItem(),
};
var target = new TestSelector
{
Items = items,
Template = Template(),
};
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
var selection = new SelectionModel<object> { SingleSelect = false };
selection.SelectRange(0, 1);
target.Selection = selection;
Assert.True(items[0].IsSelected);
Assert.True(items[1].IsSelected);
Assert.False(items[2].IsSelected);
}
[Fact]
public void Assigning_Selection_Should_Raise_SelectionChanged()
{
var items = new[] { "foo", "bar", "baz" };
var target = new TestSelector
{
Items = items,
Template = Template(),
SelectedItem = "bar",
};
var raised = 0;
target.SelectionChanged += (s, e) =>
{
if (raised == 0)
{
Assert.Empty(e.AddedItems.Cast<object>());
Assert.Equal(new[] { "bar" }, e.RemovedItems.Cast<object>());
}
else
{
Assert.Equal(new[] { "foo", "baz" }, e.AddedItems.Cast<object>());
Assert.Empty(e.RemovedItems.Cast<object>());
}
++raised;
};
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
var selection = new SelectionModel<string> { Source = items, SingleSelect = false };
selection.Select(0);
selection.Select(2);
target.Selection = selection;
Assert.Equal(2, raised);
}
private IEnumerable<int> SelectedContainers(SelectingItemsControl target)
{
return target.Presenter.Panel.Children
.Select((x, i) => x.Classes.Contains(":selected") ? i : -1)
.Where(x => x != -1);
}
private FuncControlTemplate Template()
{
return new FuncControlTemplate<SelectingItemsControl>((control, scope) =>
new ItemsPresenter
{
Name = "PART_ItemsPresenter",
[~ItemsPresenter.ItemsProperty] = control[~ItemsControl.ItemsProperty],
[~ItemsPresenter.ItemsPanelProperty] = control[~ItemsControl.ItemsPanelProperty],
}.RegisterInNameScope(scope));
}
private class TestSelector : SelectingItemsControl
{
public static readonly new AvaloniaProperty<IList> SelectedItemsProperty =
SelectingItemsControl.SelectedItemsProperty;
public static readonly new DirectProperty<SelectingItemsControl, ISelectionModel> SelectionProperty =
SelectingItemsControl.SelectionProperty;
public TestSelector()
{
SelectionMode = SelectionMode.Multiple;
}
public new IList SelectedItems
{
get { return base.SelectedItems; }
set { base.SelectedItems = value; }
}
public new ISelectionModel Selection
{
get => base.Selection;
set => base.Selection = value;
}
public new SelectionMode SelectionMode
{
get { return base.SelectionMode; }
set { base.SelectionMode = value; }
}
public void SelectAll() => Selection.SelectAll();
public void UnselectAll() => Selection.Clear();
public void SelectRange(int index) => UpdateSelection(index, true, true);
public void Toggle(int index) => UpdateSelection(index, true, false, true);
}
private class OldDataContextViewModel
{
public OldDataContextViewModel()
{
Items = new List<string> { "foo", "bar" };
SelectedItems = new List<string>();
Selection = new SelectionModel<string>();
}
public List<string> Items { get; }
public List<string> SelectedItems { get; }
public SelectionModel<string> Selection { get; }
}
private class ItemContainer : Control, ISelectable
{
public string Value { get; set; }
public bool IsSelected { get; set; }
}
}
}
| |
#region License
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Globalization;
using System.Runtime.Remoting;
using Common.Logging;
using Spring.Core.TypeConversion;
using Spring.Expressions;
using Spring.Objects.Factory.Config;
namespace Spring.Objects.Factory.Support
{
/// <summary>
/// Helper class for use in object factory implementations,
/// resolving values contained in object definition objects
/// into the actual values applied to the target object instance.
/// </summary>
/// <remarks>
/// Used by <see cref="AbstractAutowireCapableObjectFactory"/>.
/// </remarks>
/// <author>Juergen Hoeller</author>
/// <author>Mark Pollack (.NET)</author>
public class ObjectDefinitionValueResolver
{
private readonly ILog log;
private readonly AbstractObjectFactory objectFactory;
/// <summary>
/// Initializes a new instance of the <see cref="ObjectDefinitionValueResolver"/> class.
/// </summary>
/// <param name="objectFactory">The object factory.</param>
public ObjectDefinitionValueResolver(AbstractObjectFactory objectFactory)
{
this.log = LogManager.GetLogger(this.GetType());
this.objectFactory = objectFactory;
}
/// <summary>
/// Given a property value, return a value, resolving any references to other
/// objects in the factory if necessary.
/// </summary>
/// <remarks>
/// <p>
/// The value could be :
/// <list type="bullet">
/// <item>
/// <p>
/// An <see cref="Spring.Objects.Factory.Config.IObjectDefinition"/>,
/// which leads to the creation of a corresponding new object instance.
/// Singleton flags and names of such "inner objects" are always ignored: inner objects
/// are anonymous prototypes.
/// </p>
/// </item>
/// <item>
/// <p>
/// A <see cref="Spring.Objects.Factory.Config.RuntimeObjectReference"/>, which must
/// be resolved.
/// </p>
/// </item>
/// <item>
/// <p>
/// An <see cref="Spring.Objects.Factory.Config.IManagedCollection"/>. This is a
/// special placeholder collection that may contain
/// <see cref="Spring.Objects.Factory.Config.RuntimeObjectReference"/>s or
/// collections that will need to be resolved.
/// </p>
/// </item>
/// <item>
/// <p>
/// An ordinary object or <see langword="null"/>, in which case it's left alone.
/// </p>
/// </item>
/// </list>
/// </p>
/// </remarks>
/// <param name="name">
/// The name of the object that is having the value of one of its properties resolved.
/// </param>
/// <param name="definition">
/// The definition of the named object.
/// </param>
/// <param name="argumentName">
/// The name of the property the value of which is being resolved.
/// </param>
/// <param name="argumentValue">
/// The value of the property that is being resolved.
/// </param>
public virtual object ResolveValueIfNecessary(string name, IObjectDefinition definition, string argumentName, object argumentValue)
{
object resolvedValue = null;
resolvedValue = ResolvePropertyValue(name, definition, argumentName, argumentValue);
return resolvedValue;
}
/// <summary>
/// TODO
/// </summary>
/// <param name="name">
/// The name of the object that is having the value of one of its properties resolved.
/// </param>
/// <param name="definition">
/// The definition of the named object.
/// </param>
/// <param name="argumentName">
/// The name of the property the value of which is being resolved.
/// </param>
/// <param name="argumentValue">
/// The value of the property that is being resolved.
/// </param>
private object ResolvePropertyValue(string name, IObjectDefinition definition, string argumentName, object argumentValue)
{
object resolvedValue = null;
// we must check the argument value to see whether it requires a runtime
// reference to another object to be resolved.
// if it does, we'll attempt to instantiate the object and set the reference.
if (RemotingServices.IsTransparentProxy(argumentValue))
{
resolvedValue = argumentValue;
}
else if (argumentValue is ICustomValueReferenceHolder)
{
resolvedValue = ((ICustomValueReferenceHolder) argumentValue).Resolve(objectFactory, name, definition, argumentName, argumentValue);
}
else if (argumentValue is ObjectDefinitionHolder)
{
// contains an IObjectDefinition with name and aliases...
ObjectDefinitionHolder holder = (ObjectDefinitionHolder)argumentValue;
resolvedValue = ResolveInnerObjectDefinition(name, holder.ObjectName, argumentName, holder.ObjectDefinition, definition.IsSingleton);
}
else if (argumentValue is IObjectDefinition)
{
// resolve plain IObjectDefinition, without contained name: use dummy name...
IObjectDefinition def = (IObjectDefinition)argumentValue;
resolvedValue = ResolveInnerObjectDefinition(name, "(inner object)", argumentName, def, definition.IsSingleton);
}
else if (argumentValue is RuntimeObjectReference)
{
RuntimeObjectReference roref = (RuntimeObjectReference)argumentValue;
resolvedValue = ResolveReference(definition, name, argumentName, roref);
}
else if (argumentValue is ExpressionHolder)
{
ExpressionHolder expHolder = (ExpressionHolder)argumentValue;
object context = null;
IDictionary variables = null;
if (expHolder.Properties != null)
{
PropertyValue contextProperty = expHolder.Properties.GetPropertyValue("Context");
context = contextProperty == null
? null
: ResolveValueIfNecessary(name, definition, "Context",
contextProperty.Value);
PropertyValue variablesProperty = expHolder.Properties.GetPropertyValue("Variables");
object vars = (variablesProperty == null
? null
: ResolveValueIfNecessary(name, definition, "Variables",
variablesProperty.Value));
if (vars is IDictionary)
{
variables = (IDictionary)vars;
}
else
{
if (vars != null) throw new ArgumentException("'Variables' must resolve to an IDictionary");
}
}
if (variables == null) variables = CollectionsUtil.CreateCaseInsensitiveHashtable();
// add 'this' objectfactory reference to variables
variables.Add(Expression.ReservedVariableNames.CurrentObjectFactory, objectFactory);
resolvedValue = expHolder.Expression.GetValue(context, variables);
}
else if (argumentValue is IManagedCollection)
{
resolvedValue =
((IManagedCollection)argumentValue).Resolve(name, definition, argumentName,
new ManagedCollectionElementResolver(ResolveValueIfNecessary));
}
else if (argumentValue is TypedStringValue)
{
TypedStringValue tsv = (TypedStringValue)argumentValue;
try
{
Type resolvedTargetType = ResolveTargetType(tsv);
if (resolvedTargetType != null)
{
resolvedValue = TypeConversionUtils.ConvertValueIfNecessary(tsv.TargetType, tsv.Value, null);
}
else
{
resolvedValue = tsv.Value;
}
}
catch (Exception ex)
{
throw new ObjectCreationException(definition.ResourceDescription, name,
"Error converted typed String value for " + argumentName, ex);
}
}
else
{
// no need to resolve value...
resolvedValue = argumentValue;
}
return resolvedValue;
}
/// <summary>
/// Resolve the target type of the passed <see cref="TypedStringValue"/>.
/// </summary>
/// <param name="value">The <see cref="TypedStringValue"/> who's target type is to be resolved</param>
/// <returns>The resolved target type, if any. <see lang="null" /> otherwise.</returns>
protected virtual Type ResolveTargetType(TypedStringValue value)
{
if (value.HasTargetType)
{
return value.TargetType;
}
return value.ResolveTargetType();
}
/// <summary>
/// Resolves an inner object definition.
/// </summary>
/// <param name="name">
/// The name of the object that surrounds this inner object definition.
/// </param>
/// <param name="innerObjectName">
/// The name of the inner object definition... note: this is a synthetic
/// name assigned by the factory (since it makes no sense for inner object
/// definitions to have names).
/// </param>
/// <param name="argumentName">
/// The name of the property the value of which is being resolved.
/// </param>
/// <param name="definition">
/// The definition of the inner object that is to be resolved.
/// </param>
/// <param name="singletonOwner">
/// <see langword="true"/> if the owner of the property is a singleton.
/// </param>
/// <returns>
/// The resolved object as defined by the inner object definition.
/// </returns>
protected virtual object ResolveInnerObjectDefinition(string name, string innerObjectName, string argumentName, IObjectDefinition definition,
bool singletonOwner)
{
RootObjectDefinition mod = objectFactory.GetMergedObjectDefinition(innerObjectName, definition);
// Check given bean name whether it is unique. If not already unique,
// add counter - increasing the counter until the name is unique.
String actualInnerObjectName = innerObjectName;
if (mod.IsSingleton)
{
actualInnerObjectName = AdaptInnerObjectName(innerObjectName);
}
mod.IsSingleton = singletonOwner;
object instance;
object result;
try
{
//SPRNET-986 ObjectUtils.EmptyObjects -> null
instance = objectFactory.InstantiateObject(actualInnerObjectName, mod, null, false, false);
result = objectFactory.GetObjectForInstance(instance, actualInnerObjectName, actualInnerObjectName, mod);
}
catch (ObjectsException ex)
{
throw ObjectCreationException.GetObjectCreationException(ex, name, argumentName, definition.ResourceDescription, innerObjectName);
}
if (singletonOwner && instance is IDisposable)
{
// keep a reference to the inner object instance, to be able to destroy
// it on factory shutdown...
objectFactory.DisposableInnerObjects.Add(instance);
}
return result;
}
/// <summary>
/// Checks the given bean name whether it is unique. If not already unique,
/// a counter is added, increasing the counter until the name is unique.
/// </summary>
/// <param name="innerObjectName">Original Name of the inner object.</param>
/// <returns>The Adapted name for the inner object</returns>
private string AdaptInnerObjectName(string innerObjectName)
{
string actualInnerObjectName = innerObjectName;
int counter = 0;
while (this.objectFactory.IsObjectNameInUse(actualInnerObjectName))
{
counter++;
actualInnerObjectName = innerObjectName + ObjectFactoryUtils.GENERATED_OBJECT_NAME_SEPARATOR + counter;
}
return actualInnerObjectName;
}
/// <summary>
/// Resolve a reference to another object in the factory.
/// </summary>
/// <param name="name">
/// The name of the object that is having the value of one of its properties resolved.
/// </param>
/// <param name="definition">
/// The definition of the named object.
/// </param>
/// <param name="argumentName">
/// The name of the property the value of which is being resolved.
/// </param>
/// <param name="reference">
/// The runtime reference containing the value of the property.
/// </param>
/// <returns>A reference to another object in the factory.</returns>
protected virtual object ResolveReference(IObjectDefinition definition, string name, string argumentName, RuntimeObjectReference reference)
{
#region Instrumentation
if (log.IsDebugEnabled)
{
log.Debug(
string.Format(CultureInfo.InvariantCulture, "Resolving reference from property '{0}' in object '{1}' to object '{2}'.",
argumentName, name, reference.ObjectName));
}
#endregion
try
{
if (reference.IsToParent)
{
if (null == objectFactory.ParentObjectFactory)
{
throw new ObjectCreationException(definition.ResourceDescription, name,
string.Format(
"Can't resolve reference to '{0}' in parent factory: " + "no parent factory available.",
reference.ObjectName));
}
return objectFactory.ParentObjectFactory.GetObject(reference.ObjectName);
}
return objectFactory.GetObject(reference.ObjectName);
}
catch (ObjectsException ex)
{
throw ObjectCreationException.GetObjectCreationException(ex, name, argumentName, definition.ResourceDescription, reference.ObjectName);
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl.Services
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Impl.Unmanaged;
using Apache.Ignite.Core.Services;
using UU = Apache.Ignite.Core.Impl.Unmanaged.UnmanagedUtils;
/// <summary>
/// Services implementation.
/// </summary>
internal sealed class Services : PlatformTarget, IServices
{
/** */
private const int OpDeploy = 1;
/** */
private const int OpDeployMultiple = 2;
/** */
private const int OpDotnetServices = 3;
/** */
private const int OpInvokeMethod = 4;
/** */
private const int OpDescriptors = 5;
/** */
private readonly IClusterGroup _clusterGroup;
/** Invoker binary flag. */
private readonly bool _keepBinary;
/** Server binary flag. */
private readonly bool _srvKeepBinary;
/** Async instance. */
private readonly Lazy<Services> _asyncInstance;
/// <summary>
/// Initializes a new instance of the <see cref="Services" /> class.
/// </summary>
/// <param name="target">Target.</param>
/// <param name="marsh">Marshaller.</param>
/// <param name="clusterGroup">Cluster group.</param>
/// <param name="keepBinary">Invoker binary flag.</param>
/// <param name="srvKeepBinary">Server binary flag.</param>
public Services(IUnmanagedTarget target, Marshaller marsh, IClusterGroup clusterGroup,
bool keepBinary, bool srvKeepBinary)
: base(target, marsh)
{
Debug.Assert(clusterGroup != null);
_clusterGroup = clusterGroup;
_keepBinary = keepBinary;
_srvKeepBinary = srvKeepBinary;
_asyncInstance = new Lazy<Services>(() => new Services(this));
}
/// <summary>
/// Initializes a new async instance.
/// </summary>
/// <param name="services">The services.</param>
private Services(Services services) : base(UU.ServicesWithAsync(services.Target), services.Marshaller)
{
_clusterGroup = services.ClusterGroup;
_keepBinary = services._keepBinary;
_srvKeepBinary = services._srvKeepBinary;
}
/** <inheritDoc /> */
public IServices WithKeepBinary()
{
if (_keepBinary)
return this;
return new Services(Target, Marshaller, _clusterGroup, true, _srvKeepBinary);
}
/** <inheritDoc /> */
public IServices WithServerKeepBinary()
{
if (_srvKeepBinary)
return this;
return new Services(UU.ServicesWithServerKeepBinary(Target), Marshaller, _clusterGroup, _keepBinary, true);
}
/** <inheritDoc /> */
public IClusterGroup ClusterGroup
{
get { return _clusterGroup; }
}
/// <summary>
/// Gets the asynchronous instance.
/// </summary>
private Services AsyncInstance
{
get { return _asyncInstance.Value; }
}
/** <inheritDoc /> */
public void DeployClusterSingleton(string name, IService service)
{
IgniteArgumentCheck.NotNullOrEmpty(name, "name");
IgniteArgumentCheck.NotNull(service, "service");
DeployMultiple(name, service, 1, 1);
}
/** <inheritDoc /> */
public Task DeployClusterSingletonAsync(string name, IService service)
{
AsyncInstance.DeployClusterSingleton(name, service);
return AsyncInstance.GetTask();
}
/** <inheritDoc /> */
public void DeployNodeSingleton(string name, IService service)
{
IgniteArgumentCheck.NotNullOrEmpty(name, "name");
IgniteArgumentCheck.NotNull(service, "service");
DeployMultiple(name, service, 0, 1);
}
/** <inheritDoc /> */
public Task DeployNodeSingletonAsync(string name, IService service)
{
AsyncInstance.DeployNodeSingleton(name, service);
return AsyncInstance.GetTask();
}
/** <inheritDoc /> */
public void DeployKeyAffinitySingleton<TK>(string name, IService service, string cacheName, TK affinityKey)
{
IgniteArgumentCheck.NotNullOrEmpty(name, "name");
IgniteArgumentCheck.NotNull(service, "service");
IgniteArgumentCheck.NotNull(affinityKey, "affinityKey");
Deploy(new ServiceConfiguration
{
Name = name,
Service = service,
CacheName = cacheName,
AffinityKey = affinityKey,
TotalCount = 1,
MaxPerNodeCount = 1
});
}
/** <inheritDoc /> */
public Task DeployKeyAffinitySingletonAsync<TK>(string name, IService service, string cacheName, TK affinityKey)
{
AsyncInstance.DeployKeyAffinitySingleton(name, service, cacheName, affinityKey);
return AsyncInstance.GetTask();
}
/** <inheritDoc /> */
public void DeployMultiple(string name, IService service, int totalCount, int maxPerNodeCount)
{
IgniteArgumentCheck.NotNullOrEmpty(name, "name");
IgniteArgumentCheck.NotNull(service, "service");
DoOutOp(OpDeployMultiple, w =>
{
w.WriteString(name);
w.WriteObject(service);
w.WriteInt(totalCount);
w.WriteInt(maxPerNodeCount);
});
}
/** <inheritDoc /> */
public Task DeployMultipleAsync(string name, IService service, int totalCount, int maxPerNodeCount)
{
AsyncInstance.DeployMultiple(name, service, totalCount, maxPerNodeCount);
return AsyncInstance.GetTask();
}
/** <inheritDoc /> */
public void Deploy(ServiceConfiguration configuration)
{
IgniteArgumentCheck.NotNull(configuration, "configuration");
DoOutOp(OpDeploy, w =>
{
w.WriteString(configuration.Name);
w.WriteObject(configuration.Service);
w.WriteInt(configuration.TotalCount);
w.WriteInt(configuration.MaxPerNodeCount);
w.WriteString(configuration.CacheName);
w.WriteObject(configuration.AffinityKey);
if (configuration.NodeFilter != null)
w.WriteObject(configuration.NodeFilter);
else
w.WriteObject<object>(null);
});
}
/** <inheritDoc /> */
public Task DeployAsync(ServiceConfiguration configuration)
{
AsyncInstance.Deploy(configuration);
return AsyncInstance.GetTask();
}
/** <inheritDoc /> */
public void Cancel(string name)
{
IgniteArgumentCheck.NotNullOrEmpty(name, "name");
UU.ServicesCancel(Target, name);
}
/** <inheritDoc /> */
public Task CancelAsync(string name)
{
AsyncInstance.Cancel(name);
return AsyncInstance.GetTask();
}
/** <inheritDoc /> */
public void CancelAll()
{
UU.ServicesCancelAll(Target);
}
/** <inheritDoc /> */
public Task CancelAllAsync()
{
AsyncInstance.CancelAll();
return AsyncInstance.GetTask();
}
/** <inheritDoc /> */
public ICollection<IServiceDescriptor> GetServiceDescriptors()
{
return DoInOp(OpDescriptors, stream =>
{
var reader = Marshaller.StartUnmarshal(stream, _keepBinary);
var size = reader.ReadInt();
var result = new List<IServiceDescriptor>(size);
for (var i = 0; i < size; i++)
{
var name = reader.ReadString();
result.Add(new ServiceDescriptor(name, reader, this));
}
return result;
});
}
/** <inheritDoc /> */
public T GetService<T>(string name)
{
IgniteArgumentCheck.NotNullOrEmpty(name, "name");
var services = GetServices<T>(name);
if (services == null)
return default(T);
return services.FirstOrDefault();
}
/** <inheritDoc /> */
public ICollection<T> GetServices<T>(string name)
{
IgniteArgumentCheck.NotNullOrEmpty(name, "name");
return DoOutInOp<ICollection<T>>(OpDotnetServices, w => w.WriteString(name),
r =>
{
bool hasVal = r.ReadBool();
if (hasVal)
{
var count = r.ReadInt();
var res = new List<T>(count);
for (var i = 0; i < count; i++)
res.Add((T)Marshaller.Ignite.HandleRegistry.Get<IService>(r.ReadLong()));
return res;
}
return null;
});
}
/** <inheritDoc /> */
public T GetServiceProxy<T>(string name) where T : class
{
return GetServiceProxy<T>(name, false);
}
/** <inheritDoc /> */
public T GetServiceProxy<T>(string name, bool sticky) where T : class
{
IgniteArgumentCheck.NotNullOrEmpty(name, "name");
IgniteArgumentCheck.Ensure(typeof(T).IsInterface, "T", "Service proxy type should be an interface: " + typeof(T));
// In local scenario try to return service instance itself instead of a proxy
// Get as object because proxy interface may be different from real interface
var locInst = GetService<object>(name) as T;
if (locInst != null)
return locInst;
var javaProxy = UU.ServicesGetServiceProxy(Target, name, sticky);
return new ServiceProxy<T>((method, args) => InvokeProxyMethod(javaProxy, method, args))
.GetTransparentProxy();
}
/// <summary>
/// Invokes the service proxy method.
/// </summary>
/// <param name="proxy">Unmanaged proxy.</param>
/// <param name="method">Method to invoke.</param>
/// <param name="args">Arguments.</param>
/// <returns>
/// Invocation result.
/// </returns>
private unsafe object InvokeProxyMethod(IUnmanagedTarget proxy, MethodBase method, object[] args)
{
return DoOutInOp(OpInvokeMethod,
writer => ServiceProxySerializer.WriteProxyMethod(writer, method, args),
stream => ServiceProxySerializer.ReadInvocationResult(stream, Marshaller, _keepBinary), proxy.Target);
}
}
}
| |
//
// 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 Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.Sql;
using Microsoft.Azure.Management.Sql.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Sql
{
/// <summary>
/// Represents all the operations for operating on Azure SQL Database
/// Server Firewall Rules. Contains operations to: Create, Retrieve,
/// Update, and Delete firewall rules.
/// </summary>
internal partial class FirewallRuleOperations : IServiceOperations<SqlManagementClient>, IFirewallRuleOperations
{
/// <summary>
/// Initializes a new instance of the FirewallRuleOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal FirewallRuleOperations(SqlManagementClient client)
{
this._client = client;
}
private SqlManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Sql.SqlManagementClient.
/// </summary>
public SqlManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Creates or updates an Azure SQL Database Server Firewall rule.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <param name='firewallRule'>
/// Required. The name of the Azure SQL Database Server Firewall Rule.
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for createing or updating a
/// firewall rule.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response to a List Firewall Rules request.
/// </returns>
public async Task<FirewallRuleGetResponse> CreateOrUpdateAsync(string resourceGroupName, string serverName, string firewallRule, FirewallRuleCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (firewallRule == null)
{
throw new ArgumentNullException("firewallRule");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Properties == null)
{
throw new ArgumentNullException("parameters.Properties");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("firewallRule", firewallRule);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Sql";
url = url + "/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/firewallRules/";
url = url + Uri.EscapeDataString(firewallRule);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
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
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject firewallRuleCreateOrUpdateParametersValue = new JObject();
requestDoc = firewallRuleCreateOrUpdateParametersValue;
JObject propertiesValue = new JObject();
firewallRuleCreateOrUpdateParametersValue["properties"] = propertiesValue;
if (parameters.Properties.StartIpAddress != null)
{
propertiesValue["startIpAddress"] = parameters.Properties.StartIpAddress;
}
if (parameters.Properties.EndIpAddress != null)
{
propertiesValue["endIpAddress"] = parameters.Properties.EndIpAddress;
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// 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.OK && statusCode != HttpStatusCode.Created)
{
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
FirewallRuleGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new FirewallRuleGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
FirewallRule firewallRuleInstance = new FirewallRule();
result.FirewallRule = firewallRuleInstance;
JToken propertiesValue2 = responseDoc["properties"];
if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
{
FirewallRuleProperties propertiesInstance = new FirewallRuleProperties();
firewallRuleInstance.Properties = propertiesInstance;
JToken startIpAddressValue = propertiesValue2["startIpAddress"];
if (startIpAddressValue != null && startIpAddressValue.Type != JTokenType.Null)
{
string startIpAddressInstance = ((string)startIpAddressValue);
propertiesInstance.StartIpAddress = startIpAddressInstance;
}
JToken endIpAddressValue = propertiesValue2["endIpAddress"];
if (endIpAddressValue != null && endIpAddressValue.Type != JTokenType.Null)
{
string endIpAddressInstance = ((string)endIpAddressValue);
propertiesInstance.EndIpAddress = endIpAddressInstance;
}
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
firewallRuleInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
firewallRuleInstance.Name = nameInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
firewallRuleInstance.Type = typeInstance;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
firewallRuleInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
firewallRuleInstance.Tags.Add(tagsKey, tagsValue);
}
}
}
}
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>
/// Deletes an Azure SQL Database Server Firewall rule.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <param name='firewallRule'>
/// Required. The name of the Azure SQL Database Server Firewall Rule.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, string serverName, string firewallRule, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (firewallRule == null)
{
throw new ArgumentNullException("firewallRule");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("firewallRule", firewallRule);
TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Sql";
url = url + "/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/firewallRules/";
url = url + Uri.EscapeDataString(firewallRule);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
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
// 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.OK && statusCode != HttpStatusCode.NoContent)
{
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
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
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>
/// Returns an Azure SQL Database Server Firewall rule.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <param name='firewallRule'>
/// Required. The name of the Azure SQL Database Server Firewall Rule.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response to a List Firewall Rules request.
/// </returns>
public async Task<FirewallRuleGetResponse> GetAsync(string resourceGroupName, string serverName, string firewallRule, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (firewallRule == null)
{
throw new ArgumentNullException("firewallRule");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("firewallRule", firewallRule);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Sql";
url = url + "/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/firewallRules/";
url = url + Uri.EscapeDataString(firewallRule);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
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.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// 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.OK)
{
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
FirewallRuleGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new FirewallRuleGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
FirewallRule firewallRuleInstance = new FirewallRule();
result.FirewallRule = firewallRuleInstance;
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
FirewallRuleProperties propertiesInstance = new FirewallRuleProperties();
firewallRuleInstance.Properties = propertiesInstance;
JToken startIpAddressValue = propertiesValue["startIpAddress"];
if (startIpAddressValue != null && startIpAddressValue.Type != JTokenType.Null)
{
string startIpAddressInstance = ((string)startIpAddressValue);
propertiesInstance.StartIpAddress = startIpAddressInstance;
}
JToken endIpAddressValue = propertiesValue["endIpAddress"];
if (endIpAddressValue != null && endIpAddressValue.Type != JTokenType.Null)
{
string endIpAddressInstance = ((string)endIpAddressValue);
propertiesInstance.EndIpAddress = endIpAddressInstance;
}
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
firewallRuleInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
firewallRuleInstance.Name = nameInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
firewallRuleInstance.Type = typeInstance;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
firewallRuleInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
firewallRuleInstance.Tags.Add(tagsKey, tagsValue);
}
}
}
}
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>
/// Returns a list of Azure SQL Database Server Firewall rules.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response to a List Firewall Rules request.
/// </returns>
public async Task<FirewallRuleListResponse> ListAsync(string resourceGroupName, string serverName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Sql";
url = url + "/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/firewallRules";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
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.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// 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.OK)
{
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
FirewallRuleListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new FirewallRuleListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
FirewallRule firewallRuleInstance = new FirewallRule();
result.FirewallRules.Add(firewallRuleInstance);
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
FirewallRuleProperties propertiesInstance = new FirewallRuleProperties();
firewallRuleInstance.Properties = propertiesInstance;
JToken startIpAddressValue = propertiesValue["startIpAddress"];
if (startIpAddressValue != null && startIpAddressValue.Type != JTokenType.Null)
{
string startIpAddressInstance = ((string)startIpAddressValue);
propertiesInstance.StartIpAddress = startIpAddressInstance;
}
JToken endIpAddressValue = propertiesValue["endIpAddress"];
if (endIpAddressValue != null && endIpAddressValue.Type != JTokenType.Null)
{
string endIpAddressInstance = ((string)endIpAddressValue);
propertiesInstance.EndIpAddress = endIpAddressInstance;
}
}
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
firewallRuleInstance.Id = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
firewallRuleInstance.Name = nameInstance;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
firewallRuleInstance.Type = typeInstance;
}
JToken locationValue = valueValue["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
firewallRuleInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)valueValue["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
firewallRuleInstance.Tags.Add(tagsKey, tagsValue);
}
}
}
}
}
}
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();
}
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace ASP.NET_Web_API_application.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using Xunit;
namespace System.IO.Tests
{
public class File_Copy_str_str : FileSystemTest
{
#region Utilities
public static string[] WindowsInvalidUnixValid = new string[] { " ", " ", "\n", ">", "<", "\t" };
public virtual void Copy(string source, string dest)
{
File.Copy(source, dest);
}
#endregion
#region UniversalTests
[Fact]
public void NullFileName()
{
Assert.Throws<ArgumentNullException>(() => Copy(null, "."));
Assert.Throws<ArgumentNullException>(() => Copy(".", null));
}
[Fact]
public void EmptyFileName()
{
Assert.Throws<ArgumentException>(() => Copy(string.Empty, "."));
Assert.Throws<ArgumentException>(() => Copy(".", string.Empty));
}
[Fact]
public void CopyOntoDirectory()
{
string testFile = GetTestFilePath();
File.Create(testFile).Dispose();
Assert.Throws<IOException>(() => Copy(testFile, TestDirectory));
}
[Fact]
public void CopyOntoSelf()
{
string testFile = GetTestFilePath();
File.Create(testFile).Dispose();
Assert.Throws<IOException>(() => Copy(testFile, testFile));
}
[Fact]
public void NonExistentPath()
{
FileInfo testFile = new FileInfo(GetTestFilePath());
testFile.Create().Dispose();
Assert.Throws<FileNotFoundException>(() => Copy(GetTestFilePath(), testFile.FullName));
Assert.Throws<DirectoryNotFoundException>(() => Copy(testFile.FullName, Path.Combine(TestDirectory, GetTestFileName(), GetTestFileName())));
Assert.Throws<DirectoryNotFoundException>(() => Copy(Path.Combine(TestDirectory, GetTestFileName(), GetTestFileName()), testFile.FullName));
}
[Fact]
public void CopyValid()
{
string testFileSource = GetTestFilePath();
string testFileDest = GetTestFilePath();
File.Create(testFileSource).Dispose();
Copy(testFileSource, testFileDest);
Assert.True(File.Exists(testFileDest));
Assert.True(File.Exists(testFileSource));
}
[Fact]
public void ShortenLongPath()
{
string testFileSource = GetTestFilePath();
string testFileDest = Path.GetDirectoryName(testFileSource) + string.Concat(Enumerable.Repeat(Path.DirectorySeparatorChar + ".", 90).ToArray()) + Path.DirectorySeparatorChar + Path.GetFileName(testFileSource);
File.Create(testFileSource).Dispose();
Assert.Throws<IOException>(() => Copy(testFileSource, testFileDest));
}
[Fact]
public void InvalidFileNames()
{
string testFile = GetTestFilePath();
File.Create(testFile).Dispose();
Assert.Throws<ArgumentException>(() => Copy(testFile, "\0"));
Assert.Throws<ArgumentException>(() => Copy(testFile, "*\0*"));
Assert.Throws<ArgumentException>(() => Copy("*\0*", testFile));
Assert.Throws<ArgumentException>(() => Copy("\0", testFile));
}
public static IEnumerable<object[]> CopyFileWithData_MemberData()
{
var rand = new Random();
foreach (bool readOnly in new[] { true, false })
{
foreach (int length in new[] { 0, 1, 3, 4096, 1024 * 80, 1024 * 1024 * 10 })
{
char[] data = new char[length];
for (int i = 0; i < data.Length; i++)
{
data[i] = (char)rand.Next(0, 256);
}
yield return new object[] { data, readOnly};
}
}
}
[Theory]
[MemberData(nameof(CopyFileWithData_MemberData))]
public void CopyFileWithData_MemberData(char[] data, bool readOnly)
{
string testFileSource = GetTestFilePath();
string testFileDest = GetTestFilePath();
// Write and copy file
using (StreamWriter stream = new StreamWriter(File.Create(testFileSource)))
{
stream.Write(data, 0, data.Length);
}
// Set the last write time of the source file to something a while ago
DateTime lastWriteTime = DateTime.UtcNow.Subtract(TimeSpan.FromHours(1));
File.SetLastWriteTime(testFileSource, lastWriteTime);
if (readOnly)
{
File.SetAttributes(testFileSource, FileAttributes.ReadOnly);
}
// Copy over the data
Copy(testFileSource, testFileDest);
// Ensure copy transferred written data
using (StreamReader stream = new StreamReader(File.OpenRead(testFileDest)))
{
char[] readData = new char[data.Length];
stream.Read(readData, 0, data.Length);
Assert.Equal(data, readData);
}
// Ensure last write/access time on the new file is appropriate
Assert.InRange(File.GetLastWriteTimeUtc(testFileDest), lastWriteTime.AddSeconds(-1), lastWriteTime.AddSeconds(1));
Assert.Equal(readOnly, (File.GetAttributes(testFileDest) & FileAttributes.ReadOnly) != 0);
if (readOnly)
{
File.SetAttributes(testFileSource, FileAttributes.Normal);
File.SetAttributes(testFileDest, FileAttributes.Normal);
}
}
#endregion
#region PlatformSpecific
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Whitespace path throws ArgumentException
public void WindowsWhitespacePath()
{
string testFile = GetTestFilePath();
File.Create(testFile).Dispose();
foreach (string invalid in WindowsInvalidUnixValid)
{
Assert.Throws<ArgumentException>(() => Copy(testFile, invalid));
Assert.Throws<ArgumentException>(() => Copy(invalid, testFile));
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Whitespace path allowed
public void UnixWhitespacePath()
{
string testFile = GetTestFilePath();
File.Create(testFile).Dispose();
foreach (string valid in WindowsInvalidUnixValid)
{
Copy(testFile, Path.Combine(TestDirectory, valid));
Assert.True(File.Exists(testFile));
Assert.True(File.Exists(Path.Combine(TestDirectory, valid)));
}
}
#endregion
}
public class File_Copy_str_str_b : File_Copy_str_str
{
#region Utilities
public override void Copy(string source, string dest)
{
File.Copy(source, dest, false);
}
public virtual void Copy(string source, string dest, bool overwrite)
{
File.Copy(source, dest, overwrite);
}
#endregion
#region UniversalTests
[Fact]
public void OverwriteTrue()
{
string testFileSource = GetTestFilePath();
string testFileDest = GetTestFilePath();
char[] sourceData = { 'a', 'A', 'b' };
char[] destData = { 'x', 'X', 'y' };
// Write and copy file
using (StreamWriter sourceStream = new StreamWriter(File.Create(testFileSource)))
using (StreamWriter destStream = new StreamWriter(File.Create(testFileDest)))
{
sourceStream.Write(sourceData, 0, sourceData.Length);
destStream.Write(destData, 0, destData.Length);
}
Copy(testFileSource, testFileDest, true);
// Ensure copy transferred written data
using (StreamReader stream = new StreamReader(File.OpenRead(testFileDest)))
{
char[] readData = new char[sourceData.Length];
stream.Read(readData, 0, sourceData.Length);
Assert.Equal(sourceData, readData);
}
}
[Fact]
public void OverwriteFalse()
{
string testFileSource = GetTestFilePath();
string testFileDest = GetTestFilePath();
char[] sourceData = { 'a', 'A', 'b' };
char[] destData = { 'x', 'X', 'y' };
// Write and copy file
using (StreamWriter sourceStream = new StreamWriter(File.Create(testFileSource)))
using (StreamWriter destStream = new StreamWriter(File.Create(testFileDest)))
{
sourceStream.Write(sourceData, 0, sourceData.Length);
destStream.Write(destData, 0, destData.Length);
}
Assert.Throws<IOException>(() => Copy(testFileSource, testFileDest, false));
// Ensure copy didn't overwrite existing data
using (StreamReader stream = new StreamReader(File.OpenRead(testFileDest)))
{
char[] readData = new char[sourceData.Length];
stream.Read(readData, 0, sourceData.Length);
Assert.Equal(destData, readData);
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using Microsoft.Extensions.Logging;
using Umbraco.Cms.Core.Cache;
using Umbraco.Extensions;
namespace Umbraco.Cms.Core.Services.Implement
{
/// <summary>
/// Exposes the XDocument sources from files for the default localization text service and ensure caching is taken care of
/// </summary>
public class LocalizedTextServiceFileSources
{
private readonly ILogger<LocalizedTextServiceFileSources> _logger;
private readonly IAppPolicyCache _cache;
private readonly IEnumerable<LocalizedTextServiceSupplementaryFileSource> _supplementFileSources;
private readonly DirectoryInfo _fileSourceFolder;
// TODO: See other notes in this class, this is purely a hack because we store 2 letter culture file names that contain 4 letter cultures :(
private readonly Dictionary<string, CultureInfo> _twoLetterCultureConverter = new Dictionary<string, CultureInfo>();
private readonly Lazy<Dictionary<CultureInfo, Lazy<XDocument>>> _xmlSources;
/// <summary>
/// This is used to configure the file sources with the main file sources shipped with Umbraco and also including supplemental/plugin based
/// localization files. The supplemental files will be loaded in and merged in after the primary files.
/// The supplemental files must be named with the 4 letter culture name with a hyphen such as : en-AU.xml
/// </summary>
/// <param name="logger"></param>
/// <param name="cache"></param>
/// <param name="fileSourceFolder"></param>
/// <param name="supplementFileSources"></param>
public LocalizedTextServiceFileSources(
ILogger<LocalizedTextServiceFileSources> logger,
AppCaches appCaches,
DirectoryInfo fileSourceFolder,
IEnumerable<LocalizedTextServiceSupplementaryFileSource> supplementFileSources)
{
if (logger == null) throw new ArgumentNullException("logger");
if (appCaches == null) throw new ArgumentNullException("cache");
if (fileSourceFolder == null) throw new ArgumentNullException("fileSourceFolder");
_logger = logger;
_cache = appCaches.RuntimeCache;
if (fileSourceFolder.Exists == false)
{
_logger.LogWarning("The folder does not exist: {FileSourceFolder}, therefore no sources will be discovered", fileSourceFolder.FullName);
}
else
{
_fileSourceFolder = fileSourceFolder;
_supplementFileSources = supplementFileSources;
}
//Create the lazy source for the _xmlSources
_xmlSources = new Lazy<Dictionary<CultureInfo, Lazy<XDocument>>>(() =>
{
var result = new Dictionary<CultureInfo, Lazy<XDocument>>();
if (_fileSourceFolder == null) return result;
foreach (var fileInfo in _fileSourceFolder.GetFiles("*.xml"))
{
var localCopy = fileInfo;
var filename = Path.GetFileNameWithoutExtension(localCopy.FullName).Replace("_", "-");
// TODO: Fix this nonsense... would have to wait until v8 to store the language files with their correct
// names instead of storing them as 2 letters but actually having a 4 letter culture. So now, we
// need to check if the file is 2 letters, then open it to try to find it's 4 letter culture, then use that
// if it's successful. We're going to assume (though it seems assuming in the legacy logic is never a great idea)
// that any 4 letter file is named with the actual culture that it is!
CultureInfo culture = null;
if (filename.Length == 2)
{
//we need to open the file to see if we can read it's 'real' culture, we'll use XmlReader since we don't
//want to load in the entire doc into mem just to read a single value
using (var fs = fileInfo.OpenRead())
using (var reader = XmlReader.Create(fs))
{
if (reader.IsStartElement())
{
if (reader.Name == "language")
{
if (reader.MoveToAttribute("culture"))
{
var cultureVal = reader.Value;
try
{
culture = CultureInfo.GetCultureInfo(cultureVal);
//add to the tracked dictionary
_twoLetterCultureConverter[filename] = culture;
}
catch (CultureNotFoundException)
{
_logger.LogWarning("The culture {CultureValue} found in the file {CultureFile} is not a valid culture", cultureVal, fileInfo.FullName);
//If the culture in the file is invalid, we'll just hope the file name is a valid culture below, otherwise
// an exception will be thrown.
}
}
}
}
}
}
if (culture == null)
{
culture = CultureInfo.GetCultureInfo(filename);
}
//get the lazy value from cache
result[culture] = new Lazy<XDocument>(() => _cache.GetCacheItem<XDocument>(
string.Format("{0}-{1}", typeof(LocalizedTextServiceFileSources).Name, culture.Name), () =>
{
XDocument xdoc;
//load in primary
using (var fs = localCopy.OpenRead())
{
xdoc = XDocument.Load(fs);
}
//load in supplementary
MergeSupplementaryFiles(culture, xdoc);
return xdoc;
}, isSliding: true, timeout: TimeSpan.FromMinutes(10), dependentFiles: new[] { localCopy.FullName }));
}
return result;
});
}
/// <summary>
/// Constructor
/// </summary>
public LocalizedTextServiceFileSources(ILogger<LocalizedTextServiceFileSources> logger, AppCaches appCaches, DirectoryInfo fileSourceFolder)
: this(logger, appCaches, fileSourceFolder, Enumerable.Empty<LocalizedTextServiceSupplementaryFileSource>())
{ }
/// <summary>
/// returns all xml sources for all culture files found in the folder
/// </summary>
/// <returns></returns>
public IDictionary<CultureInfo, Lazy<XDocument>> GetXmlSources()
{
return _xmlSources.Value;
}
// TODO: See other notes in this class, this is purely a hack because we store 2 letter culture file names that contain 4 letter cultures :(
public Attempt<CultureInfo> TryConvert2LetterCultureTo4Letter(string twoLetterCulture)
{
if (twoLetterCulture.Length != 2) return Attempt<CultureInfo>.Fail();
//This needs to be resolved before continuing so that the _twoLetterCultureConverter cache is initialized
var resolved = _xmlSources.Value;
return _twoLetterCultureConverter.ContainsKey(twoLetterCulture)
? Attempt.Succeed(_twoLetterCultureConverter[twoLetterCulture])
: Attempt<CultureInfo>.Fail();
}
// TODO: See other notes in this class, this is purely a hack because we store 2 letter culture file names that contain 4 letter cultures :(
public Attempt<string> TryConvert4LetterCultureTo2Letter(CultureInfo culture)
{
if (culture == null) throw new ArgumentNullException("culture");
//This needs to be resolved before continuing so that the _twoLetterCultureConverter cache is initialized
var resolved = _xmlSources.Value;
return _twoLetterCultureConverter.Values.Contains(culture)
? Attempt.Succeed(culture.Name.Substring(0, 2))
: Attempt<string>.Fail();
}
private void MergeSupplementaryFiles(CultureInfo culture, XDocument xMasterDoc)
{
if (xMasterDoc.Root == null) return;
if (_supplementFileSources != null)
{
//now load in supplementary
var found = _supplementFileSources.Where(x =>
{
var extension = Path.GetExtension(x.File.FullName);
var fileCultureName = Path.GetFileNameWithoutExtension(x.File.FullName).Replace("_", "-").Replace(".user", "");
return extension.InvariantEquals(".xml") && (
fileCultureName.InvariantEquals(culture.Name)
|| fileCultureName.InvariantEquals(culture.TwoLetterISOLanguageName)
);
});
foreach (var supplementaryFile in found)
{
using (var fs = supplementaryFile.File.OpenRead())
{
XDocument xChildDoc;
try
{
xChildDoc = XDocument.Load(fs);
}
catch (Exception ex)
{
_logger.LogError(ex, "Could not load file into XML {File}", supplementaryFile.File.FullName);
continue;
}
if (xChildDoc.Root == null || xChildDoc.Root.Name != "language") continue;
foreach (var xArea in xChildDoc.Root.Elements("area")
.Where(x => ((string)x.Attribute("alias")).IsNullOrWhiteSpace() == false))
{
var areaAlias = (string)xArea.Attribute("alias");
var areaFound = xMasterDoc.Root.Elements("area").FirstOrDefault(x => ((string)x.Attribute("alias")) == areaAlias);
if (areaFound == null)
{
//add the whole thing
xMasterDoc.Root.Add(xArea);
}
else
{
MergeChildKeys(xArea, areaFound, supplementaryFile.OverwriteCoreKeys);
}
}
}
}
}
}
private void MergeChildKeys(XElement source, XElement destination, bool overwrite)
{
if (destination == null) throw new ArgumentNullException("destination");
if (source == null) throw new ArgumentNullException("source");
//merge in the child elements
foreach (var key in source.Elements("key")
.Where(x => ((string)x.Attribute("alias")).IsNullOrWhiteSpace() == false))
{
var keyAlias = (string)key.Attribute("alias");
var keyFound = destination.Elements("key").FirstOrDefault(x => ((string)x.Attribute("alias")) == keyAlias);
if (keyFound == null)
{
//append, it doesn't exist
destination.Add(key);
}
else if (overwrite)
{
//overwrite
keyFound.Value = key.Value;
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using NUnit.Framework;
using NServiceKit.Common.Extensions;
using NServiceKit.Text;
namespace NServiceKit.Redis.Tests
{
[TestFixture, Category("Integration")]
public class RedisPubSubTests
: RedisClientTestsBase
{
public override void OnBeforeEachTest()
{
base.OnBeforeEachTest();
Redis.NamespacePrefix = "RedisPubSubTests";
}
[Test]
public void Can_Subscribe_and_Publish_single_message()
{
var channelName = PrefixedKey("CHANNEL1");
const string message = "Hello, World!";
var key = PrefixedKey("Can_Subscribe_and_Publish_single_message");
Redis.IncrementValue(key);
using (var subscription = Redis.CreateSubscription())
{
subscription.OnSubscribe = channel =>
{
Log("Subscribed to '{0}'", channel);
Assert.That(channel, Is.EqualTo(channelName));
};
subscription.OnUnSubscribe = channel =>
{
Log("UnSubscribed from '{0}'", channel);
Assert.That(channel, Is.EqualTo(channelName));
};
subscription.OnMessage = (channel, msg) =>
{
Log("Received '{0}' from channel '{1}'", msg, channel);
Assert.That(channel, Is.EqualTo(channelName));
Assert.That(msg, Is.EqualTo(message));
subscription.UnSubscribeFromAllChannels();
};
ThreadPool.QueueUserWorkItem(x =>
{
Thread.Sleep(100); // to be sure that we have subscribers
using (var redisClient = CreateRedisClient())
{
Log("Publishing '{0}' to '{1}'", message, channelName);
redisClient.PublishMessage(channelName, message);
}
});
Log("Start Listening On " + channelName);
subscription.SubscribeToChannels(channelName); //blocking
}
Log("Using as normal client again...");
Redis.IncrementValue(key);
Assert.That(Redis.Get<int>(key), Is.EqualTo(2));
}
[Test]
public void Can_Subscribe_and_Publish_single_message_using_wildcard()
{
var channelWildcard = PrefixedKey("CHANNEL.*");
var channelName = PrefixedKey("CHANNEL.1");
const string message = "Hello, World!";
var key = PrefixedKey("Can_Subscribe_and_Publish_single_message");
Redis.IncrementValue(key);
using (var subscription = Redis.CreateSubscription())
{
subscription.OnSubscribe = channel =>
{
Log("Subscribed to '{0}'", channelWildcard);
Assert.That(channel, Is.EqualTo(channelWildcard));
};
subscription.OnUnSubscribe = channel =>
{
Log("UnSubscribed from '{0}'", channelWildcard);
Assert.That(channel, Is.EqualTo(channelWildcard));
};
subscription.OnMessage = (channel, msg) =>
{
Log("Received '{0}' from channel '{1}'", msg, channel);
Assert.That(channel, Is.EqualTo(channelName));
Assert.That(msg, Is.EqualTo(message), "we should get the message, not the channel");
subscription.UnSubscribeFromChannelsMatching();
};
ThreadPool.QueueUserWorkItem(x =>
{
Thread.Sleep(100); // to be sure that we have subscribers
using (var redisClient = CreateRedisClient())
{
Log("Publishing '{0}' to '{1}'", message, channelName);
redisClient.PublishMessage(channelName, message);
}
});
Log("Start Listening On " + channelName);
subscription.SubscribeToChannelsMatching(channelWildcard); //blocking
}
Log("Using as normal client again...");
Redis.IncrementValue(key);
Assert.That(Redis.Get<int>(key), Is.EqualTo(2));
}
[Test]
public void Can_Subscribe_and_Publish_multiple_message()
{
var channelName = PrefixedKey("CHANNEL2");
const string messagePrefix = "MESSAGE ";
string key = PrefixedKey("Can_Subscribe_and_Publish_multiple_message");
const int publishMessageCount = 5;
var messagesReceived = 0;
Redis.IncrementValue(key);
using (var subscription = Redis.CreateSubscription())
{
subscription.OnSubscribe = channel =>
{
Log("Subscribed to '{0}'", channel);
Assert.That(channel, Is.EqualTo(channelName));
};
subscription.OnUnSubscribe = channel =>
{
Log("UnSubscribed from '{0}'", channel);
Assert.That(channel, Is.EqualTo(channelName));
};
subscription.OnMessage = (channel, msg) =>
{
Log("Received '{0}' from channel '{1}'", msg, channel);
Assert.That(channel, Is.EqualTo(channelName));
Assert.That(msg, Is.EqualTo(messagePrefix + messagesReceived++));
if (messagesReceived == publishMessageCount)
{
subscription.UnSubscribeFromAllChannels();
}
};
ThreadPool.QueueUserWorkItem(x =>
{
Thread.Sleep(100); // to be sure that we have subscribers
using (var redisClient = CreateRedisClient())
{
for (var i = 0; i < publishMessageCount; i++)
{
var message = messagePrefix + i;
Log("Publishing '{0}' to '{1}'", message, channelName);
redisClient.PublishMessage(channelName, message);
}
}
});
Log("Start Listening On");
subscription.SubscribeToChannels(channelName); //blocking
}
Log("Using as normal client again...");
Redis.IncrementValue(key);
Assert.That(Redis.Get<int>(key), Is.EqualTo(2));
Assert.That(messagesReceived, Is.EqualTo(publishMessageCount));
}
[Test]
public void Can_Subscribe_and_Publish_message_to_multiple_channels()
{
var channelPrefix = PrefixedKey("CHANNEL3 ");
const string message = "MESSAGE";
const int publishChannelCount = 5;
var key = PrefixedKey("Can_Subscribe_and_Publish_message_to_multiple_channels");
var channels = new List<string>();
publishChannelCount.Times(i => channels.Add(channelPrefix + i));
var messagesReceived = 0;
var channelsSubscribed = 0;
var channelsUnSubscribed = 0;
Redis.IncrementValue(key);
using (var subscription = Redis.CreateSubscription())
{
subscription.OnSubscribe = channel =>
{
Log("Subscribed to '{0}'", channel);
Assert.That(channel, Is.EqualTo(channelPrefix + channelsSubscribed++));
};
subscription.OnUnSubscribe = channel =>
{
Log("UnSubscribed from '{0}'", channel);
Assert.That(channel, Is.EqualTo(channelPrefix + channelsUnSubscribed++));
};
subscription.OnMessage = (channel, msg) =>
{
Log("Received '{0}' from channel '{1}'", msg, channel);
Assert.That(channel, Is.EqualTo(channelPrefix + messagesReceived++));
Assert.That(msg, Is.EqualTo(message));
subscription.UnSubscribeFromChannels(channel);
};
ThreadPool.QueueUserWorkItem(x =>
{
Thread.Sleep(100); // to be sure that we have subscribers
using (var redisClient = CreateRedisClient())
{
foreach (var channel in channels)
{
Log("Publishing '{0}' to '{1}'", message, channel);
redisClient.PublishMessage(channel, message);
}
}
});
Log("Start Listening On");
subscription.SubscribeToChannels(channels.ToArray()); //blocking
}
Log("Using as normal client again...");
Redis.IncrementValue(key);
Assert.That(Redis.Get<int>(key), Is.EqualTo(2));
Assert.That(messagesReceived, Is.EqualTo(publishChannelCount));
Assert.That(channelsSubscribed, Is.EqualTo(publishChannelCount));
Assert.That(channelsUnSubscribed, Is.EqualTo(publishChannelCount));
}
[Test]
public void Can_Subscribe_to_channel_pattern()
{
int msgs = 0;
using (var subscription = Redis.CreateSubscription())
{
subscription.OnMessage = (channel, msg) => {
Debug.WriteLine(String.Format("{0}: {1}", channel, msg + msgs++));
subscription.UnSubscribeFromChannelsMatching(PrefixedKey("CHANNEL4:TITLE*"));
};
ThreadPool.QueueUserWorkItem(x =>
{
Thread.Sleep(100); // to be sure that we have subscribers
using (var redisClient = CreateRedisClient())
{
Log("Publishing msg...");
redisClient.Publish(PrefixedKey("CHANNEL4:TITLE1"), "hello".ToUtf8Bytes());
}
});
Log("Start Listening On");
subscription.SubscribeToChannelsMatching(PrefixedKey("CHANNEL4:TITLE*"));
}
}
[Test]
public void Can_Subscribe_to_multiplechannel_pattern()
{
var channels = new[] {PrefixedKey("CHANNEL5:TITLE*"), PrefixedKey("CHANNEL5:BODY*")};
int msgs = 0;
using (var subscription = Redis.CreateSubscription())
{
subscription.OnMessage = (channel, msg) =>
{
Debug.WriteLine(String.Format("{0}: {1}", channel, msg + msgs++));
subscription.UnSubscribeFromChannelsMatching(channels);
};
ThreadPool.QueueUserWorkItem(x =>
{
Thread.Sleep(100); // to be sure that we have subscribers
using (var redisClient = CreateRedisClient())
{
Log("Publishing msg...");
redisClient.Publish(PrefixedKey("CHANNEL5:BODY"), "hello".ToUtf8Bytes());
}
});
Log("Start Listening On");
subscription.SubscribeToChannelsMatching(channels);
}
}
}
}
| |
// Copyright (c) 2015 fjz13. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Text;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using GameKit.Log;
using GameKit.Publish;
using Color = System.Drawing.Color;
using PixelFormat = System.Drawing.Imaging.PixelFormat;
namespace GameKit.Resource
{
public class ImageFile : FileListFile, IComparable<ImageFile>
{
public ImageFile(FileInfo filePath, bool enablePacking = true,bool isCoded=false)
: base(filePath, enablePacking,isCoded)
{
if (filePath.Exists)
{
OriginalSize = GetImageSize(filePath);
ResultSize = OriginalSize;
}
IsOptimzed = true;
}
public static Size GetImageSize(FileInfo filePath)
{
if (filePath.Name.EndsWith(".png"))
{
var buff = new byte[32];
using (var d = filePath.OpenRead())
{
d.Read(buff, 0, 32);
}
const int wOff = 16;
const int hOff = 20;
var Width = BitConverter.ToInt32(new[] { buff[wOff + 3], buff[wOff + 2], buff[wOff + 1], buff[wOff + 0], }, 0);
var Height = BitConverter.ToInt32(new[] { buff[hOff + 3], buff[hOff + 2], buff[hOff + 1], buff[hOff + 0], }, 0);
return new Size(Width, Height);
}
else
{
GC.Collect();
var tempImage = (Bitmap)Bitmap.FromFile(filePath.FullName);
Size size = tempImage.Size;
tempImage.Dispose();
return size;
}
}
public Bitmap ResultImage
{
get;
set;
}
public Rectangle? TextureRect { get; set; }
public Point? Offset { get; set; }
public bool IsOptimzed { get; set; }
public Size OriginalSize { get; private set; }
public Size ResultSize { get; set; }
public int CompareTo(ImageFile other)
{
int widthDiff = other.ResultSize.Width - ResultSize.Width;
if (widthDiff != 0)
{
return widthDiff;
}
return other.ResultSize.Height - ResultSize.Height;
}
void ConvertTo8bpp(Bitmap sourceBitmap, string outputFileName)
{
int width = sourceBitmap.Width;
int height = sourceBitmap.Height;
int stride = sourceBitmap.Width;
// generate a custom palette for the bitmap (I already had a list of colors
// from a previous operation
Dictionary<System.Drawing.Color, byte> colorDict = new Dictionary<System.Drawing.Color, byte>(); // lookup table for conversion to indexed color
List<System.Windows.Media.Color> colorList = new List<System.Windows.Media.Color>(); // list for palette creation
byte index = 0;
for (int x = 0; x < width; ++x)
{
for (int y = 0; y < height; ++y)
{
var pixelColor = sourceBitmap.GetPixel(x, y);
if (!colorDict.ContainsKey(pixelColor))
{
colorDict.Add(pixelColor, index++);
System.Windows.Media.Color mediaColor = new System.Windows.Media.Color();
mediaColor.A = pixelColor.A;
mediaColor.R = pixelColor.R;
mediaColor.G = pixelColor.G;
mediaColor.B = pixelColor.B;
colorList.Add(mediaColor);
}
}
}
// create the byte array of raw image data
byte[] imageData = new byte[width * height];
for (int x = 0; x < width; ++x)
{
for (int y = 0; y < height; ++y)
{
var pixelColor = sourceBitmap.GetPixel(x, y);
imageData[x + (stride * y)] = colorDict[pixelColor];
}
}
System.Windows.Media.Imaging.BitmapPalette bmpPal = new System.Windows.Media.Imaging.BitmapPalette(colorList);
// generate the image source
var bsource = BitmapSource.Create(width, height, 96, 96, PixelFormats.Indexed8, bmpPal, imageData, stride);
// encode the image
PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Interlace = PngInterlaceOption.On;
encoder.Frames.Add(BitmapFrame.Create(bsource));
using (var stream = new FileStream(outputFileName, FileMode.Create))
{
encoder.Save(stream);
}
}
public void Save()
{
//ConvertTo8bpp(ResultImage, FileInfo.FullName);
if (IsOptimzed)
{
ResultImage.Save(FileInfo.FullName, ImageFormat.Png);
}
}
private Bitmap ChangePixelFormat(Bitmap inputImage, PixelFormat newFormat)
{
Bitmap bmp = new Bitmap(inputImage.Width, inputImage.Height, newFormat);
using (Graphics g = Graphics.FromImage(bmp))
{
g.DrawImage(inputImage, 0, 0);
}
return bmp;
}
public override string ToString()
{
var sb = new StringBuilder();
bool isAdd = false;
if (PublishGroup != null)
{
isAdd = true;
sb.Append(PublishGroup);
}
//if (ResultFile != null && !ReferenceEquals(ResultFile, OriginalFile))
//{
// if (isAdd)
// {
// sb.Append("\t");
// }
// sb.Append(ResultFile.FileInfo.Name);
// isAdd = true;
//}
if (!OriginalSize.IsEmpty && ResultImage != null)
{
if (isAdd)
{
sb.Append("\t");
}
sb.AppendFormat("{0}=>{1}", OriginalSize, ResultImage.Size);
isAdd = true;
}
if (TextureRect.HasValue)
{
if (isAdd)
{
sb.Append("\t");
}
sb.Append(TextureRect.ToString());
isAdd = true;
}
if (Offset.HasValue)
{
if (isAdd)
{
sb.Append("\t");
}
sb.Append(Offset.ToString());
}
return sb.ToString();
}
public void Optimze()
{
if (!IsOptimzed)
{
return;
}
if (PublishTarget.Current.IsCacheEnabled && FileCacheCenter.IsInCache(FileInfo,Md5,FileCacheOperation.ImageOptimzed))
{
var fileInfo = FileCacheCenter.GetCacheFileInfo(FileInfo,Md5,FileCacheOperation.ImageOptimzed);
var cacheItem = FileCacheCenter.GetCacheFileItem(FileInfo,Md5,FileCacheOperation.ImageOptimzed);
if (ResultImage!=null)
{
ResultImage.Dispose();
GC.Collect();
ResultImage = null;
}
//ResultImage = (Bitmap)Bitmap.FromFile(fileInfo.FullName);
ResultSize = GetImageSize(fileInfo);
if (cacheItem.TextureRect != null)
{
Rectangle rect=new Rectangle();
rect.X = (int)cacheItem.TextureRect.Origin.X;
rect.Y = (int)cacheItem.TextureRect.Origin.Y;
rect.Width = (int) cacheItem.TextureRect.Size.Width;
rect.Height = (int)cacheItem.TextureRect.Size.Height;
TextureRect = rect;
}
if (cacheItem.Offset!=null)
{
Point pos=new Point();
pos.X = (int) cacheItem.Offset.X;
pos.Y = (int)cacheItem.Offset.Y;
Offset = pos;
}
Logger.LogInfoLine("FileCache Hit:Optimze {0} ", FileInfo.FullName);
UpdateFileInfo(fileInfo);
}
else
{
var originalImage = (Bitmap)Bitmap.FromFile(FileInfo.FullName);
var leftBottom = new Point(int.MaxValue, int.MaxValue);
var rightTop = Point.Empty;
bool isBreak = false;
for (int i = 0; i < originalImage.Width; i++)
{
for (int j = 0; j < originalImage.Height; j++)
{
var color = originalImage.GetPixel(i, j);
if (color.A != 0)
{
leftBottom.X = i;
isBreak = true;
break;
}
}
if (isBreak)
{
break;
}
}
isBreak = false;
for (int i = originalImage.Width - 1; i >= 0; i--)
{
for (int j = 0; j < originalImage.Height; j++)
{
var color = originalImage.GetPixel(i, j);
if (color.A != 0)
{
rightTop.X = i;
isBreak = true;
break;
}
}
if (isBreak)
{
break;
}
}
isBreak = false;
for (int i = 0; i < originalImage.Height; i++)
{
for (int j = 0; j < originalImage.Width; j++)
{
var color = originalImage.GetPixel(j, i);
if (color.A != 0)
{
leftBottom.Y = i;
isBreak = true;
break;
}
}
if (isBreak)
{
break;
}
}
isBreak = false;
for (int i = originalImage.Height - 1; i >= 0; i--)
{
for (int j = 0; j < originalImage.Width; j++)
{
var color = originalImage.GetPixel(j, i);
if (color.A != 0)
{
rightTop.Y = i;
isBreak = true;
break;
}
}
if (isBreak)
{
break;
}
}
var clipRect = new Rectangle(leftBottom,
new Size(rightTop.X - leftBottom.X + 1, rightTop.Y - leftBottom.Y + 1));
if (leftBottom.X == int.MaxValue || leftBottom.Y == int.MaxValue)
{
ResultImage = originalImage;
Logger.LogError("Empty image:{0}\r\n", FileInfo);
}
else
{
if (clipRect.Size != originalImage.Size)
{
Offset = new Point(leftBottom.X, originalImage.Size.Height - clipRect.Bottom);
ResultImage = ClipImage(originalImage, clipRect);
originalImage.Dispose();
ResultSize = ResultImage.Size;
}
else
{
ResultImage = originalImage;
}
}
if (PublishTarget.Current.IsCacheEnabled)
{
var newFileInfo = FileCacheCenter.GetCacheNewFileInfo(FileInfo.FullName, FileCacheOperation.ImageOptimzed);
if (newFileInfo.Exists)
{
newFileInfo.Delete();
}
ResultImage.Save(newFileInfo.FullName, ImageFormat.Png);
FileCacheCenter.AddToCacheWithoutCopy(Md5, FileInfo,TextureRect,Offset,FileCacheOperation.ImageOptimzed);
UpdateFileInfo(newFileInfo);
}
else
{
UpdateFileInfo(FileInfo);
}
ResultImage.Dispose();
GC.Collect();
ResultImage = null;
}
//Logger.LogInfoLine("Optimze image:{0}", ToString());
}
private Bitmap ClipImage(Bitmap image, Rectangle clipRect)
{
var resultImage = new Bitmap(clipRect.Width, clipRect.Height);
using (var graphics = Graphics.FromImage(resultImage))
{
graphics.Clear(Color.Transparent);
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
var toRect = new Rectangle(0, 0, clipRect.Width, clipRect.Height);
graphics.DrawImage(image, toRect, clipRect, GraphicsUnit.Pixel);
}
return resultImage;
}
public static bool IsPOTSize(int val)
{
return (val & (val - 1)) == 0;
}
public string TryConvertSelfToPVR()
{
if (PublishTarget.Current.IsPVR && IsPVREnabled)
{
if (!IsPOTSize(ResultSize.Width) || !IsPOTSize(ResultSize.Height))
{
Logger.LogAllLine("NOT POT image size :{0}-{1} of {2}", ResultSize.Width, ResultSize.Height, FileInfo);
return FileInfo.FullName;
}
string newFilePath = TryConvertToPVR(FileInfo, Md5);
UpdateFileInfo(new FileInfo(newFilePath));
return newFilePath;
}
return FileInfo.FullName;
}
public static string TryConvertToPVR(FileInfo filePath, string md5)
{
if (!PublishTarget.Current.IsPVR)
{
return filePath.FullName;
}
string outFilePath = filePath.FullName;
outFilePath = outFilePath.Replace(filePath.Extension, ".pvr");
if (PublishTarget.Current.IsCacheEnabled && FileCacheCenter.IsInCache(new FileInfo(outFilePath), md5, FileCacheOperation.PVR))
{
outFilePath = FileCacheCenter.CopyCacheToDirectory(new FileInfo(outFilePath), md5, filePath.Directory, FileCacheOperation.PVR);
Logger.LogInfoLine("FileCache Hit:TryConvertToPVR {0} ", filePath.FullName);
filePath.Delete(); //delete original file
return outFilePath;
}
else
{
string arguments = string.Format("-i {0} -o {1} -f {2} -q {3}", filePath.FullName, outFilePath,
PublishTarget.Current.PVRFormat, PublishTarget.Current.PVRQuality.ToString());
ProcessStartInfo start = new ProcessStartInfo("PVRTexToolCLI.exe");
Logger.LogInfoLine("PVRTexToolCLI.exe {0} {1}", filePath.FullName, outFilePath);
start.Arguments = arguments;//??????
start.CreateNoWindow = true;//???dos?????
start.RedirectStandardOutput = true;//
start.RedirectStandardInput = true;//
start.UseShellExecute = false;//????????????????
Process p = Process.Start(start);
StreamReader reader = p.StandardOutput;//?????
do
{
string line = reader.ReadLine();//??????
if (!string.IsNullOrEmpty(line))
{
Logger.LogInfoLine(line);
}
} while (!reader.EndOfStream);
p.WaitForExit();//???????????
p.Close();//????
reader.Close();//???
filePath.Delete(); //delete original file
if (PublishTarget.Current.IsCacheEnabled)
{
FileCacheCenter.AddToCache(md5, new FileInfo(outFilePath), FileCacheOperation.PVR);
}
return outFilePath;
}
}
}
}
| |
using System;
using System.Diagnostics;
using MatterHackers.Agg.Image;
using MatterHackers.Agg.Platform;
using MatterHackers.Agg.RasterizerScanline;
using MatterHackers.Agg.Transform;
using MatterHackers.Agg.UI;
using MatterHackers.Agg.UI.Examples;
using MatterHackers.Agg.VertexSource;
using MatterHackers.VectorMath;
namespace MatterHackers.Agg
{
public class image_resample : GuiWidget, IDemoApp
{
private Stopwatch stopwatch = new Stopwatch();
public static ImageBuffer m_SourceImage = new ImageBuffer();
private ScanlineRasterizer g_rasterizer;
private scanline_unpacked_8 g_scanline;
private double g_x1 = 0;
private double g_y1 = 0;
private double g_x2 = 0;
private double g_y2 = 0;
private GammaLookUpTable m_gamma_lut;
private UI.PolygonEditWidget m_quad;
private MatterHackers.Agg.UI.RadioButtonGroup m_trans_type;
private MatterHackers.Agg.UI.Slider m_gamma;
private MatterHackers.Agg.UI.Slider m_blur;
private double m_old_gamma;
public image_resample()
{
m_gamma_lut = new GammaLookUpTable(2.0);
m_quad = new MatterHackers.Agg.UI.PolygonEditWidget(4, 5.0);
m_trans_type = new MatterHackers.Agg.UI.RadioButtonGroup(new Vector2(400, 5.0), new Vector2(30 + 170.0, 95));
m_gamma = new MatterHackers.Agg.UI.Slider(5.0, 5.0 + 15 * 0, 400 - 5, 10.0 + 15 * 0);
m_blur = new MatterHackers.Agg.UI.Slider(5.0, 5.0 + 15 * 1, 400 - 5, 10.0 + 15 * 1);
m_blur.ValueChanged += new EventHandler(NeedRedraw);
m_gamma.ValueChanged += new EventHandler(NeedRedraw);
m_old_gamma = 2.0;
g_rasterizer = new ScanlineRasterizer();
g_scanline = new scanline_unpacked_8();
m_trans_type.AddRadioButton("Affine No Resample");
m_trans_type.AddRadioButton("Affine Resample");
m_trans_type.AddRadioButton("Perspective No Resample LERP");
m_trans_type.AddRadioButton("Perspective No Resample Exact");
m_trans_type.AddRadioButton("Perspective Resample LERP");
m_trans_type.AddRadioButton("Perspective Resample Exact");
m_trans_type.SelectedIndex = 4;
AddChild(m_trans_type);
m_gamma.SetRange(0.5, 3.0);
m_gamma.Value = 2.0;
m_gamma.Text = "Gamma={0:F3}";
AddChild(m_gamma);
m_blur.SetRange(0.5, 5.0);
m_blur.Value = 1.0;
m_blur.Text = "Blur={0:F3}";
AddChild(m_blur);
}
public string Title { get; } = "Image Transformations with Resampling";
public string DemoCategory { get; } = "Bitmap";
public string DemoDescription { get; } = "The demonstration of image transformations with resampling. You can see the difference in quality between regular image transformers and the ones with resampling. Of course, image tranformations with resampling work slower because they provide the best possible quality.";
public override void OnParentChanged(EventArgs e)
{
AnchorAll();
string img_name = "spheres.bmp";
if (!ImageIO.LoadImageData(img_name, image_resample.m_SourceImage))
{
string buf;
buf = "File not found: "
+ img_name
+ ".bmp"
+ ". Download http://www.antigrain.com/" + img_name + ".bmp" + "\n"
+ "or copy it from another directory if available.";
throw new NotImplementedException(buf);
}
else
{
if (image_resample.m_SourceImage.BitDepth != 32)
{
throw new Exception("we are expecting 32 bit source.");
}
// give the image some alpha. [4/6/2009 lbrubaker]
ImageBuffer image32 = new ImageBuffer(image_resample.m_SourceImage.Width, image_resample.m_SourceImage.Height, 32, new BlenderBGRA());
int offset;
byte[] source = image_resample.m_SourceImage.GetBuffer(out offset);
byte[] dest = image32.GetBuffer(out offset);
for (int y = 0; y < image32.Height; y++)
for (int x = 0; x < image32.Width; x++)
{
int i = y * image32.Width + x;
dest[i * 4 + 0] = source[i * 4 + 0];
dest[i * 4 + 1] = source[i * 4 + 1];
dest[i * 4 + 2] = source[i * 4 + 2];
Vector2 pixel = new Vector2(x, y);
Vector2 center = new Vector2(image32.Width / 2, image32.Height / 2);
Vector2 delta = pixel - center;
int length = (int)Math.Min(delta.Length * 3, 255);
dest[i * 4 + 3] = (byte)length;
}
// and set our new image with alpha
image_resample.m_SourceImage = image32;
//image_resample_application.m_SourceImage.SetBlender(new BlenderBGR());
}
base.OnParentChanged(e);
}
private void NeedRedraw(object sender, EventArgs e)
{
Invalidate();
}
public void OnInitialize()
{
g_x1 = 0.0;
g_y1 = 0.0;
g_x2 = m_SourceImage.Width;
g_y2 = m_SourceImage.Height;
double x1 = g_x1;// * 100.0;
double y1 = g_y1;// * 100.0;
double x2 = g_x2;// * 100.0;
double y2 = g_y2;// * 100.0;
double dx = Width / 2.0 - (x2 - x1) / 2.0;
double dy = Height / 2.0 - (y2 - y1) / 2.0;
m_quad.SetXN(0, Math.Floor(x1 + dx));
m_quad.SetYN(0, Math.Floor(y1 + dy));// - 150;
m_quad.SetXN(1, Math.Floor(x2 + dx));
m_quad.SetYN(1, Math.Floor(y1 + dy));// - 110;
m_quad.SetXN(2, Math.Floor(x2 + dx));
m_quad.SetYN(2, Math.Floor(y2 + dy));// - 300;
m_quad.SetXN(3, Math.Floor(x1 + dx));
m_quad.SetYN(3, Math.Floor(y2 + dy));// - 200;
//m_SourceImage.apply_gamma_dir(m_gamma_lut);
}
private bool didInit = false;
public override void OnDraw(Graphics2D graphics2D)
{
ImageBuffer widgetsSubImage = ImageBuffer.NewSubImageReference(graphics2D.DestImage, graphics2D.GetClippingRect());
if (!didInit)
{
didInit = true;
OnInitialize();
}
if (m_gamma.Value != m_old_gamma)
{
m_gamma_lut.SetGamma(m_gamma.Value);
ImageIO.LoadImageData("spheres.bmp", m_SourceImage);
//m_SourceImage.apply_gamma_dir(m_gamma_lut);
m_old_gamma = m_gamma.Value;
}
ImageBuffer pixf = new ImageBuffer();
switch (widgetsSubImage.BitDepth)
{
case 24:
pixf.Attach(widgetsSubImage, new BlenderBGR());
break;
case 32:
pixf.Attach(widgetsSubImage, new BlenderBGRA());
break;
default:
throw new NotImplementedException();
}
ImageClippingProxy clippingProxy = new ImageClippingProxy(pixf);
clippingProxy.clear(new ColorF(1, 1, 1));
if (m_trans_type.SelectedIndex < 2)
{
// For the affine parallelogram transformations we
// calculate the 4-th (implicit) point of the parallelogram
m_quad.SetXN(3, m_quad.GetXN(0) + (m_quad.GetXN(2) - m_quad.GetXN(1)));
m_quad.SetYN(3, m_quad.GetYN(0) + (m_quad.GetYN(2) - m_quad.GetYN(1)));
}
ScanlineRenderer scanlineRenderer = new ScanlineRenderer();
// draw a background to show how the alpha is working
int RectWidth = 70;
int xoffset = 50;
int yoffset = 50;
for (int i = 0; i < 7; i++)
{
for (int j = 0; j < 7; j++)
{
if ((i + j) % 2 != 0)
{
VertexSource.RoundedRect rect = new VertexSource.RoundedRect(i * RectWidth + xoffset, j * RectWidth + yoffset,
(i + 1) * RectWidth + xoffset, (j + 1) * RectWidth + yoffset, 2);
rect.normalize_radius();
g_rasterizer.add_path(rect);
scanlineRenderer.RenderSolid(clippingProxy, g_rasterizer, g_scanline, new Color(.2, .2, .2));
}
}
}
//--------------------------
// Render the "quad" tool and controls
g_rasterizer.add_path(m_quad);
scanlineRenderer.RenderSolid(clippingProxy, g_rasterizer, g_scanline, new Color(0, 0.3, 0.5, 0.1));
// Prepare the polygon to rasterize. Here we need to fill
// the destination (transformed) polygon.
g_rasterizer.SetVectorClipBox(0, 0, Width, Height);
g_rasterizer.reset();
int b = 0;
g_rasterizer.move_to_d(m_quad.GetXN(0) - b, m_quad.GetYN(0) - b);
g_rasterizer.line_to_d(m_quad.GetXN(1) + b, m_quad.GetYN(1) - b);
g_rasterizer.line_to_d(m_quad.GetXN(2) + b, m_quad.GetYN(2) + b);
g_rasterizer.line_to_d(m_quad.GetXN(3) - b, m_quad.GetYN(3) + b);
//typedef agg::span_allocator<color_type> span_alloc_type;
span_allocator sa = new span_allocator();
image_filter_bilinear filter_kernel = new image_filter_bilinear();
ImageFilterLookUpTable filter = new ImageFilterLookUpTable(filter_kernel, true);
ImageBufferAccessorClamp source = new ImageBufferAccessorClamp(m_SourceImage);
stopwatch.Restart();
switch (m_trans_type.SelectedIndex)
{
case 0:
{
/*
agg::trans_affine tr(m_quad.polygon(), g_x1, g_y1, g_x2, g_y2);
typedef agg::span_interpolator_linear<agg::trans_affine> interpolator_type;
interpolator_type interpolator(tr);
typedef image_filter_2x2_type<source_type,
interpolator_type> span_gen_type;
span_gen_type sg(source, interpolator, filter);
agg::render_scanlines_aa(g_rasterizer, g_scanline, rb_pre, sa, sg);
*/
break;
}
case 1:
{
/*
agg::trans_affine tr(m_quad.polygon(), g_x1, g_y1, g_x2, g_y2);
typedef agg::span_interpolator_linear<agg::trans_affine> interpolator_type;
typedef image_resample_affine_type<source_type> span_gen_type;
interpolator_type interpolator(tr);
span_gen_type sg(source, interpolator, filter);
sg.blur(m_blur.Value);
agg::render_scanlines_aa(g_rasterizer, g_scanline, rb_pre, sa, sg);
*/
break;
}
case 2:
{
/*
agg::trans_perspective tr(m_quad.polygon(), g_x1, g_y1, g_x2, g_y2);
if(tr.is_valid())
{
typedef agg::span_interpolator_linear_subdiv<agg::trans_perspective> interpolator_type;
interpolator_type interpolator(tr);
typedef image_filter_2x2_type<source_type,
interpolator_type> span_gen_type;
span_gen_type sg(source, interpolator, filter);
agg::render_scanlines_aa(g_rasterizer, g_scanline, rb_pre, sa, sg);
}
*/
break;
}
case 3:
{
/*
agg::trans_perspective tr(m_quad.polygon(), g_x1, g_y1, g_x2, g_y2);
if(tr.is_valid())
{
typedef agg::span_interpolator_trans<agg::trans_perspective> interpolator_type;
interpolator_type interpolator(tr);
typedef image_filter_2x2_type<source_type,
interpolator_type> span_gen_type;
span_gen_type sg(source, interpolator, filter);
agg::render_scanlines_aa(g_rasterizer, g_scanline, rb_pre, sa, sg);
}
*/
break;
}
case 4:
{
//typedef agg::span_interpolator_persp_lerp<> interpolator_type;
//typedef agg::span_subdiv_adaptor<interpolator_type> subdiv_adaptor_type;
span_interpolator_persp_lerp interpolator = new span_interpolator_persp_lerp(m_quad.polygon(), g_x1, g_y1, g_x2, g_y2);
span_subdiv_adaptor subdiv_adaptor = new span_subdiv_adaptor(interpolator);
span_image_resample sg = null;
if (interpolator.is_valid())
{
switch (source.SourceImage.BitDepth)
{
case 24:
sg = new span_image_resample_rgb(source, subdiv_adaptor, filter);
break;
case 32:
sg = new span_image_resample_rgba(source, subdiv_adaptor, filter);
break;
}
sg.blur(m_blur.Value);
scanlineRenderer.GenerateAndRender(g_rasterizer, g_scanline, clippingProxy, sa, sg);
}
break;
}
case 5:
{
/*
typedef agg::span_interpolator_persp_exact<> interpolator_type;
typedef agg::span_subdiv_adaptor<interpolator_type> subdiv_adaptor_type;
interpolator_type interpolator(m_quad.polygon(), g_x1, g_y1, g_x2, g_y2);
subdiv_adaptor_type subdiv_adaptor(interpolator);
if(interpolator.is_valid())
{
typedef image_resample_type<source_type,
subdiv_adaptor_type> span_gen_type;
span_gen_type sg(source, subdiv_adaptor, filter);
sg.blur(m_blur.Value);
agg::render_scanlines_aa(g_rasterizer, g_scanline, rb_pre, sa, sg);
}
*/
break;
}
}
double tm = stopwatch.ElapsedMilliseconds;
//pixf.apply_gamma_inv(m_gamma_lut);
gsv_text t = new gsv_text();
t.SetFontSize(10.0);
Stroke pt = new Stroke(t);
pt.Width = 1.5;
string buf = string.Format("{0:F2} ms", tm);
t.start_point(10.0, 70.0);
t.text(buf);
g_rasterizer.add_path(pt);
scanlineRenderer.RenderSolid(clippingProxy, g_rasterizer, g_scanline, new Color(0, 0, 0));
//--------------------------
//m_trans_type.Render(g_rasterizer, g_scanline, clippingProxy);
//m_gamma.Render(g_rasterizer, g_scanline, clippingProxy);
//m_blur.Render(g_rasterizer, g_scanline, clippingProxy);
base.OnDraw(graphics2D);
}
public override void OnMouseDown(MouseEventArgs mouseEvent)
{
base.OnMouseDown(mouseEvent);
if (mouseEvent.Button == MouseButtons.Left)
{
m_quad.OnMouseDown(mouseEvent);
if (MouseCaptured)
{
Invalidate();
}
}
}
public override void OnMouseMove(MouseEventArgs mouseEvent)
{
if (mouseEvent.Button == MouseButtons.Left)
{
m_quad.OnMouseMove(mouseEvent);
if (MouseCaptured)
{
Invalidate();
}
}
base.OnMouseMove(mouseEvent);
}
public override void OnMouseUp(MouseEventArgs mouseEvent)
{
m_quad.OnMouseUp(mouseEvent);
if (MouseCaptured)
{
Invalidate();
}
base.OnMouseUp(mouseEvent);
}
public override void OnKeyDown(MatterHackers.Agg.UI.KeyEventArgs keyEvent)
{
if (keyEvent.KeyCode == Keys.Space)
{
double cx = (m_quad.GetXN(0) + m_quad.GetXN(1) + m_quad.GetXN(2) + m_quad.GetXN(3)) / 4;
double cy = (m_quad.GetYN(0) + m_quad.GetYN(1) + m_quad.GetYN(2) + m_quad.GetYN(3)) / 4;
Affine tr = Affine.NewTranslation(-cx, -cy);
tr *= Affine.NewRotation(Math.PI / 2.0);
tr *= Affine.NewTranslation(cx, cy);
double xn0 = m_quad.GetXN(0); double yn0 = m_quad.GetYN(0);
double xn1 = m_quad.GetXN(1); double yn1 = m_quad.GetYN(1);
double xn2 = m_quad.GetXN(2); double yn2 = m_quad.GetYN(2);
double xn3 = m_quad.GetXN(3); double yn3 = m_quad.GetYN(3);
tr.transform(ref xn0, ref yn0);
tr.transform(ref xn1, ref yn1);
tr.transform(ref xn2, ref yn2);
tr.transform(ref xn3, ref yn3);
m_quad.SetXN(0, xn0); m_quad.SetYN(0, yn0);
m_quad.SetXN(1, xn1); m_quad.SetYN(1, yn1);
m_quad.SetXN(2, xn2); m_quad.SetYN(2, yn2);
m_quad.SetXN(3, xn3); m_quad.SetYN(3, yn3);
Invalidate();
}
base.OnKeyDown(keyEvent);
}
[STAThread]
public static void Main(string[] args)
{
var demoWidget = new image_resample();
var systemWindow = new SystemWindow(600, 600);
systemWindow.Title = demoWidget.Title;
systemWindow.AddChild(demoWidget);
systemWindow.ShowAsSystemWindow();
}
}
}
| |
// 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.Globalization;
using System.IO;
using System.Threading;
using Xunit;
namespace System.ComponentModel.DataAnnotations.Tests
{
public class RangeAttributeTests : ValidationAttributeTestBase
{
protected override IEnumerable<TestCase> ValidValues()
{
RangeAttribute intRange = new RangeAttribute(1, 3);
yield return new TestCase(intRange, null);
yield return new TestCase(intRange, string.Empty);
yield return new TestCase(intRange, 1);
yield return new TestCase(intRange, 2);
yield return new TestCase(intRange, 3);
yield return new TestCase(new RangeAttribute(1, 1), 1);
RangeAttribute doubleRange = new RangeAttribute(1.0, 3.0);
yield return new TestCase(doubleRange, null);
yield return new TestCase(doubleRange, string.Empty);
yield return new TestCase(doubleRange, 1.0);
yield return new TestCase(doubleRange, 2.0);
yield return new TestCase(doubleRange, 3.0);
yield return new TestCase(new RangeAttribute(1.0, 1.0), 1);
RangeAttribute stringIntRange = new RangeAttribute(typeof(int), "1", "3");
yield return new TestCase(stringIntRange, null);
yield return new TestCase(stringIntRange, string.Empty);
yield return new TestCase(stringIntRange, 1);
yield return new TestCase(stringIntRange, "1");
yield return new TestCase(stringIntRange, 2);
yield return new TestCase(stringIntRange, "2");
yield return new TestCase(stringIntRange, 3);
yield return new TestCase(stringIntRange, "3");
RangeAttribute stringDoubleRange = new RangeAttribute(typeof(double), (1.0).ToString("F1"), (3.0).ToString("F1"));
yield return new TestCase(stringDoubleRange, null);
yield return new TestCase(stringDoubleRange, string.Empty);
yield return new TestCase(stringDoubleRange, 1.0);
yield return new TestCase(stringDoubleRange, (1.0).ToString("F1"));
yield return new TestCase(stringDoubleRange, 2.0);
yield return new TestCase(stringDoubleRange, (2.0).ToString("F1"));
yield return new TestCase(stringDoubleRange, 3.0);
yield return new TestCase(stringDoubleRange, (3.0).ToString("F1"));
}
protected override IEnumerable<TestCase> InvalidValues()
{
RangeAttribute intRange = new RangeAttribute(1, 3);
yield return new TestCase(intRange, 0);
yield return new TestCase(intRange, 4);
yield return new TestCase(intRange, "abc");
yield return new TestCase(intRange, new object());
// Implements IConvertible (throws NotSupportedException - is caught)
yield return new TestCase(intRange, new IConvertibleImplementor() { IntThrow = new NotSupportedException() });
RangeAttribute doubleRange = new RangeAttribute(1.0, 3.0);
yield return new TestCase(doubleRange, 0.9999999);
yield return new TestCase(doubleRange, 3.0000001);
yield return new TestCase(doubleRange, "abc");
yield return new TestCase(doubleRange, new object());
// Implements IConvertible (throws NotSupportedException - is caught)
yield return new TestCase(doubleRange, new IConvertibleImplementor() { DoubleThrow = new NotSupportedException() });
RangeAttribute stringIntRange = new RangeAttribute(typeof(int), "1", "3");
yield return new TestCase(stringIntRange, 0);
yield return new TestCase(stringIntRange, "0");
yield return new TestCase(stringIntRange, 4);
yield return new TestCase(stringIntRange, "4");
yield return new TestCase(stringIntRange, new object());
// Implements IConvertible (throws NotSupportedException - is caught)
yield return new TestCase(stringIntRange, new IConvertibleImplementor() { IntThrow = new NotSupportedException() });
RangeAttribute stringDoubleRange = new RangeAttribute(typeof(double), (1.0).ToString("F1"), (3.0).ToString("F1"));
yield return new TestCase(stringDoubleRange, 0.9999999);
yield return new TestCase(stringDoubleRange, (0.9999999).ToString());
yield return new TestCase(stringDoubleRange, 3.0000001);
yield return new TestCase(stringDoubleRange, (3.0000001).ToString());
yield return new TestCase(stringDoubleRange, new object());
// Implements IConvertible (throws NotSupportedException - is caught)
yield return new TestCase(stringDoubleRange, new IConvertibleImplementor() { DoubleThrow = new NotSupportedException() });
}
public static IEnumerable<object[]> DotDecimalRanges()
{
yield return new object[] {typeof(decimal), "1.0", "3.0"};
yield return new object[] {typeof(double), "1.0", "3.0"};
}
public static IEnumerable<object[]> CommaDecimalRanges()
{
yield return new object[] { typeof(decimal), "1,0", "3,0" };
yield return new object[] { typeof(double), "1,0", "3,0" };
}
public static IEnumerable<object[]> DotDecimalValidValues()
{
yield return new object[] { typeof(decimal), "1.0", "3.0", "1.0" };
yield return new object[] { typeof(decimal), "1.0", "3.0", "3.0" };
yield return new object[] { typeof(decimal), "1.0", "3.0", "2.9999999999999999999999999999999999999999999" };
yield return new object[] { typeof(decimal), "1.0", "3.0", "2.9999999999999999999999999999" };
yield return new object[] { typeof(double), "1.0", "3.0", "1.0" };
yield return new object[] { typeof(double), "1.0", "3.0", "3.0" };
yield return new object[] { typeof(double), "1.0", "3.0", "2.9999999999999999999999999999999999999999999" };
yield return new object[] { typeof(double), "1.0", "3.0", "2.99999999999999" };
}
public static IEnumerable<object[]> CommaDecimalValidValues()
{
yield return new object[] { typeof(decimal), "1,0", "3,0", "1,0" };
yield return new object[] { typeof(decimal), "1,0", "3,0", "3,0" };
yield return new object[] { typeof(decimal), "1,0", "3,0", "2,9999999999999999999999999999999999999999999" };
yield return new object[] { typeof(decimal), "1,0", "3,0", "2,9999999999999999999999999999" };
yield return new object[] { typeof(double), "1,0", "3,0", "1,0" };
yield return new object[] { typeof(double), "1,0", "3,0", "3,0" };
yield return new object[] { typeof(double), "1,0", "3,0", "2,99999999999999" };
}
public static IEnumerable<object[]> DotDecimalInvalidValues()
{
yield return new object[] { typeof(decimal), "1.0", "3.0", "9.0" };
yield return new object[] { typeof(decimal), "1.0", "3.0", "0.1" };
yield return new object[] { typeof(decimal), "1.0", "3.0", "3.9999999999999999999999999999999999999999999" };
yield return new object[] { typeof(decimal), "1.0", "3.0", "3.9999999999999999999999999999" };
yield return new object[] { typeof(double), "1.0", "3.0", "9.0" };
yield return new object[] { typeof(double), "1.0", "3.0", "0.1" };
yield return new object[] { typeof(double), "1.0", "3.0", "3.9999999999999999999999999999999999999999999" };
yield return new object[] { typeof(double), "1.0", "3.0", "3.99999999999999" };
}
public static IEnumerable<object[]> CommaDecimalInvalidValues()
{
yield return new object[] { typeof(decimal), "1,0", "3,0", "9,0" };
yield return new object[] { typeof(decimal), "1,0", "3,0", "0,1" };
yield return new object[] { typeof(decimal), "1,0", "3,0", "3,9999999999999999999999999999999999999999999" };
yield return new object[] { typeof(decimal), "1,0", "3,0", "3,9999999999999999999999999999" };
yield return new object[] { typeof(double), "1,0", "3,0", "9,0" };
yield return new object[] { typeof(double), "1,0", "3,0", "0,1" };
yield return new object[] { typeof(double), "1,0", "3,0", "3,9999999999999999999999999999999999999999999" };
yield return new object[] { typeof(double), "1,0", "3,0", "3,99999999999999" };
}
public static IEnumerable<object[]> DotDecimalNonStringValidValues()
{
yield return new object[] { typeof(decimal), "1.0", "3.0", 1.0m };
yield return new object[] { typeof(decimal), "1.0", "3.0", 3.0m };
yield return new object[] { typeof(decimal), "1.0", "3.0", 2.9999999999999999999999999999m };
yield return new object[] { typeof(double), "1.0", "3.0", 1.0 };
yield return new object[] { typeof(double), "1.0", "3.0", 3.0 };
yield return new object[] { typeof(double), "1.0", "3.0", 2.99999999999999 };
}
public static IEnumerable<object[]> CommaDecimalNonStringValidValues()
{
yield return new object[] { typeof(decimal), "1,0", "3,0", 1.0m };
yield return new object[] { typeof(decimal), "1,0", "3,0", 3.0m };
yield return new object[] { typeof(decimal), "1,0", "3,0", 2.9999999999999999999999999999m };
yield return new object[] { typeof(double), "1,0", "3,0", 1.0 };
yield return new object[] { typeof(double), "1,0", "3,0", 3.0 };
yield return new object[] { typeof(double), "1,0", "3,0", 2.99999999999999 };
}
private class TempCulture : IDisposable
{
private readonly CultureInfo _original;
public TempCulture(string culture)
{
Thread currentThread = Thread.CurrentThread;
_original = currentThread.CurrentCulture;
currentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag(culture);
}
public void Dispose()
{
Thread.CurrentThread.CurrentCulture = _original;
}
}
[Theory]
[MemberData(nameof(DotDecimalRanges))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "2648 not fixed on NetFX")]
public static void ParseDotSeparatorExtremaInCommaSeparatorCultures(Type type, string min, string max)
{
RemoteInvoke((t, m1, m2) =>
{
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("en-US");
Assert.True(new RangeAttribute(Type.GetType(t), m1, m2).IsValid(null));
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("fr-FR");
RangeAttribute range = new RangeAttribute(Type.GetType(t), m1, m2);
AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(null));
}, type.ToString(), min, max).Dispose();
}
[Theory]
[MemberData(nameof(DotDecimalRanges))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "2648 not fixed on NetFX")]
public static void ParseDotSeparatorInvariantExtremaInCommaSeparatorCultures(Type type, string min, string max)
{
RemoteInvoke((t, m1, m2) =>
{
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("en-US");
Assert.True(
new RangeAttribute(Type.GetType(t), m1, m2)
{
ParseLimitsInInvariantCulture = true
}.IsValid(null));
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("fr-FR");
Assert.True(
new RangeAttribute(Type.GetType(t), m1, m2)
{
ParseLimitsInInvariantCulture = true
}.IsValid(null));
}, type.ToString(), min, max).Dispose();
}
[Theory]
[MemberData(nameof(CommaDecimalRanges))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "2648 not fixed on NetFX")]
public static void ParseCommaSeparatorExtremaInCommaSeparatorCultures(Type type, string min, string max)
{
RemoteInvoke((t, m1, m2) =>
{
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("en-US");
RangeAttribute range = new RangeAttribute(Type.GetType(t), m1, m2);
AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(null));
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("fr-FR");
Assert.True(new RangeAttribute(Type.GetType(t), m1, m2).IsValid(null));
}, type.ToString(), min, max).Dispose();
}
[Theory]
[MemberData(nameof(CommaDecimalRanges))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "2648 not fixed on NetFX")]
public static void ParseCommaSeparatorInvariantExtremaInCommaSeparatorCultures(Type type, string min, string max)
{
RemoteInvoke((t, m1, m2) =>
{
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("en-US");
RangeAttribute range = new RangeAttribute(Type.GetType(t), m1, m2);
AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(null));
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("fr-FR");
Assert.True(new RangeAttribute(Type.GetType(t), m1, m2).IsValid(null));
}, type.ToString(), min, max).Dispose();
}
[Theory][MemberData(nameof(DotDecimalValidValues))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "2648 not fixed on NetFX")]
public static void DotDecimalExtremaAndValues(Type type, string min, string max, string value)
{
RemoteInvoke((t, m1, m2, v) =>
{
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("en-US");
Assert.True(new RangeAttribute(Type.GetType(t), m1, m2).IsValid(v));
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("fr-FR");
RangeAttribute range = new RangeAttribute(Type.GetType(t), m1, m2);
AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
}, type.ToString(), min, max, value).Dispose();
}
[Theory]
[MemberData(nameof(DotDecimalValidValues))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "2648 not fixed on NetFX")]
public static void DotDecimalExtremaAndValuesInvariantParse(Type type, string min, string max, string value)
{
RemoteInvoke((t, m1, m2, v) =>
{
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("en-US");
Assert.True(
new RangeAttribute(Type.GetType(t), m1, m2)
{
ParseLimitsInInvariantCulture = true
}.IsValid(v));
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("fr-FR");
RangeAttribute range = new RangeAttribute(Type.GetType(t), m1, m2)
{
ParseLimitsInInvariantCulture = true
};
AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
}, type.ToString(), min, max, value).Dispose();
}
[Theory]
[MemberData(nameof(DotDecimalValidValues))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "2648 not fixed on NetFX")]
public static void DotDecimalExtremaAndValuesInvariantConvert(Type type, string min, string max, string value)
{
RemoteInvoke((t, m1, m2, v) =>
{
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("en-US");
Assert.True(
new RangeAttribute(Type.GetType(t), m1, m2)
{
ConvertValueInInvariantCulture = true
}.IsValid(v));
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("fr-FR");
RangeAttribute range = new RangeAttribute(Type.GetType(t), m1, m2)
{
ConvertValueInInvariantCulture = true
};
AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
}, type.ToString(), min, max, value).Dispose();
}
[Theory]
[MemberData(nameof(DotDecimalValidValues))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "2648 not fixed on NetFX")]
public static void DotDecimalExtremaAndValuesInvariantBoth(Type type, string min, string max, string value)
{
RemoteInvoke((t, m1, m2, v) =>
{
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("en-US");
Assert.True(
new RangeAttribute(Type.GetType(t), m1, m2)
{
ConvertValueInInvariantCulture = true,
ParseLimitsInInvariantCulture = true
}.IsValid(v));
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("fr-FR");
Assert.True(
new RangeAttribute(Type.GetType(t), m1, m2)
{
ConvertValueInInvariantCulture = true,
ParseLimitsInInvariantCulture = true
}.IsValid(v));
}, type.ToString(), min, max, value).Dispose();
}
[Theory]
[MemberData(nameof(DotDecimalNonStringValidValues))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "2648 not fixed on NetFX")]
public static void DotDecimalExtremaAndNonStringValues(Type type, string min, string max, object value)
{
using (new TempCulture("en-US"))
{
Assert.True(new RangeAttribute(type, min, max).IsValid(value));
}
using (new TempCulture("fr-FR"))
{
RangeAttribute range = new RangeAttribute(type, min, max);
AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(value));
}
}
[Theory]
[MemberData(nameof(DotDecimalNonStringValidValues))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "2648 not fixed on NetFX")]
public static void DotDecimalExtremaAndNonStringValuesInvariantParse(Type type, string min, string max, object value)
{
using (new TempCulture("en-US"))
{
Assert.True(
new RangeAttribute(type, min, max)
{
ParseLimitsInInvariantCulture = true
}.IsValid(value));
}
using (new TempCulture("fr-FR"))
{
Assert.True(
new RangeAttribute(type, min, max)
{
ParseLimitsInInvariantCulture = true
}.IsValid(value));
}
}
[Theory]
[MemberData(nameof(DotDecimalNonStringValidValues))][SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "2648 not fixed on NetFX")]
public static void DotDecimalExtremaAndNonStringValuesInvariantConvert(Type type, string min, string max, object value)
{
using (new TempCulture("en-US"))
{
Assert.True(
new RangeAttribute(type, min, max)
{
ConvertValueInInvariantCulture = true
}.IsValid(value));
}
using (new TempCulture("fr-FR"))
{
RangeAttribute range = new RangeAttribute(type, min, max)
{
ConvertValueInInvariantCulture = true
};
AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(value));
}
}
[Theory]
[MemberData(nameof(DotDecimalNonStringValidValues))][SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "2648 not fixed on NetFX")]
public static void DotDecimalExtremaAndNonStringValuesInvariantBoth(Type type, string min, string max, object value)
{
using (new TempCulture("en-US"))
{
Assert.True(
new RangeAttribute(type, min, max)
{
ConvertValueInInvariantCulture = true,
ParseLimitsInInvariantCulture = true
}.IsValid(value));
}
using (new TempCulture("fr-FR"))
{
Assert.True(
new RangeAttribute(type, min, max)
{
ConvertValueInInvariantCulture = true,
ParseLimitsInInvariantCulture = true
}.IsValid(value));
}
}
[Theory]
[MemberData(nameof(CommaDecimalNonStringValidValues))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "2648 not fixed on NetFX")]
public static void CommaDecimalExtremaAndNonStringValues(Type type, string min, string max, object value)
{
using (new TempCulture("en-US"))
{
RangeAttribute range = new RangeAttribute(type, min, max);
AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(value));
}
using (new TempCulture("fr-FR"))
{
Assert.True(new RangeAttribute(type, min, max).IsValid(value));
}
}
[Theory]
[MemberData(nameof(CommaDecimalNonStringValidValues))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "2648 not fixed on NetFX")]
public static void CommaDecimalExtremaAndNonStringValuesInvariantParse(Type type, string min, string max, object value)
{
using (new TempCulture("en-US"))
{
RangeAttribute range = new RangeAttribute(type, min, max)
{
ParseLimitsInInvariantCulture = true
};
AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(value));
}
using (new TempCulture("fr-FR"))
{
RangeAttribute range = new RangeAttribute(type, min, max)
{
ParseLimitsInInvariantCulture = true
};
AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(value));
}
}
[Theory]
[MemberData(nameof(CommaDecimalNonStringValidValues))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "2648 not fixed on NetFX")]
public static void CommaDecimalExtremaAndNonStringValuesInvariantConvert(Type type, string min, string max, object value)
{
using (new TempCulture("en-US"))
{
RangeAttribute range = new RangeAttribute(type, min, max)
{
ConvertValueInInvariantCulture = true
};
AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(value));
}
using (new TempCulture("fr-FR"))
{
Assert.True(
new RangeAttribute(type, min, max)
{
ConvertValueInInvariantCulture = true
}.IsValid(value));
}
}
[Theory]
[MemberData(nameof(CommaDecimalNonStringValidValues))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "2648 not fixed on NetFX")]
public static void CommaDecimalExtremaAndNonStringValuesInvariantBoth(Type type, string min, string max, object value)
{
using (new TempCulture("en-US"))
{
RangeAttribute range = new RangeAttribute(type, min, max)
{
ConvertValueInInvariantCulture = true,
ParseLimitsInInvariantCulture = true
};
AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(value));
}
using (new TempCulture("fr-FR"))
{
RangeAttribute range = new RangeAttribute(type, min, max)
{
ConvertValueInInvariantCulture = true,
ParseLimitsInInvariantCulture = true
};
AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(value));
}
}
[Theory]
[MemberData(nameof(DotDecimalInvalidValues))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "2648 not fixed on NetFX")]
public static void DotDecimalExtremaAndInvalidValues(Type type, string min, string max, string value)
{
RemoteInvoke((t, m1, m2, v) =>
{
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("en-US");
Assert.False(new RangeAttribute(Type.GetType(t), m1, m2).IsValid(v));
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("fr-FR");
RangeAttribute range = new RangeAttribute(Type.GetType(t), m1, m2);
AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
}, type.ToString(), min, max, value).Dispose();
}
[Theory]
[MemberData(nameof(DotDecimalInvalidValues))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "2648 not fixed on NetFX")]
public static void DotDecimalExtremaAndInvalidValuesInvariantParse(Type type, string min, string max, string value)
{
RemoteInvoke((t, m1, m2, v) =>
{
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("en-US");
Assert.False(
new RangeAttribute(Type.GetType(t), m1, m2)
{
ParseLimitsInInvariantCulture = true
}.IsValid(v));
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("fr-FR");
RangeAttribute range = new RangeAttribute(Type.GetType(t), m1, m2)
{
ParseLimitsInInvariantCulture = true
};
AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
}, type.ToString(), min, max, value).Dispose();
}
[Theory]
[MemberData(nameof(DotDecimalInvalidValues))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "2648 not fixed on NetFX")]
public static void DotDecimalExtremaAndInvalidValuesInvariantConvert(Type type, string min, string max, string value)
{
RemoteInvoke((t, m1, m2, v) =>
{
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("en-US");
Assert.False(
new RangeAttribute(Type.GetType(t), m1, m2)
{
ConvertValueInInvariantCulture = true
}.IsValid(v));
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("fr-FR");
RangeAttribute range = new RangeAttribute(Type.GetType(t), m1, m2)
{
ConvertValueInInvariantCulture = true
};
AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
}, type.ToString(), min, max, value).Dispose();
}
[Theory]
[MemberData(nameof(DotDecimalInvalidValues))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "2648 not fixed on NetFX")]
public static void DotDecimalExtremaAndInvalidValuesInvariantBoth(Type type, string min, string max, string value)
{
RemoteInvoke((t, m1, m2, v) =>
{
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("en-US");
Assert.False(
new RangeAttribute(Type.GetType(t), m1, m2)
{
ConvertValueInInvariantCulture = true,
ParseLimitsInInvariantCulture = true
}.IsValid(v));
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("fr-FR");
Assert.False(
new RangeAttribute(Type.GetType(t), m1, m2)
{
ConvertValueInInvariantCulture = true,
ParseLimitsInInvariantCulture = true
}.IsValid(v));
}, type.ToString(), min, max, value).Dispose();
}
[Theory]
[MemberData(nameof(CommaDecimalValidValues))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "2648 not fixed on NetFX")]
public static void CommaDecimalExtremaAndValues(Type type, string min, string max, string value)
{
RemoteInvoke((t, m1, m2, v) =>
{
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("en-US");
RangeAttribute range = new RangeAttribute(Type.GetType(t), m1, m2);
AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("fr-FR");
Assert.True(new RangeAttribute(Type.GetType(t), m1, m2).IsValid(v));
}, type.ToString(), min, max, value).Dispose();
}
[Theory]
[MemberData(nameof(CommaDecimalValidValues))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "2648 not fixed on NetFX")]
public static void CommaDecimalExtremaAndValuesInvariantParse(Type type, string min, string max, string value)
{
RemoteInvoke((t, m1, m2, v) =>
{
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("en-US");
RangeAttribute range = new RangeAttribute(Type.GetType(t), m1, m2)
{
ParseLimitsInInvariantCulture = true
};
AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("fr-FR");
range = new RangeAttribute(Type.GetType(t), m1, m2)
{
ParseLimitsInInvariantCulture = true
};
AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
}, type.ToString(), min, max, value).Dispose();
}
[Theory]
[MemberData(nameof(CommaDecimalValidValues))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "2648 not fixed on NetFX")]
public static void CommaDecimalExtremaAndValuesInvariantConvert(Type type, string min, string max, string value)
{
RemoteInvoke((t, m1, m2, v) =>
{
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("en-US");
RangeAttribute range = new RangeAttribute(Type.GetType(t), m1, m2)
{
ConvertValueInInvariantCulture = true
};
AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("fr-FR");
range = new RangeAttribute(Type.GetType(t), m1, m2)
{
ConvertValueInInvariantCulture = true
};
AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
}, type.ToString(), min, max, value).Dispose();
}
[Theory]
[MemberData(nameof(CommaDecimalValidValues))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "2648 not fixed on NetFX")]
public static void CommaDecimalExtremaAndValuesInvariantBoth(Type type, string min, string max, string value)
{
RemoteInvoke((t, m1, m2, v) =>
{
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("en-US");
RangeAttribute range = new RangeAttribute(Type.GetType(t), m1, m2)
{
ConvertValueInInvariantCulture = true,
ParseLimitsInInvariantCulture = true
};
AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("fr-FR");
range = new RangeAttribute(Type.GetType(t), m1, m2)
{
ConvertValueInInvariantCulture = true,
ParseLimitsInInvariantCulture = true
};
AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
}, type.ToString(), min, max, value).Dispose();
}
[Theory]
[MemberData(nameof(CommaDecimalInvalidValues))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "2648 not fixed on NetFX")]
public static void CommaDecimalExtremaAndInvalidValues(Type type, string min, string max, string value)
{
RemoteInvoke((t, m1, m2, v) =>
{
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("en-US");
RangeAttribute range = new RangeAttribute(Type.GetType(t), m1, m2);
AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("fr-FR");
Assert.False(new RangeAttribute(Type.GetType(t), m1, m2).IsValid(v));
}, type.ToString(), min, max, value).Dispose();
}
[Theory]
[MemberData(nameof(CommaDecimalInvalidValues))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "2648 not fixed on NetFX")]
public static void CommaDecimalExtremaAndInvalidValuesInvariantParse(Type type, string min, string max, string value)
{
RemoteInvoke((t, m1, m2, v) =>
{
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("en-US");
RangeAttribute range = new RangeAttribute(Type.GetType(t), m1, m2)
{
ParseLimitsInInvariantCulture = true
};
AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("fr-FR");
range = new RangeAttribute(Type.GetType(t), m1, m2)
{
ParseLimitsInInvariantCulture = true
};
AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
}, type.ToString(), min, max, value).Dispose();
}
[Theory]
[MemberData(nameof(CommaDecimalInvalidValues))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "2648 not fixed on NetFX")]
public static void CommaDecimalExtremaAndInvalidValuesInvariantConvert(Type type, string min, string max, string value)
{
RemoteInvoke((t, m1, m2, v) =>
{
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("en-US");
RangeAttribute range = new RangeAttribute(Type.GetType(t), m1, m2)
{
ConvertValueInInvariantCulture = true
};
AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("fr-FR");
range = new RangeAttribute(Type.GetType(t), m1, m2)
{
ConvertValueInInvariantCulture = true
};
AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
}, type.ToString(), min, max, value).Dispose();
}
[Theory]
[MemberData(nameof(CommaDecimalInvalidValues))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "2648 not fixed on NetFX")]
public static void CommaDecimalExtremaAndInvalidValuesInvariantBoth(Type type, string min, string max, string value)
{
RemoteInvoke((t, m1, m2, v) =>
{
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("en-US");
RangeAttribute range = new RangeAttribute(Type.GetType(t), m1, m2)
{
ConvertValueInInvariantCulture = true,
ParseLimitsInInvariantCulture = true
};
AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("fr-FR");
range = new RangeAttribute(Type.GetType(t), m1, m2)
{
ConvertValueInInvariantCulture = true,
ParseLimitsInInvariantCulture = true
};
AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
}, type.ToString(), min, max, value).Dispose();
}
[Theory]
[InlineData(typeof(int), "1", "3")]
[InlineData(typeof(double), "1", "3")]
public static void Validate_CantConvertValueToTargetType_ThrowsException(Type type, string minimum, string maximum)
{
var attribute = new RangeAttribute(type, minimum, maximum);
AssertExtensions.Throws<ArgumentException, Exception>(() => attribute.Validate("abc", new ValidationContext(new object())));
AssertExtensions.Throws<ArgumentException, Exception>(() => attribute.IsValid("abc"));
}
[Fact]
public static void Ctor_Int_Int()
{
var attribute = new RangeAttribute(1, 3);
Assert.Equal(1, attribute.Minimum);
Assert.Equal(3, attribute.Maximum);
Assert.Equal(typeof(int), attribute.OperandType);
}
[Fact]
public static void Ctor_Double_Double()
{
var attribute = new RangeAttribute(1.0, 3.0);
Assert.Equal(1.0, attribute.Minimum);
Assert.Equal(3.0, attribute.Maximum);
Assert.Equal(typeof(double), attribute.OperandType);
}
[Theory]
[InlineData(null)]
[InlineData(typeof(object))]
public static void Ctor_Type_String_String(Type type)
{
var attribute = new RangeAttribute(type, "SomeMinimum", "SomeMaximum");
Assert.Equal("SomeMinimum", attribute.Minimum);
Assert.Equal("SomeMaximum", attribute.Maximum);
Assert.Equal(type, attribute.OperandType);
}
[Theory]
[InlineData(null)]
[InlineData(typeof(object))]
public static void Validate_InvalidOperandType_ThrowsInvalidOperationException(Type type)
{
var attribute = new RangeAttribute(type, "someMinimum", "someMaximum");
Assert.Throws<InvalidOperationException>(() => attribute.Validate("Any", new ValidationContext(new object())));
}
[Fact]
public static void Validate_MinimumGreaterThanMaximum_ThrowsInvalidOperationException()
{
var attribute = new RangeAttribute(3, 1);
Assert.Throws<InvalidOperationException>(() => attribute.Validate("Any", new ValidationContext(new object())));
attribute = new RangeAttribute(3.0, 1.0);
Assert.Throws<InvalidOperationException>(() => attribute.Validate("Any", new ValidationContext(new object())));
attribute = new RangeAttribute(typeof(int), "3", "1");
Assert.Throws<InvalidOperationException>(() => attribute.Validate("Any", new ValidationContext(new object())));
attribute = new RangeAttribute(typeof(double), (3.0).ToString("F1"), (1.0).ToString("F1"));
Assert.Throws<InvalidOperationException>(() => attribute.Validate("Any", new ValidationContext(new object())));
attribute = new RangeAttribute(typeof(string), "z", "a");
Assert.Throws<InvalidOperationException>(() => attribute.Validate("Any", new ValidationContext(new object())));
}
[Theory]
[InlineData(null, "3")]
[InlineData("3", null)]
public static void Validate_MinimumOrMaximumNull_ThrowsInvalidOperationException(string minimum, string maximum)
{
RangeAttribute attribute = new RangeAttribute(typeof(int), minimum, maximum);
Assert.Throws<InvalidOperationException>(() => attribute.Validate("Any", new ValidationContext(new object())));
}
[Theory]
[InlineData(typeof(int), "Cannot Convert", "3")]
[InlineData(typeof(int), "1", "Cannot Convert")]
[InlineData(typeof(double), "Cannot Convert", "3")]
[InlineData(typeof(double), "1", "Cannot Convert")]
public static void Validate_MinimumOrMaximumCantBeConvertedToIntegralType_ThrowsException(Type type, string minimum, string maximum)
{
RangeAttribute attribute = new RangeAttribute(type, minimum, maximum);
AssertExtensions.Throws<ArgumentException, Exception>(() => attribute.Validate("Any", new ValidationContext(new object())));
}
[Theory]
[InlineData(typeof(DateTime), "Cannot Convert", "2014-03-19")]
[InlineData(typeof(DateTime), "2014-03-19", "Cannot Convert")]
public static void Validate_MinimumOrMaximumCantBeConvertedToDateTime_ThrowsFormatException(Type type, string minimum, string maximum)
{
RangeAttribute attribute = new RangeAttribute(type, minimum, maximum);
Assert.Throws<FormatException>(() => attribute.Validate("Any", new ValidationContext(new object())));
}
[Theory]
[InlineData(1, 2, "2147483648")]
[InlineData(1, 2, "-2147483649")]
public static void Validate_IntConversionOverflows_ThrowsOverflowException(int minimum, int maximum, object value)
{
RangeAttribute attribute = new RangeAttribute(minimum, maximum);
Assert.Throws<OverflowException>(() => attribute.Validate(value, new ValidationContext(new object())));
}
[Theory]
[InlineData(1.0, 2.0, "2E+308")]
[InlineData(1.0, 2.0, "-2E+308")]
public static void Validate_DoubleConversionOverflows_ThrowsOverflowException(double minimum, double maximum, object value)
{
RangeAttribute attribute = new RangeAttribute(minimum, maximum);
Assert.Throws<OverflowException>(() => attribute.Validate(value, new ValidationContext(new object())));
}
[Fact]
public static void Validate_IConvertibleThrowsCustomException_IsNotCaught()
{
RangeAttribute attribute = new RangeAttribute(typeof(int), "1", "1");
Assert.Throws<ValidationException>(() => attribute.Validate(new IConvertibleImplementor() { IntThrow = new ArithmeticException() }, new ValidationContext(new object())));
}
}
}
| |
// MIT License
//
// Copyright(c) 2022 ICARUS Consulting GmbH
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using System;
using System.Collections;
using System.Collections.Generic;
using Yaapii.Atoms.Enumerable;
using Yaapii.Atoms.Scalar;
namespace Yaapii.Atoms.Enumerator
{
/// <summary>
/// An enumerator which is sticky.
/// </summary>
/// <typeparam name="T"></typeparam>
public sealed class Sticky<T> : IEnumerator<T>
{
private readonly int[] position;
private readonly IDictionary<int, T> cache;
/// In order to allow enumerables to not pre-compute/copy all elements,
/// this ctor allows injecting and therefore re-using the caching elements.
/// An enumerable like <see cref="ManyEnvelope"/> can then issue multiple
/// Enumerators while the same cache is filled when advancing them.
public Sticky(IEnumerator<T> origin) : this(() => origin)
{ }
/// In order to allow enumerables to not pre-compute/copy all elements,
/// this ctor allows injecting and therefore re-using the caching elements.
/// An enumerable like <see cref="ManyEnvelope"/> can then issue multiple
/// Enumerators while the same cache is filled when advancing them.
public Sticky(Func<IEnumerator<T>> origin) : this(new Cache<T>(origin))
{ }
/// In order to allow enumerables to not pre-compute/copy all elements,
/// this ctor allows injecting and therefore re-using the caching elements.
/// An enumerable like <see cref="ManyEnvelope"/> can then issue multiple
/// Enumerators while the same cache is filled when advancing them.
public Sticky(IDictionary<int, T> cache)
{
this.position = new int[1] { -1 };
this.cache = cache;
}
public T Current
{
get
{
if (this.position[0] == -1)
{
throw new InvalidOperationException("Cannot get current element - move the enumerator first.");
}
return this.cache[this.position[0]];
}
}
object IEnumerator.Current => this.Current;
public bool MoveNext()
{
bool moved = false;
var next = this.position[0] + 1;
if (this.cache.ContainsKey(next))
{
this.position[0] = next;
moved = true;
}
return moved;
}
public void Reset()
{
this.position[0] = -1;
}
public void Dispose()
{
}
/// <summary>
/// A cache for the enumerator, realized as map.
/// When asking for a key, the enumerator will be advanced until the
/// position, if existing, is found.
/// All values which are visited will be cached.
/// </summary>
public sealed class Cache<T> : IDictionary<int, T>
{
private readonly IScalar<IEnumerator<T>> origin;
private readonly List<T> cache;
private readonly bool[] reachedEnd;
private readonly int[] count;
public Cache(Func<IEnumerator<T>> origin)
{
this.count = new int[1] { 0 };
this.reachedEnd = new bool[1] { false };
this.origin = new ScalarOf<IEnumerator<T>>(origin);
this.cache = new List<T>();
}
public bool ContainsKey(int itemIndex)
{
var enumerator = this.origin.Value();
while (!this.reachedEnd[0] && this.count[0] - 1 < itemIndex)
{
if (enumerator.MoveNext())
{
this.count[0]++;
this.cache.Add(enumerator.Current);
}
else
{
this.reachedEnd[0] = true;
break;
}
}
return this.count[0] > itemIndex;
}
public T this[int key]
{
get
{
if (this.ContainsKey(key))
{
return this.cache[key];
}
else
{
throw new ArgumentException($"Cannot get value number {key} the origin enumerator did only have {this.cache.Count} elements.");
}
}
set
{
throw new InvalidOperationException("Setting a value is not supported.");
}
}
public ICollection<int> Keys => throw new InvalidOperationException("Enumerating keys is not supported.");
public ICollection<T> Values => throw new InvalidOperationException("Enumerating values is not supported.");
public int Count
{
get
{
var count = 0;
if (!this.reachedEnd[0])
{
while (this.ContainsKey(count))
{
count++;
this.count[0] = count;
}
}
return this.count[0];
}
}
public bool IsReadOnly => true;
public void Add(int key, T value) => throw new InvalidOperationException("Adding values is not supported.");
public void Add(KeyValuePair<int, T> item) => throw new InvalidOperationException("Adding values is not supported.");
public void Clear() => throw new InvalidOperationException("Clearing is not supported.");
public bool Contains(KeyValuePair<int, T> item) => throw new InvalidOperationException("Testing contained items is not supported.");
public void CopyTo(KeyValuePair<int, T>[] array, int arrayIndex) => throw new InvalidOperationException("Copying this map is not supported.");
public IEnumerator<KeyValuePair<int, T>> GetEnumerator() => throw new InvalidOperationException("Getting the enumerator is not supported.");
public bool Remove(int key) => throw new InvalidOperationException("Removing elements is not supported.");
public bool Remove(KeyValuePair<int, T> item) => throw new InvalidOperationException("Removing elements is not supported.");
public bool TryGetValue(int key, out T value) => throw new InvalidOperationException("Trying to get values is not supported.");
IEnumerator IEnumerable.GetEnumerator() => throw new InvalidOperationException("Getting the enumerator is not supported.");
}
}
/// <summary>
/// An enumerator which is sticky.
/// </summary>
public sealed class Sticky
{
/// In order to allow enumerables to not pre-compute/copy all elements,
/// this ctor allows injecting and therefore re-using the caching elements.
/// An enumerable like <see cref="ManyEnvelope"/> can then issue multiple
/// Enumerators while the same cache is filled when advancing them.
public IEnumerator<T> New<T>(IEnumerator<T> origin) => new Sticky<T>(origin);
/// In order to allow enumerables to not pre-compute/copy all elements,
/// this ctor allows injecting and therefore re-using the caching elements.
/// An enumerable like <see cref="ManyEnvelope"/> can then issue multiple
/// Enumerators while the same cache is filled when advancing them.
public IEnumerator<T> New<T>(Func<IEnumerator<T>> origin) => new Sticky<T>(origin);
/// In order to allow enumerables to not pre-compute/copy all elements,
/// this ctor allows injecting and therefore re-using the caching elements.
/// An enumerable like <see cref="ManyEnvelope"/> can then issue multiple
/// Enumerators while the same cache is filled when advancing them.
public IEnumerator<T> New<T>(IDictionary<int, T> cache) => new Sticky<T>(cache);
}
}
| |
/*==============================================================================
Copyright (c) 2013 Disney Research
All Rights Reserved.
==============================================================================*/
// debug display
#define SHOW_DEBUG
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
/// <summary>
/// Defines the AR exposure modes
/// </summary>
public enum ARExposureMode
{
Locked = 0,
AutoExpose = 1,
ContinuousAutoExposure = 2,
}
/// <summary>
/// Defines the AR focus modes
/// </summary>
public enum ARFocusMode
{
Locked = 0,
AutoFocus = 1,
ContinuousAutoFocus = 2,
}
/// <summary>
/// Defines the AR debug modes
/// </summary>
public enum ARDebugMode
{
Off = 0,
Gray = 1,
Distance = 2,
CentroidX = 3,
CentroidY = 4,
Centroid0X = 5,
Centroid0Y = 6,
Centroid1X = 7,
Centroid1Y = 8,
KMeans = 9
}
// Defines the AR feature tracking modes
public enum ARFeatureTrackingMode
{
kMeansCPU = 0,
MomentGPU = 1
}
/// <summary>
/// SkyePeek Plugin Interface
/// </summary>
public class SkyePeek : MonoBehaviour
{
#region PEEK_IMPORTS
#if UNITY_IOS && !UNITY_EDITOR
[DllImport ("__Internal")]
private static extern void _peekStart(bool useFront, int texId);
[DllImport ("__Internal")]
private static extern void _peekReadPixels(int dstTexId, int srcTexId, int width, int height, IntPtr data);
[DllImport ("__Internal")]
private static extern void _peekEnd();
[DllImport("__Internal")]
private static extern void _peekSetFocusMode( int focusMode );
[DllImport("__Internal")]
private static extern void _peekSetExposureMode( int exposureMode );
[DllImport("__Internal")]
private static extern float _peekHalf2Float( short sum );
#else
/// <summary>
/// Starts the camera capture
/// </summary>
private void _peekStart(bool useFront, int texId) {}
/// <summary>
/// Stops the camera capture
/// </summary>
private void _peekEnd() {}
/// <summary>
/// Sets the camera focus mode
/// </summary>
private void _peekSetFocusMode(int focusMode ) {}
/// <summary>
/// Sets the camera exposure mode
/// </summary>
private void _peekSetExposureMode(int exposureMode ) {}
#endif
/// <summary>
/// Writes a RenderTexture into a Texture2D
/// </summary>
private void TextureFromRT(Texture2D dstTex, RenderTexture srcTex)
{
int width=dstTex.width;
int height=dstTex.height;
#if UNITY_IOS && !UNITY_EDITOR
if (handlePx.IsAllocated)
handlePx.Free();
handlePx = GCHandle.Alloc (curTexData, GCHandleType.Pinned);
_peekReadPixels(dstTex.GetNativeTextureID(), srcTex.GetNativeTextureID(), width, height, handlePx.AddrOfPinnedObject());
#else
RenderTexture.active = srcTex;
dstTex.ReadPixels(new Rect(0,0, width, height), 0,0, false);
//dstTex.Apply(); only need if rendering with this tex
#endif
curTex=dstTex;
}
/// <summary>
/// Accumulates sum and vol from texture
/// </summary>
private void AccumulateFromTex(ref float sum, ref float vol, int x, int y)
{
#if UNITY_IOS && !UNITY_EDITOR
int idx=(y*curTex.width + x)*2;
sum += _peekHalf2Float(curTexData[idx++]);
vol += _peekHalf2Float(curTexData[idx]);
#else
Color rg=curTex.GetPixel(x,y);
sum += rg.r;
vol += rg.g;
#endif
}
/// <summary>
/// Frees handles in iOS
/// </summary>
private void DoneAccumulation()
{
#if UNITY_IOS && !UNITY_EDITOR
if (handlePx.IsAllocated)
handlePx.Free();
#endif
}
#endregion // PEEK_IMPORTS
#region PUBLIC_METHODS
/// <summary>
/// Disables AR debugging
/// </summary>
public void DisableDebug(bool disable)
{
debugMode = ARDebugMode.Off;
}
/// <summary>
/// Sets the blimp color
/// </summary>
public void SetBlimpColor(Color color)
{
this.refColor = color;
}
/// <summary>
/// Starts the camera capture and returns a Texture2D that will have the camera output as it's content
/// </summary>
public void startCameraCapture( bool useFrontCameraIfAvailable )
{
// Create texture that will be updated in the plugin code/webcam
MakeVideoTexture();
if( Application.platform == RuntimePlatform.IPhonePlayer )
_peekStart( useFrontCameraIfAvailable, videoTexture.GetNativeTextureID() );
}
/// <summary>
/// Stops the camera capture
/// </summary>
public void stopCameraCapture()
{
_peekEnd();
}
/// <summary>
/// Sets the exposure mode. Capture must be started for this to work!
/// </summary>
public void setExposureMode( ARExposureMode mode )
{
_peekSetExposureMode( (int)mode );
}
/// <summary>
/// Sets the focus mode. Capture must be started for this to work!
/// </summary>
public void setFocusMode( ARFocusMode mode )
{
_peekSetFocusMode( (int)mode );
}
/// <summary>
/// Updates the materials UV offset to accommodate the texture being placed into the next biggest power of 2 container
/// </summary>
public void updateMaterialUVScaleForTexture( Material material, Texture2D texture )
{
Vector2 textureOffset = new Vector2( (float)texture.width / (float)nearestPowerOfTwo( texture.width ), (float)texture.height / (float)nearestPowerOfTwo( texture.height ) );
material.mainTextureScale = textureOffset;
}
#endregion // PUBLIC_METHODS
#region PUBLIC_MEMBERS
public bool useFrontCamera = false;
public ARFocusMode focusMode = ARFocusMode.ContinuousAutoFocus;
public ARExposureMode exposureMode = ARExposureMode.ContinuousAutoExposure;
public int videoWidth = 640;
public int videoHeight = 480;
public int videoFPS = 60;
public int numPassSamples = 8;
public float offsetScale = 1.0f;
public Color refColor;
public GameObject backdropObj;
public Transform blimp;
public float baseDistance = 40;
public float initialBlimpDistance;
#if SHOW_DEBUG
public ARDebugMode debugMode = ARDebugMode.Gray;
#endif
public ARFeatureTrackingMode trackingMode = ARFeatureTrackingMode.MomentGPU;
public Shader centroid0XShader;
public Shader centroid1XShader;
public Shader centroid0YShader;
public Shader centroid1YShader;
#if SHOW_DEBUG
public Shader grayShader;
public Shader distShader;
#endif
#endregion
#region PRIVATE_MEMBERS
[HideInInspector] // Hides var below
public Texture2D videoTexture;
private RenderTexture centTex0X=null;
private RenderTexture centTex1X=null;
private RenderTexture centTex0Y=null;
private RenderTexture centTex1Y=null;
#if SHOW_DEBUG
private RenderTexture debugRTex=null;
private Material grayMaterial=null;
private Material distMaterial=null;
private Texture2D debugTex=null;
private GameObject debugObj;
#endif
private Texture2D centTexX=null;
private Texture2D centTexY=null;
private Texture2D curTex; // used to abstract texture data access
private short[] curTexData= new short[256*256*2];
GCHandle handlePx;
private Material cent0XMaterial=null;
private Material cent1XMaterial=null;
private Material cent0YMaterial=null;
private Material cent1YMaterial=null;
private Vector4 offsets0;
private Vector4 offsets1;
private string deviceName;
private WebCamTexture wct;
private Pixel oldA, oldB, oldC;
private Vector3 initialScreenPos;
private Vector2 trackingCenter;
private float trackingScale;
private bool trackingFound=false;
private Vector3 lastCenter= new Vector3(0,0,0);
#if UNITY_IOS && !UNITY_EDITOR
private static iPhoneGeneration[] unsupportedDevices =
{
iPhoneGeneration.iPad1Gen,
iPhoneGeneration.iPhone,
iPhoneGeneration.iPhone3G,
iPhoneGeneration.iPhone3GS,
iPhoneGeneration.iPodTouch1Gen,
iPhoneGeneration.iPodTouch2Gen,
iPhoneGeneration.iPodTouch3Gen,
iPhoneGeneration.iPhone4,
iPhoneGeneration.iPodTouch4Gen
};
#endif
/// <summary>
/// Defines the Pixel struct
/// </summary>
struct Pixel
{
public int x, y;
public float DistSquare(Pixel other)
{
return (x - other.x) * (x - other.x) + (y - other.y) * (y - other.y);
}
public Vector2 toVector2()
{
return new Vector2(x, y);
}
};
/// <summary>
/// Calculates the nearest power of two for a number
/// </summary>
private int nearestPowerOfTwo( float number )
{
int n = 1;
while( n < number )
n <<= 1;
return n;
}
/// <summary>
/// Sets up debugging objects
/// </summary>
private void DebugSetup()
{
#if SHOW_DEBUG
#if UNITY_IOS && !UNITY_EDITOR
//debug.transform.Rotate(270,0,0);
//debug.transform.localScale=new Vector3(-1,1,1);
#else
//debugObj.transform.Rotate(90,180,0);
#endif
debugTex = new Texture2D(videoWidth, videoHeight, TextureFormat.RGBA32, false);
debugTex.filterMode = FilterMode.Point;
debugObj = new GameObject("Debug");
debugObj.AddComponent("GUITexture");
debugObj.guiTexture.texture = debugTex;
debugObj.transform.localScale = new Vector3(.06f, .3f, 0f);
debugObj.transform.position = new Vector3(.06f, .2f, 0f);
debugObj.guiTexture.pixelInset = new Rect(8.0f,8.0f,videoWidth/2,videoHeight/2);
//grayShader = Shader.Find("Custom/BGRA2Gray");
grayMaterial = new Material(grayShader);
//distShader = Shader.Find ("Custom/ColorDistance");
distMaterial = new Material(distShader);
debugRTex = new RenderTexture(videoWidth,videoHeight,-1,RenderTextureFormat.ARGB32);
debugRTex.filterMode = FilterMode.Point;
Debug.Log(initialScreenPos);
Debug.Log(initialBlimpDistance);
Debug.Log ("Screen:" + Screen.width + "," + Screen.height + " Video:" + videoWidth + "," + videoHeight + " " + videoFPS );
#endif
}
private void DebugUpdate()
{
if (debugMode==ARDebugMode.Off) debugObj.SetActive(false);
else
{
if (!debugObj.activeSelf) debugObj.SetActive(true);
switch (debugMode)
{
case ARDebugMode.KMeans : debugObj.guiTexture.texture = debugTex; break;
case ARDebugMode.CentroidX : debugObj.guiTexture.texture = centTexX; break;
case ARDebugMode.Centroid0X : debugObj.guiTexture.texture = centTex0X; break;
case ARDebugMode.Centroid1X : debugObj.guiTexture.texture = centTex1X; break;
case ARDebugMode.CentroidY : debugObj.guiTexture.texture = centTexY; break;
case ARDebugMode.Centroid0Y : debugObj.guiTexture.texture = centTex0Y; break;
case ARDebugMode.Centroid1Y : debugObj.guiTexture.texture = centTex1Y; break;
case ARDebugMode.Gray : debugObj.guiTexture.texture = debugRTex; break;
case ARDebugMode.Distance : debugObj.guiTexture.texture = debugRTex; break;
default : debugObj.guiTexture.texture = videoTexture; break;
}
}
}
/// <summary>
/// Sets up a Texture2D for video capturing
/// </summary>
private void MakeVideoTexture()
{
#if UNITY_IOS && !UNITY_EDITOR
videoTexture = new Texture2D( videoWidth, videoHeight, TextureFormat.BGRA32, false);
backdropObj.guiTexture.texture = videoTexture;
backdropObj.transform.localScale=new Vector3(1,-1,1);
#else
videoTexture = new Texture2D( videoWidth, videoHeight, TextureFormat.RGBA32, false);
WebCamDevice[] cameras = WebCamTexture.devices;
if ((cameras != null) && (cameras.Length > 0))
{
deviceName = cameras[cameras.Length-1].name;
wct = new WebCamTexture(deviceName, videoWidth, videoHeight, videoFPS);
backdropObj.guiTexture.texture = wct;
wct.Play();
Debug.Log("Created web cam texture");
}
else
Debug.Log("No cameras " + cameras.Length);
#endif // UNITY_IOS/EDITOR
videoTexture.filterMode = FilterMode.Point;
}
/// <summary>
/// For PC (not iphone): ensure that webcam image is in video texture
/// </summary>
void UpdateVideoTexture()
{
#if UNITY_EDITOR || !UNITY_IOS
if (wct!=null && wct.isPlaying && wct.didUpdateThisFrame)
{
Color[] textureData = wct.GetPixels();
if (textureData!=null)
{
videoTexture.SetPixels(textureData);
videoTexture.Apply();
}
}
#endif
}
/// <summary>
/// Creates the centroid texture using grayscale image and scaling down
/// </summary>
void MakeCentroidTexture()
{
#if UNITY_IOS && !UNITY_EDITOR
foreach (iPhoneGeneration gen in unsupportedDevices)
{
if (gen == iPhone.generation)
{
return;
}
}
#endif
// these have to be manually assigned for the build to include them...
//centroid0XShader=Shader.Find("Custom/Centroid0X");
//centroid0YShader=Shader.Find("Custom/Centroid0Y");
//centroid1XShader=Shader.Find("Custom/Centroid1X");
//centroid1YShader=Shader.Find("Custom/Centroid1Y");
cent0XMaterial=new Material(centroid0XShader);
cent1XMaterial=new Material(centroid1XShader);
cent0YMaterial=new Material(centroid0YShader);
cent1YMaterial=new Material(centroid1YShader);
int passXSamples = numPassSamples;
int passYSamples = numPassSamples;
//int totalPassSamples = passXSamples*passYSamples;
int passWidth = videoWidth/passXSamples;
int passHeight = videoHeight/passYSamples;
Debug.Log("Centroid texture axes pass 0:" + passWidth + "," + passHeight);
offsets0 = new Vector4(offsetScale/videoWidth,offsetScale/videoHeight,offsetScale/videoWidth,offsetScale/videoHeight);
cent0XMaterial.SetVector ("offsets", offsets0);
cent0YMaterial.SetVector ("offsets", offsets0);
centTex0X = new RenderTexture(passWidth,videoHeight,-1,RenderTextureFormat.RGHalf);
centTex0X.filterMode=FilterMode.Point;
centTex0Y = new RenderTexture(videoWidth,passHeight,-1,RenderTextureFormat.RGHalf);
centTex0Y.filterMode=FilterMode.Point;
offsets1 = new Vector4(offsetScale/passWidth,offsetScale/passHeight,offsetScale/passWidth,offsetScale/passHeight);
cent1XMaterial.SetVector("offsets", offsets1);
cent1YMaterial.SetVector("offsets", offsets1);
passWidth/=passXSamples;
passHeight/=passYSamples;
Debug.Log("Centroid texture axes pass 1:" + passWidth + "," + passHeight);
centTex1X = new RenderTexture(passWidth,videoHeight,-1,RenderTextureFormat.RGHalf);
centTex1X.filterMode=FilterMode.Point;
centTex1Y = new RenderTexture(videoWidth,passHeight,-1,RenderTextureFormat.RGHalf);
centTex1Y.filterMode=FilterMode.Point;
// converting RenderTexture to texture2D
centTexX = new Texture2D(passWidth,videoHeight);
centTexX.filterMode=FilterMode.Point;
centTexY = new Texture2D(videoWidth,passHeight);
centTexY.filterMode=FilterMode.Point;
}
/// <summary>
/// Calculates the centroid for the momentGPU tracking method
/// </summary>
void CalculateCentroid()
{
#if UNITY_IOS && !UNITY_EDITOR
foreach (iPhoneGeneration gen in unsupportedDevices)
{
if (gen == iPhone.generation)
{
return;
}
}
#endif
if (!centTex0X.IsCreated()) centTex0X.Create();
if (!centTex0Y.IsCreated()) centTex0Y.Create();
if (!centTex1X.IsCreated()) centTex1X.Create();
if (!centTex1Y.IsCreated()) centTex1Y.Create();
cent0XMaterial.SetColor("_Color",refColor);
cent0YMaterial.SetColor("_Color",refColor);
cent1XMaterial.SetColor("_Color",refColor);
cent1YMaterial.SetColor("_Color",refColor);
// 2-pass accumulating downsample: sum up all the gray scale values
Graphics.Blit(videoTexture, centTex0X, cent0XMaterial);
Graphics.Blit(centTex0X, centTex1X, cent1XMaterial);
TextureFromRT(centTexX, centTex1X);
float[] sumsX = new float[videoHeight];
float[] volX = new float[videoHeight];
for (int y=0; y<videoHeight; y++)
{
sumsX[y]=0.0f;
volX[y]=0.0f;
for (int x=0; x<centTexX.width; x++)
{
AccumulateFromTex(ref sumsX[y], ref volX[y], x, y);
}
sumsX[y]*=videoWidth/centTexX.width;
volX[y]*=videoWidth/centTexX.width;
}
DoneAccumulation(); // release memory
// compute average x
float avgX = 0.0f;
float hitX = 0.0f;
for (int y=0; y<videoHeight; y++)
{
if (volX[y]>0.0f)
{
avgX+=sumsX[y]/volX[y];
hitX+=1.0f;
}
}
avgX/=hitX;
Graphics.Blit(videoTexture, centTex0Y, cent0YMaterial);
Graphics.Blit(centTex0Y, centTex1Y, cent1YMaterial);
TextureFromRT(centTexY, centTex1Y);
float[] sumsY = new float[videoWidth];
float[] volY = new float[videoWidth];
for (int x=0; x<videoWidth; x++)
{
sumsY[x]=0.0f;
volY[x]=0.0f;
for (int y=0; y<centTexY.height; y++)
{
AccumulateFromTex(ref sumsY[x], ref volY[x], x, y);
}
sumsY[x]*=videoHeight/centTexY.height;
volY[x]*=videoHeight/centTexY.height;
}
DoneAccumulation(); // release memory
// compute average y
float avgY = 0.0f;
float hitY = 0.0f;
for (int x=0; x<videoWidth; x++)
{
if (volY[x]>0.0f)
{
avgY+=sumsY[x]/volY[x];
hitY+=1.0f;
}
}
avgY/=hitY;
trackingCenter.Set (avgX, avgY);
trackingScale=0.5f; // size of blob
#if SHOW_DEBUG
// grey and color distance
if (debugMode==ARDebugMode.Gray || debugMode==ARDebugMode.Distance)
{
if (debugMode==ARDebugMode.Gray)
{
Graphics.Blit(videoTexture, debugRTex, grayMaterial);
}
else
{
distMaterial.SetColor("_Color",refColor);
Graphics.Blit(videoTexture, debugRTex, distMaterial);
}
}
else if (debugMode==ARDebugMode.CentroidX) centTexX.Apply();
else if (debugMode==ARDebugMode.CentroidY) centTexY.Apply();
//Debug.Log("Moment: " + avgX + "," + avgY + " " + hitX + " " + hitY + " " + trackingFound);
#endif
}
/// <summary>
/// Runs kMeans
/// </summary>
private void kMeanDetection()
{
// Find candidates
List<Pixel> candidates = new List<Pixel>();
for (int j = 0; j < videoTexture.height; j++)
{
for (int i = 0; i < videoTexture.width; i++)
{
Color cc = videoTexture.GetPixel(i, j);
if (Detect(cc))
{
Pixel p; p.x = i; p.y = j;
candidates.Add(p);
#if SHOW_DEBUG
debugTex.SetPixel(i, j, Color.black);
}
else
debugTex.SetPixel(i, j, Color.white);
}
}
debugTex.Apply();
#else
}
}
}
#endif
if (candidates.Count < 3)
{
// Detection has problems, do something else (or do nothing...)
return;
}
// Groups
List<int> A = new List<int>(); List<int> B = new List<int>(); List<int> C = new List<int>();
Pixel pA; Pixel pB; Pixel pC;
// Set Group Seeds
int a = 0; int b = (candidates.Count - 1); int c = b / 2;
if ((oldA.x == 0) && (oldA.y == 0)) { pA = candidates[a]; pB = candidates[b]; pC = candidates[c]; }
else { pA = oldA; pB = oldB; pC = oldC; }
// Perform k-mean clustering
for (int iteration = 0; iteration < 3; iteration++)
{
A.Clear(); B.Clear(); C.Clear();
// Partition candidates into 3 groups
for (int i = 0; i < candidates.Count; i++)
{
if (i == a) { A.Add(i); continue; }
if (i == b) { B.Add(i); continue; }
if (i == c) { C.Add(i); continue; }
Pixel p = candidates[i];
float dA = p.DistSquare(pA);
float dB = p.DistSquare(pB);
float dC = p.DistSquare(pC);
// Add candidate to the appropriate group
if (dA < dB) if (dA < dC) A.Add(i); else C.Add(i); else if (dB < dC) B.Add(i); else C.Add(i);
}
// Find the mean of every group
Mean(A, candidates, out pA);
Mean(B, candidates, out pB);
Mean(C, candidates, out pC);
}
#if SHOW_DEBUG
// Color mean pixels
debugTex.SetPixel(pA.x, pA.y, new Color(1, 1, 1, 1));
debugTex.SetPixel(pB.x, pB.y, new Color(0, 1, 0, 1));
debugTex.SetPixel(pC.x, pC.y, new Color(0, 0, 1, 1));
debugTex.Apply();
#endif
//setMarker(Camera.main.ScreenPointToRay(new Vector3(pA.x, pA.y, 0)), marker);
//setMarker(Camera.main.ScreenPointToRay(new Vector3(pB.x, pB.y, 0)), marker2);
//setMarker(Camera.main.ScreenPointToRay(new Vector3(pC.x, pC.y, 0)), marker3);
oldA = pA;
oldB = pB;
oldC = pC;
}
/// <summary>
/// Updates the blimp using kMeans
/// </summary>
private void kMeanUpdateBlimp()
{
Vector2 a, b, c;
a = oldA.toVector2();
b = oldB.toVector2();
c = oldC.toVector2();
trackingCenter = (a + b + c) / 3.0f;
trackingScale = ((a - trackingCenter).magnitude + (b - trackingCenter).magnitude + (c - trackingCenter).magnitude) / 3.0f;
trackingScale /= baseDistance;
}
/// <summary>
/// Updates the blimp using local window transformation
/// </summary>
private void UpdateBlimp()
{
Vector3 center = trackingCenter;
if (float.IsNaN(center.x) || float.IsNaN(center.y) || center.x>1.0f || center.y>1.0f)
{
trackingFound = false;
center = lastCenter;
}
else
{
trackingFound = true;
lastCenter=center;
}
#if UNITY_EDITOR || !UNITY_IOS
Vector3 sVec=new Vector3(center.x*Screen.width, center.y*Screen.height, 0);
#else
Vector3 sVec=new Vector3(center.x*Screen.width, Screen.height-center.y*Screen.height, 0);
#endif
Ray blimpRay = Camera.main.ScreenPointToRay(sVec);
var newPos = Camera.main.transform.position + blimpRay.direction * initialBlimpDistance / trackingScale;
if (!float.IsInfinity(newPos.x))
blimp.position = newPos;
}
/// <summary>
/// Checks if transform intersects with a ray
/// </summary>
private void setMarker(Ray ray, Transform m)
{
RaycastHit info;
float distance = 1000.0f;
if (this.gameObject.collider.Raycast(ray, out info, distance))
{
var pos = info.point;
m.position = pos;
}
}
/// <summary>
/// Calculates the mean of pixels
/// </summary>
private void Mean(List<int> indices, List<Pixel> candidates, out Pixel meanPixel)
{
float x = 0.0f, y = 0.0f;
for (int i = 0; i < indices.Count; i++)
{
x += candidates[indices[i]].x;
y += candidates[indices[i]].y;
}
meanPixel.x = (int)(x / indices.Count + 0.5f);
meanPixel.y = (int)(y / indices.Count + 0.5f);
}
/// <summary>
/// Hard coded color threshold
/// </summary>
private bool Detect(Color c)
{
return (c.r > 0.9 && c.g < 0.75 && c.b < 0.75);
//float i = c.r - 0.5f * (c.g + c.b);
//return (i > 0.6f);
}
#endregion // PRIVATE_MEMBERS
#region UNITY_MONOBEHAVIOUR_METHODS
/// <summary>
/// Starts up the camera
/// </summary>
void Start()
{
Application.targetFrameRate=videoFPS;
Screen.SetResolution (1024, 768, true);
if (trackingMode==ARFeatureTrackingMode.MomentGPU) {
MakeCentroidTexture(); // prepare texture results
}
// setup camera capture properties
setFocusMode(focusMode);
setExposureMode(exposureMode);
startCameraCapture(useFrontCamera);
initialBlimpDistance = (blimp.position - Camera.main.transform.position).magnitude;
initialScreenPos = Camera.main.WorldToScreenPoint(blimp.position);
DebugSetup(); // create debug texture and window
}
/// <summary>
/// Updates the scene with new tracking data. Calls registered ITrackerEventHandlers
/// </summary>
void Update()
{
UpdateVideoTexture();
// two tracking implementations available
if (trackingMode==ARFeatureTrackingMode.kMeansCPU) // works well on PC but too slow on iPhone
{
kMeanDetection();
kMeanUpdateBlimp();
}
else
{
// works well on iphone
CalculateCentroid();
}
UpdateBlimp();
DebugUpdate();
}
/// <summary>
/// Does currently nothing
/// </summary>
void OnDrawGizmosSelected()
{
//Gizmos.DrawLine(from, to);
}
#endregion // UNITY_MONOBEHAVIOUR_METHDS
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Web.Services.Description
{
using System;
using Microsoft.Xml;
/// <include file='doc\ServiceDescriptions.uex' path='docs/doc[@for="ServiceDescriptionCollection"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public sealed class ServiceDescriptionCollection : ServiceDescriptionBaseCollection
{
/// <include file='doc\ServiceDescriptions.uex' path='docs/doc[@for="ServiceDescriptionCollection.ServiceDescriptionCollection"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public ServiceDescriptionCollection() : base(null) { }
/// <include file='doc\ServiceDescriptions.uex' path='docs/doc[@for="ServiceDescriptionCollection.this"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public ServiceDescription this[int index]
{
get { return (ServiceDescription)List[index]; }
set { List[index] = value; }
}
/// <include file='doc\ServiceDescriptions.uex' path='docs/doc[@for="ServiceDescriptionCollection.this1"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public ServiceDescription this[string ns]
{
get { return (ServiceDescription)Table[ns]; }
}
/// <include file='doc\ServiceDescriptions.uex' path='docs/doc[@for="ServiceDescriptionCollection.Add"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public int Add(ServiceDescription serviceDescription)
{
return List.Add(serviceDescription);
}
/// <include file='doc\ServiceDescriptions.uex' path='docs/doc[@for="ServiceDescriptionCollection.Insert"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Insert(int index, ServiceDescription serviceDescription)
{
List.Insert(index, serviceDescription);
}
/// <include file='doc\ServiceDescriptions.uex' path='docs/doc[@for="ServiceDescriptionCollection.IndexOf"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public int IndexOf(ServiceDescription serviceDescription)
{
return List.IndexOf(serviceDescription);
}
/// <include file='doc\ServiceDescriptions.uex' path='docs/doc[@for="ServiceDescriptionCollection.Contains"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public bool Contains(ServiceDescription serviceDescription)
{
return List.Contains(serviceDescription);
}
/// <include file='doc\ServiceDescriptions.uex' path='docs/doc[@for="ServiceDescriptionCollection.Remove"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Remove(ServiceDescription serviceDescription)
{
List.Remove(serviceDescription);
}
/// <include file='doc\ServiceDescriptions.uex' path='docs/doc[@for="ServiceDescriptionCollection.CopyTo"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void CopyTo(ServiceDescription[] array, int index)
{
List.CopyTo(array, index);
}
/// <include file='doc\ServiceDescriptions.uex' path='docs/doc[@for="ServiceDescriptionCollection.GetKey"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
protected override string GetKey(object value)
{
string ns = ((ServiceDescription)value).TargetNamespace;
if (ns == null)
return string.Empty;
return ns;
}
private Exception ItemNotFound(XmlQualifiedName name, string type)
{
return new Exception(string.Format(ResWebServices.WebDescriptionMissingItem, type, name.Name, name.Namespace));
}
/// <include file='doc\ServiceDescriptions.uex' path='docs/doc[@for="ServiceDescriptionCollection.GetMessage"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public Message GetMessage(XmlQualifiedName name)
{
ServiceDescription sd = GetServiceDescription(name);
Message message = null;
while (message == null && sd != null)
{
message = sd.Messages[name.Name];
sd = sd.Next;
}
if (message == null) throw ItemNotFound(name, "message");
return message;
}
/// <include file='doc\ServiceDescriptions.uex' path='docs/doc[@for="ServiceDescriptionCollection.GetPortType"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public PortType GetPortType(XmlQualifiedName name)
{
ServiceDescription sd = GetServiceDescription(name);
PortType portType = null;
while (portType == null && sd != null)
{
portType = sd.PortTypes[name.Name];
sd = sd.Next;
}
if (portType == null) throw ItemNotFound(name, "message");
return portType;
}
/// <include file='doc\ServiceDescriptions.uex' path='docs/doc[@for="ServiceDescriptionCollection.GetService"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public Service GetService(XmlQualifiedName name)
{
ServiceDescription sd = GetServiceDescription(name);
Service service = null;
while (service == null && sd != null)
{
service = sd.Services[name.Name];
sd = sd.Next;
}
if (service == null) throw ItemNotFound(name, "service");
return service;
}
/// <include file='doc\ServiceDescriptions.uex' path='docs/doc[@for="ServiceDescriptionCollection.GetBinding"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public Binding GetBinding(XmlQualifiedName name)
{
ServiceDescription sd = GetServiceDescription(name);
Binding binding = null;
while (binding == null && sd != null)
{
binding = sd.Bindings[name.Name];
sd = sd.Next;
}
if (binding == null) throw ItemNotFound(name, "binding");
return binding;
}
private ServiceDescription GetServiceDescription(XmlQualifiedName name)
{
ServiceDescription serviceDescription = this[name.Namespace];
if (serviceDescription == null)
{
throw new ArgumentException(string.Format(ResWebServices.WebDescriptionMissing, name.ToString(), name.Namespace), "name");
}
return serviceDescription;
}
/// <include file='doc\ServiceDescriptions.uex' path='docs/doc[@for="ServiceDescriptionCollection.SetParent"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
protected override void SetParent(object value, object parent)
{
((ServiceDescription)value).SetParent((ServiceDescriptionCollection)parent);
}
/// <include file='doc\ServiceDescriptions.uex' path='docs/doc[@for="ServiceDescriptionBaseCollection.OnInsertComplete"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
protected override void OnInsertComplete(int index, object value)
{
string key = GetKey(value);
if (key != null)
{
ServiceDescription item = (ServiceDescription)Table[key];
((ServiceDescription)value).Next = (ServiceDescription)Table[key];
Table[key] = value;
}
SetParent(value, this);
}
}
}
| |
using System;
using System.Windows.Controls;
using System.Windows;
using System.Windows.Threading;
using System.ComponentModel;
using System.Windows.Input;
using System.Windows.Media;
namespace MahApps.Metro.Controls
{
[TemplatePart(Name = "PART_ScrollViewer", Type = typeof(ScrollViewer))]
public class Panorama : ItemsControl
{
public static readonly DependencyProperty ItemBoxProperty = DependencyProperty.Register("ItemHeight", typeof(double), typeof(Panorama), new FrameworkPropertyMetadata(120.0));
public static readonly DependencyProperty GroupHeightProperty = DependencyProperty.Register("GroupHeight", typeof(double), typeof(Panorama), new FrameworkPropertyMetadata(640.0));
public static readonly DependencyProperty HeaderFontSizeProperty = DependencyProperty.Register("HeaderFontSize", typeof(double), typeof(Panorama), new FrameworkPropertyMetadata(40.0));
public static readonly DependencyProperty HeaderFontColorProperty = DependencyProperty.Register("HeaderFontColor", typeof(Brush), typeof(Panorama), new FrameworkPropertyMetadata(Brushes.White));
public static readonly DependencyProperty HeaderFontFamilyProperty = DependencyProperty.Register("HeaderFontFamily", typeof(FontFamily), typeof(Panorama), new FrameworkPropertyMetadata(new FontFamily("Segoe UI Light")));
public static readonly DependencyProperty UseSnapBackScrollingProperty = DependencyProperty.Register("UseSnapBackScrolling", typeof(bool), typeof(Panorama), new FrameworkPropertyMetadata(true));
public static readonly DependencyProperty MouseScrollEnabledProperty = DependencyProperty.Register("MouseScrollEnabled", typeof(bool), typeof(Panorama), new FrameworkPropertyMetadata(true));
public static readonly DependencyProperty HorizontalScrollBarEnabledProperty = DependencyProperty.Register("HorizontalScrollBarEnabled", typeof(bool), typeof(Panorama), new FrameworkPropertyMetadata(true));
public static readonly DependencyProperty DynamicGroupHeaderProperty = DependencyProperty.Register("DynamicGroupHeader", typeof(bool), typeof(Panorama), new FrameworkPropertyMetadata(true));
public double Friction
{
get { return 1.0 - friction; }
set { friction = Math.Min(Math.Max(1.0 - value, 0), 1.0); }
}
public double ItemBox
{
get { return (double)GetValue(ItemBoxProperty); }
set { SetValue(ItemBoxProperty, value); }
}
public double GroupHeight
{
get { return (double)GetValue(GroupHeightProperty); }
set { SetValue(GroupHeightProperty, value); }
}
public double HeaderFontSize
{
get { return (double)GetValue(HeaderFontSizeProperty); }
set { SetValue(HeaderFontSizeProperty, value); }
}
public Brush HeaderFontColor
{
get { return (Brush)GetValue(HeaderFontColorProperty); }
set { SetValue(HeaderFontColorProperty, value); }
}
public FontFamily HeaderFontFamily
{
get { return (FontFamily)GetValue(HeaderFontFamilyProperty); }
set { SetValue(HeaderFontFamilyProperty, value); }
}
public bool UseSnapBackScrolling
{
get { return (bool)GetValue(UseSnapBackScrollingProperty); }
set { SetValue(UseSnapBackScrollingProperty, value); }
}
public bool DynamicGroupHeader
{
get { return (bool)GetValue(DynamicGroupHeaderProperty); }
set { SetValue(DynamicGroupHeaderProperty, value); }
}
public bool MouseScrollEnabled
{
get { return (bool)GetValue(MouseScrollEnabledProperty); }
set { SetValue(MouseScrollEnabledProperty, value); }
}
public bool HorizontalScrollBarEnabled
{
get { return (bool)GetValue(HorizontalScrollBarEnabledProperty); }
set { SetValue(HorizontalScrollBarEnabledProperty, value); }
}
private ScrollViewer sv;
private Point scrollTarget;
private Point scrollStartPoint;
private Point scrollStartOffset;
private Point previousPoint;
private Vector velocity;
private double friction;
private readonly DispatcherTimer animationTimer = new DispatcherTimer(DispatcherPriority.DataBind);
private readonly DispatcherTimer scrollBarTimer = new DispatcherTimer(DispatcherPriority.DataBind);
private static int PixelsToMoveToBeConsideredScroll = 5;
private static int PixelsToMoveToBeConsideredClick = 2;
private IPanoramaTile tile;
private bool touchCaptured;
private Point lastTouchPosition;
public Panorama()
{
friction = 0.85;
animationTimer.Interval = new TimeSpan(0, 0, 0, 0, 20);
animationTimer.Tick += HandleWorldTimerTick;
scrollBarTimer.Interval = TimeSpan.FromSeconds(1);
scrollBarTimer.Tick += (s, e) => HideHorizontalScrollBar();
this.Loaded += (sender, e) => animationTimer.Start();
this.Unloaded += (sender, e) => animationTimer.Stop();
lastTouchPosition = new Point();
}
static Panorama()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(Panorama), new FrameworkPropertyMetadata(typeof(Panorama)));
}
private void DoStandardScrolling()
{
sv.ScrollToHorizontalOffset(scrollTarget.X);
sv.ScrollToVerticalOffset(scrollTarget.Y);
scrollTarget.X += velocity.X;
scrollTarget.Y += velocity.Y;
velocity *= friction;
}
private void HandleWorldTimerTick(object sender, EventArgs e)
{
if (sv == null)
return;
var prop = DesignerProperties.IsInDesignModeProperty;
var isInDesignMode = (bool)DependencyPropertyDescriptor.FromProperty(prop, typeof(FrameworkElement)).Metadata.DefaultValue;
if (isInDesignMode)
return;
if (IsMouseCaptured || touchCaptured)
{
Point currentPoint = IsMouseCaptured ? Mouse.GetPosition(this) : lastTouchPosition;
velocity = previousPoint - currentPoint;
previousPoint = currentPoint;
}
else
{
if (velocity.Length > 1)
{
DoStandardScrolling();
}
else
{
if (UseSnapBackScrolling)
{
int mx = (int)sv.HorizontalOffset % (int)ActualWidth;
if (mx == 0)
return;
int ix = (int)sv.HorizontalOffset / (int)ActualWidth;
double snapBackX = mx > ActualWidth / 2 ? (ix + 1) * ActualWidth : ix * ActualWidth;
sv.ScrollToHorizontalOffset(sv.HorizontalOffset + (snapBackX - sv.HorizontalOffset) / 4.0);
}
else
{
DoStandardScrolling();
}
}
}
}
private void HideHorizontalScrollBar()
{
// Ignore when scroll happen with mouse drag or not to be viewed
if (!HorizontalScrollBarEnabled || Mouse.LeftButton == MouseButtonState.Pressed) return;
// Hide the scrollbar
scrollBarTimer.Stop();
if (sv.HorizontalScrollBarVisibility == ScrollBarVisibility.Visible)
sv.HorizontalScrollBarVisibility = ScrollBarVisibility.Hidden;
}
private void ShowHorizontalScrollBar()
{
// Ignore if scrollbar is visible yet or not to be viewed
if (!HorizontalScrollBarEnabled || sv.HorizontalScrollBarVisibility == ScrollBarVisibility.Visible) return;
// Restart the timer and show the scrollbar
scrollBarTimer.Stop();
if (sv.HorizontalScrollBarVisibility == ScrollBarVisibility.Hidden)
sv.HorizontalScrollBarVisibility = ScrollBarVisibility.Visible;
scrollBarTimer.Start();
}
public override void OnApplyTemplate()
{
sv = (ScrollViewer)Template.FindName("PART_ScrollViewer", this);
// Apply the handler for scrollbar visibility
sv.ScrollChanged += (s, e) =>
{
if (HorizontalScrollBarEnabled && Math.Abs(e.HorizontalChange) > PixelsToMoveToBeConsideredScroll)
ShowHorizontalScrollBar();
};
base.OnApplyTemplate();
}
protected override void OnPreviewMouseDown(MouseButtonEventArgs e)
{
if (sv.IsMouseOver)
{
// Save starting point, used later when determining how much to scroll.
scrollStartPoint = e.GetPosition(this);
// Update the cursor if can scroll or not.
Cursor = (sv.ExtentWidth > sv.ViewportWidth) || (sv.ExtentHeight > sv.ViewportHeight) ? Cursors.ScrollAll : Cursors.Arrow;
HandleMouseDown();
}
base.OnPreviewMouseDown(e);
}
protected override void OnPreviewTouchDown(TouchEventArgs e)
{
scrollStartPoint = e.GetTouchPoint(this).Position;
HandleMouseDown();
}
private void HandleMouseDown()
{
tile = null;
scrollStartOffset.X = sv.HorizontalOffset;
scrollStartOffset.Y = sv.VerticalOffset;
//store Control if one was found, so we can call its command later
var x = TreeHelper.TryFindFromPoint<ListBoxItem>(this, scrollStartPoint);
if (x != null)
{
x.IsSelected = !x.IsSelected;
ItemsControl tiles = ItemsControlFromItemContainer(x);
var data = tiles.ItemContainerGenerator.ItemFromContainer(x);
if (data != null && data is IPanoramaTile)
{
tile = (IPanoramaTile)data;
}
}
}
protected override void OnPreviewMouseMove(MouseEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
Point currentPoint = e.GetPosition(this);
if (HandleMouseMove(currentPoint))
{
CaptureMouse();
}
}
base.OnPreviewMouseMove(e);
}
protected override void OnPreviewTouchMove(TouchEventArgs e)
{
Point currentPoint = e.GetTouchPoint(this).Position;
if (HandleMouseMove(currentPoint))
{
touchCaptured = true;
lastTouchPosition = currentPoint;
}
}
private bool HandleMouseMove(Point currentPoint)
{
// Determine the new amount to scroll.
var delta = new Point(scrollStartPoint.X - currentPoint.X, scrollStartPoint.Y - currentPoint.Y);
if (Math.Abs(delta.X) < PixelsToMoveToBeConsideredScroll &&
Math.Abs(delta.Y) < PixelsToMoveToBeConsideredScroll)
return false;
scrollTarget.X = scrollStartOffset.X + delta.X;
scrollTarget.Y = scrollStartOffset.Y + delta.Y;
// Scroll to the new position.
sv.ScrollToHorizontalOffset(scrollTarget.X);
sv.ScrollToVerticalOffset(scrollTarget.Y);
return true;
}
protected override void OnPreviewMouseUp(MouseButtonEventArgs e)
{
Point currentPoint = e.GetPosition(this);
if (IsMouseCaptured)
{
ReleaseMouseCapture();
}
Cursor = Cursors.Arrow;
HandleMouseUp(currentPoint);
base.OnPreviewMouseUp(e);
}
protected override void OnPreviewTouchUp(TouchEventArgs e)
{
if (touchCaptured)
{
touchCaptured = false;
}
Point currentPoint = e.GetTouchPoint(this).Position;
HandleMouseUp(currentPoint);
base.OnPreviewTouchUp(e);
}
private void HandleMouseUp(Point currentPoint)
{
// Determine the new amount to scroll.
var delta = new Point(scrollStartPoint.X - currentPoint.X, scrollStartPoint.Y - currentPoint.Y);
if (Math.Abs(delta.X) < PixelsToMoveToBeConsideredClick &&
Math.Abs(delta.Y) < PixelsToMoveToBeConsideredClick && tile != null)
{
if (tile.TileClickedCommand != null)
//Ok, its a click ask the tile to do its job
if (tile.TileClickedCommand.CanExecute(null))
{
tile.TileClickedCommand.Execute(null);
}
}
}
protected override void OnPreviewMouseWheel(MouseWheelEventArgs e)
{
if (!MouseScrollEnabled) return;
// Pause the scrollbar timer
if (scrollBarTimer.IsEnabled)
scrollBarTimer.Stop();
// Determine the new amount to scroll.
scrollTarget.X = sv.HorizontalOffset + ((e.Delta * -1) / 3);
// Scroll to the new position.
sv.ScrollToHorizontalOffset(scrollTarget.X);
CaptureMouse();
// Save starting point, used later when determining how much to scroll.
scrollStartPoint = e.GetPosition(this);
scrollStartOffset.X = sv.HorizontalOffset;
// Restart the scrollbar timer
if (HorizontalScrollBarEnabled)
scrollBarTimer.Start();
base.OnPreviewMouseWheel(e);
}
}
}
| |
/******************************************************************************
* The MIT License
* Copyright (c) 2003 Novell Inc. www.novell.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the Software), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*******************************************************************************/
//
// Novell.Directory.Ldap.LdapAttributeSchema.cs
//
// Author:
// Sunil Kumar (Sunilk@novell.com)
//
// (C) 2003 Novell, Inc (http://www.novell.com)
//
using System.Collections;
using System.IO;
using System.Text;
namespace Novell.Directory.Ldap.Utilclass
{
public class SchemaParser
{
private void InitBlock()
{
usage = LdapAttributeSchema.USER_APPLICATIONS;
qualifiers = new ArrayList();
}
public virtual string RawString
{
get { return rawString; }
set { rawString = value; }
}
public virtual string[] Names
{
get { return names; }
}
public virtual IEnumerator Qualifiers
{
get { return new ArrayEnumeration(qualifiers.ToArray()); }
}
public virtual string ID
{
get { return id; }
}
public virtual string Description
{
get { return description; }
}
public virtual string Syntax
{
get { return syntax; }
}
public virtual string Superior
{
get { return superior; }
}
public virtual bool Single
{
get { return single; }
}
public virtual bool Obsolete
{
get { return obsolete; }
}
public virtual string Equality
{
get { return equality; }
}
public virtual string Ordering
{
get { return ordering; }
}
public virtual string Substring
{
get { return substring; }
}
public virtual bool Collective
{
get { return collective; }
}
public virtual bool UserMod
{
get { return userMod; }
}
public virtual int Usage
{
get { return usage; }
}
public virtual int Type
{
get { return type; }
}
public virtual string[] Superiors
{
get { return superiors; }
}
public virtual string[] Required
{
get { return required; }
}
public virtual string[] Optional
{
get { return optional; }
}
public virtual string[] Auxiliary
{
get { return auxiliary; }
}
public virtual string[] Precluded
{
get { return precluded; }
}
public virtual string[] Applies
{
get { return applies; }
}
public virtual string NameForm
{
get { return nameForm; }
}
public virtual string ObjectClass
{
get { return nameForm; }
}
internal string rawString;
internal string[] names;
internal string id;
internal string description;
internal string syntax;
internal string superior;
internal string nameForm;
internal string objectClass;
internal string[] superiors;
internal string[] required;
internal string[] optional;
internal string[] auxiliary;
internal string[] precluded;
internal string[] applies;
internal bool single;
internal bool obsolete;
internal string equality;
internal string ordering;
internal string substring;
internal bool collective;
internal bool userMod = true;
internal int usage;
internal int type = -1;
internal int result;
internal ArrayList qualifiers;
public SchemaParser(string aString)
{
InitBlock();
int index;
if ((index = aString.IndexOf('\\')) != -1)
{
/*
* Unless we escape the slash, StreamTokenizer will interpret the
* single slash and convert it assuming octal values.
* Two successive back slashes are intrepreted as one backslash.
*/
var newString = new StringBuilder(aString.Substring(0, index - 0));
for (var i = index; i < aString.Length; i++)
{
newString.Append(aString[i]);
if (aString[i] == '\\')
{
newString.Append('\\');
}
}
rawString = newString.ToString();
}
else
{
rawString = aString;
}
var st2 = new SchemaTokenCreator(new StringReader(rawString));
st2.OrdinaryCharacter('.');
st2.OrdinaryCharacters('0', '9');
st2.OrdinaryCharacter('{');
st2.OrdinaryCharacter('}');
st2.OrdinaryCharacter('_');
st2.OrdinaryCharacter(';');
st2.WordCharacters('.', '9');
st2.WordCharacters('{', '}');
st2.WordCharacters('_', '_');
st2.WordCharacters(';', ';');
//First parse out the OID
try
{
string currName;
if ((int) TokenTypes.EOF != st2.nextToken())
{
if (st2.lastttype == '(')
{
if ((int) TokenTypes.WORD == st2.nextToken())
{
id = st2.StringValue;
}
while ((int) TokenTypes.EOF != st2.nextToken())
{
if (st2.lastttype == (int) TokenTypes.WORD)
{
if (st2.StringValue.ToUpper().Equals("NAME".ToUpper()))
{
if (st2.nextToken() == '\'')
{
names = new string[1];
names[0] = st2.StringValue;
}
else
{
if (st2.lastttype == '(')
{
var nameList = new ArrayList();
while (st2.nextToken() == '\'')
{
if ((object) st2.StringValue != null)
{
nameList.Add(st2.StringValue);
}
}
if (nameList.Count > 0)
{
names = new string[nameList.Count];
SupportClass.ArrayListSupport.ToArray(nameList, names);
}
}
}
continue;
}
if (st2.StringValue.ToUpper().Equals("DESC".ToUpper()))
{
if (st2.nextToken() == '\'')
{
description = st2.StringValue;
}
continue;
}
if (st2.StringValue.ToUpper().Equals("SYNTAX".ToUpper()))
{
result = st2.nextToken();
if (result == (int) TokenTypes.WORD || result == '\'')
//Test for non-standard schema
{
syntax = st2.StringValue;
}
continue;
}
if (st2.StringValue.ToUpper().Equals("EQUALITY".ToUpper()))
{
if (st2.nextToken() == (int) TokenTypes.WORD)
{
equality = st2.StringValue;
}
continue;
}
if (st2.StringValue.ToUpper().Equals("ORDERING".ToUpper()))
{
if (st2.nextToken() == (int) TokenTypes.WORD)
{
ordering = st2.StringValue;
}
continue;
}
if (st2.StringValue.ToUpper().Equals("SUBSTR".ToUpper()))
{
if (st2.nextToken() == (int) TokenTypes.WORD)
{
substring = st2.StringValue;
}
continue;
}
if (st2.StringValue.ToUpper().Equals("FORM".ToUpper()))
{
if (st2.nextToken() == (int) TokenTypes.WORD)
{
nameForm = st2.StringValue;
}
continue;
}
if (st2.StringValue.ToUpper().Equals("OC".ToUpper()))
{
if (st2.nextToken() == (int) TokenTypes.WORD)
{
objectClass = st2.StringValue;
}
continue;
}
if (st2.StringValue.ToUpper().Equals("SUP".ToUpper()))
{
var values = new ArrayList();
st2.nextToken();
if (st2.lastttype == '(')
{
st2.nextToken();
while (st2.lastttype != ')')
{
if (st2.lastttype != '$')
{
values.Add(st2.StringValue);
}
st2.nextToken();
}
}
else
{
values.Add(st2.StringValue);
superior = st2.StringValue;
}
if (values.Count > 0)
{
superiors = new string[values.Count];
SupportClass.ArrayListSupport.ToArray(values, superiors);
}
continue;
}
if (st2.StringValue.ToUpper().Equals("SINGLE-VALUE".ToUpper()))
{
single = true;
continue;
}
if (st2.StringValue.ToUpper().Equals("OBSOLETE".ToUpper()))
{
obsolete = true;
continue;
}
if (st2.StringValue.ToUpper().Equals("COLLECTIVE".ToUpper()))
{
collective = true;
continue;
}
if (st2.StringValue.ToUpper().Equals("NO-USER-MODIFICATION".ToUpper()))
{
userMod = false;
continue;
}
if (st2.StringValue.ToUpper().Equals("MUST".ToUpper()))
{
var values = new ArrayList();
st2.nextToken();
if (st2.lastttype == '(')
{
st2.nextToken();
while (st2.lastttype != ')')
{
if (st2.lastttype != '$')
{
values.Add(st2.StringValue);
}
st2.nextToken();
}
}
else
{
values.Add(st2.StringValue);
}
if (values.Count > 0)
{
required = new string[values.Count];
SupportClass.ArrayListSupport.ToArray(values, required);
}
continue;
}
if (st2.StringValue.ToUpper().Equals("MAY".ToUpper()))
{
var values = new ArrayList();
st2.nextToken();
if (st2.lastttype == '(')
{
st2.nextToken();
while (st2.lastttype != ')')
{
if (st2.lastttype != '$')
{
values.Add(st2.StringValue);
}
st2.nextToken();
}
}
else
{
values.Add(st2.StringValue);
}
if (values.Count > 0)
{
optional = new string[values.Count];
SupportClass.ArrayListSupport.ToArray(values, optional);
}
continue;
}
if (st2.StringValue.ToUpper().Equals("NOT".ToUpper()))
{
var values = new ArrayList();
st2.nextToken();
if (st2.lastttype == '(')
{
st2.nextToken();
while (st2.lastttype != ')')
{
if (st2.lastttype != '$')
{
values.Add(st2.StringValue);
}
st2.nextToken();
}
}
else
{
values.Add(st2.StringValue);
}
if (values.Count > 0)
{
precluded = new string[values.Count];
SupportClass.ArrayListSupport.ToArray(values, precluded);
}
continue;
}
if (st2.StringValue.ToUpper().Equals("AUX".ToUpper()))
{
var values = new ArrayList();
st2.nextToken();
if (st2.lastttype == '(')
{
st2.nextToken();
while (st2.lastttype != ')')
{
if (st2.lastttype != '$')
{
values.Add(st2.StringValue);
}
st2.nextToken();
}
}
else
{
values.Add(st2.StringValue);
}
if (values.Count > 0)
{
auxiliary = new string[values.Count];
SupportClass.ArrayListSupport.ToArray(values, auxiliary);
}
continue;
}
if (st2.StringValue.ToUpper().Equals("ABSTRACT".ToUpper()))
{
type = LdapObjectClassSchema.ABSTRACT;
continue;
}
if (st2.StringValue.ToUpper().Equals("STRUCTURAL".ToUpper()))
{
type = LdapObjectClassSchema.STRUCTURAL;
continue;
}
if (st2.StringValue.ToUpper().Equals("AUXILIARY".ToUpper()))
{
type = LdapObjectClassSchema.AUXILIARY;
continue;
}
if (st2.StringValue.ToUpper().Equals("USAGE".ToUpper()))
{
if (st2.nextToken() == (int) TokenTypes.WORD)
{
currName = st2.StringValue;
if (currName.ToUpper().Equals("directoryOperation".ToUpper()))
{
usage = LdapAttributeSchema.DIRECTORY_OPERATION;
}
else if (currName.ToUpper().Equals("distributedOperation".ToUpper()))
{
usage = LdapAttributeSchema.DISTRIBUTED_OPERATION;
}
else if (currName.ToUpper().Equals("dSAOperation".ToUpper()))
{
usage = LdapAttributeSchema.DSA_OPERATION;
}
else if (currName.ToUpper().Equals("userApplications".ToUpper()))
{
usage = LdapAttributeSchema.USER_APPLICATIONS;
}
}
continue;
}
if (st2.StringValue.ToUpper().Equals("APPLIES".ToUpper()))
{
var values = new ArrayList();
st2.nextToken();
if (st2.lastttype == '(')
{
st2.nextToken();
while (st2.lastttype != ')')
{
if (st2.lastttype != '$')
{
values.Add(st2.StringValue);
}
st2.nextToken();
}
}
else
{
values.Add(st2.StringValue);
}
if (values.Count > 0)
{
applies = new string[values.Count];
SupportClass.ArrayListSupport.ToArray(values, applies);
}
continue;
}
currName = st2.StringValue;
var q = parseQualifier(st2, currName);
if (q != null)
{
qualifiers.Add(q);
}
}
}
}
}
}
catch (IOException e)
{
throw e;
}
}
private AttributeQualifier parseQualifier(SchemaTokenCreator st, string name)
{
var values = new ArrayList(5);
try
{
if (st.nextToken() == '\'')
{
values.Add(st.StringValue);
}
else
{
if (st.lastttype == '(')
{
while (st.nextToken() == '\'')
{
values.Add(st.StringValue);
}
}
}
}
catch (IOException e)
{
throw e;
}
var valArray = new string[values.Count];
valArray = (string[]) SupportClass.ArrayListSupport.ToArray(values, valArray);
return new AttributeQualifier(name, valArray);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Numerics;
using System.Linq;
using GlmSharp.Swizzle;
// ReSharper disable InconsistentNaming
namespace GlmSharp
{
/// <summary>
/// A matrix of type bool with 2 columns and 4 rows.
/// </summary>
[Serializable]
[DataContract(Namespace = "mat")]
[StructLayout(LayoutKind.Sequential)]
public struct bmat2x4 : IReadOnlyList<bool>, IEquatable<bmat2x4>
{
#region Fields
/// <summary>
/// Column 0, Rows 0
/// </summary>
[DataMember]
public bool m00;
/// <summary>
/// Column 0, Rows 1
/// </summary>
[DataMember]
public bool m01;
/// <summary>
/// Column 0, Rows 2
/// </summary>
[DataMember]
public bool m02;
/// <summary>
/// Column 0, Rows 3
/// </summary>
[DataMember]
public bool m03;
/// <summary>
/// Column 1, Rows 0
/// </summary>
[DataMember]
public bool m10;
/// <summary>
/// Column 1, Rows 1
/// </summary>
[DataMember]
public bool m11;
/// <summary>
/// Column 1, Rows 2
/// </summary>
[DataMember]
public bool m12;
/// <summary>
/// Column 1, Rows 3
/// </summary>
[DataMember]
public bool m13;
#endregion
#region Constructors
/// <summary>
/// Component-wise constructor
/// </summary>
public bmat2x4(bool m00, bool m01, bool m02, bool m03, bool m10, bool m11, bool m12, bool m13)
{
this.m00 = m00;
this.m01 = m01;
this.m02 = m02;
this.m03 = m03;
this.m10 = m10;
this.m11 = m11;
this.m12 = m12;
this.m13 = m13;
}
/// <summary>
/// Constructs this matrix from a bmat2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public bmat2x4(bmat2 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = false;
this.m03 = false;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = false;
this.m13 = false;
}
/// <summary>
/// Constructs this matrix from a bmat3x2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public bmat2x4(bmat3x2 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = false;
this.m03 = false;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = false;
this.m13 = false;
}
/// <summary>
/// Constructs this matrix from a bmat4x2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public bmat2x4(bmat4x2 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = false;
this.m03 = false;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = false;
this.m13 = false;
}
/// <summary>
/// Constructs this matrix from a bmat2x3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public bmat2x4(bmat2x3 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m03 = false;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m13 = false;
}
/// <summary>
/// Constructs this matrix from a bmat3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public bmat2x4(bmat3 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m03 = false;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m13 = false;
}
/// <summary>
/// Constructs this matrix from a bmat4x3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public bmat2x4(bmat4x3 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m03 = false;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m13 = false;
}
/// <summary>
/// Constructs this matrix from a bmat2x4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public bmat2x4(bmat2x4 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m03 = m.m03;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m13 = m.m13;
}
/// <summary>
/// Constructs this matrix from a bmat3x4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public bmat2x4(bmat3x4 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m03 = m.m03;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m13 = m.m13;
}
/// <summary>
/// Constructs this matrix from a bmat4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public bmat2x4(bmat4 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m03 = m.m03;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m13 = m.m13;
}
/// <summary>
/// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix.
/// </summary>
public bmat2x4(bvec2 c0, bvec2 c1)
{
this.m00 = c0.x;
this.m01 = c0.y;
this.m02 = false;
this.m03 = false;
this.m10 = c1.x;
this.m11 = c1.y;
this.m12 = false;
this.m13 = false;
}
/// <summary>
/// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix.
/// </summary>
public bmat2x4(bvec3 c0, bvec3 c1)
{
this.m00 = c0.x;
this.m01 = c0.y;
this.m02 = c0.z;
this.m03 = false;
this.m10 = c1.x;
this.m11 = c1.y;
this.m12 = c1.z;
this.m13 = false;
}
/// <summary>
/// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix.
/// </summary>
public bmat2x4(bvec4 c0, bvec4 c1)
{
this.m00 = c0.x;
this.m01 = c0.y;
this.m02 = c0.z;
this.m03 = c0.w;
this.m10 = c1.x;
this.m11 = c1.y;
this.m12 = c1.z;
this.m13 = c1.w;
}
#endregion
#region Properties
/// <summary>
/// Creates a 2D array with all values (address: Values[x, y])
/// </summary>
public bool[,] Values => new[,] { { m00, m01, m02, m03 }, { m10, m11, m12, m13 } };
/// <summary>
/// Creates a 1D array with all values (internal order)
/// </summary>
public bool[] Values1D => new[] { m00, m01, m02, m03, m10, m11, m12, m13 };
/// <summary>
/// Gets or sets the column nr 0
/// </summary>
public bvec4 Column0
{
get
{
return new bvec4(m00, m01, m02, m03);
}
set
{
m00 = value.x;
m01 = value.y;
m02 = value.z;
m03 = value.w;
}
}
/// <summary>
/// Gets or sets the column nr 1
/// </summary>
public bvec4 Column1
{
get
{
return new bvec4(m10, m11, m12, m13);
}
set
{
m10 = value.x;
m11 = value.y;
m12 = value.z;
m13 = value.w;
}
}
/// <summary>
/// Gets or sets the row nr 0
/// </summary>
public bvec2 Row0
{
get
{
return new bvec2(m00, m10);
}
set
{
m00 = value.x;
m10 = value.y;
}
}
/// <summary>
/// Gets or sets the row nr 1
/// </summary>
public bvec2 Row1
{
get
{
return new bvec2(m01, m11);
}
set
{
m01 = value.x;
m11 = value.y;
}
}
/// <summary>
/// Gets or sets the row nr 2
/// </summary>
public bvec2 Row2
{
get
{
return new bvec2(m02, m12);
}
set
{
m02 = value.x;
m12 = value.y;
}
}
/// <summary>
/// Gets or sets the row nr 3
/// </summary>
public bvec2 Row3
{
get
{
return new bvec2(m03, m13);
}
set
{
m03 = value.x;
m13 = value.y;
}
}
#endregion
#region Static Properties
/// <summary>
/// Predefined all-zero matrix
/// </summary>
public static bmat2x4 Zero { get; } = new bmat2x4(false, false, false, false, false, false, false, false);
/// <summary>
/// Predefined all-ones matrix
/// </summary>
public static bmat2x4 Ones { get; } = new bmat2x4(true, true, true, true, true, true, true, true);
/// <summary>
/// Predefined identity matrix
/// </summary>
public static bmat2x4 Identity { get; } = new bmat2x4(true, false, false, false, false, true, false, false);
#endregion
#region Functions
/// <summary>
/// Returns an enumerator that iterates through all fields.
/// </summary>
public IEnumerator<bool> GetEnumerator()
{
yield return m00;
yield return m01;
yield return m02;
yield return m03;
yield return m10;
yield return m11;
yield return m12;
yield return m13;
}
/// <summary>
/// Returns an enumerator that iterates through all fields.
/// </summary>
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
#endregion
/// <summary>
/// Returns the number of Fields (2 x 4 = 8).
/// </summary>
public int Count => 8;
/// <summary>
/// Gets/Sets a specific indexed component (a bit slower than direct access).
/// </summary>
public bool this[int fieldIndex]
{
get
{
switch (fieldIndex)
{
case 0: return m00;
case 1: return m01;
case 2: return m02;
case 3: return m03;
case 4: return m10;
case 5: return m11;
case 6: return m12;
case 7: return m13;
default: throw new ArgumentOutOfRangeException("fieldIndex");
}
}
set
{
switch (fieldIndex)
{
case 0: this.m00 = value; break;
case 1: this.m01 = value; break;
case 2: this.m02 = value; break;
case 3: this.m03 = value; break;
case 4: this.m10 = value; break;
case 5: this.m11 = value; break;
case 6: this.m12 = value; break;
case 7: this.m13 = value; break;
default: throw new ArgumentOutOfRangeException("fieldIndex");
}
}
}
/// <summary>
/// Gets/Sets a specific 2D-indexed component (a bit slower than direct access).
/// </summary>
public bool this[int col, int row]
{
get
{
return this[col * 4 + row];
}
set
{
this[col * 4 + row] = value;
}
}
/// <summary>
/// Returns true iff this equals rhs component-wise.
/// </summary>
public bool Equals(bmat2x4 rhs) => (((m00.Equals(rhs.m00) && m01.Equals(rhs.m01)) && (m02.Equals(rhs.m02) && m03.Equals(rhs.m03))) && ((m10.Equals(rhs.m10) && m11.Equals(rhs.m11)) && (m12.Equals(rhs.m12) && m13.Equals(rhs.m13))));
/// <summary>
/// Returns true iff this equals rhs type- and component-wise.
/// </summary>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
return obj is bmat2x4 && Equals((bmat2x4) obj);
}
/// <summary>
/// Returns true iff this equals rhs component-wise.
/// </summary>
public static bool operator ==(bmat2x4 lhs, bmat2x4 rhs) => lhs.Equals(rhs);
/// <summary>
/// Returns true iff this does not equal rhs (component-wise).
/// </summary>
public static bool operator !=(bmat2x4 lhs, bmat2x4 rhs) => !lhs.Equals(rhs);
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
public override int GetHashCode()
{
unchecked
{
return ((((((((((((((m00.GetHashCode()) * 2) ^ m01.GetHashCode()) * 2) ^ m02.GetHashCode()) * 2) ^ m03.GetHashCode()) * 2) ^ m10.GetHashCode()) * 2) ^ m11.GetHashCode()) * 2) ^ m12.GetHashCode()) * 2) ^ m13.GetHashCode();
}
}
/// <summary>
/// Returns a transposed version of this matrix.
/// </summary>
public bmat4x2 Transposed => new bmat4x2(m00, m10, m01, m11, m02, m12, m03, m13);
/// <summary>
/// Returns the minimal component of this matrix.
/// </summary>
public bool MinElement => (((m00 && m01) && (m02 && m03)) && ((m10 && m11) && (m12 && m13)));
/// <summary>
/// Returns the maximal component of this matrix.
/// </summary>
public bool MaxElement => (((m00 || m01) || (m02 || m03)) || ((m10 || m11) || (m12 || m13)));
/// <summary>
/// Returns true if all component are true.
/// </summary>
public bool All => (((m00 && m01) && (m02 && m03)) && ((m10 && m11) && (m12 && m13)));
/// <summary>
/// Returns true if any component is true.
/// </summary>
public bool Any => (((m00 || m01) || (m02 || m03)) || ((m10 || m11) || (m12 || m13)));
/// <summary>
/// Executes a component-wise &&. (sorry for different overload but && cannot be overloaded directly)
/// </summary>
public static bmat2x4 operator&(bmat2x4 lhs, bmat2x4 rhs) => new bmat2x4(lhs.m00 && rhs.m00, lhs.m01 && rhs.m01, lhs.m02 && rhs.m02, lhs.m03 && rhs.m03, lhs.m10 && rhs.m10, lhs.m11 && rhs.m11, lhs.m12 && rhs.m12, lhs.m13 && rhs.m13);
/// <summary>
/// Executes a component-wise ||. (sorry for different overload but || cannot be overloaded directly)
/// </summary>
public static bmat2x4 operator|(bmat2x4 lhs, bmat2x4 rhs) => new bmat2x4(lhs.m00 || rhs.m00, lhs.m01 || rhs.m01, lhs.m02 || rhs.m02, lhs.m03 || rhs.m03, lhs.m10 || rhs.m10, lhs.m11 || rhs.m11, lhs.m12 || rhs.m12, lhs.m13 || rhs.m13);
}
}
| |
//
// StrongName.cs - Strong Name Implementation
//
// Author:
// Sebastien Pouliot (sebastien@ximian.com)
//
// (C) 2003 Motus Technologies Inc. (http://www.motus.com)
// (C) 2004 Novell (http://www.novell.com)
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Configuration.Assemblies;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Security.Cryptography;
using Mono.Security.Cryptography;
namespace Mono.Security {
#if INSIDE_CORLIB
internal
#else
public
#endif
sealed class StrongName {
internal class StrongNameSignature {
private byte[] hash;
private byte[] signature;
private UInt32 signaturePosition;
private UInt32 signatureLength;
private UInt32 metadataPosition;
private UInt32 metadataLength;
private byte cliFlag;
private UInt32 cliFlagPosition;
public byte[] Hash {
get { return hash; }
set { hash = value; }
}
public byte[] Signature {
get { return signature; }
set { signature = value; }
}
public UInt32 MetadataPosition {
get { return metadataPosition; }
set { metadataPosition = value; }
}
public UInt32 MetadataLength {
get { return metadataLength; }
set { metadataLength = value; }
}
public UInt32 SignaturePosition {
get { return signaturePosition; }
set { signaturePosition = value; }
}
public UInt32 SignatureLength {
get { return signatureLength; }
set { signatureLength = value; }
}
// delay signed -> flag = 0x01
// strongsigned -> flag = 0x09
public byte CliFlag {
get { return cliFlag; }
set { cliFlag = value; }
}
public UInt32 CliFlagPosition {
get { return cliFlagPosition; }
set { cliFlagPosition = value; }
}
}
internal enum StrongNameOptions {
Metadata,
Signature
}
private RSA rsa;
private byte[] publicKey;
private byte[] keyToken;
private string tokenAlgorithm;
public StrongName ()
{
}
public StrongName (int keySize)
{
rsa = new RSAManaged (keySize);
}
public StrongName (byte[] data)
{
if (data == null)
throw new ArgumentNullException ("data");
// check for ECMA key
if (data.Length == 16) {
int i = 0;
int sum = 0;
while (i < data.Length)
sum += data [i++];
if (sum == 4) {
// it is the ECMA key
publicKey = (byte[]) data.Clone ();
}
}
else {
RSA = CryptoConvert.FromCapiKeyBlob (data);
if (rsa == null)
throw new ArgumentException ("data isn't a correctly encoded RSA public key");
}
}
public StrongName (RSA rsa)
{
if (rsa == null)
throw new ArgumentNullException ("rsa");
RSA = rsa;
}
private void InvalidateCache ()
{
publicKey = null;
keyToken = null;
}
public bool CanSign {
get {
if (rsa == null)
return false;
#if INSIDE_CORLIB
// the easy way
if (RSA is RSACryptoServiceProvider) {
// available as internal for corlib
return !(rsa as RSACryptoServiceProvider).PublicOnly;
}
else
#endif
if (RSA is RSAManaged) {
return !(rsa as RSAManaged).PublicOnly;
}
else {
// the hard way
try {
RSAParameters p = rsa.ExportParameters (true);
return ((p.D != null) && (p.P != null) && (p.Q != null));
}
catch (CryptographicException) {
return false;
}
}
}
}
public RSA RSA {
get {
// if none then we create a new keypair
if (rsa == null)
rsa = (RSA) RSA.Create ();
return rsa;
}
set {
rsa = value;
InvalidateCache ();
}
}
public byte[] PublicKey {
get {
if (publicKey == null) {
byte[] keyPair = CryptoConvert.ToCapiKeyBlob (rsa, false);
// since 2.0 public keys can vary from 384 to 16384 bits
publicKey = new byte [32 + (rsa.KeySize >> 3)];
// The first 12 bytes are documented at:
// http://msdn.microsoft.com/library/en-us/cprefadd/html/grfungethashfromfile.asp
// ALG_ID - Signature
publicKey [0] = keyPair [4];
publicKey [1] = keyPair [5];
publicKey [2] = keyPair [6];
publicKey [3] = keyPair [7];
// ALG_ID - Hash (SHA1 == 0x8004)
publicKey [4] = 0x04;
publicKey [5] = 0x80;
publicKey [6] = 0x00;
publicKey [7] = 0x00;
// Length of Public Key (in bytes)
byte[] lastPart = BitConverterLE.GetBytes (publicKey.Length - 12);
publicKey [8] = lastPart [0];
publicKey [9] = lastPart [1];
publicKey [10] = lastPart [2];
publicKey [11] = lastPart [3];
// Ok from here - Same structure as keypair - expect for public key
publicKey [12] = 0x06; // PUBLICKEYBLOB
// we can copy this part
Buffer.BlockCopy (keyPair, 1, publicKey, 13, publicKey.Length - 13);
// and make a small adjustment
publicKey [23] = 0x31; // (RSA1 not RSA2)
}
return (byte[]) publicKey.Clone ();
}
}
public byte[] PublicKeyToken {
get {
if (keyToken == null) {
byte[] publicKey = PublicKey;
if (publicKey == null)
return null;
HashAlgorithm ha = HashAlgorithm.Create (TokenAlgorithm);
byte[] hash = ha.ComputeHash (publicKey);
// we need the last 8 bytes in reverse order
keyToken = new byte [8];
Buffer.BlockCopy (hash, (hash.Length - 8), keyToken, 0, 8);
Array.Reverse (keyToken, 0, 8);
}
return (byte[]) keyToken.Clone ();
}
}
public string TokenAlgorithm {
get {
if (tokenAlgorithm == null)
tokenAlgorithm = "SHA1";
return tokenAlgorithm;
}
set {
string algo = value.ToUpper (CultureInfo.InvariantCulture);
if ((algo == "SHA1") || (algo == "MD5")) {
tokenAlgorithm = value;
InvalidateCache ();
}
else
throw new ArgumentException ("Unsupported hash algorithm for token");
}
}
public byte[] GetBytes ()
{
return CryptoConvert.ToCapiPrivateKeyBlob (RSA);
}
private UInt32 RVAtoPosition (UInt32 r, int sections, byte[] headers)
{
for (int i=0; i < sections; i++) {
UInt32 p = BitConverterLE.ToUInt32 (headers, i * 40 + 20);
UInt32 s = BitConverterLE.ToUInt32 (headers, i * 40 + 12);
int l = (int) BitConverterLE.ToUInt32 (headers, i * 40 + 8);
if ((s <= r) && (r < s + l)) {
return p + r - s;
}
}
return 0;
}
internal StrongNameSignature StrongHash (Stream stream, StrongNameOptions options)
{
StrongNameSignature info = new StrongNameSignature ();
HashAlgorithm hash = HashAlgorithm.Create (TokenAlgorithm);
CryptoStream cs = new CryptoStream (Stream.Null, hash, CryptoStreamMode.Write);
// MS-DOS Header - always 128 bytes
// ref: Section 24.2.1, Partition II Metadata
byte[] mz = new byte [128];
stream.Read (mz, 0, 128);
if (BitConverterLE.ToUInt16 (mz, 0) != 0x5a4d)
return null;
UInt32 peHeader = BitConverterLE.ToUInt32 (mz, 60);
cs.Write (mz, 0, 128);
if (peHeader != 128) {
byte[] mzextra = new byte [peHeader - 128];
stream.Read (mzextra, 0, mzextra.Length);
cs.Write (mzextra, 0, mzextra.Length);
}
// PE File Header - always 248 bytes
// ref: Section 24.2.2, Partition II Metadata
byte[] pe = new byte [248];
stream.Read (pe, 0, 248);
if (BitConverterLE.ToUInt32 (pe, 0) != 0x4550)
return null;
if (BitConverterLE.ToUInt16 (pe, 4) != 0x14c)
return null;
// MUST zeroize both CheckSum and Security Directory
byte[] v = new byte [8];
Buffer.BlockCopy (v, 0, pe, 88, 4);
Buffer.BlockCopy (v, 0, pe, 152, 8);
cs.Write (pe, 0, 248);
UInt16 numSection = BitConverterLE.ToUInt16 (pe, 6);
int sectionLength = (numSection * 40);
byte[] sectionHeaders = new byte [sectionLength];
stream.Read (sectionHeaders, 0, sectionLength);
cs.Write (sectionHeaders, 0, sectionLength);
UInt32 cliHeaderRVA = BitConverterLE.ToUInt32 (pe, 232);
UInt32 cliHeaderPos = RVAtoPosition (cliHeaderRVA, numSection, sectionHeaders);
int cliHeaderSiz = (int) BitConverterLE.ToUInt32 (pe, 236);
// CLI Header
// ref: Section 24.3.3, Partition II Metadata
byte[] cli = new byte [cliHeaderSiz];
stream.Position = cliHeaderPos;
stream.Read (cli, 0, cliHeaderSiz);
UInt32 strongNameSignatureRVA = BitConverterLE.ToUInt32 (cli, 32);
info.SignaturePosition = RVAtoPosition (strongNameSignatureRVA, numSection, sectionHeaders);
info.SignatureLength = BitConverterLE.ToUInt32 (cli, 36);
UInt32 metadataRVA = BitConverterLE.ToUInt32 (cli, 8);
info.MetadataPosition = RVAtoPosition (metadataRVA, numSection, sectionHeaders);
info.MetadataLength = BitConverterLE.ToUInt32 (cli, 12);
if (options == StrongNameOptions.Metadata) {
cs.Close ();
hash.Initialize ();
byte[] metadata = new byte [info.MetadataLength];
stream.Position = info.MetadataPosition;
stream.Read (metadata, 0, metadata.Length);
info.Hash = hash.ComputeHash (metadata);
return info;
}
// now we hash every section EXCEPT the signature block
for (int i=0; i < numSection; i++) {
UInt32 start = BitConverterLE.ToUInt32 (sectionHeaders, i * 40 + 20);
int length = (int) BitConverterLE.ToUInt32 (sectionHeaders, i * 40 + 16);
byte[] section = new byte [length];
stream.Position = start;
stream.Read (section, 0, length);
if ((start <= info.SignaturePosition) && (info.SignaturePosition < start + length)) {
// hash before the signature
int before = (int)(info.SignaturePosition - start);
if (before > 0) {
cs.Write (section, 0, before);
}
// copy signature
info.Signature = new byte [info.SignatureLength];
Buffer.BlockCopy (section, before, info.Signature, 0, (int)info.SignatureLength);
Array.Reverse (info.Signature);
// hash after the signature
int s = (int)(before + info.SignatureLength);
int after = (int)(length - s);
if (after > 0) {
cs.Write (section, s, after);
}
}
else
cs.Write (section, 0, length);
}
cs.Close ();
info.Hash = hash.Hash;
return info;
}
// return the same result as the undocumented and unmanaged GetHashFromAssemblyFile
public byte[] Hash (string fileName)
{
FileStream fs = File.OpenRead (fileName);
StrongNameSignature sn = StrongHash (fs, StrongNameOptions.Metadata);
fs.Close ();
return sn.Hash;
}
public bool Sign (string fileName)
{
bool result = false;
StrongNameSignature sn;
using (FileStream fs = File.OpenRead (fileName)) {
sn = StrongHash (fs, StrongNameOptions.Signature);
fs.Close ();
}
if (sn.Hash == null)
return false;
byte[] signature = null;
try {
RSAPKCS1SignatureFormatter sign = new RSAPKCS1SignatureFormatter (rsa);
sign.SetHashAlgorithm (TokenAlgorithm);
signature = sign.CreateSignature (sn.Hash);
Array.Reverse (signature);
}
catch (CryptographicException) {
return false;
}
using (FileStream fs = File.OpenWrite (fileName)) {
fs.Position = sn.SignaturePosition;
fs.Write (signature, 0, signature.Length);
fs.Close ();
result = true;
}
return result;
}
public bool Verify (string fileName)
{
bool result = false;
using (FileStream fs = File.OpenRead (fileName)) {
result = Verify (fs);
fs.Close ();
}
return result;
}
public bool Verify (Stream stream)
{
StrongNameSignature sn = StrongHash (stream, StrongNameOptions.Signature);
if (sn.Hash == null) {
return false;
}
try {
AssemblyHashAlgorithm algorithm = AssemblyHashAlgorithm.SHA1;
if (tokenAlgorithm == "MD5")
algorithm = AssemblyHashAlgorithm.MD5;
return Verify (rsa, algorithm, sn.Hash, sn.Signature);
}
catch (CryptographicException) {
// no exception allowed
return false;
}
}
#if INSIDE_CORLIB
static object lockObject = new object ();
static bool initialized = false;
// We don't want a dependency on StrongNameManager in Mono.Security.dll
static public bool IsAssemblyStrongnamed (string assemblyName)
{
if (!initialized) {
lock (lockObject) {
if (!initialized) {
string config = Environment.GetMachineConfigPath ();
StrongNameManager.LoadConfig (config);
initialized = true;
}
}
}
try {
// this doesn't load the assembly (well it unloads it ;)
// http://weblogs.asp.net/nunitaddin/posts/9991.aspx
AssemblyName an = AssemblyName.GetAssemblyName (assemblyName);
if (an == null)
return false;
byte[] publicKey = StrongNameManager.GetMappedPublicKey (an.GetPublicKeyToken ());
if ((publicKey == null) || (publicKey.Length < 12)) {
// no mapping
publicKey = an.GetPublicKey ();
if ((publicKey == null) || (publicKey.Length < 12))
return false;
}
// Note: MustVerify is based on the original token (by design). Public key
// remapping won't affect if the assembly is verified or not.
if (!StrongNameManager.MustVerify (an)) {
return true;
}
RSA rsa = CryptoConvert.FromCapiPublicKeyBlob (publicKey, 12);
StrongName sn = new StrongName (rsa);
bool result = sn.Verify (assemblyName);
return result;
}
catch {
// no exception allowed
return false;
}
}
// TODO
// we would get better performance if the runtime hashed the
// assembly - as we wouldn't have to load it from disk a
// second time. The runtime already have implementations of
// SHA1 (and even MD5 if required someday).
static public bool VerifySignature (byte[] publicKey, int algorithm, byte[] hash, byte[] signature)
{
try {
RSA rsa = CryptoConvert.FromCapiPublicKeyBlob (publicKey);
return Verify (rsa, (AssemblyHashAlgorithm) algorithm, hash, signature);
}
catch {
// no exception allowed
return false;
}
}
#endif
static private bool Verify (RSA rsa, AssemblyHashAlgorithm algorithm, byte[] hash, byte[] signature)
{
RSAPKCS1SignatureDeformatter vrfy = new RSAPKCS1SignatureDeformatter (rsa);
switch (algorithm) {
case AssemblyHashAlgorithm.MD5:
vrfy.SetHashAlgorithm ("MD5");
break;
case AssemblyHashAlgorithm.SHA1:
case AssemblyHashAlgorithm.None:
default:
vrfy.SetHashAlgorithm ("SHA1");
break;
}
return vrfy.VerifySignature (hash, signature);
}
}
}
| |
/*
* CCControl.h
*
* Copyright 2011 Yannick Loriot.
* http://yannickloriot.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* Converted to c++ / cocos2d-x by Angus C
*/
using System;
using System.Collections.Generic;
namespace CocosSharp
{
/** Kinds of possible events for the control objects. */
[Flags]
public enum CCControlEvent
{
TouchDown = 1 << 0, // A touch-down event in the control.
TouchDragInside = 1 << 1, // An event where a finger is dragged inside the bounds of the control.
TouchDragOutside = 1 << 2, // An event where a finger is dragged just outside the bounds of the control.
TouchDragEnter = 1 << 3, // An event where a finger is dragged into the bounds of the control.
TouchDragExit = 1 << 4, // An event where a finger is dragged from within a control to outside its bounds.
TouchUpInside = 1 << 5, // A touch-up event in the control where the finger is inside the bounds of the control.
TouchUpOutside = 1 << 6, // A touch-up event in the control where the finger is outside the bounds of the control.
TouchCancel = 1 << 7, // A system event canceling the current touches for the control.
ValueChanged = 1 << 8 // A touch dragging or otherwise manipulating a control, causing it to emit a series of different values.
}
/** The possible state for a control. */
[Flags]
public enum CCControlState
{
Normal = 1 << 0, // The normal, or default state of a control that is, enabled but neither selected nor highlighted.
Highlighted = 1 << 1, // Highlighted state of a control. A control enters this state when a touch down, drag inside or drag enter is performed. You can retrieve and set this value through the highlighted property.
Disabled = 1 << 2, // Disabled state of a control. This state indicates that the control is currently disabled. You can retrieve and set this value through the enabled property.
Selected = 1 << 3 // Selected state of a control. This state indicates that the control is currently selected. You can retrieve and set this value through the selected property.
}
/*
* @class
* CCControl is inspired by the UIControl API class from the UIKit library of
* CocoaTouch. It provides a base class for control CCSprites such as CCButton
* or CCSlider that convey user intent to the application.
*
* The goal of CCControl is to define an interface and base implementation for
* preparing action messages and initially dispatching them to their targets when
* certain events occur.
*
* To use the CCControl you have to subclass it.
*/
public class CCControl : CCNode
{
#region Events and Handlers
public class CCControlEventArgs : EventArgs
{
public CCControlEventArgs(CCControlEvent controlEvent)
{
ControlEvent = controlEvent;
}
public CCControlEvent ControlEvent { get; protected internal set; }
}
public event EventHandler<CCControlEventArgs> ValueChanged;
public event EventHandler<CCControlEventArgs> TouchDown;
public event EventHandler<CCControlEventArgs> TouchDragInside;
public event EventHandler<CCControlEventArgs> TouchDragOutside;
public event EventHandler<CCControlEventArgs> TouchDragEnter;
public event EventHandler<CCControlEventArgs> TouchDragExit;
public event EventHandler<CCControlEventArgs> TouchUpInside;
public event EventHandler<CCControlEventArgs> TouchUpOutside;
public event EventHandler<CCControlEventArgs> TouchCancel;
#endregion
bool enabled;
bool highlighted;
bool selected;
bool isColorModifiedByOpacity;
#region Properties
public int DefaultTouchPriority { get; set; } // Changes the priority of the button. The lower the number, the higher the priority.
public CCControlState State { get; set; }
public override bool IsColorModifiedByOpacity
{
get { return isColorModifiedByOpacity; }
set
{
isColorModifiedByOpacity = value;
if (Children != null)
{
foreach (CCNode child in Children.Elements)
{
var item = child;
if (item != null) {
item.IsColorModifiedByOpacity = value;
}
}
}
}
}
public virtual bool Enabled
{
get { return enabled; }
set
{
enabled = value;
if (enabled)
{
State = CCControlState.Normal;
}
else
{
State = CCControlState.Disabled;
}
NeedsLayout();
}
}
public virtual bool Selected
{
get { return selected; }
set
{
selected = value;
NeedsLayout();
}
}
public virtual bool Highlighted
{
get { return highlighted; }
set
{
highlighted = value;
NeedsLayout();
}
}
public bool HasVisibleParents
{
get
{
CCNode parent = Parent;
for (CCNode c = parent; c != null; c = c.Parent)
{
if (!c.Visible)
{
return false;
}
}
return true;
}
}
#endregion Properties
#region EventHandlers
protected virtual void OnValueChanged()
{
EventHandler<CCControlEventArgs> handler = ValueChanged;
if (handler != null)
{
handler(this, new CCControlEventArgs(CCControlEvent.ValueChanged));
}
}
protected virtual void OnTouchDown()
{
EventHandler<CCControlEventArgs> handler = TouchDown;
if (handler != null)
{
handler(this, new CCControlEventArgs(CCControlEvent.TouchDown));
}
}
protected virtual void OnTouchDragInside()
{
EventHandler<CCControlEventArgs> handler = TouchDragInside;
if (handler != null)
{
handler(this, new CCControlEventArgs(CCControlEvent.TouchDragInside));
}
}
protected virtual void OnTouchDragOutside()
{
EventHandler<CCControlEventArgs> handler = TouchDragOutside;
if (handler != null)
{
handler(this, new CCControlEventArgs(CCControlEvent.TouchDragOutside));
}
}
protected virtual void OnTouchDragEnter()
{
EventHandler<CCControlEventArgs> handler = TouchDragEnter;
if (handler != null)
{
handler(this, new CCControlEventArgs(CCControlEvent.TouchDragEnter));
}
}
protected virtual void OnTouchDragExit()
{
EventHandler<CCControlEventArgs> handler = TouchDragExit;
if (handler != null)
{
handler(this, new CCControlEventArgs(CCControlEvent.TouchDragExit));
}
}
protected virtual void OnTouchUpInside()
{
EventHandler<CCControlEventArgs> handler = TouchUpInside;
if (handler != null)
{
handler(this, new CCControlEventArgs(CCControlEvent.TouchUpInside));
}
}
protected virtual void OnTouchUpOutside()
{
EventHandler<CCControlEventArgs> handler = TouchUpOutside;
if (handler != null)
{
handler(this, new CCControlEventArgs(CCControlEvent.TouchUpOutside));
}
}
protected virtual void OnTouchCancel()
{
EventHandler<CCControlEventArgs> handler = TouchCancel;
if (handler != null)
{
handler(this, new CCControlEventArgs(CCControlEvent.TouchCancel));
}
}
#endregion
#region Constructors
public CCControl()
{
State = CCControlState.Normal;
Enabled = true;
Selected = false;
Highlighted = false;
DefaultTouchPriority = 1;
}
#endregion Constructors
public virtual void NeedsLayout()
{
}
/**
* Returns a point corresponding to the touh location converted into the
* control space coordinates.
* @param touch A CCTouch object that represents a touch.
*/
public virtual CCPoint GetTouchLocation(CCTouch touch)
{
CCPoint touchLocation = touch.LocationOnScreen; // Get the touch position
touchLocation = WorldToParentspace(Layer.ScreenToWorldspace(touchLocation)); // Convert to the node space of this class
return touchLocation;
}
/**
* Returns a boolean value that indicates whether a touch is inside the bounds
* of the receiver. The given touch must be relative to the world.
*
* @param touch A CCTouch object that represents a touch.
*
* @return YES whether a touch is inside the receivers rect.
*/
public virtual bool IsTouchInside(CCTouch touch)
{
CCPoint touchLocation = touch.LocationOnScreen;
touchLocation = Parent.Layer.ScreenToWorldspace(touchLocation);
CCRect bBox = BoundingBoxTransformedToWorld;
return bBox.ContainsPoint(touchLocation);
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="StreamOfStreams.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using Akka.Pattern;
using Akka.Streams.Actors;
using Akka.Streams.Dsl;
using Akka.Streams.Implementation.Stages;
using Akka.Streams.Stage;
using Akka.Streams.Util;
using Akka.Util;
using Reactive.Streams;
namespace Akka.Streams.Implementation.Fusing
{
internal sealed class FlattenMerge<TGraph, T, TMat> : GraphStage<FlowShape<TGraph, T>> where TGraph : IGraph<SourceShape<T>, TMat>
{
#region internal classes
private sealed class Logic : GraphStageLogic
{
private readonly FlattenMerge<TGraph, T, TMat> _stage;
private readonly HashSet<SubSinkInlet<T>> _sources = new HashSet<SubSinkInlet<T>>();
private IBuffer<SubSinkInlet<T>> _q;
private readonly Action _outHandler;
public Logic(FlattenMerge<TGraph, T, TMat> stage) : base(stage.Shape)
{
_stage = stage;
_outHandler = () =>
{
// could be unavailable due to async input having been executed before this notification
if (_q.NonEmpty && IsAvailable(_stage._out))
PushOut();
};
SetHandler(_stage._in,
onPush: () =>
{
var source = Grab(_stage._in);
AddSource(source);
if (ActiveSources < _stage._breadth)
TryPull(_stage._in);
},
onUpstreamFinish: () =>
{
if (ActiveSources == 0)
CompleteStage();
});
SetHandler(_stage._out,
onPull: () =>
{
Pull(_stage._in);
SetHandler(_stage._out, _outHandler);
});
}
private int ActiveSources => _sources.Count;
public override void PreStart()
=> _q = Buffer.Create<SubSinkInlet<T>>(_stage._breadth, Interpreter.Materializer);
public override void PostStop()
{
foreach (var source in _sources)
source.Cancel();
}
private void PushOut()
{
var src = _q.Dequeue();
Push(_stage._out, src.Grab());
if (!src.IsClosed)
src.Pull();
else
RemoveSource(src);
}
private void RemoveSource(SubSinkInlet<T> src)
{
var pullSuppressed = ActiveSources == _stage._breadth;
_sources.Remove(src);
if (pullSuppressed)
TryPull(_stage._in);
if (ActiveSources == 0 && IsClosed(_stage._in))
CompleteStage();
}
private void AddSource(IGraph<SourceShape<T>, TMat> source)
{
var sinkIn = CreateSubSinkInlet<T>("FlattenMergeSink");
sinkIn.SetHandler(new LambdaInHandler(
onPush: () =>
{
if (IsAvailable(_stage._out))
{
Push(_stage._out, sinkIn.Grab());
sinkIn.Pull();
}
else
_q.Enqueue(sinkIn);
},
onUpstreamFinish: () =>
{
if (!sinkIn.IsAvailable)
RemoveSource(sinkIn);
}));
sinkIn.Pull();
_sources.Add(sinkIn);
Source.FromGraph(source).RunWith(sinkIn.Sink, Interpreter.SubFusingMaterializer);
}
public override string ToString() => $"FlattenMerge({_stage._breadth})";
}
#endregion
private readonly Inlet<TGraph> _in = new Inlet<TGraph>("flatten.in");
private readonly Outlet<T> _out = new Outlet<T>("flatten.out");
private readonly int _breadth;
public FlattenMerge(int breadth)
{
_breadth = breadth;
InitialAttributes = DefaultAttributes.FlattenMerge;
Shape = new FlowShape<TGraph, T>(_in, _out);
}
protected override Attributes InitialAttributes { get; }
public override FlowShape<TGraph, T> Shape { get; }
protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this);
public override string ToString() => $"FlattenMerge({_breadth})";
}
/// <summary>
/// INTERNAL API
/// </summary>
internal sealed class PrefixAndTail<T> : GraphStage<FlowShape<T, Tuple<IImmutableList<T>, Source<T, NotUsed>>>>
{
#region internal classes
private sealed class Logic : TimerGraphStageLogic
{
private const string SubscriptionTimer = "SubstreamSubscriptionTimer";
private readonly PrefixAndTail<T> _stage;
private readonly LambdaOutHandler _subHandler;
private int _left;
private ImmutableList<T>.Builder _builder;
private SubSourceOutlet<T> _tailSource;
public Logic(PrefixAndTail<T> stage) : base(stage.Shape)
{
_stage = stage;
_left = _stage._count < 0 ? 0 : _stage._count;
_builder = ImmutableList<T>.Empty.ToBuilder();
_subHandler = new LambdaOutHandler(onPull: () =>
{
SetKeepGoing(false);
CancelTimer(SubscriptionTimer);
Pull(_stage._in);
_tailSource.SetHandler(new LambdaOutHandler(onPull: () => Pull(_stage._in)));
});
SetHandler(_stage._in,
onPush: OnPush,
onUpstreamFinish: OnUpstreamFinish,
onUpstreamFailure: OnUpstreamFailure);
SetHandler(_stage._out,
onPull: OnPull,
onDownstreamFinish: OnDownstreamFinish);
}
protected internal override void OnTimer(object timerKey)
{
var materializer = ActorMaterializer.Downcast(Interpreter.Materializer);
var timeoutSettings = materializer.Settings.SubscriptionTimeoutSettings;
var timeout = timeoutSettings.Timeout;
_tailSource.Timeout(timeout);
if (_tailSource.IsClosed)
CompleteStage();
}
private bool IsPrefixComplete => ReferenceEquals(_builder, null);
private Source<T, NotUsed> OpenSubstream()
{
var timeout = ActorMaterializer.Downcast(Interpreter.Materializer).Settings.SubscriptionTimeoutSettings.Timeout;
_tailSource = new SubSourceOutlet<T>(this, "TailSource");
_tailSource.SetHandler(_subHandler);
SetKeepGoing(true);
ScheduleOnce(SubscriptionTimer, timeout);
_builder = null;
return Source.FromGraph(_tailSource.Source);
}
private void OnPush()
{
if (IsPrefixComplete)
_tailSource.Push(Grab(_stage._in));
else
{
_builder.Add(Grab(_stage._in));
_left--;
if (_left == 0)
{
Push(_stage._out, Tuple.Create((IImmutableList<T>) _builder.ToImmutable(), OpenSubstream()));
Complete(_stage._out);
}
else
Pull(_stage._in);
}
}
private void OnPull()
{
if (_left == 0)
{
Push(_stage._out, Tuple.Create((IImmutableList<T>) ImmutableList<T>.Empty, OpenSubstream()));
Complete(_stage._out);
}
else
Pull(_stage._in);
}
private void OnUpstreamFinish()
{
if (!IsPrefixComplete)
{
// This handles the unpulled out case as well
Emit(_stage._out, Tuple.Create((IImmutableList<T>) _builder.ToImmutable(), Source.Empty<T>()), CompleteStage);
}
else
{
if(!_tailSource.IsClosed)
_tailSource.Complete();
CompleteStage();
}
}
private void OnUpstreamFailure(Exception ex)
{
if (IsPrefixComplete)
{
if (!_tailSource.IsClosed)
_tailSource.Fail(ex);
CompleteStage();
}
else
FailStage(ex);
}
private void OnDownstreamFinish()
{
if (!IsPrefixComplete)
CompleteStage();
// Otherwise substream is open, ignore
}
}
#endregion
private readonly int _count;
private readonly Inlet<T> _in = new Inlet<T>("PrefixAndTail.in");
private readonly Outlet<Tuple<IImmutableList<T>, Source<T, NotUsed>>> _out = new Outlet<Tuple<IImmutableList<T>, Source<T, NotUsed>>>("PrefixAndTail.out");
public PrefixAndTail(int count)
{
_count = count;
Shape = new FlowShape<T, Tuple<IImmutableList<T>, Source<T, NotUsed>>>(_in, _out);
}
protected override Attributes InitialAttributes { get; } = DefaultAttributes.PrefixAndTail;
public override FlowShape<T, Tuple<IImmutableList<T>, Source<T, NotUsed>>> Shape { get; }
protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this);
public override string ToString() => $"PrefixAndTail({_count})";
}
/// <summary>
/// INTERNAL API
/// </summary>
internal static class Split
{
internal enum SplitDecision
{
SplitBefore,
SplitAfter
}
public static IGraph<FlowShape<T, Source<T, NotUsed>>, NotUsed> When<T>(Func<T, bool> p, SubstreamCancelStrategy substreamCancelStrategy) => new Split<T>(SplitDecision.SplitBefore, p, substreamCancelStrategy);
public static IGraph<FlowShape<T, Source<T, NotUsed>>, NotUsed> After<T>(Func<T, bool> p, SubstreamCancelStrategy substreamCancelStrategy) => new Split<T>(SplitDecision.SplitAfter, p, substreamCancelStrategy);
}
/// <summary>
/// INTERNAL API
/// </summary>
internal sealed class Split<T> : GraphStage<FlowShape<T, Source<T, NotUsed>>>
{
#region internal classes
private sealed class Logic : TimerGraphStageLogic
{
#region internal classes
private sealed class SubstreamHandler : InAndOutHandler
{
private readonly Logic _logic;
private bool _willCompleteAfterInitialElement;
public SubstreamHandler(Logic logic)
{
_logic = logic;
}
public bool HasInitialElement => FirstElement.HasValue;
public Option<T> FirstElement { private get; set; }
private void CloseThis(SubstreamHandler handler, T currentElem)
{
var decision = _logic._stage._decision;
if (decision == Split.SplitDecision.SplitAfter)
{
if (!_logic._substreamCancelled)
{
_logic._substreamSource.Push(currentElem);
_logic._substreamSource.Complete();
}
}
else if (decision == Split.SplitDecision.SplitBefore)
{
handler.FirstElement = currentElem;
if (!_logic._substreamCancelled)
_logic._substreamSource.Complete();
}
}
public override void OnPull()
{
if (HasInitialElement)
{
_logic._substreamSource.Push(FirstElement.Value);
FirstElement = Option<T>.None;
_logic.SetKeepGoing(false);
if (_willCompleteAfterInitialElement)
{
_logic._substreamSource.Complete();
_logic.CompleteStage();
}
}
else
_logic.Pull(_logic._stage._in);
}
public override void OnDownstreamFinish()
{
_logic._substreamCancelled = true;
if (_logic.IsClosed(_logic._stage._in) || _logic._stage._propagateSubstreamCancel)
_logic.CompleteStage();
else
// Start draining
if (!_logic.HasBeenPulled(_logic._stage._in))
_logic.Pull(_logic._stage._in);
}
public override void OnPush()
{
var elem = _logic.Grab(_logic._stage._in);
try
{
if (_logic._stage._predicate(elem))
{
var handler = new SubstreamHandler(_logic);
CloseThis(handler, elem);
_logic.HandOver(handler);
}
else
{
// Drain into the void
if (_logic._substreamCancelled)
_logic.Pull(_logic._stage._in);
else
_logic._substreamSource.Push(elem);
}
}
catch (Exception ex)
{
OnUpstreamFailure(ex);
}
}
public override void OnUpstreamFinish()
{
if (HasInitialElement)
_willCompleteAfterInitialElement = true;
else
{
_logic._substreamSource.Complete();
_logic.CompleteStage();
}
}
public override void OnUpstreamFailure(Exception ex)
{
_logic._substreamSource.Fail(ex);
_logic.FailStage(ex);
}
}
#endregion
private const string SubscriptionTimer = "SubstreamSubscriptionTimer";
private TimeSpan _timeout;
private SubSourceOutlet<T> _substreamSource;
private bool _substreamPushed;
private bool _substreamCancelled;
private readonly Split<T> _stage;
public Logic(Split<T> stage) : base(stage.Shape)
{
_stage = stage;
SetHandler(stage._out, onPull: () =>
{
if (_substreamSource == null)
Pull(stage._in);
else if (!_substreamPushed)
{
Push(stage._out, Source.FromGraph(_substreamSource.Source));
ScheduleOnce(SubscriptionTimer, _timeout);
_substreamPushed = true;
}
}, onDownstreamFinish: () =>
{
// If the substream is already cancelled or it has not been handed out, we can go away
if (!_substreamPushed || _substreamCancelled)
CompleteStage();
});
// initial input handler
SetHandler(stage._in, onPush: () =>
{
var handler = new SubstreamHandler(this);
var elem = Grab(_stage._in);
if (_stage._decision == Split.SplitDecision.SplitAfter && _stage._predicate(elem))
Push(_stage._out, Source.Single(elem));
// Next pull will come from the next substream that we will open
else
handler.FirstElement = elem;
HandOver(handler);
}, onUpstreamFinish: CompleteStage);
}
public override void PreStart()
{
var settings = ActorMaterializer.Downcast(Interpreter.Materializer).Settings;
_timeout = settings.SubscriptionTimeoutSettings.Timeout;
}
private void HandOver(SubstreamHandler handler)
{
if (IsClosed(_stage._out))
CompleteStage();
else
{
_substreamSource = new SubSourceOutlet<T>(this, "SplitSource");
_substreamSource.SetHandler(handler);
_substreamCancelled = false;
SetHandler(_stage._in, handler);
SetKeepGoing(handler.HasInitialElement);
if (IsAvailable(_stage._out))
{
Push(_stage._out, Source.FromGraph(_substreamSource.Source));
ScheduleOnce(SubscriptionTimer, _timeout);
_substreamPushed = true;
}
else
_substreamPushed = false;
}
}
protected internal override void OnTimer(object timerKey) => _substreamSource.Timeout(_timeout);
}
#endregion
private readonly Inlet<T> _in = new Inlet<T>("Split.in");
private readonly Outlet<Source<T, NotUsed>> _out = new Outlet<Source<T, NotUsed>>("Split.out");
private readonly Split.SplitDecision _decision;
private readonly Func<T, bool> _predicate;
private readonly bool _propagateSubstreamCancel;
public Split(Split.SplitDecision decision, Func<T, bool> predicate, SubstreamCancelStrategy substreamCancelStrategy)
{
_decision = decision;
_predicate = predicate;
_propagateSubstreamCancel = substreamCancelStrategy == SubstreamCancelStrategy.Propagate;
Shape = new FlowShape<T, Source<T, NotUsed>>(_in, _out);
}
public override FlowShape<T, Source<T, NotUsed>> Shape { get; }
protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this);
}
/// <summary>
/// INTERNAL API
/// </summary>
internal static class SubSink
{
internal interface ICommand { }
internal class RequestOne : ICommand
{
public static readonly RequestOne Instance = new RequestOne();
private RequestOne() { }
}
internal class Cancel : ICommand
{
public static readonly Cancel Instance = new Cancel();
private Cancel() { }
}
}
/// <summary>
/// INTERNAL API
/// </summary>
internal sealed class SubSink<T> : GraphStage<SinkShape<T>>
{
#region internal classes
private sealed class Logic : GraphStageLogic
{
private readonly SubSink<T> _stage;
public Logic(SubSink<T> stage) : base(stage.Shape)
{
_stage = stage;
SetHandler(stage._in,
onPush: () => _stage._externalCallback(new OnNext(Grab(_stage._in))),
onUpstreamFinish: () => _stage._externalCallback(OnComplete.Instance),
onUpstreamFailure: ex => _stage._externalCallback(new OnError(ex)));
}
private void SetCallback(Action<SubSink.ICommand> cb)
{
var status = _stage._status.Value;
if (status == null)
{
if (!_stage._status.CompareAndSet(null, cb))
SetCallback(cb);
}
else if (status is SubSink.RequestOne)
{
Pull(_stage._in);
if (!_stage._status.CompareAndSet(SubSink.RequestOne.Instance, cb))
SetCallback(cb);
}
else if (status is SubSink.Cancel)
{
CompleteStage();
if (!_stage._status.CompareAndSet(SubSink.Cancel.Instance, cb))
SetCallback(cb);
}
else if (status is Action)
FailStage(new IllegalStateException("Substream Source cannot be materialized more than once"));
}
public override void PreStart()
{
var ourOwnCallback = GetAsyncCallback<SubSink.ICommand>(cmd =>
{
if (cmd is SubSink.RequestOne)
TryPull(_stage._in);
else if (cmd is SubSink.Cancel)
CompleteStage();
else
throw new IllegalStateException("Bug");
});
SetCallback(ourOwnCallback);
}
}
#endregion
private readonly Inlet<T> _in = new Inlet<T>("SubSink.in");
private readonly AtomicReference<object> _status = new AtomicReference<object>();
private readonly string _name;
private readonly Action<IActorSubscriberMessage> _externalCallback;
public SubSink(string name, Action<IActorSubscriberMessage> externalCallback)
{
_name = name;
_externalCallback = externalCallback;
InitialAttributes = Attributes.CreateName($"SubSink({name})");
Shape = new SinkShape<T>(_in);
}
protected override Attributes InitialAttributes { get; }
public override SinkShape<T> Shape { get; }
public void PullSubstream()
{
var s = _status.Value;
var f = s as Action<SubSink.ICommand>;
if (f != null)
f(SubSink.RequestOne.Instance);
else
{
if (!_status.CompareAndSet(null, SubSink.RequestOne.Instance))
((Action<SubSink.ICommand>) _status.Value)(SubSink.RequestOne.Instance);
}
}
public void CancelSubstream()
{
var s = _status.Value;
var f = s as Action<SubSink.ICommand>;
if (f != null)
f(SubSink.Cancel.Instance);
else if (!_status.CompareAndSet(s, SubSink.Cancel.Instance)) // a potential RequestOne is overwritten
((Action<SubSink.ICommand>) _status.Value)(SubSink.Cancel.Instance);
}
protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this);
public override string ToString() => _name;
}
/// <summary>
/// INTERNAL API
/// </summary>
internal static class SubSource
{
/// <summary>
/// INTERNAL API
///
/// HERE ACTUALLY ARE DRAGONS, YOU HAVE BEEN WARNED!
///
/// FIXME #19240 (jvm)
/// </summary>
public static void Kill<T, TMat>(Source<T, TMat> s)
{
var module = s.Module as GraphStageModule;
if (module?.Stage is SubSource<T>)
{
((SubSource<T>) module.Stage).ExternalCallback(SubSink.Cancel.Instance);
return;
}
var pub = s.Module as PublisherSource<T>;
if (pub != null)
{
NotUsed _;
pub.Create(default(MaterializationContext), out _).Subscribe(CancelingSubscriber<T>.Instance);
return;
}
var intp = GraphInterpreter.CurrentInterpreterOrNull;
if (intp == null)
throw new NotSupportedException($"cannot drop Source of type {s.Module.GetType().Name}");
s.RunWith(Sink.Ignore<T>(), intp.SubFusingMaterializer);
}
}
/// <summary>
/// INTERNAL API
/// </summary>
internal sealed class SubSource<T> : GraphStage<SourceShape<T>>
{
#region internal classes
private sealed class Logic : GraphStageLogic
{
private readonly SubSource<T> _stage;
public Logic(SubSource<T> stage) : base(stage.Shape)
{
_stage = stage;
SetHandler(stage._out,
onPull: () => _stage.ExternalCallback(SubSink.RequestOne.Instance),
onDownstreamFinish: () => _stage.ExternalCallback(SubSink.Cancel.Instance));
}
private void SetCallback(Action<IActorSubscriberMessage> callback)
{
var status = _stage._status.Value;
if (status == null)
{
if (!_stage._status.CompareAndSet(null, callback))
SetCallback(callback);
}
else if (status is OnComplete)
CompleteStage();
else if (status is OnError)
FailStage(((OnError) status).Cause);
else if (status is Action<IActorSubscriberMessage>)
throw new IllegalStateException("Substream Source cannot be materialized more than once");
}
public override void PreStart()
{
var ourOwnCallback = GetAsyncCallback<IActorSubscriberMessage>(msg =>
{
if (msg is OnComplete)
CompleteStage();
else if (msg is OnError)
FailStage(((OnError) msg).Cause);
else if (msg is OnNext)
Push(_stage._out, (T) ((OnNext) msg).Element);
});
SetCallback(ourOwnCallback);
}
}
#endregion
private readonly string _name;
private readonly Outlet<T> _out = new Outlet<T>("SubSource.out");
private readonly AtomicReference<object> _status = new AtomicReference<object>();
public SubSource(string name, Action<SubSink.ICommand> externalCallback)
{
_name = name;
Shape = new SourceShape<T>(_out);
InitialAttributes = Attributes.CreateName($"SubSource({name})");
ExternalCallback = externalCallback;
}
public override SourceShape<T> Shape { get; }
protected override Attributes InitialAttributes { get; }
internal Action<SubSink.ICommand> ExternalCallback { get; }
public void PushSubstream(T elem)
{
var s = _status.Value;
var f = s as Action<IActorSubscriberMessage>;
if (f == null)
throw new IllegalStateException("cannot push to uninitialized substream");
f(new OnNext(elem));
}
public void CompleteSubstream()
{
var s = _status.Value;
var f = s as Action<IActorSubscriberMessage>;
if (f != null)
f(OnComplete.Instance);
else if (!_status.CompareAndSet(null, OnComplete.Instance))
((Action<IActorSubscriberMessage>) _status.Value)(OnComplete.Instance);
}
public void FailSubstream(Exception ex)
{
var s = _status.Value;
var f = s as Action<IActorSubscriberMessage>;
var failure = new OnError(ex);
if (f != null)
f(failure);
else if (!_status.CompareAndSet(null, failure))
((Action<IActorSubscriberMessage>) _status.Value)(failure);
}
public bool Timeout(TimeSpan d) => _status.CompareAndSet(null, new OnError(new SubscriptionTimeoutException($"Substream Source has not been materialized in {d}")));
protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this);
public override string ToString() => _name;
}
}
| |
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Numerics;
using Nethereum.Hex.HexTypes;
using Nethereum.ABI.FunctionEncoding.Attributes;
using Nethereum.Web3;
using Nethereum.RPC.Eth.DTOs;
using Nethereum.Contracts.CQS;
using Nethereum.Contracts.ContractHandlers;
using Nethereum.Contracts;
using System.Threading;
using Nethereum.ENS.ENSRegistryWithFallback.ContractDefinition;
namespace Nethereum.ENS
{
public partial class ENSRegistryWithFallbackService
{
public static Task<TransactionReceipt> DeployContractAndWaitForReceiptAsync(Nethereum.Web3.Web3 web3, ENSRegistryWithFallbackDeployment eNSRegistryWithFallbackDeployment, CancellationTokenSource cancellationTokenSource = null)
{
return web3.Eth.GetContractDeploymentHandler<ENSRegistryWithFallbackDeployment>().SendRequestAndWaitForReceiptAsync(eNSRegistryWithFallbackDeployment, cancellationTokenSource);
}
public static Task<string> DeployContractAsync(Nethereum.Web3.Web3 web3, ENSRegistryWithFallbackDeployment eNSRegistryWithFallbackDeployment)
{
return web3.Eth.GetContractDeploymentHandler<ENSRegistryWithFallbackDeployment>().SendRequestAsync(eNSRegistryWithFallbackDeployment);
}
public static async Task<ENSRegistryWithFallbackService> DeployContractAndGetServiceAsync(Nethereum.Web3.Web3 web3, ENSRegistryWithFallbackDeployment eNSRegistryWithFallbackDeployment, CancellationTokenSource cancellationTokenSource = null)
{
var receipt = await DeployContractAndWaitForReceiptAsync(web3, eNSRegistryWithFallbackDeployment, cancellationTokenSource);
return new ENSRegistryWithFallbackService(web3, receipt.ContractAddress);
}
protected Nethereum.Web3.Web3 Web3 { get; }
public ContractHandler ContractHandler { get; }
public ENSRegistryWithFallbackService(Nethereum.Web3.Web3 web3, string contractAddress)
{
Web3 = web3;
ContractHandler = web3.Eth.GetContractHandler(contractAddress);
}
public Task<bool> IsApprovedForAllQueryAsync(IsApprovedForAllFunction isApprovedForAllFunction, BlockParameter blockParameter = null)
{
return ContractHandler.QueryAsync<IsApprovedForAllFunction, bool>(isApprovedForAllFunction, blockParameter);
}
public Task<bool> IsApprovedForAllQueryAsync(string owner, string operatorx, BlockParameter blockParameter = null)
{
var isApprovedForAllFunction = new IsApprovedForAllFunction();
isApprovedForAllFunction.Owner = owner;
isApprovedForAllFunction.Operator = operatorx;
return ContractHandler.QueryAsync<IsApprovedForAllFunction, bool>(isApprovedForAllFunction, blockParameter);
}
public Task<string> OldQueryAsync(OldFunction oldFunction, BlockParameter blockParameter = null)
{
return ContractHandler.QueryAsync<OldFunction, string>(oldFunction, blockParameter);
}
public Task<string> OldQueryAsync(BlockParameter blockParameter = null)
{
return ContractHandler.QueryAsync<OldFunction, string>(null, blockParameter);
}
public Task<string> OwnerQueryAsync(OwnerFunction ownerFunction, BlockParameter blockParameter = null)
{
return ContractHandler.QueryAsync<OwnerFunction, string>(ownerFunction, blockParameter);
}
public Task<string> OwnerQueryAsync(byte[] node, BlockParameter blockParameter = null)
{
var ownerFunction = new OwnerFunction();
ownerFunction.Node = node;
return ContractHandler.QueryAsync<OwnerFunction, string>(ownerFunction, blockParameter);
}
public Task<bool> RecordExistsQueryAsync(RecordExistsFunction recordExistsFunction, BlockParameter blockParameter = null)
{
return ContractHandler.QueryAsync<RecordExistsFunction, bool>(recordExistsFunction, blockParameter);
}
public Task<bool> RecordExistsQueryAsync(byte[] node, BlockParameter blockParameter = null)
{
var recordExistsFunction = new RecordExistsFunction();
recordExistsFunction.Node = node;
return ContractHandler.QueryAsync<RecordExistsFunction, bool>(recordExistsFunction, blockParameter);
}
public Task<string> ResolverQueryAsync(ResolverFunction resolverFunction, BlockParameter blockParameter = null)
{
return ContractHandler.QueryAsync<ResolverFunction, string>(resolverFunction, blockParameter);
}
public Task<string> ResolverQueryAsync(byte[] node, BlockParameter blockParameter = null)
{
var resolverFunction = new ResolverFunction();
resolverFunction.Node = node;
return ContractHandler.QueryAsync<ResolverFunction, string>(resolverFunction, blockParameter);
}
public Task<string> SetApprovalForAllRequestAsync(SetApprovalForAllFunction setApprovalForAllFunction)
{
return ContractHandler.SendRequestAsync(setApprovalForAllFunction);
}
public Task<TransactionReceipt> SetApprovalForAllRequestAndWaitForReceiptAsync(SetApprovalForAllFunction setApprovalForAllFunction, CancellationTokenSource cancellationToken = null)
{
return ContractHandler.SendRequestAndWaitForReceiptAsync(setApprovalForAllFunction, cancellationToken);
}
public Task<string> SetApprovalForAllRequestAsync(string operatorx, bool approved)
{
var setApprovalForAllFunction = new SetApprovalForAllFunction();
setApprovalForAllFunction.Operator = operatorx;
setApprovalForAllFunction.Approved = approved;
return ContractHandler.SendRequestAsync(setApprovalForAllFunction);
}
public Task<TransactionReceipt> SetApprovalForAllRequestAndWaitForReceiptAsync(string operatorx, bool approved, CancellationTokenSource cancellationToken = null)
{
var setApprovalForAllFunction = new SetApprovalForAllFunction();
setApprovalForAllFunction.Operator = operatorx;
setApprovalForAllFunction.Approved = approved;
return ContractHandler.SendRequestAndWaitForReceiptAsync(setApprovalForAllFunction, cancellationToken);
}
public Task<string> SetOwnerRequestAsync(SetOwnerFunction setOwnerFunction)
{
return ContractHandler.SendRequestAsync(setOwnerFunction);
}
public Task<TransactionReceipt> SetOwnerRequestAndWaitForReceiptAsync(SetOwnerFunction setOwnerFunction, CancellationTokenSource cancellationToken = null)
{
return ContractHandler.SendRequestAndWaitForReceiptAsync(setOwnerFunction, cancellationToken);
}
public Task<string> SetOwnerRequestAsync(byte[] node, string owner)
{
var setOwnerFunction = new SetOwnerFunction();
setOwnerFunction.Node = node;
setOwnerFunction.Owner = owner;
return ContractHandler.SendRequestAsync(setOwnerFunction);
}
public Task<TransactionReceipt> SetOwnerRequestAndWaitForReceiptAsync(byte[] node, string owner, CancellationTokenSource cancellationToken = null)
{
var setOwnerFunction = new SetOwnerFunction();
setOwnerFunction.Node = node;
setOwnerFunction.Owner = owner;
return ContractHandler.SendRequestAndWaitForReceiptAsync(setOwnerFunction, cancellationToken);
}
public Task<string> SetRecordRequestAsync(SetRecordFunction setRecordFunction)
{
return ContractHandler.SendRequestAsync(setRecordFunction);
}
public Task<TransactionReceipt> SetRecordRequestAndWaitForReceiptAsync(SetRecordFunction setRecordFunction, CancellationTokenSource cancellationToken = null)
{
return ContractHandler.SendRequestAndWaitForReceiptAsync(setRecordFunction, cancellationToken);
}
public Task<string> SetRecordRequestAsync(byte[] node, string owner, string resolver, ulong ttl)
{
var setRecordFunction = new SetRecordFunction();
setRecordFunction.Node = node;
setRecordFunction.Owner = owner;
setRecordFunction.Resolver = resolver;
setRecordFunction.Ttl = ttl;
return ContractHandler.SendRequestAsync(setRecordFunction);
}
public Task<TransactionReceipt> SetRecordRequestAndWaitForReceiptAsync(byte[] node, string owner, string resolver, ulong ttl, CancellationTokenSource cancellationToken = null)
{
var setRecordFunction = new SetRecordFunction();
setRecordFunction.Node = node;
setRecordFunction.Owner = owner;
setRecordFunction.Resolver = resolver;
setRecordFunction.Ttl = ttl;
return ContractHandler.SendRequestAndWaitForReceiptAsync(setRecordFunction, cancellationToken);
}
public Task<string> SetResolverRequestAsync(SetResolverFunction setResolverFunction)
{
return ContractHandler.SendRequestAsync(setResolverFunction);
}
public Task<TransactionReceipt> SetResolverRequestAndWaitForReceiptAsync(SetResolverFunction setResolverFunction, CancellationTokenSource cancellationToken = null)
{
return ContractHandler.SendRequestAndWaitForReceiptAsync(setResolverFunction, cancellationToken);
}
public Task<string> SetResolverRequestAsync(byte[] node, string resolver)
{
var setResolverFunction = new SetResolverFunction();
setResolverFunction.Node = node;
setResolverFunction.Resolver = resolver;
return ContractHandler.SendRequestAsync(setResolverFunction);
}
public Task<TransactionReceipt> SetResolverRequestAndWaitForReceiptAsync(byte[] node, string resolver, CancellationTokenSource cancellationToken = null)
{
var setResolverFunction = new SetResolverFunction();
setResolverFunction.Node = node;
setResolverFunction.Resolver = resolver;
return ContractHandler.SendRequestAndWaitForReceiptAsync(setResolverFunction, cancellationToken);
}
public Task<string> SetSubnodeOwnerRequestAsync(SetSubnodeOwnerFunction setSubnodeOwnerFunction)
{
return ContractHandler.SendRequestAsync(setSubnodeOwnerFunction);
}
public Task<TransactionReceipt> SetSubnodeOwnerRequestAndWaitForReceiptAsync(SetSubnodeOwnerFunction setSubnodeOwnerFunction, CancellationTokenSource cancellationToken = null)
{
return ContractHandler.SendRequestAndWaitForReceiptAsync(setSubnodeOwnerFunction, cancellationToken);
}
public Task<string> SetSubnodeOwnerRequestAsync(byte[] node, byte[] label, string owner)
{
var setSubnodeOwnerFunction = new SetSubnodeOwnerFunction();
setSubnodeOwnerFunction.Node = node;
setSubnodeOwnerFunction.Label = label;
setSubnodeOwnerFunction.Owner = owner;
return ContractHandler.SendRequestAsync(setSubnodeOwnerFunction);
}
public Task<TransactionReceipt> SetSubnodeOwnerRequestAndWaitForReceiptAsync(byte[] node, byte[] label, string owner, CancellationTokenSource cancellationToken = null)
{
var setSubnodeOwnerFunction = new SetSubnodeOwnerFunction();
setSubnodeOwnerFunction.Node = node;
setSubnodeOwnerFunction.Label = label;
setSubnodeOwnerFunction.Owner = owner;
return ContractHandler.SendRequestAndWaitForReceiptAsync(setSubnodeOwnerFunction, cancellationToken);
}
public Task<string> SetSubnodeRecordRequestAsync(SetSubnodeRecordFunction setSubnodeRecordFunction)
{
return ContractHandler.SendRequestAsync(setSubnodeRecordFunction);
}
public Task<TransactionReceipt> SetSubnodeRecordRequestAndWaitForReceiptAsync(SetSubnodeRecordFunction setSubnodeRecordFunction, CancellationTokenSource cancellationToken = null)
{
return ContractHandler.SendRequestAndWaitForReceiptAsync(setSubnodeRecordFunction, cancellationToken);
}
public Task<string> SetSubnodeRecordRequestAsync(byte[] node, byte[] label, string owner, string resolver, ulong ttl)
{
var setSubnodeRecordFunction = new SetSubnodeRecordFunction();
setSubnodeRecordFunction.Node = node;
setSubnodeRecordFunction.Label = label;
setSubnodeRecordFunction.Owner = owner;
setSubnodeRecordFunction.Resolver = resolver;
setSubnodeRecordFunction.Ttl = ttl;
return ContractHandler.SendRequestAsync(setSubnodeRecordFunction);
}
public Task<TransactionReceipt> SetSubnodeRecordRequestAndWaitForReceiptAsync(byte[] node, byte[] label, string owner, string resolver, ulong ttl, CancellationTokenSource cancellationToken = null)
{
var setSubnodeRecordFunction = new SetSubnodeRecordFunction();
setSubnodeRecordFunction.Node = node;
setSubnodeRecordFunction.Label = label;
setSubnodeRecordFunction.Owner = owner;
setSubnodeRecordFunction.Resolver = resolver;
setSubnodeRecordFunction.Ttl = ttl;
return ContractHandler.SendRequestAndWaitForReceiptAsync(setSubnodeRecordFunction, cancellationToken);
}
public Task<string> SetTTLRequestAsync(SetTTLFunction setTTLFunction)
{
return ContractHandler.SendRequestAsync(setTTLFunction);
}
public Task<TransactionReceipt> SetTTLRequestAndWaitForReceiptAsync(SetTTLFunction setTTLFunction, CancellationTokenSource cancellationToken = null)
{
return ContractHandler.SendRequestAndWaitForReceiptAsync(setTTLFunction, cancellationToken);
}
public Task<string> SetTTLRequestAsync(byte[] node, ulong ttl)
{
var setTTLFunction = new SetTTLFunction();
setTTLFunction.Node = node;
setTTLFunction.Ttl = ttl;
return ContractHandler.SendRequestAsync(setTTLFunction);
}
public Task<TransactionReceipt> SetTTLRequestAndWaitForReceiptAsync(byte[] node, ulong ttl, CancellationTokenSource cancellationToken = null)
{
var setTTLFunction = new SetTTLFunction();
setTTLFunction.Node = node;
setTTLFunction.Ttl = ttl;
return ContractHandler.SendRequestAndWaitForReceiptAsync(setTTLFunction, cancellationToken);
}
public Task<ulong> TtlQueryAsync(TtlFunction ttlFunction, BlockParameter blockParameter = null)
{
return ContractHandler.QueryAsync<TtlFunction, ulong>(ttlFunction, blockParameter);
}
public Task<ulong> TtlQueryAsync(byte[] node, BlockParameter blockParameter = null)
{
var ttlFunction = new TtlFunction();
ttlFunction.Node = node;
return ContractHandler.QueryAsync<TtlFunction, ulong>(ttlFunction, blockParameter);
}
}
}
| |
//
// 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.Globalization;
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 Hyak.Common;
using Microsoft.Azure.Management.StreamAnalytics;
using Microsoft.Azure.Management.StreamAnalytics.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.StreamAnalytics
{
/// <summary>
/// Operations for managing the transformation definition of the stream
/// analytics job.
/// </summary>
internal partial class TransformationOperations : IServiceOperations<StreamAnalyticsManagementClient>, ITransformationOperations
{
/// <summary>
/// Initializes a new instance of the TransformationOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal TransformationOperations(StreamAnalyticsManagementClient client)
{
this._client = client;
}
private StreamAnalyticsManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.StreamAnalytics.StreamAnalyticsManagementClient.
/// </summary>
public StreamAnalyticsManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Create or update a transformation for a stream analytics job.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the stream analytics job.
/// </param>
/// <param name='jobName'>
/// Required. The name of the stream analytics job.
/// </param>
/// <param name='parameters'>
/// Required. The parameters required to create or update a
/// transformation for the stream analytics job.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response of the transformation create operation.
/// </returns>
public async Task<TransformationCreateOrUpdateResponse> CreateOrUpdateAsync(string resourceGroupName, string jobName, TransformationCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (jobName == null)
{
throw new ArgumentNullException("jobName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Transformation != null)
{
if (parameters.Transformation.Name == null)
{
throw new ArgumentNullException("parameters.Transformation.Name");
}
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("jobName", jobName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourcegroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/Microsoft.StreamAnalytics/streamingjobs/";
url = url + Uri.EscapeDataString(jobName);
url = url + "/transformations/";
if (parameters.Transformation != null && parameters.Transformation.Name != null)
{
url = url + Uri.EscapeDataString(parameters.Transformation.Name);
}
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-10-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
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("x-ms-client-request-id", Guid.NewGuid().ToString());
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject transformationCreateOrUpdateParametersValue = new JObject();
requestDoc = transformationCreateOrUpdateParametersValue;
if (parameters.Transformation != null)
{
transformationCreateOrUpdateParametersValue["name"] = parameters.Transformation.Name;
if (parameters.Transformation.Properties != null)
{
JObject propertiesValue = new JObject();
transformationCreateOrUpdateParametersValue["properties"] = propertiesValue;
if (parameters.Transformation.Properties.Etag != null)
{
propertiesValue["etag"] = parameters.Transformation.Properties.Etag;
}
if (parameters.Transformation.Properties.StreamingUnits != null)
{
propertiesValue["streamingUnits"] = parameters.Transformation.Properties.StreamingUnits.Value;
}
if (parameters.Transformation.Properties.Query != null)
{
propertiesValue["query"] = parameters.Transformation.Properties.Query;
}
}
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
// 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.OK && statusCode != HttpStatusCode.Created)
{
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
TransformationCreateOrUpdateResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new TransformationCreateOrUpdateResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
Transformation transformationInstance = new Transformation();
result.Transformation = transformationInstance;
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
transformationInstance.Name = nameInstance;
}
JToken propertiesValue2 = responseDoc["properties"];
if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
{
TransformationProperties propertiesInstance = new TransformationProperties();
transformationInstance.Properties = propertiesInstance;
JToken etagValue = propertiesValue2["etag"];
if (etagValue != null && etagValue.Type != JTokenType.Null)
{
string etagInstance = ((string)etagValue);
propertiesInstance.Etag = etagInstance;
}
JToken streamingUnitsValue = propertiesValue2["streamingUnits"];
if (streamingUnitsValue != null && streamingUnitsValue.Type != JTokenType.Null)
{
int streamingUnitsInstance = ((int)streamingUnitsValue);
propertiesInstance.StreamingUnits = streamingUnitsInstance;
}
JToken queryValue = propertiesValue2["query"];
if (queryValue != null && queryValue.Type != JTokenType.Null)
{
string queryInstance = ((string)queryValue);
propertiesInstance.Query = queryInstance;
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("Date"))
{
result.Date = DateTime.Parse(httpResponse.Headers.GetValues("Date").FirstOrDefault(), CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime();
}
if (httpResponse.Headers.Contains("ETag"))
{
result.Transformation.Properties.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>
/// Create or update a transformation for a stream analytics job. The
/// raw json content will be used.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the stream analytics job.
/// </param>
/// <param name='jobName'>
/// Required. The name of the stream analytics job.
/// </param>
/// <param name='transformationName'>
/// Required. The name of the transformation for the stream analytics
/// job.
/// </param>
/// <param name='parameters'>
/// Required. The parameters required to create or update a
/// transformation for the stream analytics job. It is in json format.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response of the transformation create operation.
/// </returns>
public async Task<TransformationCreateOrUpdateResponse> CreateOrUpdateWithRawJsonContentAsync(string resourceGroupName, string jobName, string transformationName, TransformationCreateOrUpdateWithRawJsonContentParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (jobName == null)
{
throw new ArgumentNullException("jobName");
}
if (transformationName == null)
{
throw new ArgumentNullException("transformationName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Content == null)
{
throw new ArgumentNullException("parameters.Content");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("jobName", jobName);
tracingParameters.Add("transformationName", transformationName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateOrUpdateWithRawJsonContentAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourcegroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/Microsoft.StreamAnalytics/streamingjobs/";
url = url + Uri.EscapeDataString(jobName);
url = url + "/transformations/";
url = url + Uri.EscapeDataString(transformationName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-10-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
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("x-ms-client-request-id", Guid.NewGuid().ToString());
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = parameters.Content;
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
// 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.OK && statusCode != HttpStatusCode.Created)
{
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
TransformationCreateOrUpdateResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new TransformationCreateOrUpdateResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
Transformation transformationInstance = new Transformation();
result.Transformation = transformationInstance;
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
transformationInstance.Name = nameInstance;
}
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
TransformationProperties propertiesInstance = new TransformationProperties();
transformationInstance.Properties = propertiesInstance;
JToken etagValue = propertiesValue["etag"];
if (etagValue != null && etagValue.Type != JTokenType.Null)
{
string etagInstance = ((string)etagValue);
propertiesInstance.Etag = etagInstance;
}
JToken streamingUnitsValue = propertiesValue["streamingUnits"];
if (streamingUnitsValue != null && streamingUnitsValue.Type != JTokenType.Null)
{
int streamingUnitsInstance = ((int)streamingUnitsValue);
propertiesInstance.StreamingUnits = streamingUnitsInstance;
}
JToken queryValue = propertiesValue["query"];
if (queryValue != null && queryValue.Type != JTokenType.Null)
{
string queryInstance = ((string)queryValue);
propertiesInstance.Query = queryInstance;
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("Date"))
{
result.Date = DateTime.Parse(httpResponse.Headers.GetValues("Date").FirstOrDefault(), CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime();
}
if (httpResponse.Headers.Contains("ETag"))
{
result.Transformation.Properties.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>
/// Get the transformation for a stream analytics job.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the stream analytics job.
/// </param>
/// <param name='jobName'>
/// Required. The name of the stream analytics job.
/// </param>
/// <param name='transformationName'>
/// Required. The name of the transformation for the stream analytics
/// job.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response of the transformation get operation.
/// </returns>
public async Task<TransformationsGetResponse> GetAsync(string resourceGroupName, string jobName, string transformationName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (jobName == null)
{
throw new ArgumentNullException("jobName");
}
if (transformationName == null)
{
throw new ArgumentNullException("transformationName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("jobName", jobName);
tracingParameters.Add("transformationName", transformationName);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourcegroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/Microsoft.StreamAnalytics/streamingjobs/";
url = url + Uri.EscapeDataString(jobName);
url = url + "/transformations/";
url = url + Uri.EscapeDataString(transformationName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-10-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
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.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString());
// 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.OK)
{
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
TransformationsGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new TransformationsGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
Transformation transformationInstance = new Transformation();
result.Transformation = transformationInstance;
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
transformationInstance.Name = nameInstance;
}
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
TransformationProperties propertiesInstance = new TransformationProperties();
transformationInstance.Properties = propertiesInstance;
JToken etagValue = propertiesValue["etag"];
if (etagValue != null && etagValue.Type != JTokenType.Null)
{
string etagInstance = ((string)etagValue);
propertiesInstance.Etag = etagInstance;
}
JToken streamingUnitsValue = propertiesValue["streamingUnits"];
if (streamingUnitsValue != null && streamingUnitsValue.Type != JTokenType.Null)
{
int streamingUnitsInstance = ((int)streamingUnitsValue);
propertiesInstance.StreamingUnits = streamingUnitsInstance;
}
JToken queryValue = propertiesValue["query"];
if (queryValue != null && queryValue.Type != JTokenType.Null)
{
string queryInstance = ((string)queryValue);
propertiesInstance.Query = queryInstance;
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("Date"))
{
result.Date = DateTime.Parse(httpResponse.Headers.GetValues("Date").FirstOrDefault(), CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime();
}
if (httpResponse.Headers.Contains("ETag"))
{
result.Transformation.Properties.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>
/// Update an transformation for a stream analytics job.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the stream analytics job.
/// </param>
/// <param name='jobName'>
/// Required. The name of the stream analytics job.
/// </param>
/// <param name='transformationName'>
/// Required. The name of the transformation for the stream analytics
/// job.
/// </param>
/// <param name='parameters'>
/// Required. The parameters required to update an transformation for
/// the stream analytics job.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response of the transformation patch operation.
/// </returns>
public async Task<TransformationPatchResponse> PatchAsync(string resourceGroupName, string jobName, string transformationName, TransformationPatchParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (jobName == null)
{
throw new ArgumentNullException("jobName");
}
if (transformationName == null)
{
throw new ArgumentNullException("transformationName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Properties == null)
{
throw new ArgumentNullException("parameters.Properties");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("jobName", jobName);
tracingParameters.Add("transformationName", transformationName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "PatchAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourcegroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/Microsoft.StreamAnalytics/streamingjobs/";
url = url + Uri.EscapeDataString(jobName);
url = url + "/transformations/";
url = url + Uri.EscapeDataString(transformationName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-10-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
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 = new HttpMethod("PATCH");
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString());
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject transformationPatchParametersValue = new JObject();
requestDoc = transformationPatchParametersValue;
JObject propertiesValue = new JObject();
transformationPatchParametersValue["properties"] = propertiesValue;
if (parameters.Properties.Etag != null)
{
propertiesValue["etag"] = parameters.Properties.Etag;
}
if (parameters.Properties.StreamingUnits != null)
{
propertiesValue["streamingUnits"] = parameters.Properties.StreamingUnits.Value;
}
if (parameters.Properties.Query != null)
{
propertiesValue["query"] = parameters.Properties.Query;
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
// 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.OK)
{
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
TransformationPatchResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new TransformationPatchResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken propertiesValue2 = responseDoc["properties"];
if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
{
TransformationProperties propertiesInstance = new TransformationProperties();
result.Properties = propertiesInstance;
JToken etagValue = propertiesValue2["etag"];
if (etagValue != null && etagValue.Type != JTokenType.Null)
{
string etagInstance = ((string)etagValue);
propertiesInstance.Etag = etagInstance;
}
JToken streamingUnitsValue = propertiesValue2["streamingUnits"];
if (streamingUnitsValue != null && streamingUnitsValue.Type != JTokenType.Null)
{
int streamingUnitsInstance = ((int)streamingUnitsValue);
propertiesInstance.StreamingUnits = streamingUnitsInstance;
}
JToken queryValue = propertiesValue2["query"];
if (queryValue != null && queryValue.Type != JTokenType.Null)
{
string queryInstance = ((string)queryValue);
propertiesInstance.Query = queryInstance;
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("Date"))
{
result.Date = DateTime.Parse(httpResponse.Headers.GetValues("Date").FirstOrDefault(), CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime();
}
if (httpResponse.Headers.Contains("ETag"))
{
result.Properties.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();
}
}
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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.
//-----------------------------------------------------------------------------
$River::EditorOpen = false;
$River::wireframe = true;
$River::showSpline = true;
$River::showRiver = true;
$River::showWalls = true;
function RiverEditorGui::onEditorActivated( %this )
{
%count = EWorldEditor.getSelectionSize();
for ( %i = 0; %i < %count; %i++ )
{
%obj = EWorldEditor.getSelectedObject(%i);
if ( %obj.getClassName() !$= "River" )
EWorldEditor.unselectObject( %obj );
else
%this.setSelectedRiver( %obj );
}
%this.onRiverSelected( %this.getSelectedRiver() );
%this.onNodeSelected(-1);
}
function RiverEditorGui::onEditorDeactivated( %this )
{
}
function RiverEditorGui::createRiver( %this )
{
%river = new River()
{
rippleDir[0] = "0.000000 1.000000";
rippleDir[1] = "0.707000 0.707000";
rippleDir[2] = "0.500000 0.860000";
rippleSpeed[0] = "-0.065";
rippleSpeed[1] = "0.09";
rippleSpeed[2] = "0.04";
rippleTexScale[0] = "7.140000 7.140000";
rippleTexScale[1] = "6.250000 12.500000";
rippleTexScale[2] = "50.000000 50.000000";
waveDir[0] = "0.000000 1.000000";
waveDir[1] = "0.707000 0.707000";
waveDir[2] = "0.500000 0.860000";
waveSpeed[0] = "1";
waveSpeed[1] = "1";
waveSpeed[2] = "1";
waveMagnitude[0] = "0.2";
waveMagnitude[1] = "0.2";
waveMagnitude[2] = "0.2";
baseColor = "45 108 171 255";
rippleTex = "core/art/water/ripple.dds";
foamTex = "core/art/water/foam";
cubemap = "DefaultSkyCubemap";
depthGradientTex = "core/art/water/depthcolor_ramp";
};
return %river;
}
function RiverEditorGui::paletteSync( %this, %mode )
{
%evalShortcut = "ToolsPaletteArray-->" @ %mode @ ".setStateOn(1);";
eval(%evalShortcut);
}
function RiverEditorGui::onEscapePressed( %this )
{
if( %this.getMode() $= "RiverEditorAddNodeMode" )
{
%this.prepSelectionMode();
return true;
}
return false;
}
function RiverEditorGui::onRiverSelected( %this, %river )
{
%this.river = %river;
RiverInspector.inspect( %river );
RiverTreeView.buildVisibleTree(true);
if( RiverTreeView.getSelectedObject() != %river )
{
RiverTreeView.clearSelection();
%treeId = RiverTreeView.findItemByObjectId( %river );
RiverTreeView.selectItem( %treeId );
}
}
function RiverEditorGui::onNodeSelected( %this, %nodeIdx )
{
if ( %nodeIdx == -1 )
{
RiverEditorOptionsWindow-->position.setActive( false );
RiverEditorOptionsWindow-->position.setValue( "" );
RiverEditorOptionsWindow-->rotation.setActive( false );
RiverEditorOptionsWindow-->rotation.setValue( "" );
RiverEditorOptionsWindow-->width.setActive( false );
RiverEditorOptionsWindow-->width.setValue( "" );
RiverEditorOptionsWindow-->depth.setActive( false );
RiverEditorOptionsWindow-->depth.setValue( "" );
}
else
{
RiverEditorOptionsWindow-->position.setActive( true );
RiverEditorOptionsWindow-->position.setValue( %this.getNodePosition() );
RiverEditorOptionsWindow-->rotation.setActive( true );
RiverEditorOptionsWindow-->rotation.setValue( %this.getNodeNormal() );
RiverEditorOptionsWindow-->width.setActive( true );
RiverEditorOptionsWindow-->width.setValue( %this.getNodeWidth() );
RiverEditorOptionsWindow-->depth.setActive( true );
RiverEditorOptionsWindow-->depth.setValue( %this.getNodeDepth() );
}
}
function RiverEditorGui::onNodeModified( %this, %nodeIdx )
{
RiverEditorOptionsWindow-->position.setValue( %this.getNodePosition() );
RiverEditorOptionsWindow-->rotation.setValue( %this.getNodeNormal() );
RiverEditorOptionsWindow-->width.setValue( %this.getNodeWidth() );
RiverEditorOptionsWindow-->depth.setValue( %this.getNodeDepth() );
}
function RiverEditorGui::editNodeDetails( %this )
{
%this.setNodePosition( RiverEditorOptionsWindow-->position.getText() );
%this.setNodeNormal( RiverEditorOptionsWindow-->rotation.getText() );
%this.setNodeWidth( RiverEditorOptionsWindow-->width.getText() );
%this.setNodeDepth( RiverEditorOptionsWindow-->depth.getText() );
}
function RiverInspector::inspect( %this, %obj )
{
%name = "";
if ( isObject( %obj ) )
%name = %obj.getName();
else
RiverFieldInfoControl.setText( "" );
//RiverInspectorNameEdit.setValue( %name );
Parent::inspect( %this, %obj );
}
function RiverInspector::onInspectorFieldModified( %this, %object, %fieldName, %arrayIndex, %oldValue, %newValue )
{
// Same work to do as for the regular WorldEditor Inspector.
Inspector::onInspectorFieldModified( %this, %object, %fieldName, %arrayIndex, %oldValue, %newValue );
}
function RiverInspector::onFieldSelected( %this, %fieldName, %fieldTypeStr, %fieldDoc )
{
RiverFieldInfoControl.setText( "<font:ArialBold:14>" @ %fieldName @ "<font:ArialItalic:14> (" @ %fieldTypeStr @ ") " NL "<font:Arial:14>" @ %fieldDoc );
}
function RiverTreeView::onInspect(%this, %obj)
{
RiverInspector.inspect(%obj);
}
function RiverTreeView::onSelect(%this, %obj)
{
RiverEditorGui.road = %obj;
RiverInspector.inspect( %obj );
if(%obj != RiverEditorGui.getSelectedRiver())
{
RiverEditorGui.setSelectedRiver( %obj );
}
}
function RiverEditorGui::prepSelectionMode( %this )
{
%mode = %this.getMode();
if ( %mode $= "RiverEditorAddNodeMode" )
{
if ( isObject( %this.getSelectedRiver() ) )
%this.deleteNode();
}
%this.setMode( "RiverEditorSelectMode" );
ToolsPaletteArray-->RiverEditorSelectMode.setStateOn(1);
}
//------------------------------------------------------------------------------
function ERiverEditorSelectModeBtn::onClick(%this)
{
EditorGuiStatusBar.setInfo(%this.ToolTip);
}
function ERiverEditorAddModeBtn::onClick(%this)
{
EditorGuiStatusBar.setInfo(%this.ToolTip);
}
function ERiverEditorMoveModeBtn::onClick(%this)
{
EditorGuiStatusBar.setInfo(%this.ToolTip);
}
function ERiverEditorRotateModeBtn::onClick(%this)
{
EditorGuiStatusBar.setInfo(%this.ToolTip);
}
function ERiverEditorScaleModeBtn::onClick(%this)
{
EditorGuiStatusBar.setInfo(%this.ToolTip);
}
function ERiverEditorInsertModeBtn::onClick(%this)
{
EditorGuiStatusBar.setInfo(%this.ToolTip);
}
function ERiverEditorRemoveModeBtn::onClick(%this)
{
EditorGuiStatusBar.setInfo(%this.ToolTip);
}
function RiverDefaultWidthSliderCtrlContainer::onWake(%this)
{
RiverDefaultWidthSliderCtrlContainer-->slider.setValue(RiverDefaultWidthTextEditContainer-->textEdit.getText());
}
function RiverDefaultDepthSliderCtrlContainer::onWake(%this)
{
RiverDefaultDepthSliderCtrlContainer-->slider.setValue(RiverDefaultDepthTextEditContainer-->textEdit.getText());
}
| |
using System;
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
[ExecuteInEditMode]
[CustomEditor(typeof(Suimono.Core.SuimonoObject))]
public class suimono_object_editor : Editor {
int setRename = 0;
string renName = "";
public override void OnInspectorGUI() {
int localPresetIndex = -1;
int basePos = 0;
Texture logoTex;
Texture divTex;
Texture divHorizTex;
Texture bgPreset;
Texture bgPresetSt;
Texture bgPresetNd;
Color colorEnabled = new Color(1.0f,1.0f,1.0f,1.0f);
Color colorDisabled = new Color(1.0f,1.0f,1.0f,0.25f);
Color colorWarning = new Color(0.9f,0.5f,0.1f,1.0f);
Color highlightColor2 = new Color(0.7f,1f,0.2f,0.6f);
Color highlightColor = new Color(1f,0.5f,0f,0.9f);
//load textures
logoTex = Resources.Load("textures/gui_tex_suimonologo") as Texture;
divTex = Resources.Load("textures/gui_tex_suimonodiv") as Texture;
divHorizTex = Resources.Load("textures/gui_tex_suimono_divhorz") as Texture;
bgPreset = Resources.Load("textures/gui_bgpreset") as Texture;
bgPresetSt = Resources.Load("textures/gui_bgpresetSt") as Texture;
bgPresetNd = Resources.Load("textures/gui_bgpresetNd") as Texture;
#if UNITY_PRO_LICENSE
divTex = Resources.Load("textures/gui_tex_suimonodiv") as Texture;
logoTex = Resources.Load("textures/gui_tex_suimonologo") as Texture;
bgPreset = Resources.Load("textures/gui_bgpreset") as Texture;
bgPresetSt = Resources.Load("textures/gui_bgpresetSt") as Texture;
bgPresetNd = Resources.Load("textures/gui_bgpresetNd") as Texture;
highlightColor = new Color(1f,0.5f,0f,0.9f);
#else
divTex = Resources.Load("textures/gui_tex_suimonodiv_i") as Texture;
logoTex = Resources.Load("textures/gui_tex_suimonologo_i") as Texture;
bgPreset = Resources.Load("textures/gui_bgpreset_i") as Texture;
bgPresetSt = Resources.Load("textures/gui_bgpresetSt_i") as Texture;
bgPresetNd = Resources.Load("textures/gui_bgpresetNd_i") as Texture;
highlightColor = new Color(0.0f,0.81f,0.9f,0.6f);
#endif
Suimono.Core.SuimonoObject script = (Suimono.Core.SuimonoObject) target;
Undo.RecordObject(target, "Changed Area Of Effect");
if (localPresetIndex == -1) localPresetIndex = script.presetUseIndex;
//SET SCREEN WIDTH
int setWidth = (int)EditorGUIUtility.currentViewWidth-220;
if (setWidth < 120) setWidth = 120;
//SUIMONO LOGO
GUIContent buttonText = new GUIContent("");
GUIStyle buttonStyle = GUIStyle.none;
Rect rt = GUILayoutUtility.GetRect(buttonText, buttonStyle);
int margin = 15;
//start menu
GUI.contentColor = new Color(1.0f,1.0f,1.0f,0.4f);
EditorGUI.LabelField(new Rect(rt.x+margin+2, rt.y+37, 50, 18),"Version");
GUI.contentColor = new Color(1.0f,1.0f,1.0f,0.6f);
Rect linkVerRect = new Rect(rt.x+margin+51, rt.y+37, 90, 18);
EditorGUI.LabelField(linkVerRect,script.suimonoVersionNumber);
GUI.contentColor = new Color(1.0f,1.0f,1.0f,1.0f);
GUI.contentColor = new Color(1.0f,1.0f,1.0f,0.4f);
Rect linkHelpRect = new Rect(rt.x+margin+165, rt.y+37, 28, 18);
Rect linkBugRect = new Rect(rt.x+margin+165+42, rt.y+37, 65, 18);
Rect linkURLRect = new Rect(rt.x+margin+165+120, rt.y+37, 100, 18);
if (Event.current.type == EventType.MouseUp && linkHelpRect.Contains(Event.current.mousePosition)) Application.OpenURL("http://www.tanukidigital.com/forum/");
if (Event.current.type == EventType.MouseUp && linkBugRect.Contains(Event.current.mousePosition)) Application.OpenURL("http://www.tanukidigital.com/forum/");
if (Event.current.type == EventType.MouseUp && linkURLRect.Contains(Event.current.mousePosition)) Application.OpenURL("http://www.tanukidigital.com/suimono/");
EditorGUI.LabelField(new Rect(rt.x+margin+165+30, rt.y+37, 220, 18),"|");
EditorGUI.LabelField(new Rect(rt.x+margin+165+110, rt.y+37, 220, 18),"|");
GUI.contentColor = new Color(1.0f,1.0f,1.0f,0.4f);
EditorGUI.LabelField(linkHelpRect,"help");
EditorGUI.LabelField(linkBugRect,"report bug");
EditorGUI.LabelField(linkURLRect,"tanukidigital.com");
// end menu
EditorGUI.DrawPreviewTexture(new Rect(rt.x+margin,rt.y,387,36),logoTex);
GUILayout.Space(40.0f);
int tSpace = 0;
// GENERAL SETTINGS
GUI.contentColor = colorEnabled;
rt = GUILayoutUtility.GetRect(buttonText, buttonStyle);
EditorGUI.DrawPreviewTexture(new Rect(rt.x+margin,rt.y,387,24),divTex);
script.showGeneral = EditorGUI.Foldout(new Rect(rt.x+margin+3, rt.y+5, 20, 20), script.showGeneral, "");
GUI.Label (new Rect(rt.x+margin+10, rt.y+5, 300, 20), new GUIContent ("GENERAL SETTINGS"));
GUI.color = new Color(GUI.color.r,GUI.color.g,GUI.color.b,0.0f);
if (GUI.Button(new Rect(rt.x+margin+10, rt.y+5, 250, 20),"")) script.showGeneral = !script.showGeneral;
GUI.color = new Color(GUI.color.r,GUI.color.g,GUI.color.b,1.0f);
EditorGUI.LabelField(new Rect(rt.x+margin+240, rt.y+6, 80, 18),"Mode");
script.editorIndex = EditorGUI.Popup(new Rect(rt.x+margin+280, rt.y+6, 100, 18),"",script.editorIndex, script.editorOptions.ToArray());
if (script.showGeneral){
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+30, 80, 18),"Surface Type");
script.typeIndex = EditorGUI.Popup(new Rect(rt.x+margin+100, rt.y+30, 145, 18),"",script.typeIndex, script.typeOptions.ToArray());
if (script.typeIndex == 0){
EditorGUI.LabelField(new Rect(rt.x+margin+260, rt.y+30, 80, 18),"Ocean Scale");
script.oceanScale = EditorGUI.FloatField(new Rect(rt.x+margin+343, rt.y+30, 30, 18),"",script.oceanScale);
}
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+50, 80, 18),"Surface LOD");
if (script.enableCustomMesh && script.typeIndex != 0){
GUI.contentColor = colorWarning;
GUI.backgroundColor = colorWarning;
EditorGUI.LabelField(new Rect(rt.x+margin+100, rt.y+50, 275, 18),"NOTE: Not available while using custom mesh!");
GUI.contentColor = colorEnabled;
GUI.backgroundColor = colorEnabled;
} else {
if (script.typeIndex == 0){
script.lodIndex = 0;
GUI.contentColor = colorDisabled;
GUI.backgroundColor = colorDisabled;
}
if (script.typeIndex == 2){
script.lodIndex = 3;
GUI.contentColor = colorDisabled;
GUI.backgroundColor = colorDisabled;
}
script.lodIndex = EditorGUI.Popup(new Rect(rt.x+margin+100, rt.y+50, 145, 18),"",script.lodIndex, script.lodOptions.ToArray());
GUI.contentColor = colorEnabled;
GUI.backgroundColor = colorEnabled;
}
//ADVANCED FX SETTINGS
//EditorGUI.DrawPreviewTexture(new Rect(rt.x+margin+10,rt.y+76,372,1),divHorizTex);
//EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+80, 260, 18),"ADVANCED FX SETTINGS");
//EditorGUI.LabelField(new Rect(rt.x+margin+37, rt.y+100, 150, 18),"Enable Underwater FX");
//script.enableUnderwaterFX = EditorGUI.Toggle(new Rect(rt.x+margin+10, rt.y+100, 30, 18),"", script.enableUnderwaterFX);
//EditorGUI.LabelField(new Rect(rt.x+margin+220, rt.y+100, 150, 18),"Enable Caustic FX");
//script.enableCausticFX = EditorGUI.Toggle(new Rect(rt.x+margin+200, rt.y+100, 30, 18),"", script.enableCausticFX);
//SCENE REFLECTIONS
GUI.contentColor = colorEnabled;
GUI.backgroundColor = colorEnabled;
basePos = 77;
EditorGUI.DrawPreviewTexture(new Rect(rt.x+margin+10,rt.y+basePos,372,1),divHorizTex);
script.enableReflections = EditorGUI.Toggle(new Rect(rt.x+margin+10, rt.y+basePos+5, 20, 18),"", script.useEnableReflections);
EditorGUI.LabelField(new Rect(rt.x+margin+31, rt.y+basePos+5, 160, 18),"SCENE REFLECTIONS");
GUI.contentColor = colorEnabled;
GUI.backgroundColor = colorEnabled;
if (script.useEnableReflections){
script.enableDynamicReflections = EditorGUI.Toggle(new Rect(rt.x+margin+27, rt.y+basePos+28, 20, 18),"", script.useEnableDynamicReflections);
EditorGUI.LabelField(new Rect(rt.x+margin+45, rt.y+basePos+28, 160, 18),"Enable Dynamic Reflections");
if (!script.useEnableDynamicReflections){
GUI.contentColor = colorDisabled;
GUI.backgroundColor = colorDisabled;
}
EditorGUI.LabelField(new Rect(rt.x+margin+27, rt.y+basePos+48, 180, 18),"Reflect Layers");
if (script.gameObject.activeInHierarchy){
script.reflectLayer = EditorGUI.MaskField(new Rect(rt.x+margin+120, rt.y+basePos+48, 90, 18),"", script.reflectLayer, script.suiLayerMasks.ToArray());
}
EditorGUI.LabelField(new Rect(rt.x+margin+225, rt.y+basePos+48, 180, 18),"Resolution");
if (script.gameObject.activeInHierarchy){
script.reflectResolution = EditorGUI.Popup(new Rect(rt.x+margin+295, rt.y+basePos+48, 90, 18),"", script.reflectResolution, script.resOptions.ToArray());
}
//EditorGUI.LabelField(new Rect(rt.x+margin+27, rt.y+basePos+68, 180, 18),"Reflection Distance");
//script.reflectionDistance = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+basePos+68, setWidth, 18),"",script.reflectionDistance,0.0,100000.0);
//EditorGUI.LabelField(new Rect(rt.x+margin+27, rt.y+basePos+88, 180, 18),"Reflection Spread");
//script.reflectionSpread = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+basePos+88, setWidth, 18),"",script.reflectionSpread,0.0,1.0);
GUI.contentColor = colorEnabled;
GUI.backgroundColor = colorEnabled;
if (script.enableDynamicReflections && script.useEnableDynamicReflections){
GUI.contentColor = colorDisabled;
GUI.backgroundColor = colorDisabled;
}
EditorGUI.LabelField(new Rect(rt.x+margin+27, rt.y+basePos+78, 180, 18),"Fallback Mode");
if (script.gameObject.activeInHierarchy){
script.reflectFallback = EditorGUI.Popup(new Rect(rt.x+margin+120, rt.y+basePos+78, 120, 18),"", script.reflectFallback, script.resFallbackOptions.ToArray());
}
if (script.reflectFallback == 2){
script.customRefCubemap = EditorGUI.ObjectField(new Rect(rt.x+margin+250, rt.y+basePos+78, 136, 16), script.customRefCubemap, typeof(Texture), true) as Texture;
}
if (script.reflectFallback == 3){
script.customRefColor = EditorGUI.ColorField(new Rect(rt.x+margin+250, rt.y+basePos+78, 136, 16), script.customRefColor);
}
GUI.contentColor = colorEnabled;
GUI.backgroundColor = colorEnabled;
basePos += 102;
tSpace += 92;
} else {
basePos += 25;
}
//TESSELLATION
GUI.contentColor = colorEnabled;
GUI.backgroundColor = colorEnabled;
EditorGUI.DrawPreviewTexture(new Rect(rt.x+margin+10,rt.y+basePos,372,1),divHorizTex);
script.enableTess = EditorGUI.Toggle(new Rect(rt.x+margin+10, rt.y+basePos+5, 20, 18),"", script.enableTess);
EditorGUI.LabelField(new Rect(rt.x+margin+31, rt.y+basePos+5, 160, 18),"TESSELLATION");
if (script.enableTess){
GUI.contentColor = colorEnabled;
GUI.backgroundColor = colorEnabled;
#if !UNITY_STANDALONE_OSX
if (script.typeIndex == 2){
GUI.contentColor = colorDisabled;
GUI.backgroundColor = colorDisabled;
}
if (!script.enableTess){
GUI.contentColor = colorDisabled;
GUI.backgroundColor = colorDisabled;
}
#endif
#if UNITY_STANDALONE_OSX
GUI.contentColor = colorDisabled;
GUI.backgroundColor = colorDisabled;
#endif
EditorGUI.LabelField(new Rect(rt.x+margin+27, rt.y+basePos+25, 140, 18),"Tessellation Factor");
script.waveTessAmt = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+basePos+25, setWidth, 18),"",script.waveTessAmt,0.001f,100.0f);
EditorGUI.LabelField(new Rect(rt.x+margin+27, rt.y+basePos+45, 140, 18),"Tessellation Start");
script.waveTessMin = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+basePos+45, setWidth, 18),"",script.waveTessMin,0.0f,1.0f);
EditorGUI.LabelField(new Rect(rt.x+margin+27, rt.y+basePos+65, 140, 18),"Tessellation Spread");
script.waveTessSpread = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+basePos+65, setWidth, 18),"",script.waveTessSpread,0.0f,1.0f);
GUI.contentColor = colorEnabled;
GUI.backgroundColor = colorEnabled;
}
//dx11 warning messages
GUI.contentColor = colorWarning;
GUI.backgroundColor = colorWarning;
//if (script.unityVersionIndex == 0){
// EditorGUI.LabelField(new Rect(rt.x+margin+137, rt.y+basePos+5, 260, 18),"NOTE: only available on PC in dx11 mode!");
//}
#if UNITY_STANDALONE_OSX
EditorGUI.LabelField(new Rect(rt.x+margin+137, rt.y+basePos+5, 260, 18),"NOTE: only available on PC in dx11 mode!");
#endif
GUI.contentColor = colorEnabled;
GUI.backgroundColor = colorEnabled;
if (script.enableTess){
basePos += 95;
tSpace += 70;
} else {
basePos += 25;
}
// INTERACTION
GUI.contentColor = colorEnabled;
GUI.backgroundColor = colorEnabled;
EditorGUI.DrawPreviewTexture(new Rect(rt.x+margin+10,rt.y+basePos,372,1),divHorizTex);
GUI.contentColor = colorEnabled;
GUI.backgroundColor = colorEnabled;
EditorGUI.LabelField(new Rect(rt.x+margin+31, rt.y+basePos+5, 140, 18),"ENABLE INTERACTION");
script.enableInteraction = EditorGUI.Toggle(new Rect(rt.x+margin+10, rt.y+basePos+5, 20, 18),"", script.enableInteraction);
basePos += 25;
// CUSTOM TEXTURES
GUI.contentColor = colorEnabled;
GUI.backgroundColor = colorEnabled;
EditorGUI.DrawPreviewTexture(new Rect(rt.x+margin+10,rt.y+basePos,372,1),divHorizTex);
GUI.contentColor = colorEnabled;
GUI.backgroundColor = colorEnabled;
EditorGUI.LabelField(new Rect(rt.x+margin+31, rt.y+basePos+5, 140, 18),"CUSTOM TEXTURES");
script.enableCustomTextures = EditorGUI.Toggle(new Rect(rt.x+margin+10, rt.y+basePos+5, 20, 18),"", script.enableCustomTextures);
if (script.enableCustomTextures){
GUI.contentColor = colorDisabled;
GUI.backgroundColor = colorDisabled;
GUI.Label (new Rect(rt.x+margin+38, rt.y+basePos+86, 100, 18), new GUIContent ("RGBA Normal"));
GUI.contentColor = colorEnabled;
GUI.backgroundColor = colorEnabled;
GUI.Label (new Rect(rt.x+margin+34, rt.y+basePos+72, 100, 18), new GUIContent ("Shallow Waves"));
//GUI.Label (new Rect(rt.x+margin+92, rt.y+basePos+72, 100, 18), new GUIContent ("Height"));
script.customTexNormal1 = EditorGUI.ObjectField(new Rect(rt.x+margin+34, rt.y+basePos+24, 95, 45), script.customTexNormal1, typeof(Texture2D), true) as Texture2D;
//script.customTexHeight1 = EditorGUI.ObjectField(new Rect(rt.x+margin+88, rt.y+basePos+24, 45, 45), script.customTexHeight1, typeof(Texture2D), true) as Texture2D;
GUI.contentColor = colorDisabled;
GUI.backgroundColor = colorDisabled;
GUI.Label (new Rect(rt.x+margin+162, rt.y+basePos+86, 100, 18), new GUIContent ("RGBA Normal"));
GUI.contentColor = colorEnabled;
GUI.backgroundColor = colorEnabled;
GUI.Label (new Rect(rt.x+margin+152, rt.y+basePos+72, 100, 18), new GUIContent ("Turbulent Waves"));
//GUI.Label (new Rect(rt.x+margin+211, rt.y+basePos+72, 100, 18), new GUIContent ("Height"));
script.customTexNormal2 = EditorGUI.ObjectField(new Rect(rt.x+margin+155, rt.y+basePos+24, 95, 45), script.customTexNormal2, typeof(Texture2D), true) as Texture2D;
//script.customTexHeight2 = EditorGUI.ObjectField(new Rect(rt.x+margin+209, rt.y+basePos+24, 45, 45), script.customTexHeight2, typeof(Texture2D), true) as Texture2D;
GUI.contentColor = colorDisabled;
GUI.backgroundColor = colorDisabled;
GUI.Label (new Rect(rt.x+margin+284, rt.y+basePos+86, 100, 18), new GUIContent ("RGBA Normal"));
GUI.contentColor = colorEnabled;
GUI.backgroundColor = colorEnabled;
GUI.Label (new Rect(rt.x+margin+287, rt.y+basePos+72, 100, 18), new GUIContent ("Deep Waves"));
//GUI.Label (new Rect(rt.x+margin+335, rt.y+basePos+72, 100, 18), new GUIContent ("Height"));
script.customTexNormal3 = EditorGUI.ObjectField(new Rect(rt.x+margin+277, rt.y+basePos+24, 95, 45), script.customTexNormal3, typeof(Texture2D), true) as Texture2D;
//script.customTexHeight3 = EditorGUI.ObjectField(new Rect(rt.x+margin+333, rt.y+basePos+24, 45, 45), script.customTexHeight3, typeof(Texture2D), true) as Texture2D;
basePos += 110;
tSpace += 87;
} else {
basePos += 25;
}
// CUSTOM MESH
GUI.contentColor = colorEnabled;
GUI.backgroundColor = colorEnabled;
EditorGUI.DrawPreviewTexture(new Rect(rt.x+margin+10,rt.y+basePos,372,1),divHorizTex);
GUI.contentColor = colorEnabled;
GUI.backgroundColor = colorEnabled;
EditorGUI.LabelField(new Rect(rt.x+margin+31, rt.y+basePos+5, 140, 18),"CUSTOM MESH");
script.enableCustomMesh = EditorGUI.Toggle(new Rect(rt.x+margin+10, rt.y+basePos+5, 20, 18),"", script.enableCustomMesh);
if (script.enableCustomMesh){
if (script.typeIndex != 0){
script.customMesh = EditorGUI.ObjectField(new Rect(rt.x+margin+171, rt.y+basePos+8, 200, 18), script.customMesh, typeof(Mesh), true) as Mesh;
}
//infinite ocean warning messages
GUI.contentColor = colorWarning;
GUI.backgroundColor = colorWarning;
if (script.typeIndex == 0){
EditorGUI.LabelField(new Rect(rt.x+margin+132, rt.y+basePos+5, 260, 18),"NOTE: Not available in Infinite Ocean Mode!");
}
GUI.contentColor = colorEnabled;
GUI.backgroundColor = colorEnabled;
basePos += 35;
tSpace += 10;
} else {
basePos += 25;
}
GUILayout.Space(160.0f+tSpace);
}
GUILayout.Space(10.0f);
if (script.editorIndex == 1){
//WAVE SETTINGS
rt = GUILayoutUtility.GetRect(buttonText, buttonStyle);
EditorGUI.DrawPreviewTexture(new Rect(rt.x+margin,rt.y,387,24),divTex);
script.showWaves = EditorGUI.Foldout(new Rect(rt.x+margin+3, rt.y+5, 20, 20), script.showWaves, "");
GUI.Label (new Rect(rt.x+margin+10, rt.y+5, 300, 20), new GUIContent ("WAVE SETTINGS"));
GUI.color = new Color(GUI.color.r,GUI.color.g,GUI.color.b,0.0f);
if (GUI.Button(new Rect(rt.x+margin+10, rt.y+5, 370, 20),"")) script.showWaves = !script.showWaves;
GUI.color = new Color(GUI.color.r,GUI.color.g,GUI.color.b,1.0f);
if (script.showWaves){
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+30, 140, 18),"Wave Scale (Beaufort)");
if (!script.customWaves){
script.beaufortScale = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+30, setWidth, 18),"",script.beaufortScale,0.0f,12.0f);
} else {
GUI.contentColor = colorWarning;
GUI.backgroundColor = colorWarning;
EditorGUI.LabelField(new Rect(rt.x+margin+165, rt.y+30, setWidth, 18),"Disabled: Using custom settings!");
}
GUI.contentColor = colorEnabled;
GUI.backgroundColor = colorEnabled;
//if (script.useTenkoku == 1.0 && script.tenkokuUseWind){
// EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+30, 90, 18),"Flow Direction");
// GUI.contentColor = colorDisabled;
// EditorGUI.LabelField(new Rect(rt.x+margin+165, rt.y+30, 290, 18),"Currently using Tenkoku settings...");
// GUI.contentColor = colorEnabled;
// EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+50, 90, 18),"Flow Speed");
// GUI.contentColor = colorDisabled;
// EditorGUI.LabelField(new Rect(rt.x+margin+165, rt.y+50, 290, 18),"Currently using Tenkoku settings...");
// GUI.contentColor = colorEnabled;
//} else {
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+50, 90, 18),"Wave Direction");
script.flowDirection = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+50, setWidth, 18),"",script.flowDirection,0.0f,360.0f);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+70, 90, 18),"Wave Speed");
script.flowSpeed = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+70, setWidth, 18),"",script.flowSpeed,0.0f,0.1f);
if (script.typeIndex == 0 && !script.customWaves){
GUI.contentColor = colorDisabled;
GUI.backgroundColor = colorDisabled;
}
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+90, 90, 18),"Wave Scale");
script.waveScale = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+90, setWidth, 18),"",script.waveScale,0.0f,5.0f);
GUI.contentColor = colorEnabled;
GUI.backgroundColor = colorEnabled;
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+110, 110, 18),"Height Projection");
script.heightProjection = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+110, setWidth, 18),"",script.heightProjection,0.0f,1.0f);
//}
EditorGUI.DrawPreviewTexture(new Rect(rt.x+margin+10,rt.y+135,372,1),divHorizTex);
script.customWaves = EditorGUI.Toggle(new Rect(rt.x+margin+10, rt.y+140, 20, 20), "", script.customWaves);
GUI.Label (new Rect(rt.x+margin+30, rt.y+140, 300, 20), new GUIContent ("Use Custom Settings"));
if (!script.customWaves){
GUI.contentColor = colorDisabled;
GUI.backgroundColor = colorDisabled;
}
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+160, 90, 18),"Wave Height");
script.waveHeight = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+160, setWidth, 18),"",script.waveHeight,0.0f,4.0f);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+180, 120, 18),"Turbulence Amount");
script.turbulenceFactor = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+180, setWidth, 18),"",script.turbulenceFactor,0.0f,1.0f);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+200, 120, 18),"Large Wave Height");
script.lgWaveHeight = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+200, setWidth, 18),"",script.lgWaveHeight,0.0f,4.0f);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+220, 120, 18),"Large Wave Scale");
script.lgWaveScale = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+220, setWidth, 18),"",script.lgWaveScale,0.0f,4.0f);
GUILayout.Space(220.0f);
//} else {
// GUILayout.Space(110.0);
//}
GUI.contentColor = colorEnabled;
GUI.backgroundColor = colorEnabled;
}
GUILayout.Space(10.0f);
//SHORELINE SETTINGS
rt = GUILayoutUtility.GetRect(buttonText, buttonStyle);
EditorGUI.DrawPreviewTexture(new Rect(rt.x+margin,rt.y,387,24),divTex);
script.showShore = EditorGUI.Foldout(new Rect(rt.x+margin+3, rt.y+5, 20, 20), script.showShore, "");
GUI.Label (new Rect(rt.x+margin+10, rt.y+5, 300, 20), new GUIContent ("SHORELINE SETTINGS"));
GUI.color = new Color(GUI.color.r,GUI.color.g,GUI.color.b,0.0f);
if (GUI.Button(new Rect(rt.x+margin+10, rt.y+5, 370, 20),"")) script.showShore = !script.showShore;
GUI.color = new Color(GUI.color.r,GUI.color.g,GUI.color.b,1.0f);
if (script.showShore){
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+30, 130, 18),"Shoreline Height");
script.shorelineHeight = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+30, setWidth, 18),"",script.shorelineHeight,0.0f,1.0f);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+50, 130, 18),"Shoreline Frequency");
script.shorelineFreq = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+50, setWidth, 18),"",script.shorelineFreq,0.0f,1.0f);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+70, 130, 18),"Shoreline Speed");
script.shorelineSpeed = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+70, setWidth, 18),"",script.shorelineSpeed,0.0f,10.0f);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+90, 130, 18),"Shoreline Normalize");
script.shorelineNorm = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+90, setWidth, 18),"",script.shorelineNorm,0.0f,1.0f);
GUILayout.Space(100.0f);
}
GUILayout.Space(10.0f);
// SURFACE SETTINGS
rt = GUILayoutUtility.GetRect(buttonText, buttonStyle);
EditorGUI.DrawPreviewTexture(new Rect(rt.x+margin,rt.y,387,24),divTex);
script.showSurface = EditorGUI.Foldout(new Rect(rt.x+margin+3, rt.y+5, 20, 20), script.showSurface, "");
GUI.Label (new Rect(rt.x+margin+10, rt.y+5, 300, 20), new GUIContent ("WATER SURFACE"));
GUI.color = new Color(GUI.color.r,GUI.color.g,GUI.color.b,0.0f);
if (GUI.Button(new Rect(rt.x+margin+10, rt.y+5, 370, 20),"")) script.showSurface = !script.showSurface;
GUI.color = new Color(GUI.color.r,GUI.color.g,GUI.color.b,1.0f);
if (script.showSurface){
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+30, 140, 18),"Overall Brightness");
script.overallBright = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+30, setWidth, 18),"",script.overallBright,0.0f,10.0f);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+50, 140, 18),"Overall Transparency");
script.overallTransparency = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+50, setWidth, 18),"",script.overallTransparency,0.0f,1.0f);
EditorGUI.DrawPreviewTexture(new Rect(rt.x+margin+10,rt.y+75,372,1),divHorizTex);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+85, 130, 18),"Edge Blending");
script.edgeAmt = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+85, setWidth, 18),"",script.edgeAmt,0.0f,1.0f);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+105, 140, 18),"Depth Absorption");
script.depthAmt = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+105, setWidth, 18),"",script.depthAmt,0.0f,1.0f);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+125, 140, 18),"Shallow Absorption");
script.shallowAmt = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+125, setWidth, 18),"",script.shallowAmt,0.0f,1.0f);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+145, 140, 18),"Depth Color");
script.depthColor = EditorGUI.ColorField(new Rect(rt.x+margin+165, rt.y+145, setWidth, 18),"",script.depthColor);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+165, 140, 18),"Shallow Color");
script.shallowColor = EditorGUI.ColorField(new Rect(rt.x+margin+165, rt.y+165, setWidth, 18),"",script.shallowColor);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+185, 130, 18),"Surface Blend Color");
script.blendColor = EditorGUI.ColorField(new Rect(rt.x+margin+165, rt.y+185, setWidth, 18),"",script.blendColor);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+205, 130, 18),"Surface Overlay Color");
script.overlayColor = EditorGUI.ColorField(new Rect(rt.x+margin+165, rt.y+205, setWidth, 18),"",script.overlayColor);
EditorGUI.DrawPreviewTexture(new Rect(rt.x+margin+10,rt.y+230,372,1),divHorizTex);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+240, 130, 18),"Refraction Amount");
script.refractStrength = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+240, setWidth, 18),"",script.refractStrength,0.0f,1.0f);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+260, 130, 18),"Chromatic Shift");
script.aberrationScale = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+260, setWidth, 18),"",script.aberrationScale,0.0f,1.0f);
if (!script.moduleObject.enableCausticsBlending){
GUI.contentColor = colorDisabled;
GUI.backgroundColor = colorDisabled;
}
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+280, 130, 18),"Caustics Blend");
script.causticsFade = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+280, setWidth, 18),"",script.causticsFade,0.0f,1.0f);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+300, 130, 18),"Caustics Color");
script.causticsColor = EditorGUI.ColorField(new Rect(rt.x+margin+165, rt.y+300, setWidth, 18),"",script.causticsColor);
GUI.contentColor = colorEnabled;
GUI.backgroundColor = colorEnabled;
EditorGUI.DrawPreviewTexture(new Rect(rt.x+margin+10,rt.y+325,372,1),divHorizTex);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+335, 130, 18),"Reflection Blur");
script.reflectBlur = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+335, setWidth, 18),"",script.reflectBlur,0.0f,1.0f);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+355, 130, 18),"Reflection Distortion");
script.reflectProjection = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+355, setWidth, 18),"",script.reflectProjection,0.0f,1.0f);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+375, 130, 18),"Reflection Term");
script.reflectTerm = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+375, setWidth, 18),"",script.reflectTerm,0.0f,1.0f);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+395, 130, 18),"Reflection Sharpen");
script.reflectSharpen = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+395, setWidth, 18),"",script.reflectSharpen,0.0f,1.0f);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+415, 130, 18),"Reflection Color");
script.reflectionColor = EditorGUI.ColorField(new Rect(rt.x+margin+165, rt.y+415, setWidth, 18),"",script.reflectionColor);
EditorGUI.DrawPreviewTexture(new Rect(rt.x+margin+10,rt.y+440,372,1),divHorizTex);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+450, 140, 18),"Hot Specular");
script.roughness = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+450, setWidth, 18),"",script.roughness,0.0f,1.0f);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+470, 140, 18),"Wide Specular");
script.roughness2 = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+470, setWidth, 18),"",script.roughness2,0.0f,1.0f);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+490, 130, 18),"Specular Color");
script.specularColor = EditorGUI.ColorField(new Rect(rt.x+margin+165, rt.y+490, setWidth, 18),"",script.specularColor);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+510, 130, 18),"Back Light Scatter");
script.sssColor = EditorGUI.ColorField(new Rect(rt.x+margin+165, rt.y+510, setWidth, 18),"",script.sssColor);
GUILayout.Space(515.0f);
}
GUILayout.Space(10.0f);
// FOAM SETTINGS
rt = GUILayoutUtility.GetRect(buttonText, buttonStyle);
EditorGUI.DrawPreviewTexture(new Rect(rt.x+margin,rt.y,387,24),divTex);
script.showFoam = EditorGUI.Foldout(new Rect(rt.x+margin+3, rt.y+5, 20, 20), script.showFoam, "");
GUI.Label (new Rect(rt.x+margin+10, rt.y+5, 300, 20), new GUIContent ("FOAM SETTINGS"));
GUI.color = new Color(GUI.color.r,GUI.color.g,GUI.color.b,0.0f);
if (GUI.Button(new Rect(rt.x+margin+10, rt.y+5, 370, 20),"")) script.showFoam = !script.showFoam;
GUI.color = new Color(GUI.color.r,GUI.color.g,GUI.color.b,1.0f);
if (script.showFoam){
script.enableFoam = EditorGUI.Toggle(new Rect(rt.x+margin+10, rt.y+30, 20, 20),"", script.enableFoam);
EditorGUI.LabelField(new Rect(rt.x+margin+30, rt.y+30, 90, 18),"Enable Foam");
if (!script.enableFoam){
GUI.contentColor = colorDisabled;
GUI.backgroundColor = colorDisabled;
}
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+50, 90, 18),"Foam Scale");
script.foamScale = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+50, setWidth, 18),"",script.foamScale,0.0f,1.0f);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+70, 90, 18),"Foam Speed");
script.foamSpeed = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+70, setWidth, 18),"",script.foamSpeed,0.0f,1.0f);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+90, 90, 18),"Foam Color");
script.foamColor = EditorGUI.ColorField(new Rect(rt.x+margin+165, rt.y+90, setWidth, 18),"",script.foamColor);
EditorGUI.DrawPreviewTexture(new Rect(rt.x+margin+10,rt.y+115,372,1),divHorizTex);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+125, 90, 18),"Edge Foam");
script.edgeFoamAmt = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+125, setWidth, 18),"",script.edgeFoamAmt,0.0f,0.9f);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+145, 120, 18),"Shoreline Wave Foam");
script.shallowFoamAmt = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+145, setWidth, 18),"",script.shallowFoamAmt,0.0f,2.0f);
EditorGUI.DrawPreviewTexture(new Rect(rt.x+margin+10,rt.y+170,372,1),divHorizTex);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+180, 90, 18),"Wave Foam");
script.heightFoamAmt = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+180, setWidth, 18),"",script.heightFoamAmt,0.0f,1.0f);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+200, 90, 18),"Wave Height");
script.hFoamHeight = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+200, setWidth, 18),"",script.hFoamHeight,0.0f,1.0f);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+220, 90, 18),"Wave Spread");
script.hFoamSpread = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+220, setWidth, 18),"",script.hFoamSpread,0.0f,1.0f);
GUI.contentColor = colorEnabled;
GUI.backgroundColor = colorEnabled;
GUILayout.Space(220.0f);
}
GUILayout.Space(10.0f);
// UNDERWATER SETTINGS
//if (script.enableUnderwaterFX){
rt = GUILayoutUtility.GetRect(buttonText, buttonStyle);
EditorGUI.DrawPreviewTexture(new Rect(rt.x+margin,rt.y,387,24),divTex);
script.showUnderwater = EditorGUI.Foldout(new Rect(rt.x+margin+3, rt.y+5, 20, 20), script.showUnderwater, "");
GUI.Label (new Rect(rt.x+margin+10, rt.y+5, 300, 20), new GUIContent ("UNDERWATER"));
GUI.color = new Color(GUI.color.r,GUI.color.g,GUI.color.b,0.0f);
if (GUI.Button(new Rect(rt.x+margin+10, rt.y+5, 370, 20),"")) script.showUnderwater = !script.showUnderwater;
GUI.color = new Color(GUI.color.r,GUI.color.g,GUI.color.b,1.0f);
if (script.showUnderwater){
//GUI.contentColor = colorDisabled;
//GUI.backgroundColor = colorDisabled;
GUI.contentColor = colorEnabled;
GUI.backgroundColor = colorEnabled;
EditorGUI.LabelField(new Rect(rt.x+margin+30, rt.y+30, 120, 18),"Enable Underwater");
script.enableUnderwater = EditorGUI.Toggle(new Rect(rt.x+margin+10, rt.y+30, 30, 18),"", script.enableUnderwater);
if (!script.enableUnderwater){
GUI.contentColor = colorDisabled;
GUI.backgroundColor = colorDisabled;
}
EditorGUI.LabelField(new Rect(rt.x+margin+190, rt.y+30, 90, 18),"Enable Debris");
script.enableUnderDebris = EditorGUI.Toggle(new Rect(rt.x+margin+170, rt.y+30, 30, 18),"", script.enableUnderDebris);
//EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+50, 130, 18),"Underwater Depth");
//script.underwaterDepth = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+50, setWidth, 18),"",script.underwaterDepth,0.0,100.0);
EditorGUI.DrawPreviewTexture(new Rect(rt.x+margin+10,rt.y+55,372,1),divHorizTex);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+65, 130, 18),"Light Factor");
script.underLightFactor = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+65, setWidth, 18),"",script.underLightFactor,0.0f,1.0f);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+85, 130, 18),"Refraction Amount");
script.underRefractionAmount = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+85, setWidth, 18),"",script.underRefractionAmount,0.0f,0.1f);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+105, 130, 18),"Refraction Scale");
script.underRefractionScale = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+105, setWidth, 18),"",script.underRefractionScale,0.0f,3.0f);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+125, 130, 18),"Refraction Speed");
script.underRefractionSpeed = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+125, setWidth, 18),"",script.underRefractionSpeed,0.0f,5.0f);
// GUI.contentColor = colorDisabled;
//GUI.backgroundColor = colorDisabled;
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+145, 90, 18),"Blur Amount");
script.underBlurAmount = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+145, setWidth, 18),"",script.underBlurAmount,0.0f,1.0f);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+165, 170, 18),"Depth Darkening Range");
script.underDarkRange = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+165, setWidth, 18),"",script.underDarkRange,0.0f,500.0f);
//GUI.contentColor = colorEnabled;
//GUI.backgroundColor = colorEnabled;
EditorGUI.DrawPreviewTexture(new Rect(rt.x+margin+10,rt.y+190,372,1),divHorizTex);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+200, 90, 18),"Fog Distance");
script.underwaterFogDist = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+200, setWidth, 18),"",script.underwaterFogDist,0.0f,100.0f);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+220, 90, 18),"Fog Spread");
script.underwaterFogSpread = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+220, setWidth, 18),"",script.underwaterFogSpread,-20.0f,20.0f);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+240, 90, 18),"Fog Color");
script.underwaterColor = EditorGUI.ColorField(new Rect(rt.x+margin+165, rt.y+240, setWidth, 18),"",script.underwaterColor);
GUI.contentColor = colorEnabled;
GUI.backgroundColor = colorEnabled;
GUILayout.Space(245.0f);
//}
}
GUILayout.Space(10.0f);
}
// SIMPLE SETTINGS
if (script.editorIndex == 0){
rt = GUILayoutUtility.GetRect(buttonText, buttonStyle);
EditorGUI.DrawPreviewTexture(new Rect(rt.x+margin,rt.y,387,24),divTex);
script.showSimpleEditor = EditorGUI.Foldout(new Rect(rt.x+margin+3, rt.y+5, 20, 20), script.showSimpleEditor, "");
GUI.Label (new Rect(rt.x+margin+10, rt.y+5, 300, 20), new GUIContent ("SIMPLE WATER SETTINGS"));
GUI.color = new Color(GUI.color.r,GUI.color.g,GUI.color.b,0.0f);
if (GUI.Button(new Rect(rt.x+margin+10, rt.y+5, 370, 20),"")) script.showSimpleEditor = !script.showSimpleEditor;
GUI.color = new Color(GUI.color.r,GUI.color.g,GUI.color.b,1.0f);
//set settings
//script.flowSpeed = Mathf.Lerp(0.0,0.2,Mathf.Clamp01(script.waveFlowSpeed*20));
//script.surfaceSmooth = Mathf.Lerp(0.0,1.0,script.simpleWaveHeight);
//script.detailHeight = Mathf.Lerp(0.0,1.25,Mathf.Clamp(script.simpleWaveHeight*2,0.0,1.0));
//script.detailScale = 0.1;
//script.waveHeight = Mathf.Lerp(0.0,3.0,script.simpleWaveHeight);
if (script.showSimpleEditor){
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+30, 160, 18),"Wave Scale (Beaufort)");
script.beaufortScale = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+30, setWidth, 18),"",script.beaufortScale,0.0f,20.0f);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+50, 90, 18),"Wave Direction");
script.flowDirection = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+50, setWidth, 18),"",script.flowDirection,0.0f,360.0f);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+70, 90, 18),"Flow Speed");
script.flowSpeed = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+70, setWidth, 18),"",script.flowSpeed,0.0f,0.1f);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+90, 90, 18),"Wave Scale");
script.waveScale = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+90, setWidth, 18),"",script.waveScale,0.0f,1.0f);
EditorGUI.DrawPreviewTexture(new Rect(rt.x+margin+10,rt.y+115,372,1),divHorizTex);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+120, 140, 18),"Refraction Amount");
script.refractStrength = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+120, setWidth, 18),"",script.refractStrength,0.0f,1.0f);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+140, 140, 18),"Reflection Distortion");
script.reflectProjection = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+140, setWidth, 18),"",script.reflectProjection,0.0f,1.0f);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+160, 140, 18),"Reflection Color");
script.reflectionColor = EditorGUI.ColorField(new Rect(rt.x+margin+165, rt.y+160, setWidth, 18),"",script.reflectionColor);
EditorGUI.DrawPreviewTexture(new Rect(rt.x+margin+10,rt.y+185,372,1),divHorizTex);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+190, 140, 18),"Depth Absorption");
script.depthAmt = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+190, setWidth, 18),"",script.depthAmt,0.0f,1.0f);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+210, 140, 18),"Depth Color");
script.depthColor = EditorGUI.ColorField(new Rect(rt.x+margin+165, rt.y+210, setWidth, 18),"",script.depthColor);
script.shallowColor = new Color(0f,0f,0f,0f);
EditorGUI.DrawPreviewTexture(new Rect(rt.x+margin+10,rt.y+235,372,1),divHorizTex);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+240, 90, 18),"Foam Scale");
script.foamScale = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+240, setWidth, 18),"",script.foamScale,0.0f,1.0f);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+260, 90, 18),"Foam Amount");
script.edgeFoamAmt = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+260, setWidth, 18),"",script.edgeFoamAmt,0.0f,1.0f);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+280, 90, 18),"Foam Color");
script.foamColor = EditorGUI.ColorField(new Rect(rt.x+margin+165, rt.y+280, setWidth, 18),"",script.foamColor);
EditorGUI.DrawPreviewTexture(new Rect(rt.x+margin+10,rt.y+305,372,1),divHorizTex);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+310, 190, 18),"Underwater Refraction");
script.underRefractionAmount = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+310, setWidth, 18),"",script.underRefractionAmount,0.0f,0.1f);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+330, 190, 18),"Underwater Density");
script.underwaterFogSpread = EditorGUI.Slider(new Rect(rt.x+margin+165, rt.y+330, setWidth, 18),"",script.underwaterFogSpread,-20.0f,20.0f);
EditorGUI.LabelField(new Rect(rt.x+margin+10, rt.y+350, 190, 18),"Underwater Depth Color");
script.underwaterColor = EditorGUI.ColorField(new Rect(rt.x+margin+165, rt.y+350, setWidth, 18),"",script.underwaterColor);
script.underLightFactor = 1.0f;
script.underRefractionScale = 0.5f;
script.underRefractionSpeed = 1.0f;
script.underwaterFogDist = 15.0f;
GUI.contentColor = colorEnabled;
GUI.backgroundColor = colorEnabled;
GUILayout.Space(355.0f);
}
GUILayout.Space(10.0f);
}
// PRESET MANAGER
rt = GUILayoutUtility.GetRect(buttonText, buttonStyle);
EditorGUI.DrawPreviewTexture(new Rect(rt.x+margin,rt.y,387,24),divTex);
script.showPresets = EditorGUI.Foldout(new Rect(rt.x+margin+3, rt.y+5, 20, 20), script.showPresets, "");
GUI.Label (new Rect(rt.x+margin+10, rt.y+5, 300, 20), new GUIContent ("PRESET MANAGER"));
GUI.color = new Color(GUI.color.r,GUI.color.g,GUI.color.b,0.0f);
if (GUI.Button(new Rect(rt.x+margin+10, rt.y+5, 370, 16),"")) script.showPresets = !script.showPresets;
GUI.color = new Color(GUI.color.r,GUI.color.g,GUI.color.b,1.0f);
if (script.showPresets){
int presetWidth = Screen.width-78;
if (presetWidth < 120) presetWidth = 120;
//select preset file
EditorGUI.LabelField(new Rect(rt.x+margin+18, rt.y+24, 110, 18),"Use Preset Folder:");
script.presetFileIndex = EditorGUI.Popup(new Rect(rt.x+margin+130, rt.y+24, 253, 13),"",script.presetFileIndex, script.presetDirs.ToArray());
EditorGUI.LabelField(new Rect(rt.x+margin+18, rt.y+44, 100, 18),"Transition:");
script.presetTransIndexFrm = EditorGUI.Popup(new Rect(rt.x+margin+85, rt.y+44, 80, 13),"",script.presetTransIndexFrm, script.presetFiles);
EditorGUI.LabelField(new Rect(rt.x+margin+167, rt.y+44, 100, 18),"-->");
script.presetTransIndexTo = EditorGUI.Popup(new Rect(rt.x+margin+194, rt.y+44, 80, 13),"",script.presetTransIndexTo, script.presetFiles);
script.presetTransitionTime = EditorGUI.FloatField(new Rect(rt.x+margin+285, rt.y+43, 30, 18),script.presetTransitionTime);
string transAction = "Start";
//if (script.presetStartTransition) transAction = (script.presetTransitionCurrent*script.presetTransitionTime).ToString("F2");//"Stop";
if(GUI.Button(new Rect(rt.x+margin+324, rt.y+44, 60, 15), transAction)){
//script.presetStartTransition = !script.presetStartTransition;
string foldName = script.presetDirs[script.presetFileIndex];
string frmName = script.presetFiles[script.presetTransIndexFrm];
string toName = script.presetFiles[script.presetTransIndexTo];
script.SuimonoTransitionPreset(foldName,frmName, toName, script.presetTransitionTime);
}
//}
//start presets
GUI.color = new Color(1f,1f,1f,0.1f);
EditorGUI.DrawPreviewTexture(new Rect(rt.x+margin+20,rt.y+65,presetWidth,5),bgPresetSt); //364
//fill presets
//presetOptions
int prx = 0;
for (int pr = 0; pr <= script.presetFiles.Length; pr++){
prx = pr;
if (pr > 0){
//background
GUI.color = new Color(1f,1f,1f,0.1f);
if ((pr/2.0f) > Mathf.Floor(pr/2.0f)) GUI.color = new Color(1f,1f,1f,0.13f);
if (script.presetIndex == pr-1) GUI.color = highlightColor;
EditorGUI.DrawPreviewTexture(new Rect(rt.x+margin+20,rt.y+70+(pr*13),presetWidth,12),bgPreset); //364
//rename
GUI.color = new Color(1f,1f,1f,0.4f);
if (script.presetIndex == pr-1) GUI.color = highlightColor;
if (GUI.Button(new Rect(rt.x+margin+21, rt.y+67+(pr*13)+2, 11, 11),"")){
Debug.Log("rename");
setRename = (pr+1);
}
if (setRename == (pr+1)){
renName = EditorGUI.TextField(new Rect(rt.x+margin+32, rt.y+69+(pr*13), 200, 14), renName);
GUI.color = highlightColor2;
if (GUI.Button(new Rect(rt.x+margin+230, rt.y+69+(pr*13), 30, 14),"OK")){
setRename = 0;
script.PresetRename(pr-1,renName);
renName="";
}
GUI.color = new Color(1f,1f,1f,0.4f);
if (GUI.Button(new Rect(rt.x+margin+262, rt.y+69+(pr*13), 20, 14),"X")){
setRename = 0;
}
}
//add/delete
GUI.color = new Color(1f,1f,1f,0.35f);
if (script.presetIndex == pr-1) GUI.color = highlightColor;
if (GUI.Button(new Rect(rt.x+margin+(presetWidth-35), rt.y+68+(pr*13)+1, 25, 12),"+")) script.PresetSave(script.presetFileIndex,pr-1);
if (GUI.Button(new Rect(rt.x+margin+(presetWidth-9), rt.y+68+(pr*13)+1, 25, 12),"-")) script.PresetDelete(script.presetFileIndex,pr-1);
GUI.color = new Color(1f,1f,1f,1f);
//preset name/button
if (setRename != (pr+1)){
GUI.color = new Color(1f,1f,1f,0.75f);
EditorGUI.LabelField(new Rect(rt.x+margin+32, rt.y+67+(pr*13), 300, 16), script.presetFiles[pr-1]);
GUI.color = new Color(1f,1f,1f,0.12f);
if (GUI.Button(new Rect(rt.x+margin+32, rt.y+67+(pr*13)+2, (presetWidth-72), 13),"")){
localPresetIndex = pr;
script.presetIndex = pr-1;
script.PresetLoad(pr-1);
}
}
} else {
//background
GUI.color = new Color(1f,1f,1f,0.1f);
if ((pr/2.0f) > Mathf.Floor(pr/2.0f)) GUI.color = new Color(1f,1f,1f,0.13f);
if (script.presetIndex == pr-1) GUI.color = highlightColor;
EditorGUI.DrawPreviewTexture(new Rect(rt.x+margin+20,rt.y+70+(pr*13),presetWidth,12),bgPreset);
//preset name/button
if (setRename != (pr+1)){
GUI.color = new Color(1f,1f,1f,0.75f);
EditorGUI.LabelField(new Rect(rt.x+margin+32, rt.y+67+(pr*13), 300, 16), "- NONE -");
GUI.color = new Color(0f,0f,0f,0.06f);
if (GUI.Button(new Rect(rt.x+margin+32, rt.y+67+(pr*13)+2, (presetWidth-15), 13),"")){
localPresetIndex = 0;
script.presetIndex = -1;
}
}
}
}
//end presets
GUI.color = new Color(1f,1f,1f,0.1f);
EditorGUI.DrawPreviewTexture(new Rect(rt.x+margin+20,rt.y+81+((prx-1)*13),presetWidth,23),bgPresetNd);
GUI.color = new Color(1f,1f,1f,1f);
GUI.color = new Color(1f,1f,1f,0.55f);
if (GUI.Button(new Rect(rt.x+margin+(presetWidth-49), rt.y+86+((prx)*13), 65, 18),"+ NEW")) script.PresetAdd();
GUI.color = colorEnabled;
GUILayout.Space(80.0f+(prx*12f)+10f);
}
GUILayout.Space(10.0f);
EditorGUILayout.Space();
if (GUI.changed) EditorUtility.SetDirty(target);
}
}
| |
using UnityEngine;
using System;
using System.Runtime.InteropServices;
public class BluetoothLEHardwareInterface
{
public enum CBCharacteristicProperties
{
CBCharacteristicPropertyBroadcast = 0x01,
CBCharacteristicPropertyRead = 0x02,
CBCharacteristicPropertyWriteWithoutResponse = 0x04,
CBCharacteristicPropertyWrite = 0x08,
CBCharacteristicPropertyNotify = 0x10,
CBCharacteristicPropertyIndicate = 0x20,
CBCharacteristicPropertyAuthenticatedSignedWrites = 0x40,
CBCharacteristicPropertyExtendedProperties = 0x80,
CBCharacteristicPropertyNotifyEncryptionRequired = 0x100,
CBCharacteristicPropertyIndicateEncryptionRequired = 0x200,
};
public enum CBAttributePermissions
{
CBAttributePermissionsReadable = 0x01,
CBAttributePermissionsWriteable = 0x02,
CBAttributePermissionsReadEncryptionRequired = 0x04,
CBAttributePermissionsWriteEncryptionRequired = 0x08,
};
#if UNITY_IPHONE
[DllImport ("__Internal")]
private static extern void _iOSBluetoothLELog (string message);
[DllImport ("__Internal")]
private static extern void _iOSBluetoothLEInitialize (bool asCentral, bool asPeripheral);
[DllImport ("__Internal")]
private static extern void _iOSBluetoothLEDeInitialize ();
[DllImport ("__Internal")]
private static extern void _iOSBluetoothLEPauseMessages (bool isPaused);
[DllImport ("__Internal")]
private static extern void _iOSBluetoothLEScanForPeripheralsWithServices (string serviceUUIDsString, bool allowDuplicates);
[DllImport ("__Internal")]
private static extern void _iOSBluetoothLERetrieveListOfPeripheralsWithServices (string serviceUUIDsString);
[DllImport ("__Internal")]
private static extern void _iOSBluetoothLEStopScan ();
[DllImport ("__Internal")]
private static extern void _iOSBluetoothLEConnectToPeripheral (string name);
[DllImport ("__Internal")]
private static extern void _iOSBluetoothLEDisconnectPeripheral (string name);
[DllImport ("__Internal")]
private static extern void _iOSBluetoothLEReadCharacteristic (string name, string service, string characteristic);
[DllImport ("__Internal")]
private static extern void _iOSBluetoothLEWriteCharacteristic (string name, string service, string characteristic, byte[] data, int length, bool withResponse);
[DllImport ("__Internal")]
private static extern void _iOSBluetoothLESubscribeCharacteristic (string name, string service, string characteristic);
[DllImport ("__Internal")]
private static extern void _iOSBluetoothLEUnSubscribeCharacteristic (string name, string service, string characteristic);
[DllImport ("__Internal")]
private static extern void _iOSBluetoothLEPeripheralName (string newName);
[DllImport ("__Internal")]
private static extern void _iOSBluetoothLECreateService (string uuid, bool primary);
[DllImport ("__Internal")]
private static extern void _iOSBluetoothLERemoveService (string uuid);
[DllImport ("__Internal")]
private static extern void _iOSBluetoothLERemoveServices ();
[DllImport ("__Internal")]
private static extern void _iOSBluetoothLECreateCharacteristic (string uuid, int properties, int permissions, byte[] data, int length);
[DllImport ("__Internal")]
private static extern void _iOSBluetoothLERemoveCharacteristic (string uuid);
[DllImport ("__Internal")]
private static extern void _iOSBluetoothLERemoveCharacteristics ();
[DllImport ("__Internal")]
private static extern void _iOSBluetoothLEStartAdvertising ();
[DllImport ("__Internal")]
private static extern void _iOSBluetoothLEStopAdvertising ();
[DllImport ("__Internal")]
private static extern void _iOSBluetoothLEUpdateCharacteristicValue (string uuid, byte[] data, int length);
#elif UNITY_ANDROID
static AndroidJavaObject _android = null;
#endif
private static BluetoothDeviceScript bluetoothDeviceScript;
public static void Log (string message)
{
if (!Application.isEditor)
{
#if UNITY_IPHONE
_iOSBluetoothLELog (message);
#elif UNITY_ANDROID
if (_android != null)
_android.Call ("androidBluetoothLog", message);
#endif
}
}
public static BluetoothDeviceScript Initialize (bool asCentral, bool asPeripheral, bool isFirst, Action action, Action<string> errorAction)
{
bluetoothDeviceScript = null;
if (GameObject.Find ("BluetoothLEReceiver") == null) {
GameObject bluetoothLEReceiver = new GameObject ("BluetoothLEReceiver");
bluetoothDeviceScript = bluetoothLEReceiver.AddComponent<BluetoothDeviceScript> ();
if (bluetoothDeviceScript != null) {
bluetoothDeviceScript.InitializedAction = action;
bluetoothDeviceScript.ErrorAction = errorAction;
}
}
if (isFirst) {
if (Application.isEditor) {
if (bluetoothDeviceScript != null)
bluetoothDeviceScript.SendMessage ("OnBluetoothMessage", "Initialized");
} else {
#if UNITY_IPHONE
_iOSBluetoothLEInitialize (asCentral, asPeripheral);
#elif UNITY_ANDROID
if (_android == null)
{
AndroidJavaClass javaClass = new AndroidJavaClass ("com.shatalmic.unityandroidbluetoothlelib.UnityBluetoothLE");
_android = javaClass.CallStatic<AndroidJavaObject> ("getInstance");
}
if (_android != null)
_android.Call ("androidBluetoothInitialize", asCentral, asPeripheral);
#endif
}
}
return bluetoothDeviceScript;
}
public static void DeInitialize (Action action)
{
if (bluetoothDeviceScript != null)
bluetoothDeviceScript.DeinitializedAction = action;
if (Application.isEditor)
{
if (bluetoothDeviceScript != null)
bluetoothDeviceScript.SendMessage ("OnBluetoothMessage", "DeInitialized");
}
else
{
#if UNITY_IPHONE
_iOSBluetoothLEDeInitialize ();
#elif UNITY_ANDROID
if (_android != null)
_android.Call ("androidBluetoothDeInitialize");
#endif
}
}
public static void FinishDeInitialize ()
{
GameObject bluetoothLEReceiver = GameObject.Find("BluetoothLEReceiver");
if (bluetoothLEReceiver != null)
GameObject.Destroy(bluetoothLEReceiver);
}
public static void PauseMessages (bool isPaused)
{
if (!Application.isEditor)
{
#if UNITY_IPHONE
_iOSBluetoothLEPauseMessages (isPaused);
#elif UNITY_ANDROID
if (_android != null)
_android.Call ("androidBluetoothPause");
#endif
}
}
public static void ScanForPeripheralsWithServices (string[] serviceUUIDs, Action<string, string> action, Action<string, string, int, byte[]> actionAdvertisingInfo = null)
{
if (!Application.isEditor)
{
if (bluetoothDeviceScript != null)
{
bluetoothDeviceScript.DiscoveredPeripheralAction = action;
bluetoothDeviceScript.DiscoveredPeripheralWithAdvertisingInfoAction = actionAdvertisingInfo;
if (bluetoothDeviceScript.DiscoveredDeviceList != null)
bluetoothDeviceScript.DiscoveredDeviceList.Clear ();
}
string serviceUUIDsString = null;
if (serviceUUIDs != null && serviceUUIDs.Length > 0)
{
serviceUUIDsString = "";
foreach (string serviceUUID in serviceUUIDs)
serviceUUIDsString += serviceUUID + "|";
serviceUUIDsString = serviceUUIDsString.Substring (0, serviceUUIDsString.Length - 1);
}
#if UNITY_IPHONE
_iOSBluetoothLEScanForPeripheralsWithServices (serviceUUIDsString, (actionAdvertisingInfo != null));
#elif UNITY_ANDROID
if (_android != null)
{
if (serviceUUIDsString == null)
serviceUUIDsString = "";
_android.Call ("androidBluetoothScanForPeripheralsWithServices", serviceUUIDsString);
}
#endif
}
}
public static void RetrieveListOfPeripheralsWithServices (string[] serviceUUIDs, Action<string, string> action)
{
if (!Application.isEditor)
{
if (bluetoothDeviceScript != null)
{
bluetoothDeviceScript.RetrievedConnectedPeripheralAction = action;
if (bluetoothDeviceScript.DiscoveredDeviceList != null)
bluetoothDeviceScript.DiscoveredDeviceList.Clear ();
}
string serviceUUIDsString = serviceUUIDs.Length > 0 ? "" : null;
foreach (string serviceUUID in serviceUUIDs)
serviceUUIDsString += serviceUUID + "|";
// strip the last delimeter
serviceUUIDsString = serviceUUIDsString.Substring (0, serviceUUIDsString.Length - 1);
#if UNITY_IPHONE
_iOSBluetoothLERetrieveListOfPeripheralsWithServices (serviceUUIDsString);
#elif UNITY_ANDROID
if (_android != null)
_android.Call ("androidBluetoothRetrieveListOfPeripheralsWithServices", serviceUUIDsString);
#endif
}
}
public static void StopScan ()
{
if (!Application.isEditor)
{
#if UNITY_IPHONE
_iOSBluetoothLEStopScan ();
#elif UNITY_ANDROID
if (_android != null)
_android.Call ("androidBluetoothStopScan");
#endif
}
}
public static void ConnectToPeripheral (string name, Action<string> connectAction, Action<string, string> serviceAction, Action<string, string, string> characteristicAction, Action<string> disconnectAction = null)
{
if (!Application.isEditor)
{
if (bluetoothDeviceScript != null)
{
bluetoothDeviceScript.ConnectedPeripheralAction = connectAction;
bluetoothDeviceScript.DiscoveredServiceAction = serviceAction;
bluetoothDeviceScript.DiscoveredCharacteristicAction = characteristicAction;
bluetoothDeviceScript.ConnectedDisconnectPeripheralAction = disconnectAction;
}
#if UNITY_IPHONE
_iOSBluetoothLEConnectToPeripheral (name);
#elif UNITY_ANDROID
if (_android != null)
_android.Call ("androidBluetoothConnectToPeripheral", name);
#endif
}
}
public static void DisconnectPeripheral (string name, Action<string> action)
{
if (!Application.isEditor)
{
if (bluetoothDeviceScript != null)
bluetoothDeviceScript.DisconnectedPeripheralAction = action;
#if UNITY_IPHONE
_iOSBluetoothLEDisconnectPeripheral (name);
#elif UNITY_ANDROID
if (_android != null)
_android.Call ("androidBluetoothDisconnectPeripheral", name);
#endif
}
}
public static void ReadCharacteristic (string name, string service, string characteristic, Action<string, byte[]> action)
{
if (!Application.isEditor)
{
if (bluetoothDeviceScript != null)
bluetoothDeviceScript.DidUpdateCharacteristicValueAction = action;
#if UNITY_IPHONE
_iOSBluetoothLEReadCharacteristic (name, service, characteristic);
#elif UNITY_ANDROID
if (_android != null)
_android.Call ("androidReadCharacteristic", name, service, characteristic);
#endif
}
}
public static void WriteCharacteristic (string name, string service, string characteristic, byte[] data, int length, bool withResponse, Action<string> action)
{
if (!Application.isEditor)
{
if (bluetoothDeviceScript != null)
bluetoothDeviceScript.DidWriteCharacteristicAction = action;
#if UNITY_IPHONE
_iOSBluetoothLEWriteCharacteristic (name, service, characteristic, data, length, withResponse);
#elif UNITY_ANDROID
if (_android != null)
_android.Call ("androidWriteCharacteristic", name, service, characteristic, data, length, withResponse);
#endif
}
}
public static void SubscribeCharacteristic (string name, string service, string characteristic, Action<string> notificationAction, Action<string, byte[]> action)
{
if (!Application.isEditor)
{
if (bluetoothDeviceScript != null)
{
bluetoothDeviceScript.DidUpdateNotificationStateForCharacteristicAction = notificationAction;
bluetoothDeviceScript.DidUpdateCharacteristicValueAction = action;
}
#if UNITY_IPHONE
_iOSBluetoothLESubscribeCharacteristic (name, service, characteristic);
#elif UNITY_ANDROID
if (_android != null)
_android.Call ("androidSubscribeCharacteristic", name, service, characteristic);
#endif
}
}
public static void SubscribeCharacteristicWithDeviceAddress (string name, string service, string characteristic, Action<string, string> notificationAction, Action<string, string, byte[]> action)
{
if (!Application.isEditor)
{
if (bluetoothDeviceScript != null)
{
bluetoothDeviceScript.DidUpdateNotificationStateForCharacteristicWithDeviceAddressAction = notificationAction;
bluetoothDeviceScript.DidUpdateCharacteristicValueWithDeviceAddressAction = action;
}
#if UNITY_IPHONE
_iOSBluetoothLESubscribeCharacteristic (name, service, characteristic);
#elif UNITY_ANDROID
if (_android != null)
_android.Call ("androidSubscribeCharacteristic", name, service, characteristic);
#endif
}
}
public static void UnSubscribeCharacteristic (string name, string service, string characteristic, Action<string> action)
{
if (!Application.isEditor)
{
if (bluetoothDeviceScript != null)
bluetoothDeviceScript.DidUpdateNotificationStateForCharacteristicAction = action;
#if UNITY_IPHONE
_iOSBluetoothLEUnSubscribeCharacteristic (name, service, characteristic);
#elif UNITY_ANDROID
if (_android != null)
_android.Call ("androidUnsubscribeCharacteristic", name, service, characteristic);
#endif
}
}
public static void PeripheralName (string newName)
{
if (!Application.isEditor)
{
#if UNITY_IPHONE
_iOSBluetoothLEPeripheralName (newName);
#endif
}
}
public static void CreateService (string uuid, bool primary, Action<string> action)
{
if (!Application.isEditor)
{
if (bluetoothDeviceScript != null)
bluetoothDeviceScript.ServiceAddedAction = action;
#if UNITY_IPHONE
_iOSBluetoothLECreateService (uuid, primary);
#endif
}
}
public static void RemoveService (string uuid)
{
if (!Application.isEditor)
{
#if UNITY_IPHONE
_iOSBluetoothLERemoveService (uuid);
#endif
}
}
public static void RemoveServices ()
{
if (!Application.isEditor)
{
#if UNITY_IPHONE
_iOSBluetoothLERemoveServices ();
#endif
}
}
public static void CreateCharacteristic (string uuid, CBCharacteristicProperties properties, CBAttributePermissions permissions, byte[] data, int length, Action<string, byte[]> action)
{
if (!Application.isEditor)
{
if (bluetoothDeviceScript != null)
bluetoothDeviceScript.PeripheralReceivedWriteDataAction = action;
#if UNITY_IPHONE
_iOSBluetoothLECreateCharacteristic (uuid, (int)properties, (int)permissions, data, length);
#endif
}
}
public static void RemoveCharacteristic (string uuid)
{
if (!Application.isEditor)
{
if (bluetoothDeviceScript != null)
bluetoothDeviceScript.PeripheralReceivedWriteDataAction = null;
#if UNITY_IPHONE
_iOSBluetoothLERemoveCharacteristic (uuid);
#endif
}
}
public static void RemoveCharacteristics ()
{
if (!Application.isEditor)
{
#if UNITY_IPHONE
_iOSBluetoothLERemoveCharacteristics ();
#endif
}
}
public static void StartAdvertising (Action action)
{
if (!Application.isEditor)
{
if (bluetoothDeviceScript != null)
bluetoothDeviceScript.StartedAdvertisingAction = action;
#if UNITY_IPHONE
_iOSBluetoothLEStartAdvertising ();
#endif
}
}
public static void StopAdvertising (Action action)
{
if (!Application.isEditor)
{
if (bluetoothDeviceScript != null)
bluetoothDeviceScript.StoppedAdvertisingAction = action;
#if UNITY_IPHONE
_iOSBluetoothLEStopAdvertising ();
#endif
}
}
public static void UpdateCharacteristicValue (string uuid, byte[] data, int length)
{
if (!Application.isEditor)
{
#if UNITY_IPHONE
_iOSBluetoothLEUpdateCharacteristicValue (uuid, data, length);
#endif
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Description;
using BattleGame.Server.Areas.HelpPage.Models;
namespace BattleGame.Server.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
model = GenerateApiModel(apiDescription, sampleGenerator);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator)
{
HelpPageApiModel apiModel = new HelpPageApiModel();
apiModel.ApiDescription = apiDescription;
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message));
}
return apiModel;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace Uno.Web.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
namespace AutoMapper
{
using System;
using System.Linq;
using Configuration;
using Execution;
using Mappers;
public class Mapper : IRuntimeMapper
{
#region Static API
private static IConfigurationProvider _configuration;
private static IMapper _instance;
/// <summary>
/// Configuration provider for performing maps
/// </summary>
public static IConfigurationProvider Configuration
{
get
{
if (_configuration == null)
throw new InvalidOperationException("Mapper not initialized. Call Initialize with appropriate configuration.");
return _configuration;
}
private set { _configuration = value; }
}
/// <summary>
/// Static mapper instance. You can also create a <see cref="Mapper"/> instance directly using the <see cref="Configuration"/> instance.
/// </summary>
public static IMapper Instance
{
get
{
if (_instance == null)
throw new InvalidOperationException("Mapper not initialized. Call Initialize with appropriate configuration.");
return _instance;
}
private set { _instance = value; }
}
/// <summary>
/// Initialize static configuration instance
/// </summary>
/// <param name="config">Configuration action</param>
public static void Initialize(Action<IMapperConfigurationExpression> config)
{
Configuration = new MapperConfiguration(config);
Instance = new Mapper(Configuration);
}
/// <summary>
/// Execute a mapping from the source object to a new destination object.
/// The source type is inferred from the source object.
/// </summary>
/// <typeparam name="TDestination">Destination type to create</typeparam>
/// <param name="source">Source object to map from</param>
/// <returns>Mapped destination object</returns>
public static TDestination Map<TDestination>(object source) => Instance.Map<TDestination>(source);
/// <summary>
/// Execute a mapping from the source object to a new destination object with supplied mapping options.
/// </summary>
/// <typeparam name="TDestination">Destination type to create</typeparam>
/// <param name="source">Source object to map from</param>
/// <param name="opts">Mapping options</param>
/// <returns>Mapped destination object</returns>
public static TDestination Map<TDestination>(object source, Action<IMappingOperationOptions> opts)
=> Instance.Map<TDestination>(source, opts);
/// <summary>
/// Execute a mapping from the source object to a new destination object.
/// </summary>
/// <typeparam name="TSource">Source type to use, regardless of the runtime type</typeparam>
/// <typeparam name="TDestination">Destination type to create</typeparam>
/// <param name="source">Source object to map from</param>
/// <returns>Mapped destination object</returns>
public static TDestination Map<TSource, TDestination>(TSource source)
=> Instance.Map<TSource, TDestination>(source);
/// <summary>
/// Execute a mapping from the source object to a new destination object with supplied mapping options.
/// </summary>
/// <typeparam name="TSource">Source type to use</typeparam>
/// <typeparam name="TDestination">Destination type to create</typeparam>
/// <param name="source">Source object to map from</param>
/// <param name="opts">Mapping options</param>
/// <returns>Mapped destination object</returns>
public static TDestination Map<TSource, TDestination>(TSource source, Action<IMappingOperationOptions<TSource, TDestination>> opts)
=> Instance.Map(source, opts);
/// <summary>
/// Execute a mapping from the source object to the existing destination object.
/// </summary>
/// <typeparam name="TSource">Source type to use</typeparam>
/// <typeparam name="TDestination">Dsetination type</typeparam>
/// <param name="source">Source object to map from</param>
/// <param name="destination">Destination object to map into</param>
/// <returns>The mapped destination object, same instance as the <paramref name="destination"/> object</returns>
public static TDestination Map<TSource, TDestination>(TSource source, TDestination destination)
=> Instance.Map(source, destination);
/// <summary>
/// Execute a mapping from the source object to the existing destination object with supplied mapping options.
/// </summary>
/// <typeparam name="TSource">Source type to use</typeparam>
/// <typeparam name="TDestination">Destination type</typeparam>
/// <param name="source">Source object to map from</param>
/// <param name="destination">Destination object to map into</param>
/// <param name="opts">Mapping options</param>
/// <returns>The mapped destination object, same instance as the <paramref name="destination"/> object</returns>
public static TDestination Map<TSource, TDestination>(TSource source, TDestination destination, Action<IMappingOperationOptions<TSource, TDestination>> opts)
=> Instance.Map(source, destination, opts);
/// <summary>
/// Execute a mapping from the source object to a new destination object with explicit <see cref="System.Type"/> objects
/// </summary>
/// <param name="source">Source object to map from</param>
/// <param name="sourceType">Source type to use</param>
/// <param name="destinationType">Destination type to create</param>
/// <returns>Mapped destination object</returns>
public static object Map(object source, Type sourceType, Type destinationType)
=> Instance.Map(source, sourceType, destinationType);
/// <summary>
/// Execute a mapping from the source object to a new destination object with explicit <see cref="System.Type"/> objects and supplied mapping options.
/// </summary>
/// <param name="source">Source object to map from</param>
/// <param name="sourceType">Source type to use</param>
/// <param name="destinationType">Destination type to create</param>
/// <param name="opts">Mapping options</param>
/// <returns>Mapped destination object</returns>
public static object Map(object source, Type sourceType, Type destinationType, Action<IMappingOperationOptions> opts)
=> Instance.Map(source, sourceType, destinationType, opts);
/// <summary>
/// Execute a mapping from the source object to existing destination object with explicit <see cref="System.Type"/> objects
/// </summary>
/// <param name="source">Source object to map from</param>
/// <param name="destination">Destination object to map into</param>
/// <param name="sourceType">Source type to use</param>
/// <param name="destinationType">Destination type to use</param>
/// <returns>Mapped destination object, same instance as the <paramref name="destination"/> object</returns>
public static object Map(object source, object destination, Type sourceType, Type destinationType)
=> Instance.Map(source, destination, sourceType, destinationType);
/// <summary>
/// Execute a mapping from the source object to existing destination object with supplied mapping options and explicit <see cref="System.Type"/> objects
/// </summary>
/// <param name="source">Source object to map from</param>
/// <param name="destination">Destination object to map into</param>
/// <param name="sourceType">Source type to use</param>
/// <param name="destinationType">Destination type to use</param>
/// <param name="opts">Mapping options</param>
/// <returns>Mapped destination object, same instance as the <paramref name="destination"/> object</returns>
public static object Map(object source, object destination, Type sourceType, Type destinationType, Action<IMappingOperationOptions> opts)
=> Instance.Map(source, destination, sourceType, destinationType, opts);
#endregion
private readonly IConfigurationProvider _configurationProvider;
private readonly Func<Type, object> _serviceCtor;
private readonly MappingOperationOptions _defaultMappingOptions;
public Mapper(IConfigurationProvider configurationProvider)
: this(configurationProvider, configurationProvider.ServiceCtor)
{
}
public Mapper(IConfigurationProvider configurationProvider, Func<Type, object> serviceCtor)
{
_configurationProvider = configurationProvider;
_serviceCtor = serviceCtor;
_defaultMappingOptions = new MappingOperationOptions(_serviceCtor);
}
Func<Type, object> IMapper.ServiceCtor => _serviceCtor;
IConfigurationProvider IMapper.ConfigurationProvider => _configurationProvider;
TDestination IMapper.Map<TDestination>(object source)
{
if (source == null)
return default(TDestination);
var types = new TypePair(source.GetType(), typeof(TDestination));
var func = _configurationProvider.GetUntypedMapperFunc(new MapRequest(types, types));
var context = new ResolutionContext(source, null, types, _defaultMappingOptions, this);
return (TDestination) func(source, null, context);
}
TDestination IMapper.Map<TDestination>(object source, Action<IMappingOperationOptions> opts)
{
var mappedObject = default(TDestination);
if (source == null) return mappedObject;
var sourceType = source.GetType();
var destinationType = typeof(TDestination);
mappedObject = (TDestination)((IMapper)this).Map(source, sourceType, destinationType, opts);
return mappedObject;
}
TDestination IMapper.Map<TSource, TDestination>(TSource source)
{
var types = TypePair.Create(source, null, typeof(TSource), typeof (TDestination));
var func = _configurationProvider.GetMapperFunc<TSource, TDestination>(types);
var destination = default(TDestination);
var context = new ResolutionContext(source, destination, types, _defaultMappingOptions, this);
return func(source, destination, context);
}
TDestination IMapper.Map<TSource, TDestination>(TSource source, Action<IMappingOperationOptions<TSource, TDestination>> opts)
{
var types = TypePair.Create(source, null, typeof(TSource), typeof(TDestination));
var func = _configurationProvider.GetMapperFunc<TSource, TDestination>(types);
var destination = default(TDestination);
var typedOptions = new MappingOperationOptions<TSource, TDestination>(_serviceCtor);
opts(typedOptions);
var context = new ResolutionContext(source, destination, types, typedOptions, this);
return func(source, destination, context);
}
TDestination IMapper.Map<TSource, TDestination>(TSource source, TDestination destination)
{
var types = TypePair.Create(source, destination, typeof(TSource), typeof(TDestination));
var func = _configurationProvider.GetMapperFunc<TSource, TDestination>(types);
var context = new ResolutionContext(source, destination, types, _defaultMappingOptions, this);
return func(source, destination, context);
}
TDestination IMapper.Map<TSource, TDestination>(TSource source, TDestination destination, Action<IMappingOperationOptions<TSource, TDestination>> opts)
{
var types = TypePair.Create(source, destination, typeof(TSource), typeof(TDestination));
var func = _configurationProvider.GetMapperFunc<TSource, TDestination>(types);
var typedOptions = new MappingOperationOptions<TSource, TDestination>(_serviceCtor);
opts(typedOptions);
var context = new ResolutionContext(source, destination, types, typedOptions, this);
return func(source, destination, context);
}
object IMapper.Map(object source, Type sourceType, Type destinationType)
{
var types = TypePair.Create(source, null, sourceType, destinationType);
var func = _configurationProvider.GetUntypedMapperFunc(new MapRequest(new TypePair(sourceType, destinationType), types));
var context = new ResolutionContext(source, null, types, _defaultMappingOptions, this);
return func(source, null, context);
}
object IMapper.Map(object source, Type sourceType, Type destinationType, Action<IMappingOperationOptions> opts)
{
var types = TypePair.Create(source, null, sourceType, destinationType);
var func = _configurationProvider.GetUntypedMapperFunc(new MapRequest(new TypePair(sourceType, destinationType), types));
var options = new MappingOperationOptions(_serviceCtor);
opts(options);
var context = new ResolutionContext(source, null, types, options, this);
return func(source, null, context);
}
object IMapper.Map(object source, object destination, Type sourceType, Type destinationType)
{
var types = TypePair.Create(source, destination, sourceType, destinationType);
var func = _configurationProvider.GetUntypedMapperFunc(new MapRequest(new TypePair(sourceType, destinationType), types));
var context = new ResolutionContext(source, destination, types, _defaultMappingOptions, this);
return func(source, destination, context);
}
object IMapper.Map(object source, object destination, Type sourceType, Type destinationType,
Action<IMappingOperationOptions> opts)
{
var types = TypePair.Create(source, destination, sourceType, destinationType);
var func = _configurationProvider.GetUntypedMapperFunc(new MapRequest(new TypePair(sourceType, destinationType), types));
var options = new MappingOperationOptions(_serviceCtor);
opts(options);
var context = new ResolutionContext(source, destination, types, options, this);
return func(source, destination, context);
}
object IRuntimeMapper.Map(ResolutionContext context)
{
var types = TypePair.Create(context.SourceValue, context.DestinationValue, context.SourceType, context.DestinationType);
var func = _configurationProvider.GetUntypedMapperFunc(new MapRequest(new TypePair(context.SourceType, context.DestinationType), types));
return func(context.SourceValue, context.DestinationValue, context);
}
object IRuntimeMapper.Map(object source, object destination, Type sourceType, Type destinationType, ResolutionContext parent)
{
var types = TypePair.Create(source, destination, sourceType, destinationType);
var func = _configurationProvider.GetUntypedMapperFunc(new MapRequest(new TypePair(sourceType, destinationType), types));
var context = new ResolutionContext(source, destination, types, parent);
return func(source, destination, context);
}
TDestination IRuntimeMapper.Map<TSource, TDestination>(TSource source, TDestination destination, ResolutionContext parent)
{
var types = TypePair.Create(source, destination, typeof(TSource), typeof(TDestination));
var func = _configurationProvider.GetMapperFunc<TSource, TDestination>(types);
var context = new ResolutionContext(source, destination, types, parent);
return func(source, destination, context);
}
object IRuntimeMapper.CreateObject(ResolutionContext context)
{
if(context.DestinationValue != null)
{
return context.DestinationValue;
}
return !_configurationProvider.AllowNullDestinationValues
? ObjectCreator.CreateNonNullValue(context.DestinationType)
: ObjectCreator.CreateObject(context.DestinationType);
}
TDestination IRuntimeMapper.CreateObject<TDestination>(ResolutionContext context)
{
if (context.DestinationValue != null)
{
return (TDestination) context.DestinationValue;
}
return (TDestination) (!_configurationProvider.AllowNullDestinationValues
? ObjectCreator.CreateNonNullValue(typeof(TDestination))
: ObjectCreator.CreateObject(typeof(TDestination)));
}
bool IRuntimeMapper.ShouldMapSourceValueAsNull(ResolutionContext context)
{
if (context.DestinationType.IsValueType() && !context.DestinationType.IsNullableType())
return false;
var typeMap = context.GetContextTypeMap();
return typeMap?.Profile.AllowNullDestinationValues ?? _configurationProvider.AllowNullDestinationValues;
}
bool IRuntimeMapper.ShouldMapSourceCollectionAsNull(ResolutionContext context)
{
var typeMap = context.GetContextTypeMap();
return typeMap?.Profile.AllowNullCollections ?? _configurationProvider.AllowNullCollections;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
using Newtonsoft.Json.Linq;
namespace PushSharp.Apple
{
public class AppleNotificationPayload
{
public AppleNotificationAlert Alert { get; set; }
public int? ContentAvailable { get; set; }
public int? Badge { get; set; }
public string Sound { get; set; }
public bool HideActionButton { get; set; }
public string Category { get; set; }
public Dictionary<string, object[]> CustomItems
{
get;
private set;
}
public AppleNotificationPayload()
{
HideActionButton = false;
Alert = new AppleNotificationAlert();
CustomItems = new Dictionary<string, object[]>();
}
public AppleNotificationPayload(string alert)
{
HideActionButton = false;
Alert = new AppleNotificationAlert() { Body = alert };
CustomItems = new Dictionary<string, object[]>();
}
public AppleNotificationPayload(string alert, int badge)
{
HideActionButton = false;
Alert = new AppleNotificationAlert() { Body = alert };
Badge = badge;
CustomItems = new Dictionary<string, object[]>();
}
public AppleNotificationPayload(string alert, int badge, string sound)
{
HideActionButton = false;
Alert = new AppleNotificationAlert() { Body = alert };
Badge = badge;
Sound = sound;
CustomItems = new Dictionary<string, object[]>();
}
public AppleNotificationPayload(string alert, int badge, string sound, string category)
: this(alert, badge, sound)
{
Category = category;
}
public void AddCustom(string key, params object[] values)
{
if (values != null)
this.CustomItems.Add(key, values);
}
public string ToJson()
{
JObject json = new JObject();
JObject aps = new JObject();
if (!this.Alert.IsEmpty)
{
if (!string.IsNullOrEmpty(this.Alert.Body)
&& string.IsNullOrEmpty(this.Alert.LocalizedKey)
&& string.IsNullOrEmpty(this.Alert.ActionLocalizedKey)
&& (this.Alert.LocalizedArgs == null || this.Alert.LocalizedArgs.Count <= 0)
&& string.IsNullOrEmpty(this.Alert.LaunchImage)
&& !this.HideActionButton)
{
aps["alert"] = new JValue(this.Alert.Body);
}
else
{
JObject jsonAlert = new JObject();
if (!string.IsNullOrEmpty(this.Alert.LocalizedKey))
jsonAlert["loc-key"] = new JValue(this.Alert.LocalizedKey);
if (this.Alert.LocalizedArgs != null && this.Alert.LocalizedArgs.Count > 0)
jsonAlert["loc-args"] = new JArray(this.Alert.LocalizedArgs.ToArray());
if (!string.IsNullOrEmpty(this.Alert.Body))
jsonAlert["body"] = new JValue(this.Alert.Body);
if (this.HideActionButton)
jsonAlert["action-loc-key"] = new JValue((string)null);
else if (!string.IsNullOrEmpty(this.Alert.ActionLocalizedKey))
jsonAlert["action-loc-key"] = new JValue(this.Alert.ActionLocalizedKey);
if (!string.IsNullOrEmpty(this.Alert.LaunchImage))
jsonAlert["launch-image"] = new JValue(this.Alert.LaunchImage);
aps["alert"] = jsonAlert;
}
}
if (this.Badge.HasValue)
aps["badge"] = new JValue(this.Badge.Value);
if (!string.IsNullOrEmpty(this.Sound))
aps["sound"] = new JValue(this.Sound);
if (this.ContentAvailable.HasValue)
{
aps["content-available"] = new JValue(this.ContentAvailable.Value);
if (string.IsNullOrEmpty(this.Sound))
{
//You need to add an empty string for sound or the payload is not sent
aps["sound"] = new JValue("");
}
}
if (!string.IsNullOrEmpty(this.Category))
{
// iOS8 Interactive Notifications
aps["category"] = new JValue(this.Category);
}
if (aps.Count > 0)
json["aps"] = aps;
foreach (string key in this.CustomItems.Keys)
{
if (this.CustomItems[key].Length == 1)
{
object custom = this.CustomItems[key][0];
json[key] = custom is JToken ? (JToken) custom : new JValue(custom);
}
else if (this.CustomItems[key].Length > 1)
json[key] = new JArray(this.CustomItems[key]);
}
string rawString = json.ToString(Newtonsoft.Json.Formatting.None, null);
StringBuilder encodedString = new StringBuilder();
foreach (char c in rawString)
{
if ((int)c < 32 || (int)c > 127)
encodedString.Append("\\u" + String.Format("{0:x4}", Convert.ToUInt32(c)));
else
encodedString.Append(c);
}
return rawString;// encodedString.ToString();
}
//public string ToJson()
//{
// bool tmpBool;
// double tmpDbl;
// var json = new StringBuilder();
// var aps = new StringBuilder();
// if (!this.Alert.IsEmpty)
// {
// if (!string.IsNullOrEmpty(this.Alert.Body)
// && string.IsNullOrEmpty(this.Alert.LocalizedKey)
// && string.IsNullOrEmpty(this.Alert.ActionLocalizedKey)
// && (this.Alert.LocalizedArgs == null || this.Alert.LocalizedArgs.Count <= 0)
// && !this.HideActionButton)
// {
// aps.AppendFormat("\"alert\":\"{0}\",", this.Alert.Body);
// }
// else
// {
// var jsonAlert = new StringBuilder();
// if (!string.IsNullOrEmpty(this.Alert.LocalizedKey))
// jsonAlert.AppendFormat("\"loc-key\":\"{0}\",", this.Alert.LocalizedKey);
// if (this.Alert.LocalizedArgs != null && this.Alert.LocalizedArgs.Count > 0)
// {
// var locArgs = new StringBuilder();
// foreach (var larg in this.Alert.LocalizedArgs)
// {
// if (double.TryParse(larg.ToString(), out tmpDbl)
// || bool.TryParse(larg.ToString(), out tmpBool))
// locArgs.AppendFormat("{0},", larg.ToString());
// else
// locArgs.AppendFormat("\"{0}\",", larg.ToString());
// }
// jsonAlert.AppendFormat("\"loc-args\":[{0}],", locArgs.ToString().TrimEnd(','));
// }
// if (!string.IsNullOrEmpty(this.Alert.Body))
// jsonAlert.AppendFormat("\body\":\"{0}\",", this.Alert.Body);
// if (this.HideActionButton)
// jsonAlert.AppendFormat("\"action-loc-key\":null,");
// else if (!string.IsNullOrEmpty(this.Alert.ActionLocalizedKey))
// jsonAlert.AppendFormat("\action-loc-key\":\"{0}\",", this.Alert.ActionLocalizedKey);
// aps.Append("\"alert\":{");
// aps.Append(jsonAlert.ToString().TrimEnd(','));
// aps.Append("},");
// }
// }
// if (this.Badge.HasValue)
// aps.AppendFormat("\"badge\":{0},", this.Badge.Value.ToString());
// if (!string.IsNullOrEmpty(this.Sound))
// aps.AppendFormat("\"sound\":\"{0}\",", this.Sound);
// if (this.ContentAvailable.HasValue)
// aps.AppendFormat("\"content-available\":{0},", this.ContentAvailable.Value.ToString());
// json.Append("\"aps\":{");
// json.Append(aps.ToString().TrimEnd(','));
// json.Append("},");
// foreach (string key in this.CustomItems.Keys)
// {
// if (this.CustomItems[key].Length == 1)
// {
// if (double.TryParse(this.CustomItems[key].ToString(), out tmpDbl)
// || bool.TryParse(this.CustomItems[key].ToString(), out tmpBool))
// json.AppendFormat("\"{0}\":[{1}],", key, this.CustomItems[key][0].ToString());
// else
// json.AppendFormat("\"{0}\":[\"{1}\",", key, this.CustomItems[key][0].ToString());
// }
// else if (this.CustomItems[key].Length > 1)
// {
// var jarr = new StringBuilder();
// foreach (var item in this.CustomItems[key])
// {
// if (double.TryParse(item.ToString(), out tmpDbl)
// || bool.TryParse(item.ToString(), out tmpBool))
// jarr.AppendFormat("{0},", item.ToString());
// else
// jarr.AppendFormat("\"{0}\",", item.ToString());
// }
// json.AppendFormat("\"{0}\":[{1}],", key, jarr.ToString().Trim(','));
// }
// }
// string rawString = "{" + json.ToString().TrimEnd(',') + "}";
// StringBuilder encodedString = new StringBuilder();
// foreach (char c in rawString)
// {
// if ((int)c < 32 || (int)c > 127)
// encodedString.Append("\\u" + String.Format("{0:x4}", Convert.ToUInt32(c)));
// else
// encodedString.Append(c);
// }
// return rawString;// encodedString.ToString();
//}
public override string ToString()
{
return ToJson();
}
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
using System;
using System.Collections.Generic;
using System.Linq;
using Twilio.Base;
using Twilio.Converters;
using Twilio.Types;
namespace Twilio.Rest.Api.V2010.Account.Conference
{
/// <summary>
/// Fetch an instance of a participant
/// </summary>
public class FetchParticipantOptions : IOptions<ParticipantResource>
{
/// <summary>
/// The SID of the Account that created the resource to fetch
/// </summary>
public string PathAccountSid { get; set; }
/// <summary>
/// The SID of the conference with the participant to fetch
/// </summary>
public string PathConferenceSid { get; }
/// <summary>
/// The Call SID or URL encoded label of the participant to fetch
/// </summary>
public string PathCallSid { get; }
/// <summary>
/// Construct a new FetchParticipantOptions
/// </summary>
/// <param name="pathConferenceSid"> The SID of the conference with the participant to fetch </param>
/// <param name="pathCallSid"> The Call SID or URL encoded label of the participant to fetch </param>
public FetchParticipantOptions(string pathConferenceSid, string pathCallSid)
{
PathConferenceSid = pathConferenceSid;
PathCallSid = pathCallSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
return p;
}
}
/// <summary>
/// Update the properties of the participant
/// </summary>
public class UpdateParticipantOptions : IOptions<ParticipantResource>
{
/// <summary>
/// The SID of the Account that created the resources to update
/// </summary>
public string PathAccountSid { get; set; }
/// <summary>
/// The SID of the conference with the participant to update
/// </summary>
public string PathConferenceSid { get; }
/// <summary>
/// The Call SID or URL encoded label of the participant to update
/// </summary>
public string PathCallSid { get; }
/// <summary>
/// Whether the participant should be muted
/// </summary>
public bool? Muted { get; set; }
/// <summary>
/// Whether the participant should be on hold
/// </summary>
public bool? Hold { get; set; }
/// <summary>
/// The URL we call using the `hold_method` for music that plays when the participant is on hold
/// </summary>
public Uri HoldUrl { get; set; }
/// <summary>
/// The HTTP method we should use to call hold_url
/// </summary>
public Twilio.Http.HttpMethod HoldMethod { get; set; }
/// <summary>
/// The URL we call using the `announce_method` for an announcement to the participant
/// </summary>
public Uri AnnounceUrl { get; set; }
/// <summary>
/// The HTTP method we should use to call announce_url
/// </summary>
public Twilio.Http.HttpMethod AnnounceMethod { get; set; }
/// <summary>
/// URL that hosts pre-conference hold music
/// </summary>
public Uri WaitUrl { get; set; }
/// <summary>
/// The HTTP method we should use to call `wait_url`
/// </summary>
public Twilio.Http.HttpMethod WaitMethod { get; set; }
/// <summary>
/// Whether to play a notification beep to the conference when the participant exit
/// </summary>
public bool? BeepOnExit { get; set; }
/// <summary>
/// Whether to end the conference when the participant leaves
/// </summary>
public bool? EndConferenceOnExit { get; set; }
/// <summary>
/// Indicates if the participant changed to coach
/// </summary>
public bool? Coaching { get; set; }
/// <summary>
/// The SID of the participant who is being `coached`
/// </summary>
public string CallSidToCoach { get; set; }
/// <summary>
/// Construct a new UpdateParticipantOptions
/// </summary>
/// <param name="pathConferenceSid"> The SID of the conference with the participant to update </param>
/// <param name="pathCallSid"> The Call SID or URL encoded label of the participant to update </param>
public UpdateParticipantOptions(string pathConferenceSid, string pathCallSid)
{
PathConferenceSid = pathConferenceSid;
PathCallSid = pathCallSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (Muted != null)
{
p.Add(new KeyValuePair<string, string>("Muted", Muted.Value.ToString().ToLower()));
}
if (Hold != null)
{
p.Add(new KeyValuePair<string, string>("Hold", Hold.Value.ToString().ToLower()));
}
if (HoldUrl != null)
{
p.Add(new KeyValuePair<string, string>("HoldUrl", Serializers.Url(HoldUrl)));
}
if (HoldMethod != null)
{
p.Add(new KeyValuePair<string, string>("HoldMethod", HoldMethod.ToString()));
}
if (AnnounceUrl != null)
{
p.Add(new KeyValuePair<string, string>("AnnounceUrl", Serializers.Url(AnnounceUrl)));
}
if (AnnounceMethod != null)
{
p.Add(new KeyValuePair<string, string>("AnnounceMethod", AnnounceMethod.ToString()));
}
if (WaitUrl != null)
{
p.Add(new KeyValuePair<string, string>("WaitUrl", Serializers.Url(WaitUrl)));
}
if (WaitMethod != null)
{
p.Add(new KeyValuePair<string, string>("WaitMethod", WaitMethod.ToString()));
}
if (BeepOnExit != null)
{
p.Add(new KeyValuePair<string, string>("BeepOnExit", BeepOnExit.Value.ToString().ToLower()));
}
if (EndConferenceOnExit != null)
{
p.Add(new KeyValuePair<string, string>("EndConferenceOnExit", EndConferenceOnExit.Value.ToString().ToLower()));
}
if (Coaching != null)
{
p.Add(new KeyValuePair<string, string>("Coaching", Coaching.Value.ToString().ToLower()));
}
if (CallSidToCoach != null)
{
p.Add(new KeyValuePair<string, string>("CallSidToCoach", CallSidToCoach.ToString()));
}
return p;
}
}
/// <summary>
/// CreateParticipantOptions
/// </summary>
public class CreateParticipantOptions : IOptions<ParticipantResource>
{
/// <summary>
/// The SID of the Account that will create the resource
/// </summary>
public string PathAccountSid { get; set; }
/// <summary>
/// The SID of the participant's conference
/// </summary>
public string PathConferenceSid { get; }
/// <summary>
/// The phone number, Client identifier, or username portion of SIP address that made this call.
/// </summary>
public IEndpoint From { get; }
/// <summary>
/// The phone number, SIP address or Client identifier that received this call.
/// </summary>
public IEndpoint To { get; }
/// <summary>
/// The URL we should call to send status information to your application
/// </summary>
public Uri StatusCallback { get; set; }
/// <summary>
/// The HTTP method we should use to call `status_callback`
/// </summary>
public Twilio.Http.HttpMethod StatusCallbackMethod { get; set; }
/// <summary>
/// Set state change events that will trigger a callback
/// </summary>
public List<string> StatusCallbackEvent { get; set; }
/// <summary>
/// The label of this participant
/// </summary>
public string Label { get; set; }
/// <summary>
/// he number of seconds that we should wait for an answer
/// </summary>
public int? Timeout { get; set; }
/// <summary>
/// Whether to record the participant and their conferences
/// </summary>
public bool? Record { get; set; }
/// <summary>
/// Whether to mute the agent
/// </summary>
public bool? Muted { get; set; }
/// <summary>
/// Whether to play a notification beep to the conference when the participant joins
/// </summary>
public string Beep { get; set; }
/// <summary>
/// Whether the conference starts when the participant joins the conference
/// </summary>
public bool? StartConferenceOnEnter { get; set; }
/// <summary>
/// Whether to end the conference when the participant leaves
/// </summary>
public bool? EndConferenceOnExit { get; set; }
/// <summary>
/// URL that hosts pre-conference hold music
/// </summary>
public Uri WaitUrl { get; set; }
/// <summary>
/// The HTTP method we should use to call `wait_url`
/// </summary>
public Twilio.Http.HttpMethod WaitMethod { get; set; }
/// <summary>
/// Whether agents can hear the state of the outbound call
/// </summary>
public bool? EarlyMedia { get; set; }
/// <summary>
/// The maximum number of agent conference participants
/// </summary>
public int? MaxParticipants { get; set; }
/// <summary>
/// Whether to record the conference the participant is joining
/// </summary>
public string ConferenceRecord { get; set; }
/// <summary>
/// Whether to trim leading and trailing silence from your recorded conference audio files
/// </summary>
public string ConferenceTrim { get; set; }
/// <summary>
/// The callback URL for conference events
/// </summary>
public Uri ConferenceStatusCallback { get; set; }
/// <summary>
/// HTTP method for requesting `conference_status_callback` URL
/// </summary>
public Twilio.Http.HttpMethod ConferenceStatusCallbackMethod { get; set; }
/// <summary>
/// The conference state changes that should generate a call to `conference_status_callback`
/// </summary>
public List<string> ConferenceStatusCallbackEvent { get; set; }
/// <summary>
/// Specify `mono` or `dual` recording channels
/// </summary>
public string RecordingChannels { get; set; }
/// <summary>
/// The URL that we should call using the `recording_status_callback_method` when the recording status changes
/// </summary>
public Uri RecordingStatusCallback { get; set; }
/// <summary>
/// The HTTP method we should use when we call `recording_status_callback`
/// </summary>
public Twilio.Http.HttpMethod RecordingStatusCallbackMethod { get; set; }
/// <summary>
/// The SIP username used for authentication
/// </summary>
public string SipAuthUsername { get; set; }
/// <summary>
/// The SIP password for authentication
/// </summary>
public string SipAuthPassword { get; set; }
/// <summary>
/// The region where we should mix the conference audio
/// </summary>
public string Region { get; set; }
/// <summary>
/// The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available
/// </summary>
public Uri ConferenceRecordingStatusCallback { get; set; }
/// <summary>
/// The HTTP method we should use to call `conference_recording_status_callback`
/// </summary>
public Twilio.Http.HttpMethod ConferenceRecordingStatusCallbackMethod { get; set; }
/// <summary>
/// The recording state changes that should generate a call to `recording_status_callback`
/// </summary>
public List<string> RecordingStatusCallbackEvent { get; set; }
/// <summary>
/// The conference recording state changes that should generate a call to `conference_recording_status_callback`
/// </summary>
public List<string> ConferenceRecordingStatusCallbackEvent { get; set; }
/// <summary>
/// Indicates if the participant changed to coach
/// </summary>
public bool? Coaching { get; set; }
/// <summary>
/// The SID of the participant who is being `coached`
/// </summary>
public string CallSidToCoach { get; set; }
/// <summary>
/// Jitter Buffer size for the connecting participant
/// </summary>
public string JitterBufferSize { get; set; }
/// <summary>
/// BYOC trunk SID (Beta)
/// </summary>
public string Byoc { get; set; }
/// <summary>
/// The phone number, Client identifier, or username portion of SIP address that made this call.
/// </summary>
public string CallerId { get; set; }
/// <summary>
/// Reason for the call (Branded Calls Beta)
/// </summary>
public string CallReason { get; set; }
/// <summary>
/// The track(s) to record
/// </summary>
public string RecordingTrack { get; set; }
/// <summary>
/// The maximum duration of the call in seconds.
/// </summary>
public int? TimeLimit { get; set; }
/// <summary>
/// Construct a new CreateParticipantOptions
/// </summary>
/// <param name="pathConferenceSid"> The SID of the participant's conference </param>
/// <param name="from"> The phone number, Client identifier, or username portion of SIP address that made this call.
/// </param>
/// <param name="to"> The phone number, SIP address or Client identifier that received this call. </param>
public CreateParticipantOptions(string pathConferenceSid, IEndpoint from, IEndpoint to)
{
PathConferenceSid = pathConferenceSid;
From = from;
To = to;
StatusCallbackEvent = new List<string>();
ConferenceStatusCallbackEvent = new List<string>();
RecordingStatusCallbackEvent = new List<string>();
ConferenceRecordingStatusCallbackEvent = new List<string>();
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (From != null)
{
p.Add(new KeyValuePair<string, string>("From", From.ToString()));
}
if (To != null)
{
p.Add(new KeyValuePair<string, string>("To", To.ToString()));
}
if (StatusCallback != null)
{
p.Add(new KeyValuePair<string, string>("StatusCallback", Serializers.Url(StatusCallback)));
}
if (StatusCallbackMethod != null)
{
p.Add(new KeyValuePair<string, string>("StatusCallbackMethod", StatusCallbackMethod.ToString()));
}
if (StatusCallbackEvent != null)
{
p.AddRange(StatusCallbackEvent.Select(prop => new KeyValuePair<string, string>("StatusCallbackEvent", prop)));
}
if (Label != null)
{
p.Add(new KeyValuePair<string, string>("Label", Label));
}
if (Timeout != null)
{
p.Add(new KeyValuePair<string, string>("Timeout", Timeout.ToString()));
}
if (Record != null)
{
p.Add(new KeyValuePair<string, string>("Record", Record.Value.ToString().ToLower()));
}
if (Muted != null)
{
p.Add(new KeyValuePair<string, string>("Muted", Muted.Value.ToString().ToLower()));
}
if (Beep != null)
{
p.Add(new KeyValuePair<string, string>("Beep", Beep));
}
if (StartConferenceOnEnter != null)
{
p.Add(new KeyValuePair<string, string>("StartConferenceOnEnter", StartConferenceOnEnter.Value.ToString().ToLower()));
}
if (EndConferenceOnExit != null)
{
p.Add(new KeyValuePair<string, string>("EndConferenceOnExit", EndConferenceOnExit.Value.ToString().ToLower()));
}
if (WaitUrl != null)
{
p.Add(new KeyValuePair<string, string>("WaitUrl", Serializers.Url(WaitUrl)));
}
if (WaitMethod != null)
{
p.Add(new KeyValuePair<string, string>("WaitMethod", WaitMethod.ToString()));
}
if (EarlyMedia != null)
{
p.Add(new KeyValuePair<string, string>("EarlyMedia", EarlyMedia.Value.ToString().ToLower()));
}
if (MaxParticipants != null)
{
p.Add(new KeyValuePair<string, string>("MaxParticipants", MaxParticipants.ToString()));
}
if (ConferenceRecord != null)
{
p.Add(new KeyValuePair<string, string>("ConferenceRecord", ConferenceRecord));
}
if (ConferenceTrim != null)
{
p.Add(new KeyValuePair<string, string>("ConferenceTrim", ConferenceTrim));
}
if (ConferenceStatusCallback != null)
{
p.Add(new KeyValuePair<string, string>("ConferenceStatusCallback", Serializers.Url(ConferenceStatusCallback)));
}
if (ConferenceStatusCallbackMethod != null)
{
p.Add(new KeyValuePair<string, string>("ConferenceStatusCallbackMethod", ConferenceStatusCallbackMethod.ToString()));
}
if (ConferenceStatusCallbackEvent != null)
{
p.AddRange(ConferenceStatusCallbackEvent.Select(prop => new KeyValuePair<string, string>("ConferenceStatusCallbackEvent", prop)));
}
if (RecordingChannels != null)
{
p.Add(new KeyValuePair<string, string>("RecordingChannels", RecordingChannels));
}
if (RecordingStatusCallback != null)
{
p.Add(new KeyValuePair<string, string>("RecordingStatusCallback", Serializers.Url(RecordingStatusCallback)));
}
if (RecordingStatusCallbackMethod != null)
{
p.Add(new KeyValuePair<string, string>("RecordingStatusCallbackMethod", RecordingStatusCallbackMethod.ToString()));
}
if (SipAuthUsername != null)
{
p.Add(new KeyValuePair<string, string>("SipAuthUsername", SipAuthUsername));
}
if (SipAuthPassword != null)
{
p.Add(new KeyValuePair<string, string>("SipAuthPassword", SipAuthPassword));
}
if (Region != null)
{
p.Add(new KeyValuePair<string, string>("Region", Region));
}
if (ConferenceRecordingStatusCallback != null)
{
p.Add(new KeyValuePair<string, string>("ConferenceRecordingStatusCallback", Serializers.Url(ConferenceRecordingStatusCallback)));
}
if (ConferenceRecordingStatusCallbackMethod != null)
{
p.Add(new KeyValuePair<string, string>("ConferenceRecordingStatusCallbackMethod", ConferenceRecordingStatusCallbackMethod.ToString()));
}
if (RecordingStatusCallbackEvent != null)
{
p.AddRange(RecordingStatusCallbackEvent.Select(prop => new KeyValuePair<string, string>("RecordingStatusCallbackEvent", prop)));
}
if (ConferenceRecordingStatusCallbackEvent != null)
{
p.AddRange(ConferenceRecordingStatusCallbackEvent.Select(prop => new KeyValuePair<string, string>("ConferenceRecordingStatusCallbackEvent", prop)));
}
if (Coaching != null)
{
p.Add(new KeyValuePair<string, string>("Coaching", Coaching.Value.ToString().ToLower()));
}
if (CallSidToCoach != null)
{
p.Add(new KeyValuePair<string, string>("CallSidToCoach", CallSidToCoach.ToString()));
}
if (JitterBufferSize != null)
{
p.Add(new KeyValuePair<string, string>("JitterBufferSize", JitterBufferSize));
}
if (Byoc != null)
{
p.Add(new KeyValuePair<string, string>("Byoc", Byoc.ToString()));
}
if (CallerId != null)
{
p.Add(new KeyValuePair<string, string>("CallerId", CallerId));
}
if (CallReason != null)
{
p.Add(new KeyValuePair<string, string>("CallReason", CallReason));
}
if (RecordingTrack != null)
{
p.Add(new KeyValuePair<string, string>("RecordingTrack", RecordingTrack));
}
if (TimeLimit != null)
{
p.Add(new KeyValuePair<string, string>("TimeLimit", TimeLimit.ToString()));
}
return p;
}
}
/// <summary>
/// Kick a participant from a given conference
/// </summary>
public class DeleteParticipantOptions : IOptions<ParticipantResource>
{
/// <summary>
/// The SID of the Account that created the resources to delete
/// </summary>
public string PathAccountSid { get; set; }
/// <summary>
/// The SID of the conference with the participants to delete
/// </summary>
public string PathConferenceSid { get; }
/// <summary>
/// The Call SID or URL encoded label of the participant to delete
/// </summary>
public string PathCallSid { get; }
/// <summary>
/// Construct a new DeleteParticipantOptions
/// </summary>
/// <param name="pathConferenceSid"> The SID of the conference with the participants to delete </param>
/// <param name="pathCallSid"> The Call SID or URL encoded label of the participant to delete </param>
public DeleteParticipantOptions(string pathConferenceSid, string pathCallSid)
{
PathConferenceSid = pathConferenceSid;
PathCallSid = pathCallSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
return p;
}
}
/// <summary>
/// Retrieve a list of participants belonging to the account used to make the request
/// </summary>
public class ReadParticipantOptions : ReadOptions<ParticipantResource>
{
/// <summary>
/// The SID of the Account that created the resources to read
/// </summary>
public string PathAccountSid { get; set; }
/// <summary>
/// The SID of the conference with the participants to read
/// </summary>
public string PathConferenceSid { get; }
/// <summary>
/// Whether to return only participants that are muted
/// </summary>
public bool? Muted { get; set; }
/// <summary>
/// Whether to return only participants that are on hold
/// </summary>
public bool? Hold { get; set; }
/// <summary>
/// Whether to return only participants who are coaching another call
/// </summary>
public bool? Coaching { get; set; }
/// <summary>
/// Construct a new ReadParticipantOptions
/// </summary>
/// <param name="pathConferenceSid"> The SID of the conference with the participants to read </param>
public ReadParticipantOptions(string pathConferenceSid)
{
PathConferenceSid = pathConferenceSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public override List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (Muted != null)
{
p.Add(new KeyValuePair<string, string>("Muted", Muted.Value.ToString().ToLower()));
}
if (Hold != null)
{
p.Add(new KeyValuePair<string, string>("Hold", Hold.Value.ToString().ToLower()));
}
if (Coaching != null)
{
p.Add(new KeyValuePair<string, string>("Coaching", Coaching.Value.ToString().ToLower()));
}
if (PageSize != null)
{
p.Add(new KeyValuePair<string, string>("PageSize", PageSize.ToString()));
}
return p;
}
}
}
| |
/* Copyright (c) 2009-11, ReactionGrid Inc. http://reactiongrid.com
* See License.txt for full licence information.
*
* PlayerMovement.cs Revision 1.4.1107.20
* Control movement messages over the network */
using UnityEngine;
using System.Collections;
using System;
public class PlayerMovement : MonoBehaviour {
private bool isMoving;
private bool isTurning;
private bool isSitting = false;
private bool isGrounded = true;
private float horizontalInput;
private float verticalInput;
// Specify some general movement parameters
public float walkSpeed = .05f;
public float runSpeed = 1f;
public float runAfter = 400.0f;
private KeyCode runHotKey = KeyCode.LeftShift;
private GameObject netController;
private bool sendTransforms = false;
private bool isChatting = false;
private bool isIdle = false;
private float idleDuration = 0.0f;
private float idleWakeup = 30.0f;
private CharacterController character;
private Rigidbody rb;
private float walkDuration = 0.0f;
private bool isFlying = false;
private bool isJumping = false;
private float jumpDuration = 0.0f;
private bool hasLanded = false;
private double lastY = 0.0;
private bool isMovingVertically = false;
private string currentSitPose = "";
private CharacterController charController;
private bool guiForward = false;
void Start ()
{
if(GameObject.Find("localPlayer")!=null)
{
charController = GameObject.Find("localPlayer").GetComponent<CharacterController>();
}
netController = GameObject.Find("NetworkController");
character = GetComponent<CharacterController>();
rb = GetComponent<Rigidbody>();
lastY = transform.position.y;
}
public void SendTransforms(bool send)
{
sendTransforms = send;
}
void Update ()
{
//turn flying on
if(Input.GetKey("e"))
{
isFlying = true;
}
//Debug.Log("isGrounded = " + isGrounded);
verticalInput = Input.GetAxisRaw("Vertical");
horizontalInput = Input.GetAxisRaw("Horizontal");
if (character != null)
{
isFlying = !character.isGrounded;
isGrounded = character.isGrounded;
}
else if (rb != null)
{
isFlying = !rb.useGravity;
}
isMoving = Mathf.Abs(verticalInput) > 0.1;
isMovingVertically = (lastY != Math.Round(transform.position.y));
lastY = Math.Round(transform.position.y);
isTurning = Mathf.Abs(horizontalInput) > 0.1;
if (Input.GetMouseButton(0) && Input.GetMouseButton(1) || guiForward)
{
isMoving = true;
}
/* if (isMoving)
walkDuration += Time.deltaTime;
else
walkDuration = 0.0f;*/
if(Input.GetKeyUp(KeyCode.LeftShift))
{
walkDuration = 0.0f;
}
if (Input.GetKey(runHotKey))//When pushed down, avatar will run
{
walkDuration = runAfter + 0.1f;
}
//isGrounded = isFlying || isJumping;
if (sendTransforms && (isMoving || isTurning))
{
float speed = GetSpeed();
UpdateTransform(transform);
idleDuration = idleWakeup + 1; // reset idle wakeup while moving so as soon as player stops moving, they send an idle packet.
if (speed > walkSpeed)
{
if (!isFlying)
{
GetComponent<AnimationSynchronizer>().SendAnimationMessage("run");
}
else
{
GetComponent<AnimationSynchronizer>().SendAnimationMessage("fly");
}
}
else if (speed > 0.1)
{
if (!isFlying)
{
GetComponent<AnimationSynchronizer>().SendAnimationMessage("walk");
}
else
{
GetComponent<AnimationSynchronizer>().SendAnimationMessage("fly");
}
}
else if (speed < -0.1)
{
GetComponent<AnimationSynchronizer>().SendAnimationMessage("walk");
}
else if (isSitting)
{
GetComponent<AnimationSynchronizer>().SendAnimationMessage(CurrentSitPose());
}
else
{
if (!isIdle)
{
GetComponent<AnimationSynchronizer>().SendAnimationMessage("idle");
isIdle = true;
}
}
}
if (!(isMoving || isTurning))
{
idleDuration += Time.deltaTime;
if (idleDuration > idleWakeup)
{
if (sendTransforms) GetComponent<AnimationSynchronizer>().SendAnimationMessage("idle");
idleDuration = 0.0f;
isIdle = false;
}
else
{
isIdle = true;
}
}
if (!isJumping && !isFlying && Input.GetButton("Jump"))
{
if(!charController.isGrounded)
{
isJumping = true;
}
isGrounded = false;
}
else
{
jumpDuration += Time.deltaTime;
if (jumpDuration > 0.2f)
{
isJumping = false;
jumpDuration = 0.0f;
}
}
}
//Check for collisions to determine when the player is on the ground
void OnCollisionEnter(Collision collision)
{
float collisionAngle = Vector3.Angle(collision.contacts[0].normal, Vector3.up); //Calculate angle between the up vector and the collision contact's normal
if (collisionAngle < 40.0)
{ //If the angle difference is small enough, accept collision as hitting the ground
if (!isGrounded) // just landed
{
Debug.Log("HIT");
isGrounded = true; //Player is grounded
isFlying = false;
hasLanded = true;
}
}
}
//ZPWH
//this is a band-aid since char controllers cant use OnCollision functions
public void IsOnGround()
{
isGrounded = true;
isFlying = false;
hasLanded = true;
}
public bool IsMoving()
{
return isMoving;
}
public bool IsMovingVertically()
{
return isMovingVertically;
}
public bool IsTurning()
{
return isTurning;
}
public bool IsGrounded()
{
return isGrounded;
}
public float GetSpeed()
{
if (isMoving)
{
return walkSpeed;
}
else return 0;
}
public void UpdateTransform(Transform t)
{
netController.GetComponent("NetworkController").SendMessage("SendTransform", t);
}
public bool IsJumping()
{
return isJumping;
}
public bool IsFlying()
{
return isFlying;
}
public bool IsHovering()
{
return isJumping && !isFlying || isFlying && !isMoving;
}
public void SetChatting(bool chatting)
{
isChatting = chatting;
}
public bool IsChatting()
{
return isChatting;
}
public bool HasJumpReachedApex()
{
return false;
}
public bool IsGroundedWithTimeout()
{
return false;
}
public bool HasLanded()
{
return hasLanded;
}
public bool IsSitting()
{
return isSitting;
}
public string CurrentSitPose()
{
return currentSitPose;
}
public void SetSitting(bool sitting, string sitPose)
{
isSitting = sitting;
currentSitPose = sitPose;
}
public void ForwardInput()
{
guiForward=!guiForward;
}
}
| |
// Copyright (c) Russlan Akiev. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
namespace IdentityBase.Actions.Login
{
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using IdentityBase.Configuration;
using IdentityBase.Models;
using IdentityBase.ModelState;
using IdentityBase.Services;
using IdentityServer4.Models;
using IdentityServer4.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
public class LoginController : WebController
{
private readonly ApplicationOptions _applicationOptions;
private readonly ILogger<LoginController> _logger;
private readonly IIdentityServerInteractionService _interaction;
private readonly UserAccountService _userAccountService;
private readonly ClientService _clientService;
private readonly AuthenticationService _authenticationService;
private readonly IStringLocalizer _localizer;
public LoginController(
ApplicationOptions applicationOptions,
ILogger<LoginController> logger,
IIdentityServerInteractionService interaction,
UserAccountService userAccountService,
ClientService clientService,
AuthenticationService authenticationService,
IStringLocalizer localizer)
{
this._applicationOptions = applicationOptions;
this._logger = logger;
this._interaction = interaction;
this._userAccountService = userAccountService;
this._clientService = clientService;
this._authenticationService = authenticationService;
this._localizer = localizer;
}
/// <summary>
/// Shows the login page.
/// </summary>
[HttpGet("login", Name = "Login")]
[RestoreModelState]
public async Task<IActionResult> Login(string returnUrl)
{
LoginViewModel vm = await this.CreateViewModelAsync(returnUrl);
if (vm == null)
{
this._logger.LogError(
"Login attempt with missing returnUrl parameter");
return this.RedirectToAction("Index", "Error");
}
if (vm.IsExternalLoginOnly)
{
return this.ChallengeExternalLogin(
vm.ExternalProviders.First().AuthenticationScheme,
returnUrl);
}
return this.View(vm);
}
/// <summary>
/// Handle postback from username/password login
/// </summary>
[HttpPost("login", Name = "Login")]
[ValidateAntiForgeryToken]
[StoreModelState]
public async Task<IActionResult> Login(LoginInputModel model)
{
if (!this._applicationOptions.EnableAccountLogin)
{
return this.NotFound();
}
if (this.ModelState.IsValid)
{
UserAccountVerificationResult result =
await this._userAccountService
.VerifyByEmailAndPasswordAsync(
model.Email,
model.Password
);
if (result.UserAccount != null)
{
if (!result.IsLoginAllowed)
{
this.ModelState.AddModelError(this._localizer[
ErrorMessages.UserAccountIsDeactivated]);
}
else if (result.IsLocalAccount)
{
if (result.IsPasswordValid)
{
await this._authenticationService.SignInAsync(
result.UserAccount,
model.ReturnUrl,
model.RememberLogin);
return this.RedirectToReturnUrl(
model.ReturnUrl,
this._interaction);
}
else
{
await this._userAccountService
.PerceiveFailedLoginAsync(result.UserAccount);
}
}
else
{
LoginViewModel vm = await this.CreateViewModelAsync(
model,
result.UserAccount
);
return this.View(vm);
}
}
this.ModelState.AddModelError(
this._localizer[ErrorMessages.InvalidCredentials]);
}
// Something went wrong, show form with error
return this.RedirectToLogin(model.ReturnUrl);
}
[NonAction]
internal async Task<LoginViewModel> CreateViewModelAsync(
string returnUrl)
{
return await this.CreateViewModelAsync(new LoginInputModel
{
ReturnUrl = returnUrl
});
}
[NonAction]
internal async Task<LoginViewModel> CreateViewModelAsync(
LoginInputModel inputModel,
UserAccount userAccount = null)
{
AuthorizationRequest context = await this._interaction
.GetAuthorizationContextAsync(inputModel.ReturnUrl);
if (context == null)
{
return null;
}
LoginViewModel vm = new LoginViewModel(inputModel)
{
EnableRememberLogin = this._applicationOptions
.EnableRememberLogin,
EnableAccountRegistration = this._applicationOptions
.EnableAccountRegistration,
EnableAccountRecover = this._applicationOptions
.EnableAccountRecovery,
// TODO: expose AuthorizationRequest
LoginHint = context.LoginHint,
};
/*
// Not yet supported
if (context?.IdP != null)
{
// This is meant to short circuit the UI and only trigger the one external IdP
vm.EnableLocalLogin = applicationOptions.EnableLocalLogin;
vm.ExternalProviders = new ExternalProvider[] {
new ExternalProvider { AuthenticationScheme = context.IdP }
};
return vm;
}*/
Client client = await this._clientService
.FindEnabledClientByIdAsync(context.ClientId);
IEnumerable<ExternalProvider> providers = await this._clientService
.GetEnabledProvidersAsync(client);
vm.ExternalProviders = providers.ToArray();
vm.EnableLocalLogin = (client != null ?
client.EnableLocalLogin : false) &&
this._applicationOptions.EnableAccountLogin;
if (userAccount != null)
{
vm.ExternalProviderHints = userAccount?.Accounts
.Select(c => c.Provider);
}
return vm;
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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.
//-----------------------------------------------------------------------------
function EWCreatorWindow::init( %this )
{
// Just so we can recall this method for testing changes
// without restarting.
if ( isObject( %this.array ) )
%this.array.delete();
%this.array = new ArrayObject();
%this.array.caseSensitive = true;
%this.setListView( true );
%this.beginGroup( "Environment" );
// Removed Prefab as there doesn't really seem to be a point in creating a blank one
//%this.registerMissionObject( "Prefab", "Prefab" );
%this.registerMissionObject( "SkyBox", "Sky Box" );
%this.registerMissionObject( "CloudLayer", "Cloud Layer" );
%this.registerMissionObject( "BasicClouds", "Basic Clouds" );
%this.registerMissionObject( "ScatterSky", "Scatter Sky" );
%this.registerMissionObject( "Sun", "Basic Sun" );
%this.registerMissionObject( "Lightning" );
%this.registerMissionObject( "WaterBlock", "Water Block" );
%this.registerMissionObject( "SFXEmitter", "Sound Emitter" );
%this.registerMissionObject( "Precipitation" );
%this.registerMissionObject( "ParticleEmitterNode", "Particle Emitter" );
%this.registerMissionObject( "VolumetricFog", "Volumetric Fog" );
%this.registerMissionObject( "RibbonNode", "Ribbon" );
// Legacy features. Users should use Ground Cover and the Forest Editor.
//%this.registerMissionObject( "fxShapeReplicator", "Shape Replicator" );
//%this.registerMissionObject( "fxFoliageReplicator", "Foliage Replicator" );
%this.registerMissionObject( "PointLight", "Point Light" );
%this.registerMissionObject( "SpotLight", "Spot Light" );
%this.registerMissionObject( "GroundCover", "Ground Cover" );
%this.registerMissionObject( "TerrainBlock", "Terrain Block" );
%this.registerMissionObject( "GroundPlane", "Ground Plane" );
%this.registerMissionObject( "WaterPlane", "Water Plane" );
%this.registerMissionObject( "PxCloth", "Cloth" );
%this.registerMissionObject( "ForestWindEmitter", "Wind Emitter" );
%this.registerMissionObject( "DustEmitter", "Dust Emitter" );
%this.registerMissionObject( "DustSimulation", "Dust Simulation" );
%this.registerMissionObject( "DustEffecter", "Dust Effecter" );
%this.endGroup();
%this.beginGroup( "Level" );
%this.registerMissionObject( "MissionArea", "Mission Area" );
%this.registerMissionObject( "Path" );
%this.registerMissionObject( "Marker", "Path Node" );
%this.registerMissionObject( "Trigger" );
%this.registerMissionObject( "PhysicalZone", "Physical Zone" );
%this.registerMissionObject( "Camera" );
%this.registerMissionObject( "LevelInfo", "Level Info" );
%this.registerMissionObject( "TimeOfDay", "Time of Day" );
%this.registerMissionObject( "Zone", "Zone" );
%this.registerMissionObject( "Portal", "Zone Portal" );
%this.registerMissionObject( "SpawnSphere", "Player Spawn Sphere", "PlayerDropPoint" );
%this.registerMissionObject( "SpawnSphere", "Observer Spawn Sphere", "ObserverDropPoint" );
%this.registerMissionObject( "SFXSpace", "Sound Space" );
%this.registerMissionObject( "OcclusionVolume", "Occlusion Volume" );
%this.registerMissionObject( "AccumulationVolume", "Accumulation Volume" );
%this.registerMissionObject( "Entity", "Entity" );
%this.endGroup();
%this.beginGroup( "System" );
%this.registerMissionObject( "SimGroup" );
%this.endGroup();
%this.beginGroup( "ExampleObjects" );
%this.registerMissionObject( "RenderObjectExample" );
%this.registerMissionObject( "RenderMeshExample" );
%this.registerMissionObject( "RenderShapeExample" );
%this.endGroup();
}
function EWCreatorWindow::onWake( %this )
{
CreatorTabBook.selectPage( 0 );
CreatorTabBook.onTabSelected( "Scripted" );
}
function EWCreatorWindow::beginGroup( %this, %group )
{
%this.currentGroup = %group;
}
function EWCreatorWindow::endGroup( %this, %group )
{
%this.currentGroup = "";
}
function EWCreatorWindow::getCreateObjectPosition()
{
%focusPoint = LocalClientConnection.getControlObject().getLookAtPoint();
if( %focusPoint $= "" )
return "0 0 0";
else
return getWord( %focusPoint, 1 ) SPC getWord( %focusPoint, 2 ) SPC getWord( %focusPoint, 3 );
}
function EWCreatorWindow::registerMissionObject( %this, %class, %name, %buildfunc, %group )
{
if( !isClass(%class) )
return;
if ( %name $= "" )
%name = %class;
if ( %this.currentGroup !$= "" && %group $= "" )
%group = %this.currentGroup;
if ( %class $= "" || %group $= "" )
{
warn( "EWCreatorWindow::registerMissionObject, invalid parameters!" );
return;
}
%args = new ScriptObject();
%args.val[0] = %class;
%args.val[1] = %name;
%args.val[2] = %buildfunc;
%this.array.push_back( %group, %args );
}
function EWCreatorWindow::getNewObjectGroup( %this )
{
return %this.objectGroup;
}
function EWCreatorWindow::setNewObjectGroup( %this, %group )
{
if( %this.objectGroup )
{
%oldItemId = EditorTree.findItemByObjectId( %this.objectGroup );
if( %oldItemId > 0 )
EditorTree.markItem( %oldItemId, false );
}
%group = %group.getID();
%this.objectGroup = %group;
%itemId = EditorTree.findItemByObjectId( %group );
EditorTree.markItem( %itemId );
}
function EWCreatorWindow::createStatic( %this, %file )
{
if ( !$missionRunning )
return;
if( !isObject(%this.objectGroup) )
%this.setNewObjectGroup( MissionGroup );
%objId = new TSStatic()
{
shapeName = %file;
position = %this.getCreateObjectPosition();
parentGroup = %this.objectGroup;
};
%this.onObjectCreated( %objId );
}
function EWCreatorWindow::createPrefab( %this, %file )
{
if ( !$missionRunning )
return;
if( !isObject(%this.objectGroup) )
%this.setNewObjectGroup( MissionGroup );
%objId = new Prefab()
{
filename = %file;
position = %this.getCreateObjectPosition();
parentGroup = %this.objectGroup;
};
%this.onObjectCreated( %objId );
}
function EWCreatorWindow::createObject( %this, %cmd )
{
if ( !$missionRunning )
return;
if( !isObject(%this.objectGroup) )
%this.setNewObjectGroup( MissionGroup );
pushInstantGroup();
%objId = eval(%cmd);
popInstantGroup();
if( isObject( %objId ) )
%this.onFinishCreateObject( %objId );
return %objId;
}
function EWCreatorWindow::onFinishCreateObject( %this, %objId )
{
%this.objectGroup.add( %objId );
if( %objId.isMemberOfClass( "SceneObject" ) )
{
%objId.position = %this.getCreateObjectPosition();
//flush new position
%objId.setTransform( %objId.getTransform() );
}
%this.onObjectCreated( %objId );
}
function EWCreatorWindow::onObjectCreated( %this, %objId )
{
// Can we submit an undo action?
if ( isObject( %objId ) )
MECreateUndoAction::submit( %objId );
EditorTree.clearSelection();
EWorldEditor.clearSelection();
EWorldEditor.selectObject( %objId );
// When we drop the selection don't store undo
// state for it... the creation deals with it.
EWorldEditor.dropSelection( true );
}
function CreatorTabBook::onTabSelected( %this, %text, %idx )
{
if ( %this.isAwake() )
{
EWCreatorWindow.tab = %text;
EWCreatorWindow.navigate( "" );
}
}
function EWCreatorWindow::navigate( %this, %address )
{
CreatorIconArray.frozen = true;
CreatorIconArray.clear();
CreatorPopupMenu.clear();
if ( %this.tab $= "Scripted" )
{
%category = getWord( %address, 1 );
%dataGroup = "DataBlockGroup";
for ( %i = 0; %i < %dataGroup.getCount(); %i++ )
{
%obj = %dataGroup.getObject(%i);
// echo ("Obj: " @ %obj.getName() @ " - " @ %obj.category );
if ( %obj.category $= "" && %obj.category == 0 )
continue;
// Add category to popup menu if not there already
if ( CreatorPopupMenu.findText( %obj.category ) == -1 )
CreatorPopupMenu.add( %obj.category );
if ( %address $= "" )
{
%ctrl = %this.findIconCtrl( %obj.category );
if ( %ctrl == -1 )
{
%this.addFolderIcon( %obj.category );
}
}
else if ( %address $= %obj.category )
{
%ctrl = %this.findIconCtrl( %obj.getName() );
if ( %ctrl == -1 )
%this.addShapeIcon( %obj );
}
}
//Add a separate folder for Game Objects
if(isClass("Entity"))
{
if(%address $= "")
{
%this.addFolderIcon("GameObjects");
}
else
{
//find all GameObjectAssets
%assetQuery = new AssetQuery();
if(!AssetDatabase.findAssetType(%assetQuery, "GameObjectAsset"))
return 0; //if we didn't find ANY, just exit
%count = %assetQuery.getCount();
for(%i=0; %i < %count; %i++)
{
%assetId = %assetQuery.getAsset(%i);
%gameObjectAsset = AssetDatabase.acquireAsset(%assetId);
if(isFile(%gameObjectAsset.TAMLFilePath))
{
%this.addGameObjectIcon( %gameObjectAsset.gameObjectName );
}
}
}
}
}
if ( %this.tab $= "Meshes" )
{
%fullPath = findFirstFileMultiExpr( getFormatExtensions() );
while ( %fullPath !$= "" )
{
if (strstr(%fullPath, "cached.dts") != -1)
{
%fullPath = findNextFileMultiExpr( getFormatExtensions() );
continue;
}
%fullPath = makeRelativePath( %fullPath, getMainDotCSDir() );
%splitPath = strreplace( %fullPath, " ", "_" );
%splitPath = strreplace( %splitPath, "/", " " );
if( getWord(%splitPath, 0) $= "tools" )
{
%fullPath = findNextFileMultiExpr( getFormatExtensions() );
continue;
}
%dirCount = getWordCount( %splitPath ) - 1;
%pathFolders = getWords( %splitPath, 0, %dirCount - 1 );
// Add this file's path (parent folders) to the
// popup menu if it isn't there yet.
%temp = strreplace( %pathFolders, " ", "/" );
%temp = strreplace( %temp, "_", " " );
%r = CreatorPopupMenu.findText( %temp );
if ( %r == -1 )
{
CreatorPopupMenu.add( %temp );
}
// Is this file in the current folder?
if ( stricmp( %pathFolders, %address ) == 0 )
{
%this.addStaticIcon( %fullPath );
}
// Then is this file in a subfolder we need to add
// a folder icon for?
else
{
%wordIdx = 0;
%add = false;
if ( %address $= "" )
{
%add = true;
%wordIdx = 0;
}
else
{
for ( ; %wordIdx < %dirCount; %wordIdx++ )
{
%temp = getWords( %splitPath, 0, %wordIdx );
if ( stricmp( %temp, %address ) == 0 )
{
%add = true;
%wordIdx++;
break;
}
}
}
if ( %add == true )
{
%folder = getWord( %splitPath, %wordIdx );
%ctrl = %this.findIconCtrl( %folder );
if ( %ctrl == -1 )
%this.addFolderIcon( %folder );
}
}
%fullPath = findNextFileMultiExpr( getFormatExtensions() );
}
}
if ( %this.tab $= "Level" )
{
// Add groups to popup menu
%array = %this.array;
%array.sortk();
%count = %array.count();
if ( %count > 0 )
{
%lastGroup = "";
for ( %i = 0; %i < %count; %i++ )
{
%group = %array.getKey( %i );
if ( %group !$= %lastGroup )
{
CreatorPopupMenu.add( %group );
if ( %address $= "" )
%this.addFolderIcon( %group );
}
if ( %address $= %group )
{
%args = %array.getValue( %i );
%class = %args.val[0];
%name = %args.val[1];
%func = %args.val[2];
%this.addMissionObjectIcon( %class, %name, %func );
}
%lastGroup = %group;
}
}
}
if ( %this.tab $= "Prefabs" )
{
%expr = "*.prefab";
%fullPath = findFirstFile( %expr );
while ( %fullPath !$= "" )
{
%fullPath = makeRelativePath( %fullPath, getMainDotCSDir() );
%splitPath = strreplace( %fullPath, " ", "_" );
%splitPath = strreplace( %splitPath, "/", " " );
if( getWord(%splitPath, 0) $= "tools" )
{
%fullPath = findNextFile( %expr );
continue;
}
%dirCount = getWordCount( %splitPath ) - 1;
%pathFolders = getWords( %splitPath, 0, %dirCount - 1 );
// Add this file's path (parent folders) to the
// popup menu if it isn't there yet.
%temp = strreplace( %pathFolders, " ", "/" );
%temp = strreplace( %temp, "_", " " );
%r = CreatorPopupMenu.findText( %temp );
if ( %r == -1 )
{
CreatorPopupMenu.add( %temp );
}
// Is this file in the current folder?
if ( (%dirCount == 0 && %address $= "") || stricmp( %pathFolders, %address ) == 0 )
{
%this.addPrefabIcon( %fullPath );
}
// Then is this file in a subfolder we need to add
// a folder icon for?
else
{
%wordIdx = 0;
%add = false;
if ( %address $= "" )
{
%add = true;
%wordIdx = 0;
}
else
{
for ( ; %wordIdx < %dirCount; %wordIdx++ )
{
%temp = getWords( %splitPath, 0, %wordIdx );
if ( stricmp( %temp, %address ) == 0 )
{
%add = true;
%wordIdx++;
break;
}
}
}
if ( %add == true )
{
%folder = getWord( %splitPath, %wordIdx );
%ctrl = %this.findIconCtrl( %folder );
if ( %ctrl == -1 )
%this.addFolderIcon( %folder );
}
}
%fullPath = findNextFile( %expr );
}
}
CreatorIconArray.sort( "alphaIconCompare" );
for ( %i = 0; %i < CreatorIconArray.getCount(); %i++ )
{
CreatorIconArray.getObject(%i).autoSize = false;
}
CreatorIconArray.frozen = false;
CreatorIconArray.refresh();
// Recalculate the array for the parent guiScrollCtrl
CreatorIconArray.getParent().computeSizes();
%this.address = %address;
CreatorPopupMenu.sort();
%str = strreplace( %address, " ", "/" );
%r = CreatorPopupMenu.findText( %str );
if ( %r != -1 )
CreatorPopupMenu.setSelected( %r, false );
else
CreatorPopupMenu.setText( %str );
CreatorPopupMenu.tooltip = %str;
}
function EWCreatorWindow::navigateDown( %this, %folder )
{
if ( %this.address $= "" )
%address = %folder;
else
%address = %this.address SPC %folder;
// Because this is called from an IconButton::onClick command
// we have to wait a tick before actually calling navigate, else
// we would delete the button out from under itself.
%this.schedule( 1, "navigate", %address );
}
function EWCreatorWindow::navigateUp( %this )
{
%count = getWordCount( %this.address );
if ( %count == 0 )
return;
if ( %count == 1 )
%address = "";
else
%address = getWords( %this.address, 0, %count - 2 );
%this.navigate( %address );
}
function EWCreatorWindow::setListView( %this, %noupdate )
{
//CreatorIconArray.clear();
//CreatorIconArray.setVisible( false );
CreatorIconArray.setVisible( true );
%this.contentCtrl = CreatorIconArray;
%this.isList = true;
if ( %noupdate == true )
%this.navigate( %this.address );
}
//function EWCreatorWindow::setIconView( %this )
//{
//echo( "setIconView" );
//
//CreatorIconStack.clear();
//CreatorIconStack.setVisible( false );
//
//CreatorIconArray.setVisible( true );
//%this.contentCtrl = CreatorIconArray;
//%this.isList = false;
//
//%this.navigate( %this.address );
//}
function EWCreatorWindow::findIconCtrl( %this, %name )
{
for ( %i = 0; %i < %this.contentCtrl.getCount(); %i++ )
{
%ctrl = %this.contentCtrl.getObject( %i );
if ( %ctrl.text $= %name )
return %ctrl;
}
return -1;
}
function EWCreatorWindow::createIcon( %this )
{
%ctrl = new GuiIconButtonCtrl()
{
profile = "GuiCreatorIconButtonProfile";
buttonType = "radioButton";
groupNum = "-1";
};
if ( %this.isList )
{
%ctrl.iconLocation = "Left";
%ctrl.textLocation = "Right";
%ctrl.extent = "348 19";
%ctrl.textMargin = 8;
%ctrl.buttonMargin = "2 2";
%ctrl.autoSize = true;
}
else
{
%ctrl.iconLocation = "Center";
%ctrl.textLocation = "Bottom";
%ctrl.extent = "40 40";
}
return %ctrl;
}
function EWCreatorWindow::addFolderIcon( %this, %text )
{
%ctrl = %this.createIcon();
%ctrl.altCommand = "EWCreatorWindow.navigateDown(\"" @ %text @ "\");";
%ctrl.iconBitmap = "tools/gui/images/folder.png";
%ctrl.text = %text;
%ctrl.tooltip = %text;
%ctrl.class = "CreatorFolderIconBtn";
%ctrl.buttonType = "radioButton";
%ctrl.groupNum = "-1";
%this.contentCtrl.addGuiControl( %ctrl );
}
function EWCreatorWindow::addMissionObjectIcon( %this, %class, %name, %buildfunc )
{
%ctrl = %this.createIcon();
// If we don't find a specific function for building an
// object then fall back to the stock one
%method = "build" @ %buildfunc;
if( !ObjectBuilderGui.isMethod( %method ) )
%method = "build" @ %class;
if( !ObjectBuilderGui.isMethod( %method ) )
%cmd = "return new " @ %class @ "();";
else
%cmd = "ObjectBuilderGui." @ %method @ "();";
%ctrl.altCommand = "ObjectBuilderGui.newObjectCallback = \"EWCreatorWindow.onFinishCreateObject\"; EWCreatorWindow.createObject( \"" @ %cmd @ "\" );";
%ctrl.iconBitmap = EditorIconRegistry::findIconByClassName( %class );
%ctrl.text = %name;
%ctrl.class = "CreatorMissionObjectIconBtn";
%ctrl.tooltip = %class;
%ctrl.buttonType = "radioButton";
%ctrl.groupNum = "-1";
%this.contentCtrl.addGuiControl( %ctrl );
}
function EWCreatorWindow::addShapeIcon( %this, %datablock )
{
%ctrl = %this.createIcon();
%name = %datablock.getName();
%class = %datablock.getClassName();
%cmd = %class @ "::create(" @ %name @ ");";
%shapePath = ( %datablock.shapeFile !$= "" ) ? %datablock.shapeFile : %datablock.shapeName;
%createCmd = "EWCreatorWindow.createObject( \\\"" @ %cmd @ "\\\" );";
%ctrl.altCommand = "ColladaImportDlg.showDialog( \"" @ %shapePath @ "\", \"" @ %createCmd @ "\" );";
%ctrl.iconBitmap = EditorIconRegistry::findIconByClassName( %class );
%ctrl.text = %name;
%ctrl.class = "CreatorShapeIconBtn";
%ctrl.tooltip = %name;
%ctrl.buttonType = "radioButton";
%ctrl.groupNum = "-1";
%this.contentCtrl.addGuiControl( %ctrl );
}
function EWCreatorWindow::addStaticIcon( %this, %fullPath )
{
%ctrl = %this.createIcon();
%ext = fileExt( %fullPath );
%file = fileBase( %fullPath );
%fileLong = %file @ %ext;
%tip = %fileLong NL
"Size: " @ fileSize( %fullPath ) / 1000.0 SPC "KB" NL
"Date Created: " @ fileCreatedTime( %fullPath ) NL
"Last Modified: " @ fileModifiedTime( %fullPath );
%createCmd = "EWCreatorWindow.createStatic( \\\"" @ %fullPath @ "\\\" );";
%ctrl.altCommand = "ColladaImportDlg.showDialog( \"" @ %fullPath @ "\", \"" @ %createCmd @ "\" );";
%ctrl.iconBitmap = ( ( %ext $= ".dts" ) ? EditorIconRegistry::findIconByClassName( "TSStatic" ) : "tools/gui/images/iconCollada" );
%ctrl.text = %file;
%ctrl.class = "CreatorStaticIconBtn";
%ctrl.tooltip = %tip;
%ctrl.buttonType = "radioButton";
%ctrl.groupNum = "-1";
%this.contentCtrl.addGuiControl( %ctrl );
}
function EWCreatorWindow::addPrefabIcon( %this, %fullPath )
{
%ctrl = %this.createIcon();
%ext = fileExt( %fullPath );
%file = fileBase( %fullPath );
%fileLong = %file @ %ext;
%tip = %fileLong NL
"Size: " @ fileSize( %fullPath ) / 1000.0 SPC "KB" NL
"Date Created: " @ fileCreatedTime( %fullPath ) NL
"Last Modified: " @ fileModifiedTime( %fullPath );
%ctrl.altCommand = "EWCreatorWindow.createPrefab( \"" @ %fullPath @ "\" );";
%ctrl.iconBitmap = EditorIconRegistry::findIconByClassName( "Prefab" );
%ctrl.text = %file;
%ctrl.class = "CreatorPrefabIconBtn";
%ctrl.tooltip = %tip;
%ctrl.buttonType = "radioButton";
%ctrl.groupNum = "-1";
%this.contentCtrl.addGuiControl( %ctrl );
}
function EWCreatorWindow::addGameObjectIcon( %this, %gameObjectName )
{
%ctrl = %this.createIcon();
%ctrl.altCommand = "spawnGameObject( \"" @ %gameObjectName @ "\", true );";
%ctrl.iconBitmap = EditorIconRegistry::findIconByClassName( "Prefab" );
%ctrl.text = %gameObjectName;
%ctrl.class = "CreatorGameObjectIconBtn";
%ctrl.tooltip = "Spawn the " @ %gameObjectName @ " GameObject";
%ctrl.buttonType = "radioButton";
%ctrl.groupNum = "-1";
%this.contentCtrl.addGuiControl( %ctrl );
}
function CreatorPopupMenu::onSelect( %this, %id, %text )
{
%split = strreplace( %text, "/", " " );
EWCreatorWindow.navigate( %split );
}
function alphaIconCompare( %a, %b )
{
if ( %a.class $= "CreatorFolderIconBtn" )
if ( %b.class !$= "CreatorFolderIconBtn" )
return -1;
if ( %b.class $= "CreatorFolderIconBtn" )
if ( %a.class !$= "CreatorFolderIconBtn" )
return 1;
%result = stricmp( %a.text, %b.text );
return %result;
}
// Generic create object helper for use from the console.
function genericCreateObject( %class )
{
if ( !isClass( %class ) )
{
warn( "createObject( " @ %class @ " ) - Was not a valid class." );
return;
}
%cmd = "return new " @ %class @ "();";
%obj = EWCreatorWindow.createObject( %cmd );
// In case the caller wants it.
return %obj;
}
| |
using System;
using System.Threading.Tasks;
using App2Night.CustomView.Template;
using App2Night.CustomView.View;
using App2Night.Model.Enum;
using App2Night.Model.Language;
using App2Night.Model.Model;
using App2Night.PageModel.SubPages;
using App2Night.Service.Helper;
using FreshMvvm;
using Plugin.Geolocator;
using Xamarin.Forms;
using Xamarin.Forms.Maps;
namespace App2Night.Page.SubPages
{
public class MyPartyDetailPage : FreshBaseContentPage
{
private static int _defaultFontSize = 16;
private static Thickness _defaultMargin = new Thickness(5, 0);
public static int CommandHeight = 70;
#region Views
private PartyRatingView _ratingView = new PartyRatingView
{
RatingVisible = false
};
private InputContainer<Entry> _nameEntry = new InputContainer<Entry>
{
Input = { Placeholder = AppResources.PartyName, IsEnabled = false },
ValidationVisible = true,
IconCode = "\uf0fc",
Margin = _defaultMargin
};
private InputContainer<Editor> _descriptionEntry = new InputContainer<Editor>
{
Input =
{
HeightRequest = 100,
IsEnabled = false
},
IconCode = "\uf040",
Margin = _defaultMargin
};
private readonly InputContainer<DatePicker> _datePicker = new InputContainer<DatePicker>
{
Input =
{
MinimumDate = DateTime.Now,
MaximumDate = DateTime.Now.AddMonths(12),
IsEnabled = false
},
IconCode = "\uf073",
Margin = _defaultMargin
};
private InputContainer<TimePicker> _startTimePicker = new InputContainer<TimePicker>
{
IconCode = "\uf017",
Margin = _defaultMargin,
Input = { IsEnabled = false }
};
private InputContainer<EnumBindablePicker<MusicGenre>> _musicGenrePicker =
new InputContainer<EnumBindablePicker<MusicGenre>>
{
IconCode = "\uf001",
Input = { IsEnabled = false },
Margin = _defaultMargin
};
InputContainer<EnumBindablePicker<PartyType>> _partyTypePicker = new InputContainer
<EnumBindablePicker<PartyType>>
{
IconCode = "\uf0fc",
HorizontalOptions = LayoutOptions.Start,
Input =
{
IsEnabled = false
},
ValidationVisible = false,
};
ToolbarItem _editToolbarItem = new ToolbarItem
{
Text = AppResources.Edit,
Icon = "edit.png"
};
ToolbarItem _deleteParty = new ToolbarItem
{
Text = AppResources.Delete,
Icon = "trash.png"
};
readonly Map _partyLocation = new Map()
{
HeightRequest = 200,
IsShowingUser = true,
};
private Position _partyPosition;
private CustomButton _cancelButton = new CustomButton
{
Text = "\uf00d",
ButtonLabel =
{
FontFamily = "FontAwesome",
FontSize = 50,
},
IsVisible = false,
IsEnabled = true
};
private CustomButton _acceptButton = new CustomButton
{
Text = "\uf00c",
ButtonLabel =
{
FontFamily = "FontAwesome",
FontSize = 50,
},
IsVisible = false,
IsEnabled = false
};
private InputContainer<Entry> _cityNameEntry = new InputContainer<Entry>
{
Input =
{
Placeholder = AppResources.Cityname,
IsEnabled = false
},
IconCode = "\uf279"
};
private InputContainer<Entry> _streetEntry = new InputContainer<Entry>
{
Input =
{
Placeholder = AppResources.StrName,
IsEnabled = false
},
IconCode = "\uf0f3"
};
private InputContainer<Entry> _houseNumberEntry = new InputContainer<Entry>
{
Input =
{
Keyboard = Keyboard.Numeric,
Placeholder = AppResources.HNumber,
IsEnabled = false
},
};
private InputContainer<Entry> _priceEntry = new InputContainer<Entry>
{
Input =
{
Placeholder = AppResources.Location,
IsEnabled = false,
Keyboard = Keyboard.Numeric,
},
IconCode = "\uf155",
Margin = _defaultMargin,
};
InputContainer<Entry> _zipCodetEntry = new InputContainer<Entry>
{
Input =
{
Keyboard = Keyboard.Numeric,
Placeholder = AppResources.Zipcode,
IsEnabled = false
},
};
BoxView _gradientLayer = new BoxView
{
Color = Color.White.MultiplyAlpha(0.3),
IsVisible = false
};
private VerticalGallerieView _gallerieView = new VerticalGallerieView
{
};
#endregion
#region BindablePinProperty
public static BindableProperty MapPinsProperty = BindableProperty.Create(nameof(MapPins),
typeof(Pin),
typeof(DashboardPage),
propertyChanged: (bindable, value, newValue) =>
{
if (newValue != null)
{
((MyPartyDetailPage)bindable).MapPinsSet((Pin)newValue);
}
});
private void MapPinsSet(Pin pin)
{
_partyLocation.Pins.Add(pin);
}
public Pin MapPins
{
get { return (Pin)GetValue(MapPinsProperty); }
set { SetValue(MapPinsProperty, value); }
}
#endregion
public MyPartyDetailPage()
{
_gallerieView.Template = typeof(ParticipantTemplate);
SetBindings();
Device.BeginInvokeOnMainThread(async () => await InitializeMapCoordinates());
ToolbarItems.Add(_editToolbarItem);
ToolbarItems.Add(_deleteParty);
_editToolbarItem.Clicked += SetEditEnable;
_cancelButton.ButtonTapped += SetEditDisenable;
_acceptButton.ButtonTapped += SetEditDisenable;
var inputRows = CreateInputRows();
//SKIA Replace with gradient layer
Grid.SetRowSpan(inputRows, 2);
Grid.SetColumnSpan(inputRows, 2);
Content = new Grid
{
RowSpacing = 0,
ColumnDefinitions =
{
new ColumnDefinition {Width = new GridLength(1, GridUnitType.Star)},
new ColumnDefinition {Width = new GridLength(1, GridUnitType.Star)}
},
RowDefinitions =
{
new RowDefinition {Height = new GridLength(1, GridUnitType.Star)},
new RowDefinition {Height = new GridLength(CommandHeight, GridUnitType.Absolute)}
},
Children =
{
inputRows,
{_gradientLayer, 0, 1},
{_cancelButton, 0, 1},
{_acceptButton, 1, 1}
}
};
}
/// <summary>
/// Initializes ScrollView with Views.
/// </summary>
/// <returns></returns>
private ScrollView CreateInputRows()
{
return new ScrollView
{
Content = new StackLayout
{
Children =
{
_ratingView,
// Description of Party
new Frame
{
Margin = 5,
Padding = 5,
Content = new StackLayout
{
Children =
{
_nameEntry,
_descriptionEntry,
_musicGenrePicker,
_datePicker,
_startTimePicker,
_priceEntry
},
Spacing = 5
},
},
// Location of Party
new Frame
{
Margin = 5,
Padding = 5,
Content = new StackLayout
{
Children =
{
new MapWrapper(_partyLocation),
new Grid
{
ColumnDefinitions =
{
new ColumnDefinition {Width = new GridLength(3, GridUnitType.Star)},
new ColumnDefinition {Width = new GridLength(1, GridUnitType.Star)},
},
Children =
{
{_streetEntry, 0, 0},
{_houseNumberEntry, 1, 0}
},
Margin = _defaultMargin
},
new Grid
{
ColumnDefinitions =
{
new ColumnDefinition {Width = new GridLength(3, GridUnitType.Star)},
new ColumnDefinition {Width = new GridLength(1, GridUnitType.Star)},
},
Children =
{
{_cityNameEntry, 0, 0},
{_zipCodetEntry, 1, 0}
},
Margin = _defaultMargin
},
},
Spacing = 5
},
},
_gallerieView,
new BoxView
{
HeightRequest = CommandHeight,
Color = Color.Transparent
}
}
}
};
}
/// <summary>
/// Sets editable of views true and start slide in animation
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private async void SetEditEnable(object sender, EventArgs e)
{
_nameEntry.Input.IsEnabled = true;
_descriptionEntry.Input.IsEnabled = true;
_musicGenrePicker.Input.IsEnabled = true;
_partyTypePicker.Input.IsEnabled = true;
_datePicker.Input.IsEnabled = true;
_startTimePicker.Input.IsEnabled = true;
_streetEntry.Input.IsEnabled = true;
_houseNumberEntry.Input.IsEnabled = true;
_cityNameEntry.Input.IsEnabled = true;
_zipCodetEntry.Input.IsEnabled = true;
_priceEntry.Input.IsEnabled = true;
await SlideInAnimtion();
}
/// <summary>
/// Sets Views disenable and start slide out animation
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private async void SetEditDisenable(object sender, EventArgs e)
{
_nameEntry.Input.IsEnabled = false;
_descriptionEntry.Input.IsEnabled = false;
_musicGenrePicker.Input.IsEnabled = false;
_partyTypePicker.Input.IsEnabled = false;
_datePicker.Input.IsEnabled = false;
_startTimePicker.Input.IsEnabled = false;
_streetEntry.Input.IsEnabled = false;
_houseNumberEntry.Input.IsEnabled = false;
_cityNameEntry.Input.IsEnabled = false;
_zipCodetEntry.Input.IsEnabled = false;
_priceEntry.Input.IsEnabled = false;
await SlideOutAnimtion();
}
/// <summary>
/// Slides out cancel and accept <see cref="CustomButton"/>
/// </summary>
/// <returns></returns>
private async Task SlideOutAnimtion()
{
Animation slideOutAnimation = new Animation(d =>
{
_cancelButton.HeightRequest = d * 70;
_acceptButton.HeightRequest = d * 70;
_gradientLayer.HeightRequest = d * 70;
}, 1, 0);
slideOutAnimation.Commit(this, "SlideOut", length: 1000U, easing: Easing.Linear, finished: (d, b) =>
{
_cancelButton.IsVisible = false;
_acceptButton.IsVisible = false;
_gradientLayer.IsVisible = false;
});
}
/// <summary>
/// Slides in cancel and accept <see cref="CustomButton"/>
/// </summary>
/// <returns></returns>
private async Task SlideInAnimtion()
{
_gradientLayer.IsVisible = true;
_cancelButton.IsVisible = true;
_acceptButton.IsVisible = true;
Animation slideOutAnimation = new Animation(d =>
{
_cancelButton.HeightRequest = d * 70;
_acceptButton.HeightRequest = d * 70;
_gradientLayer.HeightRequest = d * 70;
}, 0, 1);
slideOutAnimation.Commit(this, "SlideOut", length: 1000U, easing: Easing.Linear);
}
private async Task InitializeMapCoordinates()
{
var coordinates = await CoordinateHelper.GetCoordinates();
if (coordinates != null)
{
MoveMapToCoordinates(coordinates);
}
}
private void MoveMapToCoordinates(Coordinates coordinates)
{
var mapSpan = MapSpan.FromCenterAndRadius(new Position(coordinates.Latitude, coordinates.Longitude),
Distance.FromKilometers(2));
_partyLocation.MoveToRegion(mapSpan);
}
private void SetBindings()
{
this.SetBinding(TitleProperty, "Party.Name");
//Buttons
_acceptButton.SetBinding(CustomButton.IsEnabledProperty, nameof(MyPartyDetailViewModel.AcceptButtonEnabled));
_acceptButton.SetBinding(CustomButton.CommandProperty, nameof(MyPartyDetailViewModel.UpdatePartyCommand));
_cancelButton.SetBinding(CustomButton.CommandProperty, nameof(MyPartyDetailViewModel.ClearFormCommand));
// set name
_nameEntry.Input.SetBinding(Entry.TextProperty, nameof(MyPartyDetailViewModel.Name));
_nameEntry.SetBinding(InputContainer<Entry>.InputValidateProperty, nameof(MyPartyDetailViewModel.ValidName));
// set description
_descriptionEntry.Input.SetBinding(Editor.TextProperty, nameof(MyPartyDetailViewModel.Description));
_descriptionEntry.SetBinding(InputContainer<Editor>.InputValidateProperty,
nameof(MyPartyDetailViewModel.ValidDescription));
// music genre
_musicGenrePicker.Input.SetBinding(EnumBindablePicker<MusicGenre>.SelectedItemProperty,
nameof(MyPartyDetailViewModel.MusicGenre));
// party type
_partyTypePicker.Input.SetBinding(EnumBindablePicker<PartyType>.SelectedItemProperty, nameof(MyPartyDetailViewModel.PartyType));
// date and time
_datePicker.Input.SetBinding(DatePicker.DateProperty, nameof(MyPartyDetailViewModel.Date));
// set start time
_startTimePicker.Input.SetBinding(TimePicker.TimeProperty, nameof(MyPartyDetailViewModel.Time));
// address
_streetEntry.Input.SetBinding(Entry.TextProperty, nameof(MyPartyDetailViewModel.StreetName));
_streetEntry.SetBinding(InputContainer<Entry>.InputValidateProperty,
nameof(MyPartyDetailViewModel.ValidStreetname));
// set city name
_cityNameEntry.Input.SetBinding(Entry.TextProperty, nameof(MyPartyDetailViewModel.CityName));
_cityNameEntry.SetBinding(InputContainer<Entry>.InputValidateProperty,
nameof(MyPartyDetailViewModel.ValidCityname));
// set house number
_houseNumberEntry.Input.SetBinding(Entry.TextProperty, nameof(MyPartyDetailViewModel.HouseNumber));
_houseNumberEntry.SetBinding(InputContainer<Entry>.InputValidateProperty,
nameof(MyPartyDetailViewModel.ValidHousenumber));
// set location
_priceEntry.Input.SetBinding(Entry.TextProperty, nameof(MyPartyDetailViewModel.Price));
_priceEntry.SetBinding(InputContainer<Entry>.InputValidateProperty,
nameof(MyPartyDetailViewModel.ValidPrice));
// set zipcode
_zipCodetEntry.Input.SetBinding(Entry.TextProperty, nameof(MyPartyDetailViewModel.Zipcode));
_zipCodetEntry.SetBinding(InputContainer<Entry>.InputValidateProperty,
nameof(MyPartyDetailViewModel.ValidZipcode));
// set MapPins
this.SetBinding(MyPartyDetailPage.MapPinsProperty, nameof(MyPartyDetailViewModel.MapPins));
_deleteParty.SetBinding(MenuItem.CommandProperty, nameof(MyPartyDetailViewModel.DeletePartyCommand));
//Participants
_gallerieView.SetBinding(GallerieView.ItemSourceProperty, "Party.Participants");
_gallerieView.SetBinding(GallerieView.IsVisibleProperty, "ParticipantsVisible");
_ratingView.SetBinding(PartyRatingView.PartyProperty, "Party");
}
protected override void OnDisappearing()
{
base.OnDisappearing();
// remove events on button
_editToolbarItem.Clicked -= SetEditEnable;
_cancelButton.ButtonTapped -= SetEditDisenable;
}
}
}
| |
// 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 Microsoft.Protocols.TestTools;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.Protocols.TestTools.StackSdk.FileAccessService;
using Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter;
using Microsoft.Protocols.TestSuites.FileSharing.Common.TestSuite;
using Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Rsvd;
using Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb2;
namespace Microsoft.Protocols.TestSuites.FileSharing.RSVD.TestSuite
{
[TestClass]
public class OpenCloseSharedVHD : RSVDTestBase
{
#region Test Suite Initialization
// Use ClassInitialize to run code before running the first test in the class
[ClassInitialize()]
public static void ClassInitialize(TestContext testContext)
{
TestClassBase.Initialize(testContext);
}
// Use ClassCleanup to run code after all tests in a class have run
[ClassCleanup()]
public static void ClassCleanup()
{
TestClassBase.Cleanup();
}
#endregion
[TestMethod]
[TestCategory(TestCategories.Bvt)]
[TestCategory(TestCategories.RsvdVersion1)]
[Description("Check if the server supports opening/closing a shared virtual disk file with SVHDX_OPEN_DEVICE_CONTEXT.")]
public void BVT_OpenCloseSharedVHD_V1()
{
BaseTestSite.Log.Add(LogEntryKind.TestStep, "1. Client opens a shared virtual disk file with SMB2 create context SVHDX_OPEN_DEVICE_CONTEXT and expects success.");
Smb2CreateContextResponse[] serverContextResponse;
OpenSharedVHD(TestConfig.NameOfSharedVHDX, RSVD_PROTOCOL_VERSION.RSVD_PROTOCOL_VERSION_1, null, true, null, out serverContextResponse);
CheckOpenDeviceContext(serverContextResponse);
BaseTestSite.Log.Add(LogEntryKind.TestStep, "2. Client closes the file.");
client.CloseSharedVirtualDisk();
}
[TestMethod]
[TestCategory(TestCategories.Bvt)]
[TestCategory(TestCategories.RsvdVersion2)]
[Description("Check if the server supports opening/closing a shared virtual disk file with SVHDX_OPEN_DEVICE_CONTEXT_V2.")]
public void BVT_OpenCloseSharedVHD_V2()
{
BaseTestSite.Log.Add(LogEntryKind.TestStep, "1. Client opens a shared virtual disk file with SMB2 create context SVHDX_OPEN_DEVICE_CONTEXT_V2 and expects success.");
Smb2CreateContextResponse[] serverContextResponse;
OpenSharedVHD(TestConfig.NameOfSharedVHDS, RSVD_PROTOCOL_VERSION.RSVD_PROTOCOL_VERSION_2, null, true, null, out serverContextResponse);
CheckOpenDeviceContext(serverContextResponse);
BaseTestSite.Log.Add(LogEntryKind.TestStep, "2. Client closes the file.");
client.CloseSharedVirtualDisk();
}
[TestMethod]
[TestCategory(TestCategories.RsvdVersion1)]
[TestCategory(TestCategories.Positive)]
[Description("Check if the client can reconnect the persistent handle to the shared virtual disk file without carrying device context.")]
public void ReconnectSharedVHDWithoutDeviceContext()
{
BaseTestSite.Log.Add(
LogEntryKind.TestStep,
"1. Client opens a shared virtual disk file with SMB2 create contexts " +
"SVHDX_OPEN_DEVICE_CONTEXT and SMB2_CREATE_DURABLE_HANDLE_REQUEST_V2 (persistent bit is set). ");
Smb2FunctionalClient clientBeforeDisconnect = new Smb2FunctionalClient(TestConfig.Timeout, TestConfig, BaseTestSite);
uint treeId;
Guid clientGuid = Guid.NewGuid();
ConnectToShare(clientBeforeDisconnect, clientGuid, TestConfig.FullPathShareContainingSharedVHD, out treeId);
Guid createGuid = Guid.NewGuid();
Guid initiatorId = Guid.NewGuid();
Smb2CreateContextResponse[] serverCreateContexts;
FILEID fileIdBeforeDisconnect;
clientBeforeDisconnect.Create
(treeId,
TestConfig.NameOfSharedVHDX + fileNameSuffix,
CreateOptions_Values.FILE_NON_DIRECTORY_FILE,
out fileIdBeforeDisconnect,
out serverCreateContexts,
RequestedOplockLevel_Values.OPLOCK_LEVEL_NONE,
new Smb2CreateContextRequest[]
{
new Smb2CreateSvhdxOpenDeviceContext
{
Version = (uint)RSVD_PROTOCOL_VERSION.RSVD_PROTOCOL_VERSION_1,
OriginatorFlags = (uint)OriginatorFlag.SVHDX_ORIGINATOR_PVHDPARSER,
InitiatorHostName = TestConfig.InitiatorHostName,
InitiatorHostNameLength = (ushort)(TestConfig.InitiatorHostName.Length * 2), // InitiatorHostName is a null-terminated Unicode UTF-16 string
InitiatorId = initiatorId
},
new Smb2CreateDurableHandleRequestV2
{
CreateGuid = createGuid,
Flags = CREATE_DURABLE_HANDLE_REQUEST_V2_Flags.DHANDLE_FLAG_PERSISTENT
}
});
bool persistentHandleReturned = false;
if (serverCreateContexts != null && serverCreateContexts[0] is Smb2CreateDurableHandleResponseV2)
{
var durableResponse = serverCreateContexts[0] as Smb2CreateDurableHandleResponseV2;
if (durableResponse.Flags.HasFlag(CREATE_DURABLE_HANDLE_RESPONSE_V2_Flags.DHANDLE_FLAG_PERSISTENT))
{
persistentHandleReturned = true;
}
}
BaseTestSite.Assert.IsTrue(persistentHandleReturned, "Server should return a persistent handle.");
BaseTestSite.Log.Add(
LogEntryKind.TestStep,
"2. Client disconnects from the server.");
clientBeforeDisconnect.Disconnect();
Smb2FunctionalClient clientAfterDisconnect = new Smb2FunctionalClient(TestConfig.Timeout, TestConfig, BaseTestSite);
ConnectToShare(clientAfterDisconnect, clientGuid, TestConfig.FullPathShareContainingSharedVHD, out treeId);
FILEID fileIdAfterDisconnect;
uint status = clientAfterDisconnect.Create
(treeId,
TestConfig.NameOfSharedVHDX + fileNameSuffix,
CreateOptions_Values.FILE_NON_DIRECTORY_FILE,
out fileIdAfterDisconnect,
out serverCreateContexts,
RequestedOplockLevel_Values.OPLOCK_LEVEL_NONE,
new Smb2CreateContextRequest[]
{
new Smb2CreateDurableHandleReconnectV2
{
CreateGuid = createGuid,
Flags = CREATE_DURABLE_HANDLE_RECONNECT_V2_Flags.DHANDLE_FLAG_PERSISTENT,
FileId = new FILEID { Persistent = fileIdBeforeDisconnect.Persistent }
}
},
checker: (header, response) => { });
BaseTestSite.Assert.AreEqual(
(uint)Smb2Status.STATUS_SUCCESS,
status,
"3. Client reconnects the persistent handle without create context SVHDX_OPEN_DEVICE_CONTEXT and expects success. Actual status is: {0}",
GetStatus(status));
clientAfterDisconnect.Close(treeId, fileIdAfterDisconnect);
clientAfterDisconnect.TreeDisconnect(treeId);
clientAfterDisconnect.LogOff();
clientAfterDisconnect.Disconnect();
}
private void ConnectToShare(Smb2FunctionalClient client, Guid clientGuid, string uncShareName, out uint treeId)
{
client.ConnectToServer(TestConfig.UnderlyingTransport, TestConfig.FileServerNameContainingSharedVHD, TestConfig.FileServerIPContainingSharedVHD);
client.Negotiate(
TestConfig.RequestDialects,
TestConfig.IsSMB1NegotiateEnabled,
SecurityMode_Values.NEGOTIATE_SIGNING_ENABLED,
Capabilities_Values.GLOBAL_CAP_PERSISTENT_HANDLES,
clientGuid);
client.SessionSetup(TestConfig.DefaultSecurityPackage, TestConfig.SutComputerName, TestConfig.AccountCredential, false);
client.TreeConnect(uncShareName, out treeId);
}
private void CheckOpenDeviceContext(Smb2CreateContextResponse[] servercreatecontexts)
{
// <9> Section 3.2.5.1: Windows Server 2012 R2 without [MSKB-3025091] doesn't return SVHDX_OPEN_DEVICE_CONTEXT_RESPONSE.
if (TestConfig.Platform == Platform.WindowsServer2012R2)
return;
foreach (var context in servercreatecontexts)
{
Type type = context.GetType();
if (type.Name == "Smb2CreateSvhdxOpenDeviceContext")
{
Smb2CreateSvhdxOpenDeviceContextResponse openDeviceContext = context as Smb2CreateSvhdxOpenDeviceContextResponse;
VerifyFieldInResponse("ServerVersion", TestConfig.ServerServiceVersion, openDeviceContext.Version);
}
if (type.Name == "Smb2CreateSvhdxOpenDeviceContextResponseV2")
{
Smb2CreateSvhdxOpenDeviceContextResponseV2 openDeviceContext = context as Smb2CreateSvhdxOpenDeviceContextResponseV2;
VerifyFieldInResponse("ServerVersion", TestConfig.ServerServiceVersion, openDeviceContext.Version);
VerifyFieldInResponse("SectorSize", TestConfig.PhysicalSectorSize, openDeviceContext.PhysicalSectorSize);
VerifyFieldInResponse("VirtualSize", TestConfig.VirtualSize, openDeviceContext.VirtualSize);
}
}
}
}
}
| |
// Copyright (c) 2012 DotNetAnywhere
//
// 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 !LOCALTEST
using System.Runtime.CompilerServices;
namespace System {
public static class Console {
static byte[] ascii2ConsoleKey_Map = new byte[128] {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 9 , 0x00, 0x00, 0x00, 13 , 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 27 , 0x00, 0x00, 0x00, 0x00,
32 , 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
48 , 49 , 50 , 51 , 52 , 53 , 54 , 55 , 56 , 57 , 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 65 , 66 , 67 , 68 , 69 , 70 , 71 , 72 , 73 , 74 , 75 , 76 , 77 , 78 , 79 ,
80 , 81 , 82 , 83 , 84 , 85 , 86 , 87 , 88 , 89 , 90 , 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 65 , 66 , 67 , 68 , 69 , 70 , 71 , 72 , 73 , 74 , 75 , 76 , 77 , 78 , 79 ,
80 , 81 , 82 , 83 , 84 , 85 , 86 , 87 , 88 , 89 , 90 , 0x00, 0x00, 0x00, 0x00, 0x00,
};
[MethodImpl(MethodImplOptions.InternalCall)]
extern public static void Write(string s);
[MethodImpl(MethodImplOptions.InternalCall)]
extern private static int Internal_ReadKey();
[MethodImpl(MethodImplOptions.InternalCall)]
extern private static bool Internal_KeyAvailable();
sealed class InternalTextWriter : IO.TextWriter {
public override System.Text.Encoding Encoding {
get {
return System.Text.Encoding.Default;
}
}
public override void Write(string s) {
Console.Write(s);
}
public override void Write(char value) {
Console.Write(value.ToString());
}
}
public static IO.TextWriter Error { get; } = new InternalTextWriter();
public static IO.TextWriter Out { get; } = new InternalTextWriter();
#region Write Methods
public static void Write(object value) {
if (value != null) {
Write(value.ToString());
}
}
public static void Write(char value) {
Write(value.ToString());
}
public static void Write(string format, params object[] args) {
Write(string.Format(format, args));
}
public static void Write(string format, object obj1) {
Write(format, new object[] { obj1 });
}
public static void Write(string format, object obj1, object obj2) {
Write(format, new object[] { obj1, obj2 });
}
public static void Write(string format, object obj1, object obj2, object obj3) {
Write(format, new object[] { obj1, obj2, obj3 });
}
public static void Write(string format, object obj1, object obj2, object obj3, object obj4) {
Write(format, new object[] { obj1, obj2, obj3, obj4 });
}
#endregion
#region WriteLine Methods
public static void WriteLine(string value) {
Write(value);
Write(Environment.NewLine);
}
public static void WriteLine() {
WriteLine(string.Empty);
}
public static void WriteLine(bool value) {
WriteLine(value.ToString());
}
public static void WriteLine(sbyte value) {
WriteLine(value.ToString());
}
public static void WriteLine(byte value) {
WriteLine(value.ToString());
}
public static void WriteLine(int value) {
WriteLine(value.ToString());
}
public static void WriteLine(uint value) {
WriteLine(value.ToString());
}
public static void WriteLine(long value) {
WriteLine(value.ToString());
}
public static void WriteLine(ulong value) {
WriteLine(value.ToString());
}
public static void WriteLine(char value) {
WriteLine(value.ToString());
}
public static void WriteLine(float value) {
WriteLine(value.ToString());
}
public static void WriteLine(double value) {
WriteLine(value.ToString());
}
public static void WriteLine(object value) {
if (value == null) {
WriteLine();
} else {
WriteLine(value.ToString());
}
}
public static void WriteLine(string format, params object[] args) {
WriteLine(string.Format(format, args));
}
public static void WriteLine(string format, object obj1) {
WriteLine(format, new object[] { obj1 });
}
public static void WriteLine(string format, object obj1, object obj2) {
WriteLine(format, new object[] { obj1, obj2 });
}
public static void WriteLine(string format, object obj1, object obj2, object obj3) {
WriteLine(format, new object[] { obj1, obj2, obj3 });
}
public static void WriteLine(string format, object obj1, object obj2, object obj3, object obj4) {
WriteLine(format, new object[] { obj1, obj2, obj3, obj4 });
}
#endregion
#region ReadKey Methods
public static bool KeyAvailable {
get {
return Internal_KeyAvailable();
}
}
public static ConsoleKeyInfo ReadKey() {
return ReadKey(false);
}
public static ConsoleKeyInfo ReadKey(bool intercept) {
int key = Internal_ReadKey();
char c = (char)key;
if (!intercept) {
Write(c);
}
ConsoleKey k;
if (key < 128) {
k = (ConsoleKey)ascii2ConsoleKey_Map[key];
} else {
k = ConsoleKey.Unknown;
}
return new ConsoleKeyInfo(c, k, false, false, false);
}
#endregion
}
}
#endif
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using Microsoft.Win32;
namespace System.Globalization
{
public partial class JapaneseCalendar : Calendar
{
private const string c_japaneseErasHive = @"System\CurrentControlSet\Control\Nls\Calendars\Japanese\Eras";
private const string c_japaneseErasHivePermissionList = @"HKEY_LOCAL_MACHINE\" + c_japaneseErasHive;
// We know about 4 built-in eras, however users may add additional era(s) from the
// registry, by adding values to HKLM\SYSTEM\CurrentControlSet\Control\Nls\Calendars\Japanese\Eras
//
// Registry values look like:
// yyyy.mm.dd=era_abbrev_english_englishabbrev
//
// Where yyyy.mm.dd is the registry value name, and also the date of the era start.
// yyyy, mm, and dd are the year, month & day the era begins (4, 2 & 2 digits long)
// era is the Japanese Era name
// abbrev is the Abbreviated Japanese Era Name
// english is the English name for the Era (unused)
// englishabbrev is the Abbreviated English name for the era.
// . is a delimiter, but the value of . doesn't matter.
// '_' marks the space between the japanese era name, japanese abbreviated era name
// english name, and abbreviated english names.
private static EraInfo[] GetJapaneseEras()
{
// Look in the registry key and see if we can find any ranges
int iFoundEras = 0;
EraInfo[] registryEraRanges = null;
try
{
// Need to access registry
RegistryKey key = RegistryKey.GetBaseKey(RegistryKey.HKEY_LOCAL_MACHINE).OpenSubKey(c_japaneseErasHive, false);
// Abort if we didn't find anything
if (key == null) return null;
// Look up the values in our reg key
String[] valueNames = key.GetValueNames();
if (valueNames != null && valueNames.Length > 0)
{
registryEraRanges = new EraInfo[valueNames.Length];
// Loop through the registry and read in all the values
for (int i = 0; i < valueNames.Length; i++)
{
// See if the era is a valid date
EraInfo era = GetEraFromValue(valueNames[i], key.GetValue(valueNames[i]).ToString());
// continue if not valid
if (era == null) continue;
// Remember we found one.
registryEraRanges[iFoundEras] = era;
iFoundEras++;
}
}
}
catch (System.Security.SecurityException)
{
// If we weren't allowed to read, then just ignore the error
return null;
}
catch (System.IO.IOException)
{
// If key is being deleted just ignore the error
return null;
}
catch (System.UnauthorizedAccessException)
{
// Registry access rights permissions, just ignore the error
return null;
}
//
// If we didn't have valid eras, then fail
// should have at least 4 eras
//
if (iFoundEras < 4) return null;
//
// Now we have eras, clean them up.
//
// Clean up array length
Array.Resize(ref registryEraRanges, iFoundEras);
// Sort them
Array.Sort(registryEraRanges, CompareEraRanges);
// Clean up era information
for (int i = 0; i < registryEraRanges.Length; i++)
{
// eras count backwards from length to 1 (and are 1 based indexes into string arrays)
registryEraRanges[i].era = registryEraRanges.Length - i;
// update max era year
if (i == 0)
{
// First range is 'til the end of the calendar
registryEraRanges[0].maxEraYear = GregorianCalendar.MaxYear - registryEraRanges[0].yearOffset;
}
else
{
// Rest are until the next era (remember most recent era is first in array)
registryEraRanges[i].maxEraYear = registryEraRanges[i - 1].yearOffset + 1 - registryEraRanges[i].yearOffset;
}
}
// Return our ranges
return registryEraRanges;
}
//
// Compare two era ranges, eg just the ticks
// Remember the era array is supposed to be in reverse chronological order
//
private static int CompareEraRanges(EraInfo a, EraInfo b)
{
return b.ticks.CompareTo(a.ticks);
}
//
// GetEraFromValue
//
// Parse the registry value name/data pair into an era
//
// Registry values look like:
// yyyy.mm.dd=era_abbrev_english_englishabbrev
//
// Where yyyy.mm.dd is the registry value name, and also the date of the era start.
// yyyy, mm, and dd are the year, month & day the era begins (4, 2 & 2 digits long)
// era is the Japanese Era name
// abbrev is the Abbreviated Japanese Era Name
// english is the English name for the Era (unused)
// englishabbrev is the Abbreviated English name for the era.
// . is a delimiter, but the value of . doesn't matter.
// '_' marks the space between the japanese era name, japanese abbreviated era name
// english name, and abbreviated english names.
private static EraInfo GetEraFromValue(String value, String data)
{
// Need inputs
if (value == null || data == null) return null;
//
// Get Date
//
// Need exactly 10 characters in name for date
// yyyy.mm.dd although the . can be any character
if (value.Length != 10) return null;
int year;
int month;
int day;
ReadOnlySpan<char> valueSpan = value.AsReadOnlySpan();
if (!Int32.TryParse(valueSpan.Slice(0, 4), NumberStyles.None, NumberFormatInfo.InvariantInfo, out year) ||
!Int32.TryParse(valueSpan.Slice(5, 2), NumberStyles.None, NumberFormatInfo.InvariantInfo, out month) ||
!Int32.TryParse(valueSpan.Slice(8, 2), NumberStyles.None, NumberFormatInfo.InvariantInfo, out day))
{
// Couldn't convert integer, fail
return null;
}
//
// Get Strings
//
// Needs to be a certain length e_a_E_A at least (7 chars, exactly 4 groups)
String[] names = data.Split('_');
// Should have exactly 4 parts
// 0 - Era Name
// 1 - Abbreviated Era Name
// 2 - English Era Name
// 3 - Abbreviated English Era Name
if (names.Length != 4) return null;
// Each part should have data in it
if (names[0].Length == 0 ||
names[1].Length == 0 ||
names[2].Length == 0 ||
names[3].Length == 0)
return null;
//
// Now we have an era we can build
// Note that the era # and max era year need cleaned up after sorting
// Don't use the full English Era Name (names[2])
//
return new EraInfo(0, year, month, day, year - 1, 1, 0,
names[0], names[1], names[3]);
}
// PAL Layer ends here
private static string[] s_japaneseErasEnglishNames = new String[] { "M", "T", "S", "H" };
private static string GetJapaneseEnglishEraName(int era)
{
Debug.Assert(era > 0);
return era <= s_japaneseErasEnglishNames.Length ? s_japaneseErasEnglishNames[era - 1] : " ";
}
}
}
| |
/*
* 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.Text;
namespace ZXing.Client.Result
{
/// <author>Sean Owen</author>
public sealed class AddressBookParsedResult : ParsedResult
{
private readonly String[] names;
private readonly String[] nicknames;
private readonly String pronunciation;
private readonly String[] phoneNumbers;
private readonly String[] phoneTypes;
private readonly String[] emails;
private readonly String[] emailTypes;
private readonly String instantMessenger;
private readonly String note;
private readonly String[] addresses;
private readonly String[] addressTypes;
private readonly String org;
private readonly String birthday;
private readonly String title;
private readonly String[] urls;
private readonly String[] geo;
public AddressBookParsedResult(String[] names,
String[] phoneNumbers,
String[] phoneTypes,
String[] emails,
String[] emailTypes,
String[] addresses,
String[] addressTypes)
: this(names,
null,
null,
phoneNumbers,
phoneTypes,
emails,
emailTypes,
null,
null,
addresses,
addressTypes,
null,
null,
null,
null,
null)
{
}
public AddressBookParsedResult(String[] names,
String[] nicknames,
String pronunciation,
String[] phoneNumbers,
String[] phoneTypes,
String[] emails,
String[] emailTypes,
String instantMessenger,
String note,
String[] addresses,
String[] addressTypes,
String org,
String birthday,
String title,
String[] urls,
String[] geo)
: base(ParsedResultType.ADDRESSBOOK)
{
this.names = names;
this.nicknames = nicknames;
this.pronunciation = pronunciation;
this.phoneNumbers = phoneNumbers;
this.phoneTypes = phoneTypes;
this.emails = emails;
this.emailTypes = emailTypes;
this.instantMessenger = instantMessenger;
this.note = note;
this.addresses = addresses;
this.addressTypes = addressTypes;
this.org = org;
this.birthday = birthday;
this.title = title;
this.urls = urls;
this.geo = geo;
displayResultValue = getDisplayResult();
}
public String[] Names
{
get { return names; }
}
public String[] Nicknames
{
get { return nicknames; }
}
/// <summary>
/// In Japanese, the name is written in kanji, which can have multiple readings. Therefore a hint
/// is often provided, called furigana, which spells the name phonetically.
/// </summary>
/// <return>The pronunciation of the getNames() field, often in hiragana or katakana.</return>
public String Pronunciation
{
get { return pronunciation; }
}
public String[] PhoneNumbers
{
get { return phoneNumbers; }
}
/// <return>optional descriptions of the type of each phone number. It could be like "HOME", but,
/// there is no guaranteed or standard format.</return>
public String[] PhoneTypes
{
get { return phoneTypes; }
}
public String[] Emails
{
get { return emails; }
}
/// <return>optional descriptions of the type of each e-mail. It could be like "WORK", but,
/// there is no guaranteed or standard format.</return>
public String[] EmailTypes
{
get { return emailTypes; }
}
public String InstantMessenger
{
get { return instantMessenger; }
}
public String Note
{
get { return note; }
}
public String[] Addresses
{
get { return addresses; }
}
/// <return>optional descriptions of the type of each e-mail. It could be like "WORK", but,
/// there is no guaranteed or standard format.</return>
public String[] AddressTypes
{
get { return addressTypes; }
}
public String Title
{
get { return title; }
}
public String Org
{
get { return org; }
}
public String[] URLs
{
get { return urls; }
}
/// <return>birthday formatted as yyyyMMdd (e.g. 19780917)</return>
public String Birthday
{
get { return birthday; }
}
/// <return>a location as a latitude/longitude pair</return>
public String[] Geo
{
get { return geo; }
}
private String getDisplayResult()
{
var result = new StringBuilder(100);
maybeAppend(names, result);
maybeAppend(nicknames, result);
maybeAppend(pronunciation, result);
maybeAppend(title, result);
maybeAppend(org, result);
maybeAppend(addresses, result);
maybeAppend(phoneNumbers, result);
maybeAppend(emails, result);
maybeAppend(instantMessenger, result);
maybeAppend(urls, result);
maybeAppend(birthday, result);
maybeAppend(geo, result);
maybeAppend(note, result);
return result.ToString();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
namespace Orleans.Runtime
{
internal class AssemblyLoader
{
private readonly Dictionary<string, SearchOption> dirEnumArgs;
private readonly HashSet<AssemblyLoaderPathNameCriterion> pathNameCriteria;
private readonly HashSet<AssemblyLoaderReflectionCriterion> reflectionCriteria;
private readonly Logger logger;
internal bool SimulateExcludeCriteriaFailure { get; set; }
internal bool SimulateLoadCriteriaFailure { get; set; }
internal bool SimulateReflectionOnlyLoadFailure { get; set; }
internal bool RethrowDiscoveryExceptions { get; set; }
private AssemblyLoader(
Dictionary<string, SearchOption> dirEnumArgs,
HashSet<AssemblyLoaderPathNameCriterion> pathNameCriteria,
HashSet<AssemblyLoaderReflectionCriterion> reflectionCriteria,
Logger logger)
{
this.dirEnumArgs = dirEnumArgs;
this.pathNameCriteria = pathNameCriteria;
this.reflectionCriteria = reflectionCriteria;
this.logger = logger;
SimulateExcludeCriteriaFailure = false;
SimulateLoadCriteriaFailure = false;
SimulateReflectionOnlyLoadFailure = false;
RethrowDiscoveryExceptions = false;
// Ensure that each assembly which is loaded is processed.
AssemblyProcessor.Initialize();
}
/// <summary>
/// Loads assemblies according to caller-defined criteria.
/// </summary>
/// <param name="dirEnumArgs">A list of arguments that are passed to Directory.EnumerateFiles().
/// The sum of the DLLs found from these searches is used as a base set of assemblies for
/// criteria to evaluate.</param>
/// <param name="pathNameCriteria">A list of criteria that are used to disqualify
/// assemblies from being loaded based on path name alone (e.g.
/// AssemblyLoaderCriteria.ExcludeFileNames) </param>
/// <param name="reflectionCriteria">A list of criteria that are used to identify
/// assemblies to be loaded based on examination of their ReflectionOnly type
/// information (e.g. AssemblyLoaderCriteria.LoadTypesAssignableFrom).</param>
/// <param name="logger">A logger to provide feedback to.</param>
/// <returns>List of discovered assembly locations</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Reflection.Assembly.LoadFrom")]
public static List<string> LoadAssemblies(
Dictionary<string, SearchOption> dirEnumArgs,
IEnumerable<AssemblyLoaderPathNameCriterion> pathNameCriteria,
IEnumerable<AssemblyLoaderReflectionCriterion> reflectionCriteria,
Logger logger)
{
var loader =
NewAssemblyLoader(
dirEnumArgs,
pathNameCriteria,
reflectionCriteria,
logger);
int count = 0;
List<string> discoveredAssemblyLocations = loader.DiscoverAssemblies();
foreach (var pathName in discoveredAssemblyLocations)
{
loader.logger.Info("Loading assembly {0}...", pathName);
// It is okay to use LoadFrom here because we are loading application assemblies deployed to the specific directory.
// Such application assemblies should not be deployed somewhere else, e.g. GAC, so this is safe.
Assembly.LoadFrom(pathName);
++count;
}
loader.logger.Info("{0} assemblies loaded.", count);
return discoveredAssemblyLocations;
}
public static T TryLoadAndCreateInstance<T>(string assemblyName, Logger logger) where T : class
{
try
{
var assembly = Assembly.Load(new AssemblyName(assemblyName));
var foundType =
TypeUtils.GetTypes(
assembly,
type =>
typeof(T).IsAssignableFrom(type) && !type.GetTypeInfo().IsInterface
&& type.GetTypeInfo().GetConstructor(Type.EmptyTypes) != null, logger).FirstOrDefault();
if (foundType == null)
{
return null;
}
return (T)Activator.CreateInstance(foundType, true);
}
catch (FileNotFoundException exception)
{
logger.Warn(ErrorCode.Loader_TryLoadAndCreateInstance_Failure, exception.Message, exception);
return null;
}
catch (Exception exc)
{
logger.Error(ErrorCode.Loader_TryLoadAndCreateInstance_Failure, exc.Message, exc);
throw;
}
}
public static T LoadAndCreateInstance<T>(string assemblyName, Logger logger) where T : class
{
try
{
var assembly = Assembly.Load(new AssemblyName(assemblyName));
var foundType = TypeUtils.GetTypes(assembly, type => typeof(T).IsAssignableFrom(type), logger).First();
return (T)Activator.CreateInstance(foundType, true);
}
catch (Exception exc)
{
logger.Error(ErrorCode.Loader_LoadAndCreateInstance_Failure, exc.Message, exc);
throw;
}
}
// this method is internal so that it can be accessed from unit tests, which only test the discovery
// process-- not the actual loading of assemblies.
internal static AssemblyLoader NewAssemblyLoader(
Dictionary<string, SearchOption> dirEnumArgs,
IEnumerable<AssemblyLoaderPathNameCriterion> pathNameCriteria,
IEnumerable<AssemblyLoaderReflectionCriterion> reflectionCriteria,
Logger logger)
{
if (null == dirEnumArgs)
throw new ArgumentNullException("dirEnumArgs");
if (dirEnumArgs.Count == 0)
throw new ArgumentException("At least one directory is necessary in order to search for assemblies.");
HashSet<AssemblyLoaderPathNameCriterion> pathNameCriteriaSet = null == pathNameCriteria
? new HashSet<AssemblyLoaderPathNameCriterion>()
: new HashSet<AssemblyLoaderPathNameCriterion>(pathNameCriteria.Distinct());
if (null == reflectionCriteria || !reflectionCriteria.Any())
throw new ArgumentException("No assemblies will be loaded unless reflection criteria are specified.");
var reflectionCriteriaSet = new HashSet<AssemblyLoaderReflectionCriterion>(reflectionCriteria.Distinct());
if (null == logger)
throw new ArgumentNullException("logger");
return new AssemblyLoader(
dirEnumArgs,
pathNameCriteriaSet,
reflectionCriteriaSet,
logger);
}
// this method is internal so that it can be accessed from unit tests, which only test the discovery
// process-- not the actual loading of assemblies.
internal List<string> DiscoverAssemblies()
{
try
{
if (dirEnumArgs.Count == 0)
throw new InvalidOperationException("Please specify a directory to search using the AddDirectory or AddRoot methods.");
AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += CachedReflectionOnlyTypeResolver.OnReflectionOnlyAssemblyResolve;
// the following explicit loop ensures that the finally clause is invoked
// after we're done enumerating.
return EnumerateApprovedAssemblies();
}
finally
{
AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve -= CachedReflectionOnlyTypeResolver.OnReflectionOnlyAssemblyResolve;
}
}
private List<string> EnumerateApprovedAssemblies()
{
var assemblies = new List<string>();
foreach (var i in dirEnumArgs)
{
var pathName = i.Key;
var searchOption = i.Value;
if (!Directory.Exists(pathName))
{
logger.Warn(ErrorCode.Loader_DirNotFound, "Unable to find directory {0}; skipping.", pathName);
continue;
}
logger.Info(
searchOption == SearchOption.TopDirectoryOnly ?
"Searching for assemblies in {0}..." :
"Recursively searching for assemblies in {0}...",
pathName);
var candidates =
Directory.EnumerateFiles(pathName, "*.dll", searchOption)
.Select(Path.GetFullPath)
.Distinct()
.ToArray();
// This is a workaround for the behavior of ReflectionOnlyLoad/ReflectionOnlyLoadFrom
// that appear not to automatically resolve dependencies.
// We are trying to pre-load all dlls we find in the folder, so that if one of these
// assemblies happens to be a dependency of an assembly we later on call
// Assembly.DefinedTypes on, the dependency will be already loaded and will get
// automatically resolved. Ugly, but seems to solve the problem.
foreach (var j in candidates)
{
try
{
if (logger.IsVerbose) logger.Verbose("Trying to pre-load {0} to reflection-only context.", j);
Assembly.ReflectionOnlyLoadFrom(j);
}
catch (Exception)
{
if (logger.IsVerbose) logger.Verbose("Failed to pre-load assembly {0} in reflection-only context.", j);
}
}
foreach (var j in candidates)
{
if (AssemblyPassesLoadCriteria(j))
assemblies.Add(j);
}
}
return assemblies;
}
private bool ShouldExcludeAssembly(string pathName)
{
foreach (var criterion in pathNameCriteria)
{
IEnumerable<string> complaints;
bool shouldExclude;
try
{
shouldExclude = !criterion.EvaluateCandidate(pathName, out complaints);
}
catch (Exception ex)
{
complaints = ReportUnexpectedException(ex);
if (RethrowDiscoveryExceptions)
throw;
shouldExclude = true;
}
if (shouldExclude)
{
LogComplaints(pathName, complaints);
return true;
}
}
return false;
}
private static Assembly MatchWithLoadedAssembly(AssemblyName searchFor, IEnumerable<Assembly> assemblies)
{
foreach (var assembly in assemblies)
{
var searchForFullName = searchFor.FullName;
var candidateFullName = assembly.FullName;
if (String.Equals(candidateFullName, searchForFullName, StringComparison.OrdinalIgnoreCase))
{
return assembly;
}
}
return null;
}
private static Assembly MatchWithLoadedAssembly(AssemblyName searchFor, AppDomain appDomain)
{
return
MatchWithLoadedAssembly(searchFor, appDomain.GetAssemblies()) ??
MatchWithLoadedAssembly(searchFor, appDomain.ReflectionOnlyGetAssemblies());
}
private static Assembly MatchWithLoadedAssembly(AssemblyName searchFor)
{
return MatchWithLoadedAssembly(searchFor, AppDomain.CurrentDomain);
}
private static bool InterpretFileLoadException(string asmPathName, out string[] complaints)
{
var matched = MatchWithLoadedAssembly(AssemblyName.GetAssemblyName(asmPathName));
if (null == matched)
{
// something unexpected has occurred. rethrow until we know what we're catching.
complaints = null;
return false;
}
if (matched.Location != asmPathName)
{
complaints = new string[] {String.Format("A conflicting assembly has already been loaded from {0}.", matched.Location)};
// exception was anticipated.
return true;
}
// we've been asked to not log this because it's not indicative of a problem.
complaints = null;
//complaints = new string[] {"Assembly has already been loaded into current application domain."};
// exception was anticipated.
return true;
}
private string[] ReportUnexpectedException(Exception exception)
{
const string msg = "An unexpected exception occurred while attempting to load an assembly.";
logger.Error(ErrorCode.Loader_UnexpectedException, msg, exception);
return new string[] {msg};
}
private bool ReflectionOnlyLoadAssembly(string pathName, out Assembly assembly, out string[] complaints)
{
try
{
if (SimulateReflectionOnlyLoadFailure)
throw NewTestUnexpectedException();
assembly = Assembly.ReflectionOnlyLoadFrom(pathName);
}
catch (FileLoadException e)
{
assembly = null;
if (!InterpretFileLoadException(pathName, out complaints))
complaints = ReportUnexpectedException(e);
if (RethrowDiscoveryExceptions)
throw;
return false;
}
catch (Exception e)
{
assembly = null;
complaints = ReportUnexpectedException(e);
if (RethrowDiscoveryExceptions)
throw;
return false;
}
complaints = null;
return true;
}
private void LogComplaint(string pathName, string complaint)
{
LogComplaints(pathName, new string[] { complaint });
}
private void LogComplaints(string pathName, IEnumerable<string> complaints)
{
var distinctComplaints = complaints.Distinct();
// generate feedback so that the operator can determine why her DLL didn't load.
var msg = new StringBuilder();
string bullet = Environment.NewLine + "\t* ";
msg.Append(String.Format("User assembly ignored: {0}", pathName));
int count = 0;
foreach (var i in distinctComplaints)
{
msg.Append(bullet);
msg.Append(i);
++count;
}
if (0 == count)
throw new InvalidOperationException("No complaint provided for assembly.");
// we can't use an error code here because we want each log message to be displayed.
logger.Info(msg.ToString());
}
private static AggregateException NewTestUnexpectedException()
{
var inner = new Exception[] { new OrleansException("Inner Exception #1"), new OrleansException("Inner Exception #2") };
return new AggregateException("Unexpected AssemblyLoader Exception Used for Unit Tests", inner);
}
private bool ShouldLoadAssembly(string pathName)
{
Assembly assembly;
string[] loadComplaints;
if (!ReflectionOnlyLoadAssembly(pathName, out assembly, out loadComplaints))
{
if (loadComplaints == null || loadComplaints.Length == 0)
return false;
LogComplaints(pathName, loadComplaints);
return false;
}
if (assembly.IsDynamic)
{
LogComplaint(pathName, "Assembly is dynamic (not supported).");
return false;
}
var criteriaComplaints = new List<string>();
foreach (var i in reflectionCriteria)
{
IEnumerable<string> complaints;
try
{
if (SimulateLoadCriteriaFailure)
throw NewTestUnexpectedException();
if (i.EvaluateCandidate(assembly, out complaints))
return true;
}
catch (Exception ex)
{
complaints = ReportUnexpectedException(ex);
if (RethrowDiscoveryExceptions)
throw;
}
criteriaComplaints.AddRange(complaints);
}
LogComplaints(pathName, criteriaComplaints);
return false;
}
private bool AssemblyPassesLoadCriteria(string pathName)
{
return !ShouldExcludeAssembly(pathName) && ShouldLoadAssembly(pathName);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
// This is used internally to create best fit behavior as per the original windows best fit behavior.
//
using System;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using System.Threading;
namespace System.Text
{
internal class InternalEncoderBestFitFallback : EncoderFallback
{
// Our variables
internal BaseCodePageEncoding encoding = null;
internal char[] arrayBestFit = null;
internal InternalEncoderBestFitFallback(BaseCodePageEncoding _encoding)
{
// Need to load our replacement characters table.
encoding = _encoding;
}
public override EncoderFallbackBuffer CreateFallbackBuffer()
{
return new InternalEncoderBestFitFallbackBuffer(this);
}
// Maximum number of characters that this instance of this fallback could return
public override int MaxCharCount
{
get
{
return 1;
}
}
public override bool Equals(object value)
{
InternalEncoderBestFitFallback that = value as InternalEncoderBestFitFallback;
if (that != null)
{
return (encoding.CodePage == that.encoding.CodePage);
}
return (false);
}
public override int GetHashCode()
{
return encoding.CodePage;
}
}
internal sealed class InternalEncoderBestFitFallbackBuffer : EncoderFallbackBuffer
{
// Our variables
private char _cBestFit = '\0';
private readonly InternalEncoderBestFitFallback _oFallback;
private int _iCount = -1;
private int _iSize;
// Private object for locking instead of locking on a public type for SQL reliability work.
private static object s_InternalSyncObject;
private static object InternalSyncObject
{
get
{
if (s_InternalSyncObject == null)
{
object o = new object();
Interlocked.CompareExchange<object>(ref s_InternalSyncObject, o, null);
}
return s_InternalSyncObject;
}
}
// Constructor
public InternalEncoderBestFitFallbackBuffer(InternalEncoderBestFitFallback fallback)
{
_oFallback = fallback;
if (_oFallback.arrayBestFit == null)
{
// Lock so we don't confuse ourselves.
lock (InternalSyncObject)
{
// Double check before we do it again.
if (_oFallback.arrayBestFit == null)
_oFallback.arrayBestFit = fallback.encoding.GetBestFitUnicodeToBytesData();
}
}
}
// Fallback methods
public override bool Fallback(char charUnknown, int index)
{
// If we had a buffer already we're being recursive, throw, it's probably at the suspect
// character in our array.
// Shouldn't be able to get here for all of our code pages, table would have to be messed up.
Debug.Assert(_iCount < 1, "[InternalEncoderBestFitFallbackBuffer.Fallback(non surrogate)] Fallback char " + ((int)_cBestFit).ToString("X4", CultureInfo.InvariantCulture) + " caused recursive fallback");
_iCount = _iSize = 1;
_cBestFit = TryBestFit(charUnknown);
if (_cBestFit == '\0')
_cBestFit = '?';
return true;
}
public override bool Fallback(char charUnknownHigh, char charUnknownLow, int index)
{
// Double check input surrogate pair
if (!char.IsHighSurrogate(charUnknownHigh))
throw new ArgumentOutOfRangeException(nameof(charUnknownHigh), SR.Format(SR.ArgumentOutOfRange_Range, 0xD800, 0xDBFF));
if (!char.IsLowSurrogate(charUnknownLow))
throw new ArgumentOutOfRangeException(nameof(charUnknownLow), SR.Format(SR.ArgumentOutOfRange_Range, 0xDC00, 0xDFFF));
// If we had a buffer already we're being recursive, throw, it's probably at the suspect
// character in our array. 0 is processing last character, < 0 is not falling back
// Shouldn't be able to get here, table would have to be messed up.
Debug.Assert(_iCount < 1, "[InternalEncoderBestFitFallbackBuffer.Fallback(surrogate)] Fallback char " + ((int)_cBestFit).ToString("X4", CultureInfo.InvariantCulture) + " caused recursive fallback");
// Go ahead and get our fallback, surrogates don't have best fit
_cBestFit = '?';
_iCount = _iSize = 2;
return true;
}
// Default version is overridden in EncoderReplacementFallback.cs
public override char GetNextChar()
{
// We want it to get < 0 because == 0 means that the current/last character is a fallback
// and we need to detect recursion. We could have a flag but we already have this counter.
_iCount--;
// Do we have anything left? 0 is now last fallback char, negative is nothing left
if (_iCount < 0)
return '\0';
// Need to get it out of the buffer.
// Make sure it didn't wrap from the fast count-- path
if (_iCount == int.MaxValue)
{
_iCount = -1;
return '\0';
}
// Return the best fit character
return _cBestFit;
}
public override bool MovePrevious()
{
// Exception fallback doesn't have anywhere to back up to.
if (_iCount >= 0)
_iCount++;
// Return true if we could do it.
return (_iCount >= 0 && _iCount <= _iSize);
}
// How many characters left to output?
public override int Remaining
{
get
{
return (_iCount > 0) ? _iCount : 0;
}
}
// Clear the buffer
public override unsafe void Reset()
{
_iCount = -1;
}
// private helper methods
private char TryBestFit(char cUnknown)
{
// Need to figure out our best fit character, low is beginning of array, high is 1 AFTER end of array
int lowBound = 0;
int highBound = _oFallback.arrayBestFit.Length;
int index;
// Binary search the array
int iDiff;
while ((iDiff = (highBound - lowBound)) > 6)
{
// Look in the middle, which is complicated by the fact that we have 2 #s for each pair,
// so we don't want index to be odd because we want to be on word boundaries.
// Also note that index can never == highBound (because diff is rounded down)
index = ((iDiff / 2) + lowBound) & 0xFFFE;
char cTest = _oFallback.arrayBestFit[index];
if (cTest == cUnknown)
{
// We found it
Debug.Assert(index + 1 < _oFallback.arrayBestFit.Length,
"[InternalEncoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array");
return _oFallback.arrayBestFit[index + 1];
}
else if (cTest < cUnknown)
{
// We weren't high enough
lowBound = index;
}
else
{
// We weren't low enough
highBound = index;
}
}
for (index = lowBound; index < highBound; index += 2)
{
if (_oFallback.arrayBestFit[index] == cUnknown)
{
// We found it
Debug.Assert(index + 1 < _oFallback.arrayBestFit.Length,
"[InternalEncoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array");
return _oFallback.arrayBestFit[index + 1];
}
}
// Char wasn't in our table
return '\0';
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Rest.Generator.CSharp.Templates
{
#line 1 "ModelTemplate.cshtml"
using System.Linq
#line default
#line hidden
;
#line 2 "ModelTemplate.cshtml"
using Microsoft.Rest.Generator.ClientModel
#line default
#line hidden
;
#line 3 "ModelTemplate.cshtml"
using Microsoft.Rest.Generator.CSharp.TemplateModels
#line default
#line hidden
;
#line 4 "ModelTemplate.cshtml"
using Microsoft.Rest.Generator.Utilities
#line default
#line hidden
;
using System.Threading.Tasks;
public class ModelTemplate : Microsoft.Rest.Generator.Template<Microsoft.Rest.Generator.CSharp.ModelTemplateModel>
{
#line hidden
public ModelTemplate()
{
}
#pragma warning disable 1998
public override async Task ExecuteAsync()
{
#line 6 "ModelTemplate.cshtml"
Write(Header("/// "));
#line default
#line hidden
WriteLiteral("\r\nnamespace ");
#line 7 "ModelTemplate.cshtml"
Write(Settings.Namespace);
#line default
#line hidden
WriteLiteral(".Models\r\n{\r\n using System;\r\n using System.Collections.Generic;\r\n using N" +
"ewtonsoft.Json;\r\n using Microsoft.Rest;\r\n using Microsoft.Rest.Serializati" +
"on;\r\n");
#line 14 "ModelTemplate.cshtml"
foreach (var usingString in Model.Usings) {
#line default
#line hidden
WriteLiteral(" using ");
#line 15 "ModelTemplate.cshtml"
Write(usingString);
#line default
#line hidden
WriteLiteral(";\r\n");
#line 16 "ModelTemplate.cshtml"
}
#line default
#line hidden
#line 17 "ModelTemplate.cshtml"
Write(EmptyLine);
#line default
#line hidden
WriteLiteral("\r\n /// <summary>\r\n ");
#line 19 "ModelTemplate.cshtml"
Write(WrapComment("/// ", Model.Documentation.EscapeXmlComment()));
#line default
#line hidden
WriteLiteral("\r\n /// </summary>\r\n");
#line 21 "ModelTemplate.cshtml"
#line default
#line hidden
#line 21 "ModelTemplate.cshtml"
if (Model.NeedsPolymorphicConverter)
{
#line default
#line hidden
WriteLiteral(" [JsonObject(\"");
#line 23 "ModelTemplate.cshtml"
Write(Model.SerializedName);
#line default
#line hidden
WriteLiteral("\")] \r\n");
#line 24 "ModelTemplate.cshtml"
}
#line default
#line hidden
WriteLiteral(" public partial class ");
#line 25 "ModelTemplate.cshtml"
Write(Model.Name);
#line default
#line hidden
#line 25 "ModelTemplate.cshtml"
Write(Model.BaseModelType != null ? " : " + Model.BaseModelType.Name : "");
#line default
#line hidden
WriteLiteral("\r\n {\r\n");
#line 27 "ModelTemplate.cshtml"
#line default
#line hidden
#line 27 "ModelTemplate.cshtml"
foreach (var property in Model.PropertyTemplateModels)
{
#line default
#line hidden
WriteLiteral(" /// <summary>\r\n ");
#line 30 "ModelTemplate.cshtml"
Write(WrapComment("/// ", property.Documentation.EscapeXmlComment()));
#line default
#line hidden
WriteLiteral("\r\n /// </summary>\r\n");
#line 32 "ModelTemplate.cshtml"
if (property.Type == PrimaryType.Date)
{
#line default
#line hidden
WriteLiteral(" [JsonConverter(typeof(DateJsonConverter))]\r\n");
#line 35 "ModelTemplate.cshtml"
}
#line default
#line hidden
WriteLiteral(" [JsonProperty(PropertyName = \"");
#line 36 "ModelTemplate.cshtml"
Write(property.SerializedName);
#line default
#line hidden
WriteLiteral("\")]\r\n public ");
#line 37 "ModelTemplate.cshtml"
Write(property.Type.Name);
#line default
#line hidden
WriteLiteral(" ");
#line 37 "ModelTemplate.cshtml"
Write(property.Name);
#line default
#line hidden
WriteLiteral(" { get; ");
#line 37 "ModelTemplate.cshtml"
Write(property.IsReadOnly ? "private " : "");
#line default
#line hidden
WriteLiteral("set; }\r\n");
#line 38 "ModelTemplate.cshtml"
#line default
#line hidden
#line 38 "ModelTemplate.cshtml"
Write(EmptyLine);
#line default
#line hidden
#line 38 "ModelTemplate.cshtml"
#line default
#line hidden
WriteLiteral(" \r\n");
#line 40 "ModelTemplate.cshtml"
}
#line default
#line hidden
#line 41 "ModelTemplate.cshtml"
if(@Model.ShouldValidate())
{
#line default
#line hidden
WriteLiteral(" /// <summary>\r\n /// Validate the object. Throws ArgumentException " +
"or ArgumentNullException if validation fails.\r\n /// </summary>\r\n p" +
"ublic ");
#line 46 "ModelTemplate.cshtml"
Write(Model.MethodQualifier);
#line default
#line hidden
WriteLiteral(" void Validate()\r\n {\r\n");
#line 48 "ModelTemplate.cshtml"
bool anythingToValidate = false;
if (Model.BaseModelType != null)
{
anythingToValidate = true;
#line default
#line hidden
WriteLiteral(" base.Validate();\r\n");
#line 54 "ModelTemplate.cshtml"
}
foreach (var property in Model.Properties.Where(p => p.IsRequired && !p.IsReadOnly))
{
anythingToValidate = true;
#line default
#line hidden
WriteLiteral(" if (");
#line 59 "ModelTemplate.cshtml"
Write(property.Name);
#line default
#line hidden
WriteLiteral(" == null)\r\n {\r\n throw new ValidationException(Validatio" +
"nRules.CannotBeNull, \"");
#line 61 "ModelTemplate.cshtml"
Write(property.Name);
#line default
#line hidden
WriteLiteral("\");\r\n }\r\n \r\n");
#line 64 "ModelTemplate.cshtml"
}
foreach (var property in Model.Properties.Where(p => !(p.Type is PrimaryType)))
{
anythingToValidate = true;
#line default
#line hidden
WriteLiteral(" ");
#line 68 "ModelTemplate.cshtml"
Write(property.Type.ValidateType(Model.Scope, string.Format("this.{0}", property.Name)));
#line default
#line hidden
WriteLiteral("\r\n \r\n");
#line 70 "ModelTemplate.cshtml"
}
if (!anythingToValidate)
{
#line default
#line hidden
WriteLiteral(" //Nothing to validate\r\n");
#line 74 "ModelTemplate.cshtml"
}
#line default
#line hidden
WriteLiteral(" }\r\n");
#line 76 "ModelTemplate.cshtml"
}
#line default
#line hidden
WriteLiteral(" }\r\n}\r\n");
}
#pragma warning restore 1998
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Runtime;
using System.Runtime.Serialization;
using System.ServiceModel.Diagnostics;
using System.ServiceModel.Dispatcher;
using System.Threading;
using System.Xml;
namespace System.ServiceModel.Channels
{
public sealed class MessageHeaders : IEnumerable<MessageHeaderInfo>
{
private int _collectionVersion;
private int _headerCount;
private Header[] _headers;
private MessageVersion _version;
private IBufferedMessageData _bufferedMessageData;
private UnderstoodHeaders _understoodHeaders;
private const int InitialHeaderCount = 4;
private const int MaxRecycledArrayLength = 8;
private static XmlDictionaryString[] s_localNames;
internal const string WildcardAction = "*";
// The highest node and attribute counts reached by the BVTs were 1829 and 667 respectively.
private const int MaxBufferedHeaderNodes = 4096;
private const int MaxBufferedHeaderAttributes = 2048;
private int _nodeCount = 0;
private int _attrCount = 0;
private bool _understoodHeadersModified;
public MessageHeaders(MessageVersion version, int initialSize)
{
Init(version, initialSize);
}
public MessageHeaders(MessageVersion version)
: this(version, InitialHeaderCount)
{
}
internal MessageHeaders(MessageVersion version, XmlDictionaryReader reader, XmlAttributeHolder[] envelopeAttributes, XmlAttributeHolder[] headerAttributes, ref int maxSizeOfHeaders)
: this(version)
{
if (maxSizeOfHeaders < 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ArgumentOutOfRangeException("maxSizeOfHeaders", maxSizeOfHeaders,
SR.ValueMustBeNonNegative));
}
if (version == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("version"));
if (reader == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("reader"));
if (reader.IsEmptyElement)
{
reader.Read();
return;
}
XmlBuffer xmlBuffer = null;
EnvelopeVersion envelopeVersion = version.Envelope;
reader.ReadStartElement(XD.MessageDictionary.Header, envelopeVersion.DictionaryNamespace);
while (reader.IsStartElement())
{
if (xmlBuffer == null)
xmlBuffer = new XmlBuffer(maxSizeOfHeaders);
BufferedHeader bufferedHeader = new BufferedHeader(version, xmlBuffer, reader, envelopeAttributes, headerAttributes);
HeaderProcessing processing = bufferedHeader.MustUnderstand ? HeaderProcessing.MustUnderstand : 0;
HeaderKind kind = GetHeaderKind(bufferedHeader);
if (kind != HeaderKind.Unknown)
{
processing |= HeaderProcessing.Understood;
MessageHeaders.TraceUnderstood(bufferedHeader);
}
Header newHeader = new Header(kind, bufferedHeader, processing);
AddHeader(newHeader);
}
if (xmlBuffer != null)
{
xmlBuffer.Close();
maxSizeOfHeaders -= xmlBuffer.BufferSize;
}
reader.ReadEndElement();
_collectionVersion = 0;
}
internal MessageHeaders(MessageVersion version, XmlDictionaryReader reader, IBufferedMessageData bufferedMessageData, RecycledMessageState recycledMessageState, bool[] understoodHeaders, bool understoodHeadersModified)
{
_headers = new Header[InitialHeaderCount];
Init(version, reader, bufferedMessageData, recycledMessageState, understoodHeaders, understoodHeadersModified);
}
internal MessageHeaders(MessageVersion version, MessageHeaders headers, IBufferedMessageData bufferedMessageData)
{
_version = version;
_bufferedMessageData = bufferedMessageData;
_headerCount = headers._headerCount;
_headers = new Header[_headerCount];
Array.Copy(headers._headers, _headers, _headerCount);
_collectionVersion = 0;
}
public MessageHeaders(MessageHeaders collection)
{
if (collection == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("collection");
Init(collection._version, collection._headers.Length);
CopyHeadersFrom(collection);
_collectionVersion = 0;
}
public string Action
{
get
{
int index = FindHeaderProperty(HeaderKind.Action);
if (index < 0)
return null;
ActionHeader actionHeader = _headers[index].HeaderInfo as ActionHeader;
if (actionHeader != null)
return actionHeader.Action;
using (XmlDictionaryReader reader = GetReaderAtHeader(index))
{
return ActionHeader.ReadHeaderValue(reader, _version.Addressing);
}
}
set
{
if (value != null)
SetActionHeader(ActionHeader.Create(value, _version.Addressing));
else
SetHeaderProperty(HeaderKind.Action, null);
}
}
internal bool CanRecycle
{
get { return _headers.Length <= MaxRecycledArrayLength; }
}
internal bool ContainsOnlyBufferedMessageHeaders
{
get { return (_bufferedMessageData != null && _collectionVersion == 0); }
}
internal int CollectionVersion
{
get { return _collectionVersion; }
}
public int Count
{
get { return _headerCount; }
}
public EndpointAddress FaultTo
{
get
{
int index = FindHeaderProperty(HeaderKind.FaultTo);
if (index < 0)
return null;
FaultToHeader faultToHeader = _headers[index].HeaderInfo as FaultToHeader;
if (faultToHeader != null)
return faultToHeader.FaultTo;
using (XmlDictionaryReader reader = GetReaderAtHeader(index))
{
return FaultToHeader.ReadHeaderValue(reader, _version.Addressing);
}
}
set
{
if (value != null)
SetFaultToHeader(FaultToHeader.Create(value, _version.Addressing));
else
SetHeaderProperty(HeaderKind.FaultTo, null);
}
}
public EndpointAddress From
{
get
{
int index = FindHeaderProperty(HeaderKind.From);
if (index < 0)
return null;
FromHeader fromHeader = _headers[index].HeaderInfo as FromHeader;
if (fromHeader != null)
return fromHeader.From;
using (XmlDictionaryReader reader = GetReaderAtHeader(index))
{
return FromHeader.ReadHeaderValue(reader, _version.Addressing);
}
}
set
{
if (value != null)
SetFromHeader(FromHeader.Create(value, _version.Addressing));
else
SetHeaderProperty(HeaderKind.From, null);
}
}
internal bool HasMustUnderstandBeenModified
{
get
{
if (_understoodHeaders != null)
{
return _understoodHeaders.Modified;
}
else
{
return _understoodHeadersModified;
}
}
}
public UniqueId MessageId
{
get
{
int index = FindHeaderProperty(HeaderKind.MessageId);
if (index < 0)
return null;
MessageIDHeader messageIDHeader = _headers[index].HeaderInfo as MessageIDHeader;
if (messageIDHeader != null)
return messageIDHeader.MessageId;
using (XmlDictionaryReader reader = GetReaderAtHeader(index))
{
return MessageIDHeader.ReadHeaderValue(reader, _version.Addressing);
}
}
set
{
if (value != null)
SetMessageIDHeader(MessageIDHeader.Create(value, _version.Addressing));
else
SetHeaderProperty(HeaderKind.MessageId, null);
}
}
public MessageVersion MessageVersion
{
get { return _version; }
}
public UniqueId RelatesTo
{
get
{
return GetRelatesTo(RelatesToHeader.ReplyRelationshipType);
}
set
{
SetRelatesTo(RelatesToHeader.ReplyRelationshipType, value);
}
}
public EndpointAddress ReplyTo
{
get
{
int index = FindHeaderProperty(HeaderKind.ReplyTo);
if (index < 0)
return null;
ReplyToHeader replyToHeader = _headers[index].HeaderInfo as ReplyToHeader;
if (replyToHeader != null)
return replyToHeader.ReplyTo;
using (XmlDictionaryReader reader = GetReaderAtHeader(index))
{
return ReplyToHeader.ReadHeaderValue(reader, _version.Addressing);
}
}
set
{
if (value != null)
SetReplyToHeader(ReplyToHeader.Create(value, _version.Addressing));
else
SetHeaderProperty(HeaderKind.ReplyTo, null);
}
}
public Uri To
{
get
{
int index = FindHeaderProperty(HeaderKind.To);
if (index < 0)
return null;
ToHeader toHeader = _headers[index].HeaderInfo as ToHeader;
if (toHeader != null)
return toHeader.To;
using (XmlDictionaryReader reader = GetReaderAtHeader(index))
{
return ToHeader.ReadHeaderValue(reader, _version.Addressing);
}
}
set
{
if (value != null)
SetToHeader(ToHeader.Create(value, _version.Addressing));
else
SetHeaderProperty(HeaderKind.To, null);
}
}
public UnderstoodHeaders UnderstoodHeaders
{
get
{
if (_understoodHeaders == null)
_understoodHeaders = new UnderstoodHeaders(this, _understoodHeadersModified);
return _understoodHeaders;
}
}
public MessageHeaderInfo this[int index]
{
get
{
if (index < 0 || index >= _headerCount)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ArgumentOutOfRangeException("index", index,
SR.Format(SR.ValueMustBeInRange, 0, _headerCount)));
}
return _headers[index].HeaderInfo;
}
}
public void Add(MessageHeader header)
{
Insert(_headerCount, header);
}
internal void AddActionHeader(ActionHeader actionHeader)
{
Insert(_headerCount, actionHeader, HeaderKind.Action);
}
internal void AddMessageIDHeader(MessageIDHeader messageIDHeader)
{
Insert(_headerCount, messageIDHeader, HeaderKind.MessageId);
}
internal void AddRelatesToHeader(RelatesToHeader relatesToHeader)
{
Insert(_headerCount, relatesToHeader, HeaderKind.RelatesTo);
}
internal void AddReplyToHeader(ReplyToHeader replyToHeader)
{
Insert(_headerCount, replyToHeader, HeaderKind.ReplyTo);
}
internal void AddToHeader(ToHeader toHeader)
{
Insert(_headerCount, toHeader, HeaderKind.To);
}
private void Add(MessageHeader header, HeaderKind kind)
{
Insert(_headerCount, header, kind);
}
private void AddHeader(Header header)
{
InsertHeader(_headerCount, header);
}
internal void AddUnderstood(int i)
{
_headers[i].HeaderProcessing |= HeaderProcessing.Understood;
MessageHeaders.TraceUnderstood(_headers[i].HeaderInfo);
}
internal void AddUnderstood(MessageHeaderInfo headerInfo)
{
if (headerInfo == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("headerInfo"));
for (int i = 0; i < _headerCount; i++)
{
if ((object)_headers[i].HeaderInfo == (object)headerInfo)
{
if ((_headers[i].HeaderProcessing & HeaderProcessing.Understood) != 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(
SR.Format(SR.HeaderAlreadyUnderstood, headerInfo.Name, headerInfo.Namespace), "headerInfo"));
}
AddUnderstood(i);
}
}
}
private void CaptureBufferedHeaders()
{
CaptureBufferedHeaders(-1);
}
private void CaptureBufferedHeaders(int exceptIndex)
{
using (XmlDictionaryReader reader = GetBufferedMessageHeaderReaderAtHeaderContents(_bufferedMessageData))
{
for (int i = 0; i < _headerCount; i++)
{
if (reader.NodeType != XmlNodeType.Element)
{
if (reader.MoveToContent() != XmlNodeType.Element)
break;
}
Header header = _headers[i];
if (i == exceptIndex || header.HeaderType != HeaderType.BufferedMessageHeader)
{
reader.Skip();
}
else
{
_headers[i] = new Header(header.HeaderKind, CaptureBufferedHeader(reader,
header.HeaderInfo), header.HeaderProcessing);
}
}
}
_bufferedMessageData = null;
}
private BufferedHeader CaptureBufferedHeader(XmlDictionaryReader reader, MessageHeaderInfo headerInfo)
{
XmlBuffer buffer = new XmlBuffer(int.MaxValue);
XmlDictionaryWriter writer = buffer.OpenSection(_bufferedMessageData.Quotas);
writer.WriteNode(reader, false);
buffer.CloseSection();
buffer.Close();
return new BufferedHeader(_version, buffer, 0, headerInfo);
}
private BufferedHeader CaptureBufferedHeader(IBufferedMessageData bufferedMessageData, MessageHeaderInfo headerInfo, int bufferedMessageHeaderIndex)
{
XmlBuffer buffer = new XmlBuffer(int.MaxValue);
XmlDictionaryWriter writer = buffer.OpenSection(bufferedMessageData.Quotas);
WriteBufferedMessageHeader(bufferedMessageData, bufferedMessageHeaderIndex, writer);
buffer.CloseSection();
buffer.Close();
return new BufferedHeader(_version, buffer, 0, headerInfo);
}
private BufferedHeader CaptureWriteableHeader(MessageHeader writeableHeader)
{
XmlBuffer buffer = new XmlBuffer(int.MaxValue);
XmlDictionaryWriter writer = buffer.OpenSection(XmlDictionaryReaderQuotas.Max);
writeableHeader.WriteHeader(writer, _version);
buffer.CloseSection();
buffer.Close();
return new BufferedHeader(_version, buffer, 0, writeableHeader);
}
public void Clear()
{
for (int i = 0; i < _headerCount; i++)
_headers[i] = new Header();
_headerCount = 0;
_collectionVersion++;
_bufferedMessageData = null;
}
public void CopyHeaderFrom(Message message, int headerIndex)
{
if (message == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("message"));
CopyHeaderFrom(message.Headers, headerIndex);
}
public void CopyHeaderFrom(MessageHeaders collection, int headerIndex)
{
if (collection == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("collection");
}
if (collection._version != _version)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.MessageHeaderVersionMismatch, collection._version.ToString(), _version.ToString()), "collection"));
}
if (headerIndex < 0 || headerIndex >= collection._headerCount)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ArgumentOutOfRangeException("headerIndex", headerIndex,
SR.Format(SR.ValueMustBeInRange, 0, collection._headerCount)));
}
Header header = collection._headers[headerIndex];
HeaderProcessing processing = header.HeaderInfo.MustUnderstand ? HeaderProcessing.MustUnderstand : 0;
if ((header.HeaderProcessing & HeaderProcessing.Understood) != 0 || header.HeaderKind != HeaderKind.Unknown)
processing |= HeaderProcessing.Understood;
switch (header.HeaderType)
{
case HeaderType.BufferedMessageHeader:
AddHeader(new Header(header.HeaderKind, collection.CaptureBufferedHeader(collection._bufferedMessageData,
header.HeaderInfo, headerIndex), processing));
break;
case HeaderType.ReadableHeader:
AddHeader(new Header(header.HeaderKind, header.ReadableHeader, processing));
break;
case HeaderType.WriteableHeader:
AddHeader(new Header(header.HeaderKind, header.MessageHeader, processing));
break;
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.InvalidEnumValue, header.HeaderType)));
}
}
public void CopyHeadersFrom(Message message)
{
if (message == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("message"));
CopyHeadersFrom(message.Headers);
}
public void CopyHeadersFrom(MessageHeaders collection)
{
if (collection == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("collection"));
for (int i = 0; i < collection._headerCount; i++)
CopyHeaderFrom(collection, i);
}
public void CopyTo(MessageHeaderInfo[] array, int index)
{
if (array == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("array");
}
if (index < 0 || (index + _headerCount) > array.Length)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ArgumentOutOfRangeException("index", index,
SR.Format(SR.ValueMustBeInRange, 0, array.Length - _headerCount)));
}
for (int i = 0; i < _headerCount; i++)
array[i + index] = _headers[i].HeaderInfo;
}
private Exception CreateDuplicateHeaderException(HeaderKind kind)
{
string name;
switch (kind)
{
case HeaderKind.Action:
name = AddressingStrings.Action;
break;
case HeaderKind.FaultTo:
name = AddressingStrings.FaultTo;
break;
case HeaderKind.From:
name = AddressingStrings.From;
break;
case HeaderKind.MessageId:
name = AddressingStrings.MessageId;
break;
case HeaderKind.ReplyTo:
name = AddressingStrings.ReplyTo;
break;
case HeaderKind.To:
name = AddressingStrings.To;
break;
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.InvalidEnumValue, kind)));
}
return new MessageHeaderException(
SR.Format(SR.MultipleMessageHeaders, name, _version.Addressing.Namespace),
name,
_version.Addressing.Namespace,
true);
}
public int FindHeader(string name, string ns)
{
if (name == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("name"));
if (ns == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("ns"));
if (ns == _version.Addressing.Namespace)
{
return FindAddressingHeader(name, ns);
}
else
{
return FindNonAddressingHeader(name, ns, _version.Envelope.UltimateDestinationActorValues);
}
}
private int FindAddressingHeader(string name, string ns)
{
int foundAt = -1;
for (int i = 0; i < _headerCount; i++)
{
if (_headers[i].HeaderKind != HeaderKind.Unknown)
{
MessageHeaderInfo info = _headers[i].HeaderInfo;
if (info.Name == name && info.Namespace == ns)
{
if (foundAt >= 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new MessageHeaderException(SR.Format(SR.MultipleMessageHeaders, name, ns), name, ns, true));
}
foundAt = i;
}
}
}
return foundAt;
}
private int FindNonAddressingHeader(string name, string ns, string[] actors)
{
int foundAt = -1;
for (int i = 0; i < _headerCount; i++)
{
if (_headers[i].HeaderKind == HeaderKind.Unknown)
{
MessageHeaderInfo info = _headers[i].HeaderInfo;
if (info.Name == name && info.Namespace == ns)
{
for (int j = 0; j < actors.Length; j++)
{
if (actors[j] == info.Actor)
{
if (foundAt >= 0)
{
if (actors.Length == 1)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageHeaderException(SR.Format(SR.MultipleMessageHeadersWithActor, name, ns, actors[0]), name, ns, true));
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageHeaderException(SR.Format(SR.MultipleMessageHeaders, name, ns), name, ns, true));
}
foundAt = i;
}
}
}
}
}
return foundAt;
}
public int FindHeader(string name, string ns, params string[] actors)
{
if (name == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("name"));
if (ns == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("ns"));
if (actors == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("actors"));
int foundAt = -1;
for (int i = 0; i < _headerCount; i++)
{
MessageHeaderInfo info = _headers[i].HeaderInfo;
if (info.Name == name && info.Namespace == ns)
{
for (int j = 0; j < actors.Length; j++)
{
if (actors[j] == info.Actor)
{
if (foundAt >= 0)
{
if (actors.Length == 1)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageHeaderException(SR.Format(SR.MultipleMessageHeadersWithActor, name, ns, actors[0]), name, ns, true));
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageHeaderException(SR.Format(SR.MultipleMessageHeaders, name, ns), name, ns, true));
}
foundAt = i;
}
}
}
}
return foundAt;
}
private int FindHeaderProperty(HeaderKind kind)
{
int index = -1;
for (int i = 0; i < _headerCount; i++)
{
if (_headers[i].HeaderKind == kind)
{
if (index >= 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateDuplicateHeaderException(kind));
index = i;
}
}
return index;
}
private int FindRelatesTo(Uri relationshipType, out UniqueId messageId)
{
UniqueId foundValue = null;
int foundIndex = -1;
for (int i = 0; i < _headerCount; i++)
{
if (_headers[i].HeaderKind == HeaderKind.RelatesTo)
{
Uri tempRelationship;
UniqueId tempValue;
GetRelatesToValues(i, out tempRelationship, out tempValue);
if (relationshipType == tempRelationship)
{
if (foundValue != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new MessageHeaderException(
SR.Format(SR.MultipleRelatesToHeaders, relationshipType.AbsoluteUri),
AddressingStrings.RelatesTo,
_version.Addressing.Namespace,
true));
}
foundValue = tempValue;
foundIndex = i;
}
}
}
messageId = foundValue;
return foundIndex;
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
public IEnumerator<MessageHeaderInfo> GetEnumerator()
{
MessageHeaderInfo[] headers = new MessageHeaderInfo[_headerCount];
CopyTo(headers, 0);
return GetEnumerator(headers);
}
private IEnumerator<MessageHeaderInfo> GetEnumerator(MessageHeaderInfo[] headers)
{
IList<MessageHeaderInfo> list = new ReadOnlyCollection<MessageHeaderInfo>(headers);
return list.GetEnumerator();
}
internal IEnumerator<MessageHeaderInfo> GetUnderstoodEnumerator()
{
List<MessageHeaderInfo> understoodHeaders = new List<MessageHeaderInfo>();
for (int i = 0; i < _headerCount; i++)
{
if ((_headers[i].HeaderProcessing & HeaderProcessing.Understood) != 0)
{
understoodHeaders.Add(_headers[i].HeaderInfo);
}
}
return understoodHeaders.GetEnumerator();
}
private static XmlDictionaryReader GetBufferedMessageHeaderReaderAtHeaderContents(IBufferedMessageData bufferedMessageData)
{
XmlDictionaryReader reader = bufferedMessageData.GetMessageReader();
if (reader.NodeType == XmlNodeType.Element)
reader.Read();
else
reader.ReadStartElement();
if (reader.NodeType == XmlNodeType.Element)
reader.Read();
else
reader.ReadStartElement();
return reader;
}
private XmlDictionaryReader GetBufferedMessageHeaderReader(IBufferedMessageData bufferedMessageData, int bufferedMessageHeaderIndex)
{
// Check if we need to change representations
if (_nodeCount > MaxBufferedHeaderNodes || _attrCount > MaxBufferedHeaderAttributes)
{
CaptureBufferedHeaders();
return _headers[bufferedMessageHeaderIndex].ReadableHeader.GetHeaderReader();
}
XmlDictionaryReader reader = GetBufferedMessageHeaderReaderAtHeaderContents(bufferedMessageData);
for (; ;)
{
if (reader.NodeType != XmlNodeType.Element)
reader.MoveToContent();
if (bufferedMessageHeaderIndex == 0)
break;
Skip(reader);
bufferedMessageHeaderIndex--;
}
return reader;
}
private void Skip(XmlDictionaryReader reader)
{
if (reader.MoveToContent() == XmlNodeType.Element && !reader.IsEmptyElement)
{
int depth = reader.Depth;
do
{
_attrCount += reader.AttributeCount;
_nodeCount++;
} while (reader.Read() && depth < reader.Depth);
// consume end tag
if (reader.NodeType == XmlNodeType.EndElement)
{
_nodeCount++;
reader.Read();
}
}
else
{
_attrCount += reader.AttributeCount;
_nodeCount++;
reader.Read();
}
}
public T GetHeader<T>(string name, string ns)
{
return GetHeader<T>(name, ns, DataContractSerializerDefaults.CreateSerializer(typeof(T), name, ns, int.MaxValue/*maxItems*/));
}
public T GetHeader<T>(string name, string ns, params string[] actors)
{
int index = FindHeader(name, ns, actors);
if (index < 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageHeaderException(SR.Format(SR.HeaderNotFound, name, ns), name, ns));
return GetHeader<T>(index);
}
public T GetHeader<T>(string name, string ns, XmlObjectSerializer serializer)
{
if (serializer == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("serializer"));
int index = FindHeader(name, ns);
if (index < 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageHeaderException(SR.Format(SR.HeaderNotFound, name, ns), name, ns));
return GetHeader<T>(index, serializer);
}
public T GetHeader<T>(int index)
{
if (index < 0 || index >= _headerCount)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ArgumentOutOfRangeException("index", index,
SR.Format(SR.ValueMustBeInRange, 0, _headerCount)));
}
MessageHeaderInfo headerInfo = _headers[index].HeaderInfo;
return GetHeader<T>(index, DataContractSerializerDefaults.CreateSerializer(typeof(T), headerInfo.Name, headerInfo.Namespace, int.MaxValue/*maxItems*/));
}
public T GetHeader<T>(int index, XmlObjectSerializer serializer)
{
if (serializer == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("serializer"));
using (XmlDictionaryReader reader = GetReaderAtHeader(index))
{
return (T)serializer.ReadObject(reader);
}
}
private HeaderKind GetHeaderKind(MessageHeaderInfo headerInfo)
{
HeaderKind headerKind = HeaderKind.Unknown;
if (headerInfo.Namespace == _version.Addressing.Namespace)
{
if (_version.Envelope.IsUltimateDestinationActor(headerInfo.Actor))
{
string name = headerInfo.Name;
if (name.Length > 0)
{
switch (name[0])
{
case 'A':
if (name == AddressingStrings.Action)
{
headerKind = HeaderKind.Action;
}
break;
case 'F':
if (name == AddressingStrings.From)
{
headerKind = HeaderKind.From;
}
else if (name == AddressingStrings.FaultTo)
{
headerKind = HeaderKind.FaultTo;
}
break;
case 'M':
if (name == AddressingStrings.MessageId)
{
headerKind = HeaderKind.MessageId;
}
break;
case 'R':
if (name == AddressingStrings.ReplyTo)
{
headerKind = HeaderKind.ReplyTo;
}
else if (name == AddressingStrings.RelatesTo)
{
headerKind = HeaderKind.RelatesTo;
}
break;
case 'T':
if (name == AddressingStrings.To)
{
headerKind = HeaderKind.To;
}
break;
}
}
}
}
ValidateHeaderKind(headerKind);
return headerKind;
}
private void ValidateHeaderKind(HeaderKind headerKind)
{
if (_version.Envelope == EnvelopeVersion.None)
{
if (headerKind != HeaderKind.Action && headerKind != HeaderKind.To)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new InvalidOperationException(SR.Format(SR.HeadersCannotBeAddedToEnvelopeVersion, _version.Envelope)));
}
}
if (_version.Addressing == AddressingVersion.None)
{
if (headerKind != HeaderKind.Unknown && headerKind != HeaderKind.Action && headerKind != HeaderKind.To)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new InvalidOperationException(SR.Format(SR.AddressingHeadersCannotBeAddedToAddressingVersion, _version.Addressing)));
}
}
}
public XmlDictionaryReader GetReaderAtHeader(int headerIndex)
{
if (headerIndex < 0 || headerIndex >= _headerCount)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ArgumentOutOfRangeException("headerIndex", headerIndex,
SR.Format(SR.ValueMustBeInRange, 0, _headerCount)));
}
switch (_headers[headerIndex].HeaderType)
{
case HeaderType.ReadableHeader:
return _headers[headerIndex].ReadableHeader.GetHeaderReader();
case HeaderType.WriteableHeader:
MessageHeader writeableHeader = _headers[headerIndex].MessageHeader;
BufferedHeader bufferedHeader = CaptureWriteableHeader(writeableHeader);
_headers[headerIndex] = new Header(_headers[headerIndex].HeaderKind, bufferedHeader, _headers[headerIndex].HeaderProcessing);
_collectionVersion++;
return bufferedHeader.GetHeaderReader();
case HeaderType.BufferedMessageHeader:
return GetBufferedMessageHeaderReader(_bufferedMessageData, headerIndex);
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.InvalidEnumValue, _headers[headerIndex].HeaderType)));
}
}
internal UniqueId GetRelatesTo(Uri relationshipType)
{
if (relationshipType == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("relationshipType"));
UniqueId messageId;
FindRelatesTo(relationshipType, out messageId);
return messageId;
}
private void GetRelatesToValues(int index, out Uri relationshipType, out UniqueId messageId)
{
RelatesToHeader relatesToHeader = _headers[index].HeaderInfo as RelatesToHeader;
if (relatesToHeader != null)
{
relationshipType = relatesToHeader.RelationshipType;
messageId = relatesToHeader.UniqueId;
}
else
{
using (XmlDictionaryReader reader = GetReaderAtHeader(index))
{
RelatesToHeader.ReadHeaderValue(reader, _version.Addressing, out relationshipType, out messageId);
}
}
}
internal string[] GetHeaderAttributes(string localName, string ns)
{
string[] attrs = null;
if (ContainsOnlyBufferedMessageHeaders)
{
XmlDictionaryReader reader = _bufferedMessageData.GetMessageReader();
reader.ReadStartElement(); // Envelope
reader.ReadStartElement(); // Header
for (int index = 0; reader.IsStartElement(); index++)
{
string value = reader.GetAttribute(localName, ns);
if (value != null)
{
if (attrs == null)
attrs = new string[_headerCount];
attrs[index] = value;
}
if (index == _headerCount - 1)
break;
reader.Skip();
}
reader.Dispose();
}
else
{
for (int index = 0; index < _headerCount; index++)
{
if (_headers[index].HeaderType != HeaderType.WriteableHeader)
{
using (XmlDictionaryReader reader = GetReaderAtHeader(index))
{
string value = reader.GetAttribute(localName, ns);
if (value != null)
{
if (attrs == null)
attrs = new string[_headerCount];
attrs[index] = value;
}
}
}
}
}
return attrs;
}
internal MessageHeader GetMessageHeader(int index)
{
if (index < 0 || index >= _headerCount)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ArgumentOutOfRangeException("headerIndex", index,
SR.Format(SR.ValueMustBeInRange, 0, _headerCount)));
}
MessageHeader messageHeader;
switch (_headers[index].HeaderType)
{
case HeaderType.WriteableHeader:
case HeaderType.ReadableHeader:
return _headers[index].MessageHeader;
case HeaderType.BufferedMessageHeader:
messageHeader = CaptureBufferedHeader(_bufferedMessageData, _headers[index].HeaderInfo, index);
_headers[index] = new Header(_headers[index].HeaderKind, messageHeader, _headers[index].HeaderProcessing);
_collectionVersion++;
return messageHeader;
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.InvalidEnumValue, _headers[index].HeaderType)));
}
}
internal Collection<MessageHeaderInfo> GetHeadersNotUnderstood()
{
Collection<MessageHeaderInfo> notUnderstoodHeaders = null;
for (int headerIndex = 0; headerIndex < _headerCount; headerIndex++)
{
if (_headers[headerIndex].HeaderProcessing == HeaderProcessing.MustUnderstand)
{
if (notUnderstoodHeaders == null)
notUnderstoodHeaders = new Collection<MessageHeaderInfo>();
MessageHeaderInfo headerInfo = _headers[headerIndex].HeaderInfo;
notUnderstoodHeaders.Add(headerInfo);
}
}
return notUnderstoodHeaders;
}
public bool HaveMandatoryHeadersBeenUnderstood()
{
return HaveMandatoryHeadersBeenUnderstood(_version.Envelope.MustUnderstandActorValues);
}
public bool HaveMandatoryHeadersBeenUnderstood(params string[] actors)
{
if (actors == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("actors"));
for (int headerIndex = 0; headerIndex < _headerCount; headerIndex++)
{
if (_headers[headerIndex].HeaderProcessing == HeaderProcessing.MustUnderstand)
{
for (int actorIndex = 0; actorIndex < actors.Length; ++actorIndex)
{
if (_headers[headerIndex].HeaderInfo.Actor == actors[actorIndex])
{
return false;
}
}
}
}
return true;
}
internal void Init(MessageVersion version, int initialSize)
{
_nodeCount = 0;
_attrCount = 0;
if (initialSize < 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ArgumentOutOfRangeException("initialSize", initialSize,
SR.ValueMustBeNonNegative));
}
if (version == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("version");
}
_version = version;
_headers = new Header[initialSize];
}
internal void Init(MessageVersion version)
{
_nodeCount = 0;
_attrCount = 0;
_version = version;
_collectionVersion = 0;
}
internal void Init(MessageVersion version, XmlDictionaryReader reader, IBufferedMessageData bufferedMessageData, RecycledMessageState recycledMessageState, bool[] understoodHeaders, bool understoodHeadersModified)
{
_nodeCount = 0;
_attrCount = 0;
_version = version;
_bufferedMessageData = bufferedMessageData;
if (version.Envelope != EnvelopeVersion.None)
{
_understoodHeadersModified = (understoodHeaders != null) && understoodHeadersModified;
if (reader.IsEmptyElement)
{
reader.Read();
return;
}
EnvelopeVersion envelopeVersion = version.Envelope;
Fx.Assert(reader.IsStartElement(XD.MessageDictionary.Header, envelopeVersion.DictionaryNamespace), "");
reader.ReadStartElement();
AddressingDictionary dictionary = XD.AddressingDictionary;
if (s_localNames == null)
{
XmlDictionaryString[] strings = new XmlDictionaryString[7];
strings[(int)HeaderKind.To] = dictionary.To;
strings[(int)HeaderKind.Action] = dictionary.Action;
strings[(int)HeaderKind.MessageId] = dictionary.MessageId;
strings[(int)HeaderKind.RelatesTo] = dictionary.RelatesTo;
strings[(int)HeaderKind.ReplyTo] = dictionary.ReplyTo;
strings[(int)HeaderKind.From] = dictionary.From;
strings[(int)HeaderKind.FaultTo] = dictionary.FaultTo;
Interlocked.MemoryBarrier();
s_localNames = strings;
}
int i = 0;
while (reader.IsStartElement())
{
ReadBufferedHeader(reader, recycledMessageState, s_localNames, (understoodHeaders == null) ? false : understoodHeaders[i++]);
}
reader.ReadEndElement();
}
_collectionVersion = 0;
}
public void Insert(int headerIndex, MessageHeader header)
{
if (header == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("header"));
if (!header.IsMessageVersionSupported(_version))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.MessageHeaderVersionNotSupported,
header.GetType().FullName, _version.Envelope.ToString()), "header"));
Insert(headerIndex, header, GetHeaderKind(header));
}
private void Insert(int headerIndex, MessageHeader header, HeaderKind kind)
{
ReadableMessageHeader readableMessageHeader = header as ReadableMessageHeader;
HeaderProcessing processing = header.MustUnderstand ? HeaderProcessing.MustUnderstand : 0;
if (kind != HeaderKind.Unknown)
processing |= HeaderProcessing.Understood;
if (readableMessageHeader != null)
InsertHeader(headerIndex, new Header(kind, readableMessageHeader, processing));
else
InsertHeader(headerIndex, new Header(kind, header, processing));
}
private void InsertHeader(int headerIndex, Header header)
{
ValidateHeaderKind(header.HeaderKind);
if (headerIndex < 0 || headerIndex > _headerCount)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ArgumentOutOfRangeException("headerIndex", headerIndex,
SR.Format(SR.ValueMustBeInRange, 0, _headerCount)));
}
if (_headerCount == _headers.Length)
{
if (_headers.Length == 0)
{
_headers = new Header[1];
}
else
{
Header[] newHeaders = new Header[_headers.Length * 2];
_headers.CopyTo(newHeaders, 0);
_headers = newHeaders;
}
}
if (headerIndex < _headerCount)
{
if (_bufferedMessageData != null)
{
for (int i = headerIndex; i < _headerCount; i++)
{
if (_headers[i].HeaderType == HeaderType.BufferedMessageHeader)
{
CaptureBufferedHeaders();
break;
}
}
}
Array.Copy(_headers, headerIndex, _headers, headerIndex + 1, _headerCount - headerIndex);
}
_headers[headerIndex] = header;
_headerCount++;
_collectionVersion++;
}
internal bool IsUnderstood(int i)
{
return (_headers[i].HeaderProcessing & HeaderProcessing.Understood) != 0;
}
internal bool IsUnderstood(MessageHeaderInfo headerInfo)
{
if (headerInfo == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("headerInfo"));
for (int i = 0; i < _headerCount; i++)
{
if ((object)_headers[i].HeaderInfo == (object)headerInfo)
{
if (IsUnderstood(i))
return true;
}
}
return false;
}
private void ReadBufferedHeader(XmlDictionaryReader reader, RecycledMessageState recycledMessageState, XmlDictionaryString[] localNames, bool understood)
{
string actor;
bool mustUnderstand;
bool relay;
bool isRefParam;
if (_version.Addressing == AddressingVersion.None && reader.NamespaceURI == AddressingVersion.None.Namespace)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new InvalidOperationException(SR.Format(SR.AddressingHeadersCannotBeAddedToAddressingVersion, _version.Addressing)));
}
MessageHeader.GetHeaderAttributes(reader, _version, out actor, out mustUnderstand, out relay, out isRefParam);
HeaderKind kind = HeaderKind.Unknown;
MessageHeaderInfo info = null;
if (_version.Envelope.IsUltimateDestinationActor(actor))
{
Fx.Assert(_version.Addressing.DictionaryNamespace != null, "non-None Addressing requires a non-null DictionaryNamespace");
kind = (HeaderKind)reader.IndexOfLocalName(localNames, _version.Addressing.DictionaryNamespace);
switch (kind)
{
case HeaderKind.To:
info = ToHeader.ReadHeader(reader, _version.Addressing, recycledMessageState.UriCache, actor, mustUnderstand, relay);
break;
case HeaderKind.Action:
info = ActionHeader.ReadHeader(reader, _version.Addressing, actor, mustUnderstand, relay);
break;
case HeaderKind.MessageId:
info = MessageIDHeader.ReadHeader(reader, _version.Addressing, actor, mustUnderstand, relay);
break;
case HeaderKind.RelatesTo:
info = RelatesToHeader.ReadHeader(reader, _version.Addressing, actor, mustUnderstand, relay);
break;
case HeaderKind.ReplyTo:
info = ReplyToHeader.ReadHeader(reader, _version.Addressing, actor, mustUnderstand, relay);
break;
case HeaderKind.From:
info = FromHeader.ReadHeader(reader, _version.Addressing, actor, mustUnderstand, relay);
break;
case HeaderKind.FaultTo:
info = FaultToHeader.ReadHeader(reader, _version.Addressing, actor, mustUnderstand, relay);
break;
default:
kind = HeaderKind.Unknown;
break;
}
}
if (info == null)
{
info = recycledMessageState.HeaderInfoCache.TakeHeaderInfo(reader, actor, mustUnderstand, relay, isRefParam);
reader.Skip();
}
HeaderProcessing processing = mustUnderstand ? HeaderProcessing.MustUnderstand : 0;
if (kind != HeaderKind.Unknown || understood)
{
processing |= HeaderProcessing.Understood;
MessageHeaders.TraceUnderstood(info);
}
AddHeader(new Header(kind, info, processing));
}
internal void Recycle(HeaderInfoCache headerInfoCache)
{
for (int i = 0; i < _headerCount; i++)
{
if (_headers[i].HeaderKind == HeaderKind.Unknown)
{
headerInfoCache.ReturnHeaderInfo(_headers[i].HeaderInfo);
}
}
Clear();
_collectionVersion = 0;
if (_understoodHeaders != null)
{
_understoodHeaders.Modified = false;
}
}
internal void RemoveUnderstood(MessageHeaderInfo headerInfo)
{
if (headerInfo == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("headerInfo"));
for (int i = 0; i < _headerCount; i++)
{
if ((object)_headers[i].HeaderInfo == (object)headerInfo)
{
if ((_headers[i].HeaderProcessing & HeaderProcessing.Understood) == 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(
SR.Format(SR.HeaderAlreadyNotUnderstood, headerInfo.Name, headerInfo.Namespace), "headerInfo"));
}
_headers[i].HeaderProcessing &= ~HeaderProcessing.Understood;
}
}
}
public void RemoveAll(string name, string ns)
{
if (name == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("name"));
if (ns == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("ns"));
for (int i = _headerCount - 1; i >= 0; i--)
{
MessageHeaderInfo info = _headers[i].HeaderInfo;
if (info.Name == name && info.Namespace == ns)
{
RemoveAt(i);
}
}
}
public void RemoveAt(int headerIndex)
{
if (headerIndex < 0 || headerIndex >= _headerCount)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ArgumentOutOfRangeException("headerIndex", headerIndex,
SR.Format(SR.ValueMustBeInRange, 0, _headerCount)));
}
if (_bufferedMessageData != null && _headers[headerIndex].HeaderType == HeaderType.BufferedMessageHeader)
CaptureBufferedHeaders(headerIndex);
Array.Copy(_headers, headerIndex + 1, _headers, headerIndex, _headerCount - headerIndex - 1);
_headers[--_headerCount] = new Header();
_collectionVersion++;
}
internal void ReplaceAt(int headerIndex, MessageHeader header)
{
if (headerIndex < 0 || headerIndex >= _headerCount)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ArgumentOutOfRangeException("headerIndex", headerIndex,
SR.Format(SR.ValueMustBeInRange, 0, _headerCount)));
}
if (header == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("header");
}
ReplaceAt(headerIndex, header, GetHeaderKind(header));
}
private void ReplaceAt(int headerIndex, MessageHeader header, HeaderKind kind)
{
HeaderProcessing processing = header.MustUnderstand ? HeaderProcessing.MustUnderstand : 0;
if (kind != HeaderKind.Unknown)
processing |= HeaderProcessing.Understood;
ReadableMessageHeader readableMessageHeader = header as ReadableMessageHeader;
if (readableMessageHeader != null)
_headers[headerIndex] = new Header(kind, readableMessageHeader, processing);
else
_headers[headerIndex] = new Header(kind, header, processing);
_collectionVersion++;
}
public void SetAction(XmlDictionaryString action)
{
if (action == null)
SetHeaderProperty(HeaderKind.Action, null);
else
SetActionHeader(ActionHeader.Create(action, _version.Addressing));
}
internal void SetActionHeader(ActionHeader actionHeader)
{
SetHeaderProperty(HeaderKind.Action, actionHeader);
}
internal void SetFaultToHeader(FaultToHeader faultToHeader)
{
SetHeaderProperty(HeaderKind.FaultTo, faultToHeader);
}
internal void SetFromHeader(FromHeader fromHeader)
{
SetHeaderProperty(HeaderKind.From, fromHeader);
}
internal void SetMessageIDHeader(MessageIDHeader messageIDHeader)
{
SetHeaderProperty(HeaderKind.MessageId, messageIDHeader);
}
internal void SetRelatesTo(Uri relationshipType, UniqueId messageId)
{
if (relationshipType == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("relationshipType");
}
RelatesToHeader relatesToHeader;
if (!object.ReferenceEquals(messageId, null))
{
relatesToHeader = RelatesToHeader.Create(messageId, _version.Addressing, relationshipType);
}
else
{
relatesToHeader = null;
}
SetRelatesTo(RelatesToHeader.ReplyRelationshipType, relatesToHeader);
}
private void SetRelatesTo(Uri relationshipType, RelatesToHeader relatesToHeader)
{
UniqueId previousUniqueId;
int index = FindRelatesTo(relationshipType, out previousUniqueId);
if (index >= 0)
{
if (relatesToHeader == null)
{
RemoveAt(index);
}
else
{
ReplaceAt(index, relatesToHeader, HeaderKind.RelatesTo);
}
}
else if (relatesToHeader != null)
{
Add(relatesToHeader, HeaderKind.RelatesTo);
}
}
internal void SetReplyToHeader(ReplyToHeader replyToHeader)
{
SetHeaderProperty(HeaderKind.ReplyTo, replyToHeader);
}
internal void SetToHeader(ToHeader toHeader)
{
SetHeaderProperty(HeaderKind.To, toHeader);
}
private void SetHeaderProperty(HeaderKind kind, MessageHeader header)
{
int index = FindHeaderProperty(kind);
if (index >= 0)
{
if (header == null)
{
RemoveAt(index);
}
else
{
ReplaceAt(index, header, kind);
}
}
else if (header != null)
{
Add(header, kind);
}
}
public void WriteHeader(int headerIndex, XmlWriter writer)
{
WriteHeader(headerIndex, XmlDictionaryWriter.CreateDictionaryWriter(writer));
}
public void WriteHeader(int headerIndex, XmlDictionaryWriter writer)
{
WriteStartHeader(headerIndex, writer);
WriteHeaderContents(headerIndex, writer);
writer.WriteEndElement();
}
public void WriteStartHeader(int headerIndex, XmlWriter writer)
{
WriteStartHeader(headerIndex, XmlDictionaryWriter.CreateDictionaryWriter(writer));
}
public void WriteStartHeader(int headerIndex, XmlDictionaryWriter writer)
{
if (writer == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
}
if (headerIndex < 0 || headerIndex >= _headerCount)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ArgumentOutOfRangeException("headerIndex", headerIndex,
SR.Format(SR.ValueMustBeInRange, 0, _headerCount)));
}
switch (_headers[headerIndex].HeaderType)
{
case HeaderType.ReadableHeader:
case HeaderType.WriteableHeader:
_headers[headerIndex].MessageHeader.WriteStartHeader(writer, _version);
break;
case HeaderType.BufferedMessageHeader:
WriteStartBufferedMessageHeader(_bufferedMessageData, headerIndex, writer);
break;
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.InvalidEnumValue, _headers[headerIndex].HeaderType)));
}
}
public void WriteHeaderContents(int headerIndex, XmlWriter writer)
{
WriteHeaderContents(headerIndex, XmlDictionaryWriter.CreateDictionaryWriter(writer));
}
public void WriteHeaderContents(int headerIndex, XmlDictionaryWriter writer)
{
if (writer == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
}
if (headerIndex < 0 || headerIndex >= _headerCount)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ArgumentOutOfRangeException("headerIndex", headerIndex,
SR.Format(SR.ValueMustBeInRange, 0, _headerCount)));
}
switch (_headers[headerIndex].HeaderType)
{
case HeaderType.ReadableHeader:
case HeaderType.WriteableHeader:
_headers[headerIndex].MessageHeader.WriteHeaderContents(writer, _version);
break;
case HeaderType.BufferedMessageHeader:
WriteBufferedMessageHeaderContents(_bufferedMessageData, headerIndex, writer);
break;
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.InvalidEnumValue, _headers[headerIndex].HeaderType)));
}
}
private static void TraceUnderstood(MessageHeaderInfo info)
{
}
private void WriteBufferedMessageHeader(IBufferedMessageData bufferedMessageData, int bufferedMessageHeaderIndex, XmlWriter writer)
{
using (XmlReader reader = GetBufferedMessageHeaderReader(bufferedMessageData, bufferedMessageHeaderIndex))
{
writer.WriteNode(reader, false);
}
}
private void WriteStartBufferedMessageHeader(IBufferedMessageData bufferedMessageData, int bufferedMessageHeaderIndex, XmlWriter writer)
{
using (XmlReader reader = GetBufferedMessageHeaderReader(bufferedMessageData, bufferedMessageHeaderIndex))
{
writer.WriteStartElement(reader.Prefix, reader.LocalName, reader.NamespaceURI);
writer.WriteAttributes(reader, false);
}
}
private void WriteBufferedMessageHeaderContents(IBufferedMessageData bufferedMessageData, int bufferedMessageHeaderIndex, XmlWriter writer)
{
using (XmlReader reader = GetBufferedMessageHeaderReader(bufferedMessageData, bufferedMessageHeaderIndex))
{
if (!reader.IsEmptyElement)
{
reader.ReadStartElement();
while (reader.NodeType != XmlNodeType.EndElement)
{
writer.WriteNode(reader, false);
}
reader.ReadEndElement();
}
}
}
internal enum HeaderType : byte
{
Invalid,
ReadableHeader,
BufferedMessageHeader,
WriteableHeader
}
internal enum HeaderKind : byte
{
Action,
FaultTo,
From,
MessageId,
ReplyTo,
RelatesTo,
To,
Unknown,
}
[Flags]
internal enum HeaderProcessing : byte
{
MustUnderstand = 0x1,
Understood = 0x2,
}
internal struct Header
{
private HeaderType _type;
private HeaderKind _kind;
private HeaderProcessing _processing;
private MessageHeaderInfo _info;
public Header(HeaderKind kind, MessageHeaderInfo info, HeaderProcessing processing)
{
_kind = kind;
_type = HeaderType.BufferedMessageHeader;
_info = info;
_processing = processing;
}
public Header(HeaderKind kind, ReadableMessageHeader readableHeader, HeaderProcessing processing)
{
_kind = kind;
_type = HeaderType.ReadableHeader;
_info = readableHeader;
_processing = processing;
}
public Header(HeaderKind kind, MessageHeader header, HeaderProcessing processing)
{
_kind = kind;
_type = HeaderType.WriteableHeader;
_info = header;
_processing = processing;
}
public HeaderType HeaderType
{
get { return _type; }
}
public HeaderKind HeaderKind
{
get { return _kind; }
}
public MessageHeaderInfo HeaderInfo
{
get { return _info; }
}
public MessageHeader MessageHeader
{
get
{
Fx.Assert(_type == HeaderType.WriteableHeader || _type == HeaderType.ReadableHeader, "");
return (MessageHeader)_info;
}
}
public HeaderProcessing HeaderProcessing
{
get { return _processing; }
set { _processing = value; }
}
public ReadableMessageHeader ReadableHeader
{
get
{
Fx.Assert(_type == HeaderType.ReadableHeader, "");
return (ReadableMessageHeader)_info;
}
}
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.Runtime.Serialization
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Security;
using System.Runtime.Diagnostics;
using System.Xml;
using System.Xml.Schema;
using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, DataContract>;
using SchemaObjectDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, SchemaObjectInfo>;
using System.Runtime.Serialization.Diagnostics;
class SchemaImporter
{
DataContractSet dataContractSet;
XmlSchemaSet schemaSet;
ICollection<XmlQualifiedName> typeNames;
ICollection<XmlSchemaElement> elements;
XmlQualifiedName[] elementTypeNames;
bool importXmlDataType;
SchemaObjectDictionary schemaObjects;
List<XmlSchemaRedefine> redefineList;
bool needToImportKnownTypesForObject;
[Fx.Tag.SecurityNote(Critical = "Static field used to store serialization schema elements from future versions."
+ " Static fields are marked SecurityCritical or readonly to prevent data from being modified or leaked to other components in appdomain.")]
[SecurityCritical]
static Hashtable serializationSchemaElements;
internal SchemaImporter(XmlSchemaSet schemas, ICollection<XmlQualifiedName> typeNames, ICollection<XmlSchemaElement> elements, XmlQualifiedName[] elementTypeNames, DataContractSet dataContractSet, bool importXmlDataType)
{
this.dataContractSet = dataContractSet;
this.schemaSet = schemas;
this.typeNames = typeNames;
this.elements = elements;
this.elementTypeNames = elementTypeNames;
this.importXmlDataType = importXmlDataType;
}
internal void Import()
{
if (!schemaSet.Contains(Globals.SerializationNamespace))
{
StringReader reader = new StringReader(Globals.SerializationSchema);
XmlSchema schema = XmlSchema.Read(reader, null);
if (schema == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.CouldNotReadSerializationSchema, Globals.SerializationNamespace)));
schemaSet.Add(schema);
}
try
{
CompileSchemaSet(schemaSet);
}
#pragma warning suppress 56500 // covered by FxCOP
catch (Exception ex)
{
if (Fx.IsFatal(ex))
{
throw;
}
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.CannotImportInvalidSchemas), ex));
}
if (typeNames == null)
{
ICollection schemaList = schemaSet.Schemas();
foreach (object schemaObj in schemaList)
{
if (schemaObj == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.CannotImportNullSchema)));
XmlSchema schema = (XmlSchema)schemaObj;
if (schema.TargetNamespace != Globals.SerializationNamespace
&& schema.TargetNamespace != Globals.SchemaNamespace)
{
foreach (XmlSchemaObject typeObj in schema.SchemaTypes.Values)
{
ImportType((XmlSchemaType)typeObj);
}
foreach (XmlSchemaElement element in schema.Elements.Values)
{
if (element.SchemaType != null)
ImportAnonymousGlobalElement(element, element.QualifiedName, schema.TargetNamespace);
}
}
}
}
else
{
foreach (XmlQualifiedName typeName in typeNames)
{
if (typeName == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.CannotImportNullDataContractName)));
ImportType(typeName);
}
if (elements != null)
{
int i = 0;
foreach (XmlSchemaElement element in elements)
{
XmlQualifiedName typeName = element.SchemaTypeName;
if (typeName != null && typeName.Name.Length > 0)
{
elementTypeNames[i++] = ImportType(typeName).StableName;
}
else
{
XmlSchema schema = SchemaHelper.GetSchemaWithGlobalElementDeclaration(element, schemaSet);
if (schema == null)
{
elementTypeNames[i++] = ImportAnonymousElement(element, element.QualifiedName).StableName;
}
else
{
elementTypeNames[i++] = ImportAnonymousGlobalElement(element, element.QualifiedName, schema.TargetNamespace).StableName;
}
}
}
}
}
ImportKnownTypesForObject();
}
internal static void CompileSchemaSet(XmlSchemaSet schemaSet)
{
if (schemaSet.Contains(XmlSchema.Namespace))
schemaSet.Compile();
else
{
// Add base XSD schema with top level element named "schema"
XmlSchema xsdSchema = new XmlSchema();
xsdSchema.TargetNamespace = XmlSchema.Namespace;
XmlSchemaElement element = new XmlSchemaElement();
element.Name = Globals.SchemaLocalName;
element.SchemaType = new XmlSchemaComplexType();
xsdSchema.Items.Add(element);
schemaSet.Add(xsdSchema);
schemaSet.Compile();
}
}
SchemaObjectDictionary SchemaObjects
{
get
{
if (schemaObjects == null)
schemaObjects = CreateSchemaObjects();
return schemaObjects;
}
}
List<XmlSchemaRedefine> RedefineList
{
get
{
if (redefineList == null)
redefineList = CreateRedefineList();
return redefineList;
}
}
void ImportKnownTypes(XmlQualifiedName typeName)
{
SchemaObjectInfo schemaObjectInfo;
if (SchemaObjects.TryGetValue(typeName, out schemaObjectInfo))
{
List<XmlSchemaType> knownTypes = schemaObjectInfo.knownTypes;
if (knownTypes != null)
{
foreach (XmlSchemaType knownType in knownTypes)
ImportType(knownType);
}
}
}
internal static bool IsObjectContract(DataContract dataContract)
{
Dictionary<Type, object> previousCollectionTypes = new Dictionary<Type, object>();
while (dataContract is CollectionDataContract)
{
if (dataContract.OriginalUnderlyingType == null)
{
dataContract = ((CollectionDataContract)dataContract).ItemContract;
continue;
}
if (!previousCollectionTypes.ContainsKey(dataContract.OriginalUnderlyingType))
{
previousCollectionTypes.Add(dataContract.OriginalUnderlyingType, dataContract.OriginalUnderlyingType);
dataContract = ((CollectionDataContract)dataContract).ItemContract;
}
else
{
break;
}
}
return dataContract is PrimitiveDataContract && ((PrimitiveDataContract)dataContract).UnderlyingType == Globals.TypeOfObject;
}
void ImportKnownTypesForObject()
{
if (!needToImportKnownTypesForObject)
return;
needToImportKnownTypesForObject = false;
if (dataContractSet.KnownTypesForObject == null)
{
SchemaObjectInfo schemaObjectInfo;
if (SchemaObjects.TryGetValue(SchemaExporter.AnytypeQualifiedName, out schemaObjectInfo))
{
List<XmlSchemaType> knownTypes = schemaObjectInfo.knownTypes;
if (knownTypes != null)
{
DataContractDictionary knownDataContracts = new DataContractDictionary();
foreach (XmlSchemaType knownType in knownTypes)
{
// Expected: will throw exception if schema set contains types that are not supported
DataContract dataContract = ImportType(knownType);
DataContract existingContract;
if (!knownDataContracts.TryGetValue(dataContract.StableName, out existingContract))
{
knownDataContracts.Add(dataContract.StableName, dataContract);
}
}
dataContractSet.KnownTypesForObject = knownDataContracts;
}
}
}
}
internal SchemaObjectDictionary CreateSchemaObjects()
{
SchemaObjectDictionary schemaObjects = new SchemaObjectDictionary();
ICollection schemaList = schemaSet.Schemas();
List<XmlSchemaType> knownTypesForObject = new List<XmlSchemaType>();
schemaObjects.Add(SchemaExporter.AnytypeQualifiedName, new SchemaObjectInfo(null, null, null, knownTypesForObject));
foreach (XmlSchema schema in schemaList)
{
if (schema.TargetNamespace != Globals.SerializationNamespace)
{
foreach (XmlSchemaObject schemaObj in schema.SchemaTypes.Values)
{
XmlSchemaType schemaType = schemaObj as XmlSchemaType;
if (schemaType != null)
{
knownTypesForObject.Add(schemaType);
XmlQualifiedName currentTypeName = new XmlQualifiedName(schemaType.Name, schema.TargetNamespace);
SchemaObjectInfo schemaObjectInfo;
if (schemaObjects.TryGetValue(currentTypeName, out schemaObjectInfo))
{
schemaObjectInfo.type = schemaType;
schemaObjectInfo.schema = schema;
}
else
{
schemaObjects.Add(currentTypeName, new SchemaObjectInfo(schemaType, null, schema, null));
}
XmlQualifiedName baseTypeName = GetBaseTypeName(schemaType);
if (baseTypeName != null)
{
SchemaObjectInfo baseTypeInfo;
if (schemaObjects.TryGetValue(baseTypeName, out baseTypeInfo))
{
if (baseTypeInfo.knownTypes == null)
{
baseTypeInfo.knownTypes = new List<XmlSchemaType>();
}
}
else
{
baseTypeInfo = new SchemaObjectInfo(null, null, null, new List<XmlSchemaType>());
schemaObjects.Add(baseTypeName, baseTypeInfo);
}
baseTypeInfo.knownTypes.Add(schemaType);
}
}
}
foreach (XmlSchemaObject schemaObj in schema.Elements.Values)
{
XmlSchemaElement schemaElement = schemaObj as XmlSchemaElement;
if (schemaElement != null)
{
XmlQualifiedName currentElementName = new XmlQualifiedName(schemaElement.Name, schema.TargetNamespace);
SchemaObjectInfo schemaObjectInfo;
if (schemaObjects.TryGetValue(currentElementName, out schemaObjectInfo))
{
schemaObjectInfo.element = schemaElement;
schemaObjectInfo.schema = schema;
}
else
{
schemaObjects.Add(currentElementName, new SchemaObjectInfo(null, schemaElement, schema, null));
}
}
}
}
}
return schemaObjects;
}
XmlQualifiedName GetBaseTypeName(XmlSchemaType type)
{
XmlQualifiedName baseTypeName = null;
XmlSchemaComplexType complexType = type as XmlSchemaComplexType;
if (complexType != null)
{
if (complexType.ContentModel != null)
{
XmlSchemaComplexContent complexContent = complexType.ContentModel as XmlSchemaComplexContent;
if (complexContent != null)
{
XmlSchemaComplexContentExtension extension = complexContent.Content as XmlSchemaComplexContentExtension;
if (extension != null)
baseTypeName = extension.BaseTypeName;
}
}
}
return baseTypeName;
}
List<XmlSchemaRedefine> CreateRedefineList()
{
List<XmlSchemaRedefine> list = new List<XmlSchemaRedefine>();
ICollection schemaList = schemaSet.Schemas();
foreach (object schemaObj in schemaList)
{
XmlSchema schema = schemaObj as XmlSchema;
if (schema == null)
continue;
foreach (XmlSchemaExternal ext in schema.Includes)
{
XmlSchemaRedefine redefine = ext as XmlSchemaRedefine;
if (redefine != null)
list.Add(redefine);
}
}
return list;
}
[Fx.Tag.SecurityNote(Critical = "Sets critical properties on XmlDataContract.",
Safe = "Called during schema import/code generation.")]
[SecuritySafeCritical]
DataContract ImportAnonymousGlobalElement(XmlSchemaElement element, XmlQualifiedName typeQName, string ns)
{
DataContract contract = ImportAnonymousElement(element, typeQName);
XmlDataContract xmlDataContract = contract as XmlDataContract;
if (xmlDataContract != null)
{
xmlDataContract.SetTopLevelElementName(new XmlQualifiedName(element.Name, ns));
xmlDataContract.IsTopLevelElementNullable = element.IsNillable;
}
return contract;
}
DataContract ImportAnonymousElement(XmlSchemaElement element, XmlQualifiedName typeQName)
{
if (SchemaHelper.GetSchemaType(SchemaObjects, typeQName) != null)
{
for (int i = 1;; i++)
{
typeQName = new XmlQualifiedName(typeQName.Name + i.ToString(NumberFormatInfo.InvariantInfo), typeQName.Namespace);
if (SchemaHelper.GetSchemaType(SchemaObjects, typeQName) == null)
break;
if (i == Int32.MaxValue)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.CannotComputeUniqueName, element.Name)));
}
}
if (element.SchemaType == null)
return ImportType(SchemaExporter.AnytypeQualifiedName);
else
return ImportType(element.SchemaType, typeQName, true/*isAnonymous*/);
}
DataContract ImportType(XmlQualifiedName typeName)
{
DataContract dataContract = DataContract.GetBuiltInDataContract(typeName.Name, typeName.Namespace);
if (dataContract == null)
{
XmlSchemaType type = SchemaHelper.GetSchemaType(SchemaObjects, typeName);
if (type == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.SpecifiedTypeNotFoundInSchema, typeName.Name, typeName.Namespace)));
dataContract = ImportType(type);
}
if (IsObjectContract(dataContract))
needToImportKnownTypesForObject = true;
return dataContract;
}
DataContract ImportType(XmlSchemaType type)
{
return ImportType(type, type.QualifiedName, false/*isAnonymous*/);
}
DataContract ImportType(XmlSchemaType type, XmlQualifiedName typeName, bool isAnonymous)
{
DataContract dataContract = dataContractSet[typeName];
if (dataContract != null)
return dataContract;
InvalidDataContractException invalidContractException;
try
{
foreach (XmlSchemaRedefine redefine in RedefineList)
{
if (redefine.SchemaTypes[typeName] != null)
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.GetString(SR.RedefineNotSupported));
}
if (type is XmlSchemaSimpleType)
{
XmlSchemaSimpleType simpleType = (XmlSchemaSimpleType)type;
XmlSchemaSimpleTypeContent content = simpleType.Content;
if (content is XmlSchemaSimpleTypeUnion)
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.GetString(SR.SimpleTypeUnionNotSupported));
else if (content is XmlSchemaSimpleTypeList)
dataContract = ImportFlagsEnum(typeName, (XmlSchemaSimpleTypeList)content, simpleType.Annotation);
else if (content is XmlSchemaSimpleTypeRestriction)
{
XmlSchemaSimpleTypeRestriction restriction = (XmlSchemaSimpleTypeRestriction)content;
if (CheckIfEnum(restriction))
{
dataContract = ImportEnum(typeName, restriction, false /*isFlags*/, simpleType.Annotation);
}
else
{
dataContract = ImportSimpleTypeRestriction(typeName, restriction);
if (dataContract.IsBuiltInDataContract && !isAnonymous)
{
dataContractSet.InternalAdd(typeName, dataContract);
}
}
}
}
else if (type is XmlSchemaComplexType)
{
XmlSchemaComplexType complexType = (XmlSchemaComplexType)type;
if (complexType.ContentModel == null)
{
CheckComplexType(typeName, complexType);
dataContract = ImportType(typeName, complexType.Particle, complexType.Attributes, complexType.AnyAttribute, null /* baseTypeName */, complexType.Annotation);
}
else
{
XmlSchemaContentModel contentModel = complexType.ContentModel;
if (contentModel is XmlSchemaSimpleContent)
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.GetString(SR.SimpleContentNotSupported));
else if (contentModel is XmlSchemaComplexContent)
{
XmlSchemaComplexContent complexContent = (XmlSchemaComplexContent)contentModel;
if (complexContent.IsMixed)
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.GetString(SR.MixedContentNotSupported));
if (complexContent.Content is XmlSchemaComplexContentExtension)
{
XmlSchemaComplexContentExtension extension = (XmlSchemaComplexContentExtension)complexContent.Content;
dataContract = ImportType(typeName, extension.Particle, extension.Attributes, extension.AnyAttribute, extension.BaseTypeName, complexType.Annotation);
}
else if (complexContent.Content is XmlSchemaComplexContentRestriction)
{
XmlSchemaComplexContentRestriction restriction = (XmlSchemaComplexContentRestriction)complexContent.Content;
XmlQualifiedName baseTypeName = restriction.BaseTypeName;
if (baseTypeName == SchemaExporter.AnytypeQualifiedName)
dataContract = ImportType(typeName, restriction.Particle, restriction.Attributes, restriction.AnyAttribute, null /* baseTypeName */, complexType.Annotation);
else
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.GetString(SR.ComplexTypeRestrictionNotSupported));
}
}
}
}
if (dataContract == null)
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, String.Empty);
if (type.QualifiedName != XmlQualifiedName.Empty)
ImportTopLevelElement(typeName);
ImportDataContractExtension(type, dataContract);
ImportGenericInfo(type, dataContract);
ImportKnownTypes(typeName);
return dataContract;
}
catch (InvalidDataContractException e)
{
invalidContractException = e;
}
// Execution gets to this point if InvalidDataContractException was thrown
if (importXmlDataType)
{
RemoveFailedContract(typeName);
return ImportXmlDataType(typeName, type, isAnonymous);
}
Type referencedType;
if (dataContractSet.TryGetReferencedType(typeName, dataContract, out referencedType)
|| (string.IsNullOrEmpty(type.Name) && dataContractSet.TryGetReferencedType(ImportActualType(type.Annotation, typeName, typeName), dataContract, out referencedType)))
{
if (Globals.TypeOfIXmlSerializable.IsAssignableFrom(referencedType))
{
RemoveFailedContract(typeName);
return ImportXmlDataType(typeName, type, isAnonymous);
}
}
XmlDataContract specialContract = ImportSpecialXmlDataType(type, isAnonymous);
if (specialContract != null)
{
this.dataContractSet.Remove(typeName);
return specialContract;
}
throw invalidContractException;
}
private void RemoveFailedContract(XmlQualifiedName typeName)
{
ClassDataContract oldContract = this.dataContractSet[typeName] as ClassDataContract;
this.dataContractSet.Remove(typeName);
if (oldContract != null)
{
ClassDataContract ancestorDataContract = oldContract.BaseContract;
while (ancestorDataContract != null)
{
ancestorDataContract.KnownDataContracts.Remove(typeName);
ancestorDataContract = ancestorDataContract.BaseContract;
}
if (dataContractSet.KnownTypesForObject != null)
dataContractSet.KnownTypesForObject.Remove(typeName);
}
}
bool CheckIfEnum(XmlSchemaSimpleTypeRestriction restriction)
{
foreach (XmlSchemaFacet facet in restriction.Facets)
{
if (!(facet is XmlSchemaEnumerationFacet))
return false;
}
XmlQualifiedName expectedBase = SchemaExporter.StringQualifiedName;
if (restriction.BaseTypeName != XmlQualifiedName.Empty)
{
return ((restriction.BaseTypeName == expectedBase && restriction.Facets.Count > 0) || ImportType(restriction.BaseTypeName) is EnumDataContract);
}
else if (restriction.BaseType != null)
{
DataContract baseContract = ImportType(restriction.BaseType);
return (baseContract.StableName == expectedBase || baseContract is EnumDataContract);
}
return false;
}
bool CheckIfCollection(XmlSchemaSequence rootSequence)
{
if (rootSequence.Items == null || rootSequence.Items.Count == 0)
return false;
RemoveOptionalUnknownSerializationElements(rootSequence.Items);
if (rootSequence.Items.Count != 1)
return false;
XmlSchemaObject o = rootSequence.Items[0];
if (!(o is XmlSchemaElement))
return false;
XmlSchemaElement localElement = (XmlSchemaElement)o;
return (localElement.MaxOccursString == Globals.OccursUnbounded || localElement.MaxOccurs > 1);
}
bool CheckIfISerializable(XmlSchemaSequence rootSequence, XmlSchemaObjectCollection attributes)
{
if (rootSequence.Items == null || rootSequence.Items.Count == 0)
return false;
RemoveOptionalUnknownSerializationElements(rootSequence.Items);
if (attributes == null || attributes.Count == 0)
return false;
return (rootSequence.Items.Count == 1 && rootSequence.Items[0] is XmlSchemaAny);
}
[Fx.Tag.SecurityNote(Critical = "Initializes critical static fields.",
Safe = "Doesn't leak anything.")]
[SecuritySafeCritical]
void RemoveOptionalUnknownSerializationElements(XmlSchemaObjectCollection items)
{
for (int i = 0; i < items.Count; i++)
{
XmlSchemaElement element = items[i] as XmlSchemaElement;
if (element != null && element.RefName != null &&
element.RefName.Namespace == Globals.SerializationNamespace &&
element.MinOccurs == 0)
{
if (serializationSchemaElements == null)
{
XmlSchema serializationSchema = XmlSchema.Read(XmlReader.Create(new StringReader(Globals.SerializationSchema)), null);
serializationSchemaElements = new Hashtable();
foreach (XmlSchemaObject schemaObject in serializationSchema.Items)
{
XmlSchemaElement schemaElement = schemaObject as XmlSchemaElement;
if (schemaElement != null)
serializationSchemaElements.Add(schemaElement.Name, schemaElement);
}
}
if (!serializationSchemaElements.ContainsKey(element.RefName.Name))
{
items.RemoveAt(i);
i--;
}
}
}
}
DataContract ImportType(XmlQualifiedName typeName, XmlSchemaParticle rootParticle, XmlSchemaObjectCollection attributes, XmlSchemaAnyAttribute anyAttribute, XmlQualifiedName baseTypeName, XmlSchemaAnnotation annotation)
{
DataContract dataContract = null;
bool isDerived = (baseTypeName != null);
bool isReference;
ImportAttributes(typeName, attributes, anyAttribute, out isReference);
if (rootParticle == null)
dataContract = ImportClass(typeName, new XmlSchemaSequence(), baseTypeName, annotation, isReference);
else if (!(rootParticle is XmlSchemaSequence))
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.GetString(SR.RootParticleMustBeSequence));
else
{
XmlSchemaSequence rootSequence = (XmlSchemaSequence)rootParticle;
if (rootSequence.MinOccurs != 1)
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.GetString(SR.RootSequenceMustBeRequired));
if (rootSequence.MaxOccurs != 1)
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.GetString(SR.RootSequenceMaxOccursMustBe));
if (!isDerived && CheckIfCollection(rootSequence))
dataContract = ImportCollection(typeName, rootSequence, attributes, annotation, isReference);
else if (CheckIfISerializable(rootSequence, attributes))
dataContract = ImportISerializable(typeName, rootSequence, baseTypeName, attributes, annotation);
else
dataContract = ImportClass(typeName, rootSequence, baseTypeName, annotation, isReference);
}
return dataContract;
}
[Fx.Tag.SecurityNote(Critical = "Sets critical properties on ClassDataContract.",
Safe = "Called during schema import/code generation.")]
[SecuritySafeCritical]
ClassDataContract ImportClass(XmlQualifiedName typeName, XmlSchemaSequence rootSequence, XmlQualifiedName baseTypeName, XmlSchemaAnnotation annotation, bool isReference)
{
ClassDataContract dataContract = new ClassDataContract();
dataContract.StableName = typeName;
AddDataContract(dataContract);
dataContract.IsValueType = IsValueType(typeName, annotation);
dataContract.IsReference = isReference;
if (baseTypeName != null)
{
ImportBaseContract(baseTypeName, dataContract);
if (dataContract.BaseContract.IsISerializable)
{
if (IsISerializableDerived(typeName, rootSequence))
dataContract.IsISerializable = true;
else
ThrowTypeCannotBeImportedException(dataContract.StableName.Name, dataContract.StableName.Namespace, SR.GetString(SR.DerivedTypeNotISerializable, baseTypeName.Name, baseTypeName.Namespace));
}
if (dataContract.BaseContract.IsReference)
{
dataContract.IsReference = true;
}
}
if (!dataContract.IsISerializable)
{
dataContract.Members = new List<DataMember>();
RemoveOptionalUnknownSerializationElements(rootSequence.Items);
for (int memberIndex = 0; memberIndex < rootSequence.Items.Count; memberIndex++)
{
XmlSchemaElement element = rootSequence.Items[memberIndex] as XmlSchemaElement;
if (element == null)
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.GetString(SR.MustContainOnlyLocalElements));
ImportClassMember(element, dataContract);
}
}
return dataContract;
}
[Fx.Tag.SecurityNote(Critical = "Sets critical properties on XmlDataContract.",
Safe = "Called during schema import/code generation.")]
[SecuritySafeCritical]
DataContract ImportXmlDataType(XmlQualifiedName typeName, XmlSchemaType xsdType, bool isAnonymous)
{
DataContract dataContract = dataContractSet[typeName];
if (dataContract != null)
return dataContract;
XmlDataContract xmlDataContract = ImportSpecialXmlDataType(xsdType, isAnonymous);
if (xmlDataContract != null)
return xmlDataContract;
xmlDataContract = new XmlDataContract();
xmlDataContract.StableName = typeName;
xmlDataContract.IsValueType = false;
AddDataContract(xmlDataContract);
if (xsdType != null)
{
ImportDataContractExtension(xsdType, xmlDataContract);
xmlDataContract.IsValueType = IsValueType(typeName, xsdType.Annotation);
xmlDataContract.IsTypeDefinedOnImport = true;
xmlDataContract.XsdType = isAnonymous ? xsdType : null;
xmlDataContract.HasRoot = !IsXmlAnyElementType(xsdType as XmlSchemaComplexType);
}
else
{
//Value type can be used by both nillable and non-nillable elements but reference type cannot be used by non nillable elements
xmlDataContract.IsValueType = true;
xmlDataContract.IsTypeDefinedOnImport = false;
xmlDataContract.HasRoot = true;
if (DiagnosticUtility.ShouldTraceVerbose)
{
TraceUtility.Trace(TraceEventType.Verbose, TraceCode.XsdImportAnnotationFailed,
SR.GetString(SR.TraceCodeXsdImportAnnotationFailed), new StringTraceRecord("Type", typeName.Namespace + ":" + typeName.Name));
}
}
if (!isAnonymous)
{
bool isNullable;
xmlDataContract.SetTopLevelElementName(SchemaHelper.GetGlobalElementDeclaration(schemaSet, typeName, out isNullable));
xmlDataContract.IsTopLevelElementNullable = isNullable;
}
return xmlDataContract;
}
private XmlDataContract ImportSpecialXmlDataType(XmlSchemaType xsdType, bool isAnonymous)
{
if (!isAnonymous)
return null;
XmlSchemaComplexType complexType = xsdType as XmlSchemaComplexType;
if (complexType == null)
return null;
if (IsXmlAnyElementType(complexType))
{
//check if the type is XElement
XmlQualifiedName xlinqTypeName = new XmlQualifiedName("XElement", "http://schemas.datacontract.org/2004/07/System.Xml.Linq");
Type referencedType;
if (dataContractSet.TryGetReferencedType(xlinqTypeName, null, out referencedType)
&& Globals.TypeOfIXmlSerializable.IsAssignableFrom(referencedType))
{
XmlDataContract xmlDataContract = new XmlDataContract(referencedType);
AddDataContract(xmlDataContract);
return xmlDataContract;
}
//otherwise, assume XmlElement
return (XmlDataContract)DataContract.GetBuiltInDataContract(Globals.TypeOfXmlElement);
}
if (IsXmlAnyType(complexType))
return (XmlDataContract)DataContract.GetBuiltInDataContract(Globals.TypeOfXmlNodeArray);
return null;
}
bool IsXmlAnyElementType(XmlSchemaComplexType xsdType)
{
if (xsdType == null)
return false;
XmlSchemaSequence sequence = xsdType.Particle as XmlSchemaSequence;
if (sequence == null)
return false;
if (sequence.Items == null || sequence.Items.Count != 1)
return false;
XmlSchemaAny any = sequence.Items[0] as XmlSchemaAny;
if (any == null || any.Namespace != null)
return false;
if (xsdType.AnyAttribute != null || (xsdType.Attributes != null && xsdType.Attributes.Count > 0))
return false;
return true;
}
bool IsXmlAnyType(XmlSchemaComplexType xsdType)
{
if (xsdType == null)
return false;
XmlSchemaSequence sequence = xsdType.Particle as XmlSchemaSequence;
if (sequence == null)
return false;
if (sequence.Items == null || sequence.Items.Count != 1)
return false;
XmlSchemaAny any = sequence.Items[0] as XmlSchemaAny;
if (any == null || any.Namespace != null)
return false;
if (any.MaxOccurs != Decimal.MaxValue)
return false;
if (xsdType.AnyAttribute == null || xsdType.Attributes.Count > 0)
return false;
return true;
}
bool IsValueType(XmlQualifiedName typeName, XmlSchemaAnnotation annotation)
{
string isValueTypeInnerText = GetInnerText(typeName, ImportAnnotation(annotation, SchemaExporter.IsValueTypeName));
if (isValueTypeInnerText != null)
{
try
{
return XmlConvert.ToBoolean(isValueTypeInnerText);
}
catch (FormatException fe)
{
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.GetString(SR.IsValueTypeFormattedIncorrectly, isValueTypeInnerText, fe.Message));
}
}
return false;
}
[Fx.Tag.SecurityNote(Critical = "Sets critical properties on ClassDataContract.",
Safe = "Called during schema import/code generation.")]
[SecuritySafeCritical]
ClassDataContract ImportISerializable(XmlQualifiedName typeName, XmlSchemaSequence rootSequence, XmlQualifiedName baseTypeName, XmlSchemaObjectCollection attributes, XmlSchemaAnnotation annotation)
{
ClassDataContract dataContract = new ClassDataContract();
dataContract.StableName = typeName;
dataContract.IsISerializable = true;
AddDataContract(dataContract);
dataContract.IsValueType = IsValueType(typeName, annotation);
if (baseTypeName == null)
CheckISerializableBase(typeName, rootSequence, attributes);
else
{
ImportBaseContract(baseTypeName, dataContract);
if (!dataContract.BaseContract.IsISerializable)
ThrowISerializableTypeCannotBeImportedException(dataContract.StableName.Name, dataContract.StableName.Namespace, SR.GetString(SR.BaseTypeNotISerializable, baseTypeName.Name, baseTypeName.Namespace));
if (!IsISerializableDerived(typeName, rootSequence))
ThrowISerializableTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.GetString(SR.ISerializableDerivedContainsOneOrMoreItems));
}
return dataContract;
}
void CheckISerializableBase(XmlQualifiedName typeName, XmlSchemaSequence rootSequence, XmlSchemaObjectCollection attributes)
{
if (rootSequence == null)
ThrowISerializableTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.GetString(SR.ISerializableDoesNotContainAny));
if (rootSequence.Items == null || rootSequence.Items.Count < 1)
ThrowISerializableTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.GetString(SR.ISerializableDoesNotContainAny));
else if (rootSequence.Items.Count > 1)
ThrowISerializableTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.GetString(SR.ISerializableContainsMoreThanOneItems));
XmlSchemaObject o = rootSequence.Items[0];
if (!(o is XmlSchemaAny))
ThrowISerializableTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.GetString(SR.ISerializableDoesNotContainAny));
XmlSchemaAny wildcard = (XmlSchemaAny)o;
XmlSchemaAny iSerializableWildcardElement = SchemaExporter.ISerializableWildcardElement;
if (wildcard.MinOccurs != iSerializableWildcardElement.MinOccurs)
ThrowISerializableTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.GetString(SR.ISerializableWildcardMinOccursMustBe, iSerializableWildcardElement.MinOccurs));
if (wildcard.MaxOccursString != iSerializableWildcardElement.MaxOccursString)
ThrowISerializableTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.GetString(SR.ISerializableWildcardMaxOccursMustBe, iSerializableWildcardElement.MaxOccursString));
if (wildcard.Namespace != iSerializableWildcardElement.Namespace)
ThrowISerializableTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.GetString(SR.ISerializableWildcardNamespaceInvalid, iSerializableWildcardElement.Namespace));
if (wildcard.ProcessContents != iSerializableWildcardElement.ProcessContents)
ThrowISerializableTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.GetString(SR.ISerializableWildcardProcessContentsInvalid, iSerializableWildcardElement.ProcessContents));
XmlQualifiedName factoryTypeAttributeRefName = SchemaExporter.ISerializableFactoryTypeAttribute.RefName;
bool containsFactoryTypeAttribute = false;
if (attributes != null)
{
for (int i = 0; i < attributes.Count; i++)
{
o = attributes[i];
if (o is XmlSchemaAttribute)
{
if (((XmlSchemaAttribute)o).RefName == factoryTypeAttributeRefName)
{
containsFactoryTypeAttribute = true;
break;
}
}
}
}
if (!containsFactoryTypeAttribute)
ThrowISerializableTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.GetString(SR.ISerializableMustRefFactoryTypeAttribute, factoryTypeAttributeRefName.Name, factoryTypeAttributeRefName.Namespace));
}
bool IsISerializableDerived(XmlQualifiedName typeName, XmlSchemaSequence rootSequence)
{
return (rootSequence == null || rootSequence.Items == null || rootSequence.Items.Count == 0);
}
[Fx.Tag.SecurityNote(Critical = "Sets critical BaseContract property on ClassDataContract.",
Safe = "Called during schema import/code generation.")]
[SecuritySafeCritical]
void ImportBaseContract(XmlQualifiedName baseTypeName, ClassDataContract dataContract)
{
ClassDataContract baseContract = ImportType(baseTypeName) as ClassDataContract;
if (baseContract == null)
ThrowTypeCannotBeImportedException(dataContract.StableName.Name, dataContract.StableName.Namespace, SR.GetString(dataContract.IsISerializable ? SR.InvalidISerializableDerivation : SR.InvalidClassDerivation, baseTypeName.Name, baseTypeName.Namespace));
// Note: code ignores IsValueType annotation if derived type exists
if (baseContract.IsValueType)
baseContract.IsValueType = false;
ClassDataContract ancestorDataContract = baseContract;
while (ancestorDataContract != null)
{
DataContractDictionary knownDataContracts = ancestorDataContract.KnownDataContracts;
if (knownDataContracts == null)
{
knownDataContracts = new DataContractDictionary();
ancestorDataContract.KnownDataContracts = knownDataContracts;
}
knownDataContracts.Add(dataContract.StableName, dataContract);
ancestorDataContract = ancestorDataContract.BaseContract;
}
dataContract.BaseContract = baseContract;
}
void ImportTopLevelElement(XmlQualifiedName typeName)
{
XmlSchemaElement topLevelElement = SchemaHelper.GetSchemaElement(SchemaObjects, typeName);
// Top level element of same name is not required, but is validated if it is present
if (topLevelElement == null)
return;
else
{
XmlQualifiedName elementTypeName = topLevelElement.SchemaTypeName;
if (elementTypeName.IsEmpty)
{
if (topLevelElement.SchemaType != null)
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.GetString(SR.AnonymousTypeNotSupported, typeName.Name, typeName.Namespace));
else
elementTypeName = SchemaExporter.AnytypeQualifiedName;
}
if (elementTypeName != typeName)
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.GetString(SR.TopLevelElementRepresentsDifferentType, topLevelElement.SchemaTypeName.Name, topLevelElement.SchemaTypeName.Namespace));
CheckIfElementUsesUnsupportedConstructs(typeName, topLevelElement);
}
}
void ImportClassMember(XmlSchemaElement element, ClassDataContract dataContract)
{
XmlQualifiedName typeName = dataContract.StableName;
if (element.MinOccurs > 1)
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.GetString(SR.ElementMinOccursMustBe, element.Name));
if (element.MaxOccurs != 1)
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.GetString(SR.ElementMaxOccursMustBe, element.Name));
DataContract memberTypeContract = null;
string memberName = element.Name;
bool memberIsRequired = (element.MinOccurs > 0);
bool memberIsNullable = element.IsNillable;
bool memberEmitDefaultValue;
int memberOrder = 0;
XmlSchemaForm elementForm = (element.Form == XmlSchemaForm.None) ? SchemaHelper.GetSchemaWithType(SchemaObjects, schemaSet, typeName).ElementFormDefault : element.Form;
if (elementForm != XmlSchemaForm.Qualified)
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.GetString(SR.FormMustBeQualified, element.Name));
CheckIfElementUsesUnsupportedConstructs(typeName, element);
if (element.SchemaTypeName.IsEmpty)
{
if (element.SchemaType != null)
memberTypeContract = ImportAnonymousElement(element, new XmlQualifiedName(String.Format(CultureInfo.InvariantCulture, "{0}.{1}Type", typeName.Name, element.Name), typeName.Namespace));
else if (!element.RefName.IsEmpty)
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.GetString(SR.ElementRefOnLocalElementNotSupported, element.RefName.Name, element.RefName.Namespace));
else
memberTypeContract = ImportType(SchemaExporter.AnytypeQualifiedName);
}
else
{
XmlQualifiedName memberTypeName = ImportActualType(element.Annotation, element.SchemaTypeName, typeName);
memberTypeContract = ImportType(memberTypeName);
if (IsObjectContract(memberTypeContract))
needToImportKnownTypesForObject = true;
}
bool? emitDefaultValueFromAnnotation = ImportEmitDefaultValue(element.Annotation, typeName);
if (!memberTypeContract.IsValueType && !memberIsNullable)
{
if (emitDefaultValueFromAnnotation != null && emitDefaultValueFromAnnotation.Value)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.InvalidEmitDefaultAnnotation, memberName, typeName.Name, typeName.Namespace)));
memberEmitDefaultValue = false;
}
else
memberEmitDefaultValue = emitDefaultValueFromAnnotation != null ? emitDefaultValueFromAnnotation.Value : Globals.DefaultEmitDefaultValue;
int prevMemberIndex = dataContract.Members.Count - 1;
if (prevMemberIndex >= 0)
{
DataMember prevMember = dataContract.Members[prevMemberIndex];
if (prevMember.Order > Globals.DefaultOrder)
memberOrder = dataContract.Members.Count;
DataMember currentMember = new DataMember(memberTypeContract, memberName, memberIsNullable, memberIsRequired, memberEmitDefaultValue, memberOrder);
int compare = ClassDataContract.DataMemberComparer.Singleton.Compare(prevMember, currentMember);
if (compare == 0)
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.GetString(SR.CannotHaveDuplicateElementNames, memberName));
else if (compare > 0)
memberOrder = dataContract.Members.Count;
}
DataMember dataMember = new DataMember(memberTypeContract, memberName, memberIsNullable, memberIsRequired, memberEmitDefaultValue, memberOrder);
XmlQualifiedName surrogateDataAnnotationName = SchemaExporter.SurrogateDataAnnotationName;
dataContractSet.SetSurrogateData(dataMember, ImportSurrogateData(ImportAnnotation(element.Annotation, surrogateDataAnnotationName), surrogateDataAnnotationName.Name, surrogateDataAnnotationName.Namespace));
dataContract.Members.Add(dataMember);
}
private bool? ImportEmitDefaultValue(XmlSchemaAnnotation annotation, XmlQualifiedName typeName)
{
XmlElement defaultValueElement = ImportAnnotation(annotation, SchemaExporter.DefaultValueAnnotation);
if (defaultValueElement == null)
return null;
XmlNode emitDefaultValueAttribute = defaultValueElement.Attributes.GetNamedItem(Globals.EmitDefaultValueAttribute);
string emitDefaultValueString = (emitDefaultValueAttribute == null) ? null : emitDefaultValueAttribute.Value;
if (emitDefaultValueString == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.AnnotationAttributeNotFound, SchemaExporter.DefaultValueAnnotation.Name, typeName.Name, typeName.Namespace, Globals.EmitDefaultValueAttribute)));
return XmlConvert.ToBoolean(emitDefaultValueString);
}
internal static XmlQualifiedName ImportActualType(XmlSchemaAnnotation annotation, XmlQualifiedName defaultTypeName, XmlQualifiedName typeName)
{
XmlElement actualTypeElement = ImportAnnotation(annotation, SchemaExporter.ActualTypeAnnotationName);
if (actualTypeElement == null)
return defaultTypeName;
XmlNode nameAttribute = actualTypeElement.Attributes.GetNamedItem(Globals.ActualTypeNameAttribute);
string name = (nameAttribute == null) ? null : nameAttribute.Value;
if (name == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.AnnotationAttributeNotFound, SchemaExporter.ActualTypeAnnotationName.Name, typeName.Name, typeName.Namespace, Globals.ActualTypeNameAttribute)));
XmlNode nsAttribute = actualTypeElement.Attributes.GetNamedItem(Globals.ActualTypeNamespaceAttribute);
string ns = (nsAttribute == null) ? null : nsAttribute.Value;
if (ns == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.AnnotationAttributeNotFound, SchemaExporter.ActualTypeAnnotationName.Name, typeName.Name, typeName.Namespace, Globals.ActualTypeNamespaceAttribute)));
return new XmlQualifiedName(name, ns);
}
[Fx.Tag.SecurityNote(Critical = "Sets critical properties on CollectionDataContract.",
Safe = "Called during schema import/code generation.")]
[SecuritySafeCritical]
CollectionDataContract ImportCollection(XmlQualifiedName typeName, XmlSchemaSequence rootSequence, XmlSchemaObjectCollection attributes, XmlSchemaAnnotation annotation, bool isReference)
{
CollectionDataContract dataContract = new CollectionDataContract(CollectionKind.Array);
dataContract.StableName = typeName;
AddDataContract(dataContract);
dataContract.IsReference = isReference;
// CheckIfCollection has already checked if sequence contains exactly one item with maxOccurs="unbounded" or maxOccurs > 1
XmlSchemaElement element = (XmlSchemaElement)rootSequence.Items[0];
dataContract.IsItemTypeNullable = element.IsNillable;
dataContract.ItemName = element.Name;
XmlSchemaForm elementForm = (element.Form == XmlSchemaForm.None) ? SchemaHelper.GetSchemaWithType(SchemaObjects, schemaSet, typeName).ElementFormDefault : element.Form;
if (elementForm != XmlSchemaForm.Qualified)
ThrowArrayTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.GetString(SR.ArrayItemFormMustBe, element.Name));
CheckIfElementUsesUnsupportedConstructs(typeName, element);
if (element.SchemaTypeName.IsEmpty)
{
if (element.SchemaType != null)
{
XmlQualifiedName shortName = new XmlQualifiedName(element.Name, typeName.Namespace);
DataContract contract = dataContractSet[shortName];
if (contract == null)
{
dataContract.ItemContract = ImportAnonymousElement(element, shortName);
}
else
{
XmlQualifiedName fullName = new XmlQualifiedName(String.Format(CultureInfo.InvariantCulture, "{0}.{1}Type", typeName.Name, element.Name), typeName.Namespace);
dataContract.ItemContract = ImportAnonymousElement(element, fullName);
}
}
else if (!element.RefName.IsEmpty)
ThrowArrayTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.GetString(SR.ElementRefOnLocalElementNotSupported, element.RefName.Name, element.RefName.Namespace));
else
dataContract.ItemContract = ImportType(SchemaExporter.AnytypeQualifiedName);
}
else
{
dataContract.ItemContract = ImportType(element.SchemaTypeName);
}
if (IsDictionary(typeName, annotation))
{
ClassDataContract keyValueContract = dataContract.ItemContract as ClassDataContract;
DataMember key = null, value = null;
if (keyValueContract == null || keyValueContract.Members == null || keyValueContract.Members.Count != 2
|| !(key = keyValueContract.Members[0]).IsRequired || !(value = keyValueContract.Members[1]).IsRequired)
{
ThrowArrayTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.GetString(SR.InvalidKeyValueType, element.Name));
}
if (keyValueContract.Namespace != dataContract.Namespace)
{
ThrowArrayTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.GetString(SR.InvalidKeyValueTypeNamespace, element.Name, keyValueContract.Namespace));
}
keyValueContract.IsValueType = true;
dataContract.KeyName = key.Name;
dataContract.ValueName = value.Name;
if (element.SchemaType != null)
{
dataContractSet.Remove(keyValueContract.StableName);
GenericInfo genericInfo = new GenericInfo(DataContract.GetStableName(Globals.TypeOfKeyValue), Globals.TypeOfKeyValue.FullName);
genericInfo.Add(GetGenericInfoForDataMember(key));
genericInfo.Add(GetGenericInfoForDataMember(value));
genericInfo.AddToLevel(0, 2);
dataContract.ItemContract.StableName = new XmlQualifiedName(genericInfo.GetExpandedStableName().Name, typeName.Namespace);
}
}
return dataContract;
}
GenericInfo GetGenericInfoForDataMember(DataMember dataMember)
{
GenericInfo genericInfo = null;
if (dataMember.MemberTypeContract.IsValueType && dataMember.IsNullable)
{
genericInfo = new GenericInfo(DataContract.GetStableName(Globals.TypeOfNullable), Globals.TypeOfNullable.FullName);
genericInfo.Add(new GenericInfo(dataMember.MemberTypeContract.StableName, null));
}
else
{
genericInfo = new GenericInfo(dataMember.MemberTypeContract.StableName, null);
}
return genericInfo;
}
bool IsDictionary(XmlQualifiedName typeName, XmlSchemaAnnotation annotation)
{
string isDictionaryInnerText = GetInnerText(typeName, ImportAnnotation(annotation, SchemaExporter.IsDictionaryAnnotationName));
if (isDictionaryInnerText != null)
{
try
{
return XmlConvert.ToBoolean(isDictionaryInnerText);
}
catch (FormatException fe)
{
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.GetString(SR.IsDictionaryFormattedIncorrectly, isDictionaryInnerText, fe.Message));
}
}
return false;
}
EnumDataContract ImportFlagsEnum(XmlQualifiedName typeName, XmlSchemaSimpleTypeList list, XmlSchemaAnnotation annotation)
{
XmlSchemaSimpleType anonymousType = list.ItemType;
if (anonymousType == null)
ThrowEnumTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.GetString(SR.EnumListMustContainAnonymousType));
XmlSchemaSimpleTypeContent content = anonymousType.Content;
if (content is XmlSchemaSimpleTypeUnion)
ThrowEnumTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.GetString(SR.EnumUnionInAnonymousTypeNotSupported));
else if (content is XmlSchemaSimpleTypeList)
ThrowEnumTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.GetString(SR.EnumListInAnonymousTypeNotSupported));
else if (content is XmlSchemaSimpleTypeRestriction)
{
XmlSchemaSimpleTypeRestriction restriction = (XmlSchemaSimpleTypeRestriction)content;
if (CheckIfEnum(restriction))
return ImportEnum(typeName, restriction, true /*isFlags*/, annotation);
else
ThrowEnumTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.GetString(SR.EnumRestrictionInvalid));
}
return null;
}
[Fx.Tag.SecurityNote(Critical = "Sets critical properties on EnumDataContract.",
Safe = "Called during schema import/code generation.")]
[SecuritySafeCritical]
EnumDataContract ImportEnum(XmlQualifiedName typeName, XmlSchemaSimpleTypeRestriction restriction, bool isFlags, XmlSchemaAnnotation annotation)
{
EnumDataContract dataContract = new EnumDataContract();
dataContract.StableName = typeName;
dataContract.BaseContractName = ImportActualType(annotation, SchemaExporter.DefaultEnumBaseTypeName, typeName);
dataContract.IsFlags = isFlags;
AddDataContract(dataContract);
// CheckIfEnum has already checked if baseType of restriction is string
dataContract.Values = new List<long>();
dataContract.Members = new List<DataMember>();
foreach (XmlSchemaFacet facet in restriction.Facets)
{
XmlSchemaEnumerationFacet enumFacet = facet as XmlSchemaEnumerationFacet;
if (enumFacet == null)
ThrowEnumTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.GetString(SR.EnumOnlyEnumerationFacetsSupported));
if (enumFacet.Value == null)
ThrowEnumTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.GetString(SR.EnumEnumerationFacetsMustHaveValue));
string valueInnerText = GetInnerText(typeName, ImportAnnotation(enumFacet.Annotation, SchemaExporter.EnumerationValueAnnotationName));
if (valueInnerText == null)
dataContract.Values.Add(SchemaExporter.GetDefaultEnumValue(isFlags, dataContract.Members.Count));
else
dataContract.Values.Add(dataContract.GetEnumValueFromString(valueInnerText));
DataMember dataMember = new DataMember(enumFacet.Value);
dataContract.Members.Add(dataMember);
}
return dataContract;
}
DataContract ImportSimpleTypeRestriction(XmlQualifiedName typeName, XmlSchemaSimpleTypeRestriction restriction)
{
DataContract dataContract = null;
if (!restriction.BaseTypeName.IsEmpty)
dataContract = ImportType(restriction.BaseTypeName);
else if (restriction.BaseType != null)
dataContract = ImportType(restriction.BaseType);
else
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.GetString(SR.SimpleTypeRestrictionDoesNotSpecifyBase));
return dataContract;
}
void ImportDataContractExtension(XmlSchemaType type, DataContract dataContract)
{
if (type.Annotation == null || type.Annotation.Items == null)
return;
foreach (XmlSchemaObject schemaObject in type.Annotation.Items)
{
XmlSchemaAppInfo appInfo = schemaObject as XmlSchemaAppInfo;
if (appInfo == null)
continue;
if (appInfo.Markup != null)
{
foreach (XmlNode xmlNode in appInfo.Markup)
{
XmlElement typeElement = xmlNode as XmlElement;
XmlQualifiedName surrogateDataAnnotationName = SchemaExporter.SurrogateDataAnnotationName;
if (typeElement != null && typeElement.NamespaceURI == surrogateDataAnnotationName.Namespace && typeElement.LocalName == surrogateDataAnnotationName.Name)
{
object surrogateData = ImportSurrogateData(typeElement, surrogateDataAnnotationName.Name, surrogateDataAnnotationName.Namespace);
dataContractSet.SetSurrogateData(dataContract, surrogateData);
}
}
}
}
}
[Fx.Tag.SecurityNote(Critical = "Sets critical properties on DataContract.",
Safe = "Called during schema import/code generation.")]
[SecuritySafeCritical]
void ImportGenericInfo(XmlSchemaType type, DataContract dataContract)
{
if (type.Annotation == null || type.Annotation.Items == null)
return;
foreach (XmlSchemaObject schemaObject in type.Annotation.Items)
{
XmlSchemaAppInfo appInfo = schemaObject as XmlSchemaAppInfo;
if (appInfo == null)
continue;
if (appInfo.Markup != null)
{
foreach (XmlNode xmlNode in appInfo.Markup)
{
XmlElement typeElement = xmlNode as XmlElement;
if (typeElement != null && typeElement.NamespaceURI == Globals.SerializationNamespace)
{
if (typeElement.LocalName == Globals.GenericTypeLocalName)
dataContract.GenericInfo = ImportGenericInfo(typeElement, type);
}
}
}
}
}
GenericInfo ImportGenericInfo(XmlElement typeElement, XmlSchemaType type)
{
XmlNode nameAttribute = typeElement.Attributes.GetNamedItem(Globals.GenericNameAttribute);
string name = (nameAttribute == null) ? null : nameAttribute.Value;
if (name == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.GenericAnnotationAttributeNotFound, type.Name, Globals.GenericNameAttribute)));
XmlNode nsAttribute = typeElement.Attributes.GetNamedItem(Globals.GenericNamespaceAttribute);
string ns = (nsAttribute == null) ? null : nsAttribute.Value;
if (ns == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.GenericAnnotationAttributeNotFound, type.Name, Globals.GenericNamespaceAttribute)));
if (typeElement.ChildNodes.Count > 0) //Generic Type
name = DataContract.EncodeLocalName(name);
int currentLevel = 0;
GenericInfo genInfo = new GenericInfo(new XmlQualifiedName(name, ns), type.Name);
foreach (XmlNode childNode in typeElement.ChildNodes)
{
XmlElement argumentElement = childNode as XmlElement;
if (argumentElement == null)
continue;
if (argumentElement.LocalName != Globals.GenericParameterLocalName ||
argumentElement.NamespaceURI != Globals.SerializationNamespace)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.GenericAnnotationHasInvalidElement, argumentElement.LocalName, argumentElement.NamespaceURI, type.Name)));
XmlNode nestedLevelAttribute = argumentElement.Attributes.GetNamedItem(Globals.GenericParameterNestedLevelAttribute);
int argumentLevel = 0;
if (nestedLevelAttribute != null)
{
if (!Int32.TryParse(nestedLevelAttribute.Value, out argumentLevel))
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.GenericAnnotationHasInvalidAttributeValue, argumentElement.LocalName, argumentElement.NamespaceURI, type.Name, nestedLevelAttribute.Value, nestedLevelAttribute.LocalName, Globals.TypeOfInt.Name)));
}
if (argumentLevel < currentLevel)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.GenericAnnotationForNestedLevelMustBeIncreasing, argumentElement.LocalName, argumentElement.NamespaceURI, type.Name)));
genInfo.Add(ImportGenericInfo(argumentElement, type));
genInfo.AddToLevel(argumentLevel, 1);
currentLevel = argumentLevel;
}
XmlNode typeNestedLevelsAttribute = typeElement.Attributes.GetNamedItem(Globals.GenericParameterNestedLevelAttribute);
if (typeNestedLevelsAttribute != null)
{
int nestedLevels = 0;
if (!Int32.TryParse(typeNestedLevelsAttribute.Value, out nestedLevels))
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.GenericAnnotationHasInvalidAttributeValue, typeElement.LocalName, typeElement.NamespaceURI, type.Name, typeNestedLevelsAttribute.Value, typeNestedLevelsAttribute.LocalName, Globals.TypeOfInt.Name)));
if ((nestedLevels - 1) > currentLevel)
genInfo.AddToLevel(nestedLevels - 1, 0);
}
return genInfo;
}
object ImportSurrogateData(XmlElement typeElement, string name, string ns)
{
if (dataContractSet.DataContractSurrogate != null && typeElement != null)
{
Collection<Type> knownTypes = new Collection<Type>();
DataContractSurrogateCaller.GetKnownCustomDataTypes(dataContractSet.DataContractSurrogate, knownTypes);
DataContractSerializer serializer = new DataContractSerializer(Globals.TypeOfObject, name, ns, knownTypes,
Int32.MaxValue, false /*ignoreExtensionDataObject*/, true /*preserveObjectReferences*/, null /*dataContractSurrogate*/);
return serializer.ReadObject(new XmlNodeReader(typeElement));
}
return null;
}
void CheckComplexType(XmlQualifiedName typeName, XmlSchemaComplexType type)
{
if (type.IsAbstract)
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.GetString(SR.AbstractTypeNotSupported));
if (type.IsMixed)
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.GetString(SR.MixedContentNotSupported));
}
void CheckIfElementUsesUnsupportedConstructs(XmlQualifiedName typeName, XmlSchemaElement element)
{
if (element.IsAbstract)
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.GetString(SR.AbstractElementNotSupported, element.Name));
if (element.DefaultValue != null)
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.GetString(SR.DefaultOnElementNotSupported, element.Name));
if (element.FixedValue != null)
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.GetString(SR.FixedOnElementNotSupported, element.Name));
if (!element.SubstitutionGroup.IsEmpty)
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.GetString(SR.SubstitutionGroupOnElementNotSupported, element.Name));
}
void ImportAttributes(XmlQualifiedName typeName, XmlSchemaObjectCollection attributes, XmlSchemaAnyAttribute anyAttribute, out bool isReference)
{
if (anyAttribute != null)
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.GetString(SR.AnyAttributeNotSupported));
isReference = false;
if (attributes != null)
{
bool foundId = false, foundRef = false;
for (int i = 0; i < attributes.Count; i++)
{
XmlSchemaObject o = attributes[i];
if (o is XmlSchemaAttribute)
{
XmlSchemaAttribute attribute = (XmlSchemaAttribute)o;
if (attribute.Use == XmlSchemaUse.Prohibited)
continue;
if (TryCheckIfAttribute(typeName, attribute, Globals.IdQualifiedName, ref foundId))
continue;
if (TryCheckIfAttribute(typeName, attribute, Globals.RefQualifiedName, ref foundRef))
continue;
if (attribute.RefName.IsEmpty || attribute.RefName.Namespace != Globals.SerializationNamespace || attribute.Use == XmlSchemaUse.Required)
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.GetString(SR.TypeShouldNotContainAttributes, Globals.SerializationNamespace));
}
}
isReference = (foundId && foundRef);
}
}
bool TryCheckIfAttribute(XmlQualifiedName typeName, XmlSchemaAttribute attribute, XmlQualifiedName refName, ref bool foundAttribute)
{
if (attribute.RefName != refName)
return false;
if (foundAttribute)
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.GetString(SR.CannotHaveDuplicateAttributeNames, refName.Name));
foundAttribute = true;
return true;
}
void AddDataContract(DataContract dataContract)
{
dataContractSet.Add(dataContract.StableName, dataContract);
}
string GetInnerText(XmlQualifiedName typeName, XmlElement xmlElement)
{
if (xmlElement != null)
{
XmlNode child = xmlElement.FirstChild;
while (child != null)
{
if (child.NodeType == XmlNodeType.Element)
ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.GetString(SR.InvalidAnnotationExpectingText, xmlElement.LocalName, xmlElement.NamespaceURI, child.LocalName, child.NamespaceURI));
child = child.NextSibling;
}
return xmlElement.InnerText;
}
return null;
}
static XmlElement ImportAnnotation(XmlSchemaAnnotation annotation, XmlQualifiedName annotationQualifiedName)
{
if (annotation != null && annotation.Items != null && annotation.Items.Count > 0 && annotation.Items[0] is XmlSchemaAppInfo)
{
XmlSchemaAppInfo appInfo = (XmlSchemaAppInfo)annotation.Items[0];
XmlNode[] markup = appInfo.Markup;
if (markup != null)
{
for (int i = 0; i < markup.Length; i++)
{
XmlElement annotationElement = markup[i] as XmlElement;
if (annotationElement != null && annotationElement.LocalName == annotationQualifiedName.Name && annotationElement.NamespaceURI == annotationQualifiedName.Namespace)
return annotationElement;
}
}
}
return null;
}
static void ThrowTypeCannotBeImportedException(string name, string ns, string message)
{
ThrowTypeCannotBeImportedException(SR.GetString(SR.TypeCannotBeImported, name, ns, message));
}
static void ThrowArrayTypeCannotBeImportedException(string name, string ns, string message)
{
ThrowTypeCannotBeImportedException(SR.GetString(SR.ArrayTypeCannotBeImported, name, ns, message));
}
static void ThrowEnumTypeCannotBeImportedException(string name, string ns, string message)
{
ThrowTypeCannotBeImportedException(SR.GetString(SR.EnumTypeCannotBeImported, name, ns, message));
}
static void ThrowISerializableTypeCannotBeImportedException(string name, string ns, string message)
{
ThrowTypeCannotBeImportedException(SR.GetString(SR.ISerializableTypeCannotBeImported, name, ns, message));
}
static void ThrowTypeCannotBeImportedException(string message)
{
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.TypeCannotBeImportedHowToFix, message)));
}
}
}
| |
////////////////////////////////////////////////////////////////////////////////
// The MIT License (MIT)
//
// Copyright (c) 2021 Tim Stair
//
// 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.
////////////////////////////////////////////////////////////////////////////////
namespace CardMaker.Forms
{
partial class MDILayoutControl
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.groupBoxCardSet = new System.Windows.Forms.GroupBox();
this.btnConfigureSize = new System.Windows.Forms.Button();
this.checkLoadAllReferences = new System.Windows.Forms.CheckBox();
this.btnScale = new System.Windows.Forms.Button();
this.resizeBtn = new System.Windows.Forms.Button();
this.listViewElements = new Support.UI.ListViewDoubleBuffered();
this.columnHeader1 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.columnHeader2 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.columnHeader3 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.contextMenuElements = new System.Windows.Forms.ContextMenuStrip(this.components);
this.copyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.pasteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.pasteReferenceToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.detachReferenceToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.pasteSettingsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.checkCardSetDrawBorder = new System.Windows.Forms.CheckBox();
this.numericCardSetDPI = new System.Windows.Forms.NumericUpDown();
this.label8 = new System.Windows.Forms.Label();
this.btnElementRename = new System.Windows.Forms.Button();
this.btnElementUp = new System.Windows.Forms.Button();
this.btnElementDown = new System.Windows.Forms.Button();
this.numericCardSetBuffer = new System.Windows.Forms.NumericUpDown();
this.label11 = new System.Windows.Forms.Label();
this.btnDuplicate = new System.Windows.Forms.Button();
this.label10 = new System.Windows.Forms.Label();
this.label9 = new System.Windows.Forms.Label();
this.btnRemoveElement = new System.Windows.Forms.Button();
this.numericCardSetHeight = new System.Windows.Forms.NumericUpDown();
this.numericCardSetWidth = new System.Windows.Forms.NumericUpDown();
this.btnAddElement = new System.Windows.Forms.Button();
this.btnGenCards = new System.Windows.Forms.Button();
this.numericCardIndex = new System.Windows.Forms.NumericUpDown();
this.lblIndex = new System.Windows.Forms.Label();
this.groupBoxCardCount = new System.Windows.Forms.GroupBox();
this.label2 = new System.Windows.Forms.Label();
this.numericRowIndex = new System.Windows.Forms.NumericUpDown();
this.label1 = new System.Windows.Forms.Label();
this.groupBoxCardSet.SuspendLayout();
this.contextMenuElements.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numericCardSetDPI)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericCardSetBuffer)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericCardSetHeight)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericCardSetWidth)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericCardIndex)).BeginInit();
this.groupBoxCardCount.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numericRowIndex)).BeginInit();
this.SuspendLayout();
//
// groupBoxCardSet
//
this.groupBoxCardSet.Controls.Add(this.btnConfigureSize);
this.groupBoxCardSet.Controls.Add(this.checkLoadAllReferences);
this.groupBoxCardSet.Controls.Add(this.btnScale);
this.groupBoxCardSet.Controls.Add(this.resizeBtn);
this.groupBoxCardSet.Controls.Add(this.listViewElements);
this.groupBoxCardSet.Controls.Add(this.checkCardSetDrawBorder);
this.groupBoxCardSet.Controls.Add(this.numericCardSetDPI);
this.groupBoxCardSet.Controls.Add(this.label8);
this.groupBoxCardSet.Controls.Add(this.btnElementRename);
this.groupBoxCardSet.Controls.Add(this.btnElementUp);
this.groupBoxCardSet.Controls.Add(this.btnElementDown);
this.groupBoxCardSet.Controls.Add(this.numericCardSetBuffer);
this.groupBoxCardSet.Controls.Add(this.label11);
this.groupBoxCardSet.Controls.Add(this.btnDuplicate);
this.groupBoxCardSet.Controls.Add(this.label10);
this.groupBoxCardSet.Controls.Add(this.label9);
this.groupBoxCardSet.Controls.Add(this.btnRemoveElement);
this.groupBoxCardSet.Controls.Add(this.numericCardSetHeight);
this.groupBoxCardSet.Controls.Add(this.numericCardSetWidth);
this.groupBoxCardSet.Controls.Add(this.btnAddElement);
this.groupBoxCardSet.Dock = System.Windows.Forms.DockStyle.Fill;
this.groupBoxCardSet.Enabled = false;
this.groupBoxCardSet.Location = new System.Drawing.Point(0, 46);
this.groupBoxCardSet.Name = "groupBoxCardSet";
this.groupBoxCardSet.Size = new System.Drawing.Size(322, 327);
this.groupBoxCardSet.TabIndex = 12;
this.groupBoxCardSet.TabStop = false;
this.groupBoxCardSet.Text = "Card Layout";
//
// btnConfigureSize
//
this.btnConfigureSize.Location = new System.Drawing.Point(257, 41);
this.btnConfigureSize.Name = "btnConfigureSize";
this.btnConfigureSize.Size = new System.Drawing.Size(59, 20);
this.btnConfigureSize.TabIndex = 34;
this.btnConfigureSize.Text = "Resize";
this.btnConfigureSize.UseVisualStyleBackColor = true;
this.btnConfigureSize.Click += new System.EventHandler(this.btnConfigureSize_Click);
//
// checkLoadAllReferences
//
this.checkLoadAllReferences.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.checkLoadAllReferences.Location = new System.Drawing.Point(152, 67);
this.checkLoadAllReferences.Name = "checkLoadAllReferences";
this.checkLoadAllReferences.Size = new System.Drawing.Size(138, 16);
this.checkLoadAllReferences.TabIndex = 33;
this.checkLoadAllReferences.Text = "Load All References";
this.checkLoadAllReferences.UseVisualStyleBackColor = true;
this.checkLoadAllReferences.CheckedChanged += new System.EventHandler(this.HandleCardSetValueChange);
//
// btnScale
//
this.btnScale.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.btnScale.Location = new System.Drawing.Point(143, 279);
this.btnScale.Name = "btnScale";
this.btnScale.Size = new System.Drawing.Size(60, 20);
this.btnScale.TabIndex = 32;
this.btnScale.Text = "Scale";
this.btnScale.UseVisualStyleBackColor = true;
this.btnScale.Click += new System.EventHandler(this.btnScale_Click);
//
// resizeBtn
//
this.resizeBtn.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.resizeBtn.Location = new System.Drawing.Point(143, 301);
this.resizeBtn.Name = "resizeBtn";
this.resizeBtn.Size = new System.Drawing.Size(60, 20);
this.resizeBtn.TabIndex = 31;
this.resizeBtn.Text = "Resize";
this.resizeBtn.UseVisualStyleBackColor = true;
this.resizeBtn.Click += new System.EventHandler(this.resize_Click);
//
// listViewElements
//
this.listViewElements.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.listViewElements.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.listViewElements.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnHeader1,
this.columnHeader2,
this.columnHeader3});
this.listViewElements.ContextMenuStrip = this.contextMenuElements;
this.listViewElements.FullRowSelect = true;
this.listViewElements.GridLines = true;
this.listViewElements.HideSelection = false;
this.listViewElements.Location = new System.Drawing.Point(6, 89);
this.listViewElements.Name = "listViewElements";
this.listViewElements.ShowItemToolTips = true;
this.listViewElements.Size = new System.Drawing.Size(310, 184);
this.listViewElements.TabIndex = 30;
this.listViewElements.UseCompatibleStateImageBehavior = false;
this.listViewElements.View = System.Windows.Forms.View.Details;
this.listViewElements.SelectedIndexChanged += new System.EventHandler(this.listViewElements_SelectedIndexChanged);
this.listViewElements.DoubleClick += new System.EventHandler(this.listViewElements_DoubleClick);
this.listViewElements.KeyDown += new System.Windows.Forms.KeyEventHandler(this.listViewElements_KeyDown);
this.listViewElements.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.listViewElements_KeyPress);
this.listViewElements.Resize += new System.EventHandler(this.listViewElements_Resize);
//
// columnHeader1
//
this.columnHeader1.Text = "Enabled";
this.columnHeader1.Width = 55;
//
// columnHeader2
//
this.columnHeader2.Text = "Element";
this.columnHeader2.Width = 161;
//
// columnHeader3
//
this.columnHeader3.Text = "Type";
this.columnHeader3.Width = 92;
//
// contextMenuElements
//
this.contextMenuElements.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.copyToolStripMenuItem,
this.pasteToolStripMenuItem,
this.pasteReferenceToolStripMenuItem,
this.detachReferenceToolStripMenuItem,
this.pasteSettingsToolStripMenuItem});
this.contextMenuElements.Name = "contextMenuElements";
this.contextMenuElements.RenderMode = System.Windows.Forms.ToolStripRenderMode.System;
this.contextMenuElements.Size = new System.Drawing.Size(180, 114);
this.contextMenuElements.Opening += new System.ComponentModel.CancelEventHandler(this.contextMenuElements_Opening);
//
// copyToolStripMenuItem
//
this.copyToolStripMenuItem.Name = "copyToolStripMenuItem";
this.copyToolStripMenuItem.Size = new System.Drawing.Size(179, 22);
this.copyToolStripMenuItem.Text = "Copy";
this.copyToolStripMenuItem.Click += new System.EventHandler(this.copyToolStripMenuItem_Click);
//
// pasteToolStripMenuItem
//
this.pasteToolStripMenuItem.Name = "pasteToolStripMenuItem";
this.pasteToolStripMenuItem.Size = new System.Drawing.Size(179, 22);
this.pasteToolStripMenuItem.Text = "Paste";
this.pasteToolStripMenuItem.Click += new System.EventHandler(this.pasteToolStripMenuItem_Click);
//
// pasteReferenceToolStripMenuItem
//
this.pasteReferenceToolStripMenuItem.Name = "pasteReferenceToolStripMenuItem";
this.pasteReferenceToolStripMenuItem.Size = new System.Drawing.Size(179, 22);
this.pasteReferenceToolStripMenuItem.Text = "Paste Reference(s)";
this.pasteReferenceToolStripMenuItem.Click += new System.EventHandler(this.pasteReferenceToolStripMenuItem_Click);
//
// detachReferenceToolStripMenuItem
//
this.detachReferenceToolStripMenuItem.Name = "detachReferenceToolStripMenuItem";
this.detachReferenceToolStripMenuItem.Size = new System.Drawing.Size(179, 22);
this.detachReferenceToolStripMenuItem.Text = "Detach Reference(s)";
this.detachReferenceToolStripMenuItem.Click += new System.EventHandler(this.detachReferenceToolStripMenuItem_Click);
//
// pasteSettingsToolStripMenuItem
//
this.pasteSettingsToolStripMenuItem.Name = "pasteSettingsToolStripMenuItem";
this.pasteSettingsToolStripMenuItem.Size = new System.Drawing.Size(179, 22);
this.pasteSettingsToolStripMenuItem.Text = "Paste Settings...";
this.pasteSettingsToolStripMenuItem.Click += new System.EventHandler(this.pasteSettingsToolStripMenuItem_Click);
//
// checkCardSetDrawBorder
//
this.checkCardSetDrawBorder.Location = new System.Drawing.Point(9, 67);
this.checkCardSetDrawBorder.Name = "checkCardSetDrawBorder";
this.checkCardSetDrawBorder.Size = new System.Drawing.Size(138, 16);
this.checkCardSetDrawBorder.TabIndex = 28;
this.checkCardSetDrawBorder.Text = "Draw Border";
this.checkCardSetDrawBorder.UseVisualStyleBackColor = true;
this.checkCardSetDrawBorder.CheckedChanged += new System.EventHandler(this.HandleCardSetValueChange);
//
// numericCardSetDPI
//
this.numericCardSetDPI.Location = new System.Drawing.Point(195, 16);
this.numericCardSetDPI.Maximum = new decimal(new int[] {
6000,
0,
0,
0});
this.numericCardSetDPI.Minimum = new decimal(new int[] {
100,
0,
0,
0});
this.numericCardSetDPI.Name = "numericCardSetDPI";
this.numericCardSetDPI.Size = new System.Drawing.Size(56, 20);
this.numericCardSetDPI.TabIndex = 27;
this.numericCardSetDPI.Value = new decimal(new int[] {
100,
0,
0,
0});
this.numericCardSetDPI.ValueChanged += new System.EventHandler(this.HandleCardSetValueChange);
//
// label8
//
this.label8.Location = new System.Drawing.Point(122, 16);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(67, 20);
this.label8.TabIndex = 26;
this.label8.Text = "Export DPI:";
this.label8.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// btnElementRename
//
this.btnElementRename.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.btnElementRename.Location = new System.Drawing.Point(77, 301);
this.btnElementRename.Name = "btnElementRename";
this.btnElementRename.Size = new System.Drawing.Size(60, 20);
this.btnElementRename.TabIndex = 25;
this.btnElementRename.Text = "Rename";
this.btnElementRename.UseVisualStyleBackColor = true;
this.btnElementRename.Click += new System.EventHandler(this.btnElementRename_Click);
//
// btnElementUp
//
this.btnElementUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnElementUp.Location = new System.Drawing.Point(263, 279);
this.btnElementUp.Name = "btnElementUp";
this.btnElementUp.Size = new System.Drawing.Size(53, 20);
this.btnElementUp.TabIndex = 24;
this.btnElementUp.Text = "Up";
this.btnElementUp.UseVisualStyleBackColor = true;
this.btnElementUp.Click += new System.EventHandler(this.btnElementChangeOrder_Click);
//
// btnElementDown
//
this.btnElementDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnElementDown.Location = new System.Drawing.Point(262, 302);
this.btnElementDown.Name = "btnElementDown";
this.btnElementDown.Size = new System.Drawing.Size(54, 20);
this.btnElementDown.TabIndex = 23;
this.btnElementDown.Text = "Down";
this.btnElementDown.UseVisualStyleBackColor = true;
this.btnElementDown.Click += new System.EventHandler(this.btnElementChangeOrder_Click);
//
// numericCardSetBuffer
//
this.numericCardSetBuffer.Location = new System.Drawing.Point(54, 16);
this.numericCardSetBuffer.Name = "numericCardSetBuffer";
this.numericCardSetBuffer.Size = new System.Drawing.Size(56, 20);
this.numericCardSetBuffer.TabIndex = 22;
this.numericCardSetBuffer.ValueChanged += new System.EventHandler(this.HandleCardSetValueChange);
//
// label11
//
this.label11.Location = new System.Drawing.Point(6, 16);
this.label11.Name = "label11";
this.label11.Size = new System.Drawing.Size(45, 20);
this.label11.TabIndex = 21;
this.label11.Text = "Buffer:";
this.label11.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// btnDuplicate
//
this.btnDuplicate.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.btnDuplicate.Location = new System.Drawing.Point(77, 279);
this.btnDuplicate.Name = "btnDuplicate";
this.btnDuplicate.Size = new System.Drawing.Size(60, 20);
this.btnDuplicate.TabIndex = 20;
this.btnDuplicate.Text = "Dupe";
this.btnDuplicate.UseVisualStyleBackColor = true;
this.btnDuplicate.Click += new System.EventHandler(this.btnDuplicate_Click);
//
// label10
//
this.label10.Location = new System.Drawing.Point(6, 41);
this.label10.Name = "label10";
this.label10.Size = new System.Drawing.Size(45, 20);
this.label10.TabIndex = 18;
this.label10.Text = "Width:";
this.label10.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// label9
//
this.label9.Location = new System.Drawing.Point(122, 41);
this.label9.Name = "label9";
this.label9.Size = new System.Drawing.Size(67, 20);
this.label9.TabIndex = 17;
this.label9.Text = "Height:";
this.label9.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// btnRemoveElement
//
this.btnRemoveElement.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.btnRemoveElement.Location = new System.Drawing.Point(6, 301);
this.btnRemoveElement.Name = "btnRemoveElement";
this.btnRemoveElement.Size = new System.Drawing.Size(65, 20);
this.btnRemoveElement.TabIndex = 15;
this.btnRemoveElement.Text = "Remove";
this.btnRemoveElement.UseVisualStyleBackColor = true;
this.btnRemoveElement.Click += new System.EventHandler(this.btnRemoveElement_Click);
//
// numericCardSetHeight
//
this.numericCardSetHeight.Location = new System.Drawing.Point(195, 41);
this.numericCardSetHeight.Maximum = new decimal(new int[] {
65536,
0,
0,
0});
this.numericCardSetHeight.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.numericCardSetHeight.Name = "numericCardSetHeight";
this.numericCardSetHeight.Size = new System.Drawing.Size(56, 20);
this.numericCardSetHeight.TabIndex = 14;
this.numericCardSetHeight.Value = new decimal(new int[] {
1,
0,
0,
0});
this.numericCardSetHeight.ValueChanged += new System.EventHandler(this.HandleCardSetValueChange);
//
// numericCardSetWidth
//
this.numericCardSetWidth.Location = new System.Drawing.Point(54, 41);
this.numericCardSetWidth.Maximum = new decimal(new int[] {
65536,
0,
0,
0});
this.numericCardSetWidth.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.numericCardSetWidth.Name = "numericCardSetWidth";
this.numericCardSetWidth.Size = new System.Drawing.Size(56, 20);
this.numericCardSetWidth.TabIndex = 13;
this.numericCardSetWidth.Value = new decimal(new int[] {
1,
0,
0,
0});
this.numericCardSetWidth.ValueChanged += new System.EventHandler(this.HandleCardSetValueChange);
//
// btnAddElement
//
this.btnAddElement.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.btnAddElement.Location = new System.Drawing.Point(6, 279);
this.btnAddElement.Name = "btnAddElement";
this.btnAddElement.Size = new System.Drawing.Size(65, 20);
this.btnAddElement.TabIndex = 10;
this.btnAddElement.Text = "Add";
this.btnAddElement.UseVisualStyleBackColor = true;
this.btnAddElement.Click += new System.EventHandler(this.btnAddElement_Click);
//
// btnGenCards
//
this.btnGenCards.Location = new System.Drawing.Point(6, 19);
this.btnGenCards.Name = "btnGenCards";
this.btnGenCards.Size = new System.Drawing.Size(25, 20);
this.btnGenCards.TabIndex = 22;
this.btnGenCards.Text = "#";
this.btnGenCards.UseVisualStyleBackColor = true;
this.btnGenCards.Click += new System.EventHandler(this.btnGenCards_Click);
//
// numericCardIndex
//
this.numericCardIndex.Location = new System.Drawing.Point(93, 19);
this.numericCardIndex.Name = "numericCardIndex";
this.numericCardIndex.Size = new System.Drawing.Size(54, 20);
this.numericCardIndex.TabIndex = 21;
this.numericCardIndex.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this.numericCardIndex.UpDownAlign = System.Windows.Forms.LeftRightAlignment.Left;
this.numericCardIndex.Value = new decimal(new int[] {
1,
0,
0,
0});
this.numericCardIndex.ValueChanged += new System.EventHandler(this.numericCardIndex_ValueChanged);
//
// lblIndex
//
this.lblIndex.Location = new System.Drawing.Point(149, 19);
this.lblIndex.Name = "lblIndex";
this.lblIndex.Size = new System.Drawing.Size(54, 20);
this.lblIndex.TabIndex = 20;
this.lblIndex.Text = "/";
this.lblIndex.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// groupBoxCardCount
//
this.groupBoxCardCount.Controls.Add(this.label2);
this.groupBoxCardCount.Controls.Add(this.numericRowIndex);
this.groupBoxCardCount.Controls.Add(this.label1);
this.groupBoxCardCount.Controls.Add(this.btnGenCards);
this.groupBoxCardCount.Controls.Add(this.lblIndex);
this.groupBoxCardCount.Controls.Add(this.numericCardIndex);
this.groupBoxCardCount.Dock = System.Windows.Forms.DockStyle.Top;
this.groupBoxCardCount.Enabled = false;
this.groupBoxCardCount.Location = new System.Drawing.Point(0, 0);
this.groupBoxCardCount.Name = "groupBoxCardCount";
this.groupBoxCardCount.Size = new System.Drawing.Size(322, 46);
this.groupBoxCardCount.TabIndex = 23;
this.groupBoxCardCount.TabStop = false;
this.groupBoxCardCount.Text = "Card Count";
//
// label2
//
this.label2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.label2.Location = new System.Drawing.Point(209, 19);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(50, 21);
this.label2.TabIndex = 25;
this.label2.Text = "Row";
this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// numericRowIndex
//
this.numericRowIndex.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.numericRowIndex.Location = new System.Drawing.Point(262, 19);
this.numericRowIndex.Name = "numericRowIndex";
this.numericRowIndex.Size = new System.Drawing.Size(54, 20);
this.numericRowIndex.TabIndex = 24;
this.numericRowIndex.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this.numericRowIndex.UpDownAlign = System.Windows.Forms.LeftRightAlignment.Left;
this.numericRowIndex.Value = new decimal(new int[] {
1,
0,
0,
0});
this.numericRowIndex.ValueChanged += new System.EventHandler(this.numericRowIndex_ValueChanged);
//
// label1
//
this.label1.Location = new System.Drawing.Point(37, 19);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(50, 21);
this.label1.TabIndex = 23;
this.label1.Text = "Card:";
this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// MDILayoutControl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(322, 373);
this.Controls.Add(this.groupBoxCardSet);
this.Controls.Add(this.groupBoxCardCount);
this.MinimumSize = new System.Drawing.Size(330, 352);
this.Name = "MDILayoutControl";
this.ShowIcon = false;
this.Text = " Layout Control";
this.Load += new System.EventHandler(this.MDILayoutControl_Load);
this.groupBoxCardSet.ResumeLayout(false);
this.contextMenuElements.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.numericCardSetDPI)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericCardSetBuffer)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericCardSetHeight)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericCardSetWidth)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericCardIndex)).EndInit();
this.groupBoxCardCount.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.numericRowIndex)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.GroupBox groupBoxCardSet;
private System.Windows.Forms.Button btnGenCards;
private System.Windows.Forms.NumericUpDown numericCardIndex;
private System.Windows.Forms.Label lblIndex;
private System.Windows.Forms.CheckBox checkCardSetDrawBorder;
private System.Windows.Forms.NumericUpDown numericCardSetDPI;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.Button btnElementRename;
private System.Windows.Forms.Button btnElementUp;
private System.Windows.Forms.Button btnElementDown;
private System.Windows.Forms.NumericUpDown numericCardSetBuffer;
private System.Windows.Forms.Label label11;
private System.Windows.Forms.Button btnDuplicate;
private System.Windows.Forms.Label label10;
private System.Windows.Forms.Label label9;
private System.Windows.Forms.Button btnRemoveElement;
private System.Windows.Forms.NumericUpDown numericCardSetHeight;
private System.Windows.Forms.NumericUpDown numericCardSetWidth;
private System.Windows.Forms.Button btnAddElement;
private System.Windows.Forms.GroupBox groupBoxCardCount;
private System.Windows.Forms.ColumnHeader columnHeader1;
private System.Windows.Forms.ColumnHeader columnHeader2;
private Support.UI.ListViewDoubleBuffered listViewElements;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.ContextMenuStrip contextMenuElements;
private System.Windows.Forms.ToolStripMenuItem copyToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem pasteToolStripMenuItem;
private System.Windows.Forms.ColumnHeader columnHeader3;
private System.Windows.Forms.NumericUpDown numericRowIndex;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Button resizeBtn;
private System.Windows.Forms.Button btnScale;
private System.Windows.Forms.CheckBox checkLoadAllReferences;
private System.Windows.Forms.ToolStripMenuItem pasteSettingsToolStripMenuItem;
private System.Windows.Forms.Button btnConfigureSize;
private System.Windows.Forms.ToolStripMenuItem pasteReferenceToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem detachReferenceToolStripMenuItem;
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System.Collections.Generic;
using Aurora.Framework;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
namespace Aurora.Services.DataService
{
public class LocalProfileConnector : ConnectorBase, IProfileConnector
{
//We can use a cache because we are the only place that profiles will be served from
private readonly Dictionary<UUID, IUserProfileInfo> UserProfilesCache = new Dictionary<UUID, IUserProfileInfo>();
private IGenericData GD;
#region IProfileConnector Members
public void Initialize(IGenericData GenericData, IConfigSource source, IRegistryCore simBase,
string defaultConnectionString)
{
GD = GenericData;
if (source.Configs[Name] != null)
defaultConnectionString = source.Configs[Name].GetString("ConnectionString", defaultConnectionString);
GD.ConnectToDatabase(defaultConnectionString, "Agent",
source.Configs["AuroraConnectors"].GetBoolean("ValidateTables", true));
DataManager.DataManager.RegisterPlugin(Name + "Local", this);
if (source.Configs["AuroraConnectors"].GetString("ProfileConnector", "LocalConnector") == "LocalConnector")
{
DataManager.DataManager.RegisterPlugin(this);
}
Init(simBase, Name);
}
public string Name
{
get { return "IProfileConnector"; }
}
/// <summary>
/// Get a user's profile
/// </summary>
/// <param name = "agentID"></param>
/// <returns></returns>
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)]
public IUserProfileInfo GetUserProfile(UUID agentID)
{
object remoteValue = DoRemote(agentID);
if (remoteValue != null || m_doRemoteOnly)
return (IUserProfileInfo)remoteValue;
IUserProfileInfo UserProfile = new IUserProfileInfo();
//Try from the user profile first before getting from the DB
if (UserProfilesCache.TryGetValue(agentID, out UserProfile))
return UserProfile;
var connector = GetWhetherUserIsForeign(agentID);
if (connector != null)
return connector.GetUserProfile(agentID);
QueryFilter filter = new QueryFilter();
filter.andFilters["ID"] = agentID;
filter.andFilters["`Key`"] = "LLProfile";
List<string> query = null;
//Grab it from the almost generic interface
query = GD.Query(new[] { "Value" }, "userdata", filter, null, null, null);
if (query == null || query.Count == 0)
return null;
//Pull out the OSDmap
OSDMap profile = (OSDMap) OSDParser.DeserializeLLSDXml(query[0]);
UserProfile = new IUserProfileInfo();
UserProfile.FromOSD(profile);
//Add to the cache
UserProfilesCache[agentID] = UserProfile;
return UserProfile;
}
private IRemoteProfileConnector GetWhetherUserIsForeign(UUID agentID)
{
OpenSim.Services.Interfaces.IUserFinder userFinder = m_registry.RequestModuleInterface<OpenSim.Services.Interfaces.IUserFinder>();
if (userFinder != null && !userFinder.IsLocalGridUser(agentID))
{
string url = userFinder.GetUserServerURL(agentID, "ProfileServerURI");
IRemoteProfileConnector connector = Aurora.DataManager.DataManager.RequestPlugin<IRemoteProfileConnector>();
if (connector != null)
connector.Init(url, m_registry);
return connector;
}
return null;
}
/// <summary>
/// Update a user's profile (Note: this does not work if the user does not have a profile)
/// </summary>
/// <param name = "Profile"></param>
/// <returns></returns>
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)]
public bool UpdateUserProfile(IUserProfileInfo Profile)
{
object remoteValue = DoRemote(Profile);
if (remoteValue != null || m_doRemoteOnly)
return remoteValue != null && (bool)remoteValue;
IUserProfileInfo previousProfile = GetUserProfile(Profile.PrincipalID);
//Make sure the previous one exists
if (previousProfile == null)
return false;
//Now fix values that the sim cannot change
Profile.Partner = previousProfile.Partner;
Profile.CustomType = previousProfile.CustomType;
Profile.MembershipGroup = previousProfile.MembershipGroup;
Profile.Created = previousProfile.Created;
Dictionary<string, object> values = new Dictionary<string, object>(1);
values["Value"] = OSDParser.SerializeLLSDXmlString(Profile.ToOSD());
QueryFilter filter = new QueryFilter();
filter.andFilters["ID"] = Profile.PrincipalID.ToString();
filter.andFilters["`Key`"] = "LLProfile";
//Update cache
UserProfilesCache[Profile.PrincipalID] = Profile;
return GD.Update("userdata", values, null, filter, null, null);
}
/// <summary>
/// Create a new profile for a user
/// </summary>
/// <param name = "AgentID"></param>
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Full)]
public void CreateNewProfile(UUID AgentID)
{
object remoteValue = DoRemote(AgentID);
if (remoteValue != null || m_doRemoteOnly)
return;
List<object> values = new List<object> {AgentID.ToString(), "LLProfile"};
//Create a new basic profile for them
IUserProfileInfo profile = new IUserProfileInfo {PrincipalID = AgentID};
values.Add(OSDParser.SerializeLLSDXmlString(profile.ToOSD())); //Value which is a default Profile
GD.Insert("userdata", values.ToArray());
}
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)]
public bool AddClassified(Classified classified)
{
object remoteValue = DoRemote(classified);
if (remoteValue != null || m_doRemoteOnly)
return remoteValue != null && (bool)remoteValue;
if (GetUserProfile(classified.CreatorUUID) == null)
return false;
string keywords = classified.Description;
if (keywords.Length > 512)
keywords = keywords.Substring(keywords.Length - 512, 512);
//It might be updating, delete the old
QueryFilter filter = new QueryFilter();
filter.andFilters["ClassifiedUUID"] = classified.ClassifiedUUID;
GD.Delete("userclassifieds", filter);
List<object> values = new List<object>{
classified.Name,
classified.Category,
classified.SimName,
classified.CreatorUUID,
classified.ClassifiedUUID,
OSDParser.SerializeJsonString(classified.ToOSD()),
classified.ScopeID,
classified.PriceForListing,
keywords
};
return GD.Insert("userclassifieds", values.ToArray());
}
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)]
public List<Classified> GetClassifieds(UUID ownerID)
{
object remoteValue = DoRemote(ownerID);
if (remoteValue != null || m_doRemoteOnly)
return (List<Classified>)remoteValue;
var connector = GetWhetherUserIsForeign(ownerID);
if (connector != null)
return connector.GetClassifieds(ownerID);
QueryFilter filter = new QueryFilter();
filter.andFilters["OwnerUUID"] = ownerID;
List<string> query = GD.Query(new[] { "*" }, "userclassifieds", filter, null, null, null);
List<Classified> classifieds = new List<Classified>();
for (int i = 0; i < query.Count; i += 9)
{
Classified classified = new Classified();
classified.FromOSD((OSDMap) OSDParser.DeserializeJson(query[i + 5]));
classifieds.Add(classified);
}
return classifieds;
}
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)]
public Classified GetClassified(UUID queryClassifiedID)
{
object remoteValue = DoRemote(queryClassifiedID);
if (remoteValue != null || m_doRemoteOnly)
return (Classified)remoteValue;
QueryFilter filter = new QueryFilter();
filter.andFilters["ClassifiedUUID"] = queryClassifiedID;
List<string> query = GD.Query(new[] { "*" }, "userclassifieds", filter, null, null, null);
if (query.Count < 6)
{
return null;
}
Classified classified = new Classified();
classified.FromOSD((OSDMap) OSDParser.DeserializeJson(query[5]));
return classified;
}
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)]
public void RemoveClassified(UUID queryClassifiedID)
{
object remoteValue = DoRemote(queryClassifiedID);
if (remoteValue != null || m_doRemoteOnly)
return;
QueryFilter filter = new QueryFilter();
filter.andFilters["ClassifiedUUID"] = queryClassifiedID;
GD.Delete("userclassifieds", filter);
}
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)]
public bool AddPick(ProfilePickInfo pick)
{
object remoteValue = DoRemote(pick);
if (remoteValue != null || m_doRemoteOnly)
return remoteValue != null && (bool)remoteValue;
if (GetUserProfile(pick.CreatorUUID) == null)
return false;
//It might be updating, delete the old
QueryFilter filter = new QueryFilter();
filter.andFilters["PickUUID"] = pick.PickUUID;
GD.Delete("userpicks", filter);
List<object> values = new List<object>
{
pick.Name,
pick.SimName,
pick.CreatorUUID,
pick.PickUUID,
OSDParser.SerializeJsonString(pick.ToOSD())
};
return GD.Insert("userpicks", values.ToArray());
}
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)]
public ProfilePickInfo GetPick(UUID queryPickID)
{
object remoteValue = DoRemote(queryPickID);
if (remoteValue != null || m_doRemoteOnly)
return (ProfilePickInfo)remoteValue;
QueryFilter filter = new QueryFilter();
filter.andFilters["PickUUID"] = queryPickID;
List<string> query = GD.Query(new[] { "*" }, "userpicks", filter, null, null, null);
if (query.Count < 5)
return null;
ProfilePickInfo pick = new ProfilePickInfo();
pick.FromOSD((OSDMap) OSDParser.DeserializeJson(query[4]));
return pick;
}
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)]
public List<ProfilePickInfo> GetPicks(UUID ownerID)
{
object remoteValue = DoRemote(ownerID);
if (remoteValue != null || m_doRemoteOnly)
return (List<ProfilePickInfo>)remoteValue;
var connector = GetWhetherUserIsForeign(ownerID);
if (connector != null)
return connector.GetPicks(ownerID);
QueryFilter filter = new QueryFilter();
filter.andFilters["OwnerUUID"] = ownerID;
List<string> query = GD.Query(new[] { "*" }, "userpicks", filter, null, null, null);
List<ProfilePickInfo> picks = new List<ProfilePickInfo>();
for (int i = 0; i < query.Count; i += 5)
{
ProfilePickInfo pick = new ProfilePickInfo();
pick.FromOSD((OSDMap) OSDParser.DeserializeJson(query[i + 4]));
picks.Add(pick);
}
return picks;
}
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)]
public void RemovePick(UUID queryPickID)
{
object remoteValue = DoRemote(queryPickID);
if (remoteValue != null || m_doRemoteOnly)
return;
QueryFilter filter = new QueryFilter();
filter.andFilters["PickUUID"] = queryPickID;
GD.Delete("userpicks", filter);
}
#endregion
public void Dispose()
{
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
namespace Microsoft.PowerShell.Commands
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Management.Automation.Runspaces;
using Microsoft.PowerShell.Commands.Internal.Format;
/// <summary>
/// Enum for SelectionMode parameter.
/// </summary>
public enum OutputModeOption
{
/// <summary>
/// None is the default and it means OK and Cancel will not be present
/// and no objects will be written to the pipeline.
/// The selectionMode of the actual list will still be multiple.
/// </summary>
None,
/// <summary>
/// Allow selection of one single item to be written to the pipeline.
/// </summary>
Single,
/// <summary>
///Allow select of multiple items to be written to the pipeline.
/// </summary>
Multiple
}
/// <summary>
/// Implementation for the Out-GridView command.
/// </summary>
[Cmdlet(VerbsData.Out, "GridView", DefaultParameterSetName = "PassThru", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113364")]
public class OutGridViewCommand : PSCmdlet, IDisposable
{
#region Properties
private const string DataNotQualifiedForGridView = "DataNotQualifiedForGridView";
private const string RemotingNotSupported = "RemotingNotSupported";
private TypeInfoDataBase _typeInfoDataBase;
private PSPropertyExpressionFactory _expressionFactory;
private OutWindowProxy _windowProxy;
private GridHeader _gridHeader;
#endregion Properties
#region Constructors
/// <summary>
/// Constructor for OutGridView.
/// </summary>
public OutGridViewCommand()
{
}
#endregion Constructors
#region Input Parameters
/// <summary>
/// This parameter specifies the current pipeline object.
/// </summary>
[Parameter(ValueFromPipeline = true)]
public PSObject InputObject { get; set; } = AutomationNull.Value;
/// <summary>
/// Gets/sets the title of the Out-GridView window.
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
public string Title { get; set; }
/// <summary>
/// Get or sets a value indicating whether the cmdlet should wait for the window to be closed.
/// </summary>
[Parameter(ParameterSetName = "Wait")]
public SwitchParameter Wait { get; set; }
/// <summary>
/// Get or sets a value indicating whether the selected items should be written to the pipeline
/// and if it should be possible to select multiple or single list items.
/// </summary>
[Parameter(ParameterSetName = "OutputMode")]
public OutputModeOption OutputMode { set; get; }
/// <summary>
/// Gets or sets a value indicating whether the selected items should be written to the pipeline.
/// Setting this to true is the same as setting the OutputMode to Multiple.
/// </summary>
[Parameter(ParameterSetName = "PassThru")]
public SwitchParameter PassThru
{
set { this.OutputMode = value.IsPresent ? OutputModeOption.Multiple : OutputModeOption.None; }
get { return OutputMode == OutputModeOption.Multiple ? new SwitchParameter(true) : new SwitchParameter(false); }
}
#endregion Input Parameters
#region Public Methods
/// <summary>
/// Provides a one-time, pre-processing functionality for the cmdlet.
/// </summary>
protected override void BeginProcessing()
{
// Set up the ExpressionFactory
_expressionFactory = new PSPropertyExpressionFactory();
// If the value of the Title parameter is valid, use it as a window's title.
if (this.Title != null)
{
_windowProxy = new OutWindowProxy(this.Title, OutputMode, this);
}
else
{
// Using the command line as a title.
_windowProxy = new OutWindowProxy(this.MyInvocation.Line, OutputMode, this);
}
// Load the Type info database.
_typeInfoDataBase = this.Context.FormatDBManager.GetTypeInfoDataBase();
}
/// <summary>
/// Blocks depending on the wait and selected.
/// </summary>
protected override void EndProcessing()
{
base.EndProcessing();
if (_windowProxy == null)
{
return;
}
// If -Wait is used or outputMode is not None we have to wait for the window to be closed
// The pipeline will be blocked while we don't return
if (this.Wait || this.OutputMode != OutputModeOption.None)
{
_windowProxy.BlockUntillClosed();
}
// Output selected items to pipeline.
List<PSObject> selectedItems = _windowProxy.GetSelectedItems();
if (this.OutputMode != OutputModeOption.None && selectedItems != null)
{
foreach (PSObject selectedItem in selectedItems)
{
if (selectedItem == null)
{
continue;
}
PSPropertyInfo originalObjectProperty = selectedItem.Properties[OutWindowProxy.OriginalObjectPropertyName];
if (originalObjectProperty == null)
{
return;
}
this.WriteObject(originalObjectProperty.Value, false);
}
}
}
/// <summary>
/// Provides a record-by-record processing functionality for the cmdlet.
/// </summary>
protected override void ProcessRecord()
{
if (InputObject == null || InputObject == AutomationNull.Value)
{
return;
}
IDictionary dictionary = InputObject.BaseObject as IDictionary;
if (dictionary != null)
{
// Dictionaries should be enumerated through because the pipeline does not enumerate through them.
foreach (DictionaryEntry entry in dictionary)
{
ProcessObject(PSObjectHelper.AsPSObject(entry));
}
}
else
{
ProcessObject(InputObject);
}
}
/// <summary>
/// StopProcessing is called close the window when Ctrl+C in the command prompt.
/// </summary>
protected override void StopProcessing()
{
if (this.Wait || this.OutputMode != OutputModeOption.None)
{
_windowProxy.CloseWindow();
}
}
/// <summary>
/// Converts the provided PSObject to a string preserving PowerShell formatting.
/// </summary>
/// <param name="liveObject">PSObject to be converted to a string.</param>
internal string ConvertToString(PSObject liveObject)
{
StringFormatError formatErrorObject = new StringFormatError();
string smartToString = PSObjectHelper.SmartToString(liveObject,
_expressionFactory,
InnerFormatShapeCommand.FormatEnumerationLimit(),
formatErrorObject);
if (formatErrorObject.exception != null)
{
// There was a formatting error that should be sent to the console.
this.WriteError(
new ErrorRecord(
formatErrorObject.exception,
"ErrorFormattingType",
ErrorCategory.InvalidResult,
liveObject)
);
}
return smartToString;
}
#endregion Public Methods
#region Private Methods
/// <summary>
/// Execute formatting on a single object.
/// </summary>
/// <param name="input">Object to process.</param>
private void ProcessObject(PSObject input)
{
// Make sure the OGV window is not closed.
if (_windowProxy.IsWindowClosed())
{
LocalPipeline pipeline = (LocalPipeline)this.Context.CurrentRunspace.GetCurrentlyRunningPipeline();
if (pipeline != null && !pipeline.IsStopping)
{
// Stop the pipeline cleanly.
pipeline.StopAsync();
}
return;
}
object baseObject = input.BaseObject;
// Throw a terminating error for types that are not supported.
if (baseObject is ScriptBlock ||
baseObject is SwitchParameter ||
baseObject is PSReference ||
baseObject is FormatInfoData ||
baseObject is PSObject)
{
ErrorRecord error = new ErrorRecord(
new FormatException(StringUtil.Format(FormatAndOut_out_gridview.DataNotQualifiedForGridView)),
DataNotQualifiedForGridView,
ErrorCategory.InvalidType,
null);
this.ThrowTerminatingError(error);
}
if (_gridHeader == null)
{
// Columns have not been added yet; Start the main window and add columns.
_windowProxy.ShowWindow();
_gridHeader = GridHeader.ConstructGridHeader(input, this);
}
else
{
_gridHeader.ProcessInputObject(input);
}
// Some thread synchronization needed.
Exception exception = _windowProxy.GetLastException();
if (exception != null)
{
ErrorRecord error = new ErrorRecord(
exception,
"ManagementListInvocationException",
ErrorCategory.OperationStopped,
null);
this.ThrowTerminatingError(error);
}
}
#endregion Private Methods
internal abstract class GridHeader
{
protected OutGridViewCommand parentCmd;
internal GridHeader(OutGridViewCommand parentCmd)
{
this.parentCmd = parentCmd;
}
internal static GridHeader ConstructGridHeader(PSObject input, OutGridViewCommand parentCmd)
{
if (DefaultScalarTypes.IsTypeInList(input.TypeNames) ||
OutOfBandFormatViewManager.IsPropertyLessObject(input))
{
return new ScalarTypeHeader(parentCmd, input);
}
return new NonscalarTypeHeader(parentCmd, input);
}
internal abstract void ProcessInputObject(PSObject input);
}
internal class ScalarTypeHeader : GridHeader
{
private Type _originalScalarType;
internal ScalarTypeHeader(OutGridViewCommand parentCmd, PSObject input) : base(parentCmd)
{
_originalScalarType = input.BaseObject.GetType();
// On scalar types the type name is used as a column name.
this.parentCmd._windowProxy.AddColumnsAndItem(input);
}
internal override void ProcessInputObject(PSObject input)
{
if (!_originalScalarType.Equals(input.BaseObject.GetType()))
{
parentCmd._gridHeader = new HeteroTypeHeader(base.parentCmd, input);
}
else
{
// Columns are already added; Add the input PSObject as an item to the underlying Management List.
base.parentCmd._windowProxy.AddItem(input);
}
}
}
internal class NonscalarTypeHeader : GridHeader
{
private AppliesTo _appliesTo = null;
internal NonscalarTypeHeader(OutGridViewCommand parentCmd, PSObject input) : base(parentCmd)
{
// Prepare a table view.
TableView tableView = new TableView();
tableView.Initialize(parentCmd._expressionFactory, parentCmd._typeInfoDataBase);
// Request a view definition from the type database.
ViewDefinition viewDefinition = DisplayDataQuery.GetViewByShapeAndType(parentCmd._expressionFactory, parentCmd._typeInfoDataBase, FormatShape.Table, input.TypeNames, null);
if (viewDefinition != null)
{
// Create a header using a view definition provided by the types database.
parentCmd._windowProxy.AddColumnsAndItem(input, tableView, (TableControlBody)viewDefinition.mainControl);
// Remember all type names and type groups the current view applies to.
_appliesTo = viewDefinition.appliesTo;
}
else
{
// Create a header using only the input object's properties.
parentCmd._windowProxy.AddColumnsAndItem(input, tableView);
_appliesTo = new AppliesTo();
// Add all type names except for Object and MarshalByRefObject types because they are too generic.
// Leave the Object type name if it is the only type name.
int index = 0;
foreach (string typeName in input.TypeNames)
{
if (index > 0 && (typeName.Equals(typeof(Object).FullName, StringComparison.OrdinalIgnoreCase) ||
typeName.Equals(typeof(MarshalByRefObject).FullName, StringComparison.OrdinalIgnoreCase)))
{
break;
}
_appliesTo.AddAppliesToType(typeName);
index++;
}
}
}
internal override void ProcessInputObject(PSObject input)
{
// Find out if the input has matching types in the this.appliesTo collection.
foreach (TypeOrGroupReference typeOrGroupRef in _appliesTo.referenceList)
{
if (typeOrGroupRef is TypeReference)
{
// Add deserialization prefix.
string deserializedTypeName = typeOrGroupRef.name;
Deserializer.AddDeserializationPrefix(ref deserializedTypeName);
for (int i = 0; i < input.TypeNames.Count; i++)
{
if (typeOrGroupRef.name.Equals(input.TypeNames[i], StringComparison.OrdinalIgnoreCase)
|| deserializedTypeName.Equals(input.TypeNames[i], StringComparison.OrdinalIgnoreCase))
{
// Current view supports the input's Type;
// Add the input PSObject as an item to the underlying Management List.
base.parentCmd._windowProxy.AddItem(input);
return;
}
}
}
else
{
// Find out if the input's Type belongs to the current TypeGroup.
// TypeGroupReference has only a group's name, so use the database to get through all actual TypeGroup's.
List<TypeGroupDefinition> typeGroupList = base.parentCmd._typeInfoDataBase.typeGroupSection.typeGroupDefinitionList;
foreach (TypeGroupDefinition typeGroup in typeGroupList)
{
if (typeGroup.name.Equals(typeOrGroupRef.name, StringComparison.OrdinalIgnoreCase))
{
// A matching TypeGroup is found in the database.
// Find out if the input's Type belongs to this TypeGroup.
foreach (TypeReference typeRef in typeGroup.typeReferenceList)
{
// Add deserialization prefix.
string deserializedTypeName = typeRef.name;
Deserializer.AddDeserializationPrefix(ref deserializedTypeName);
if (input.TypeNames.Count > 0
&& (typeRef.name.Equals(input.TypeNames[0], StringComparison.OrdinalIgnoreCase)
|| deserializedTypeName.Equals(input.TypeNames[0], StringComparison.OrdinalIgnoreCase)))
{
// Current view supports the input's Type;
// Add the input PSObject as an item to the underlying Management List.
base.parentCmd._windowProxy.AddItem(input);
return;
}
}
}
}
}
}
// The input's Type is not supported by the current view;
// Switch to the Hetero Type view.
parentCmd._gridHeader = new HeteroTypeHeader(base.parentCmd, input);
}
}
internal class HeteroTypeHeader : GridHeader
{
internal HeteroTypeHeader(OutGridViewCommand parentCmd, PSObject input) : base(parentCmd)
{
// Clear all existed columns and add Type and Value columns.
this.parentCmd._windowProxy.AddHeteroViewColumnsAndItem(input);
}
internal override void ProcessInputObject(PSObject input)
{
this.parentCmd._windowProxy.AddHeteroViewItem(input);
}
}
/// <summary>
/// Implements IDisposable logic.
/// </summary>
/// <param name="isDisposing">True if being called from Dispose.</param>
private void Dispose(bool isDisposing)
{
if (isDisposing)
{
if (_windowProxy != null)
{
_windowProxy.Dispose();
_windowProxy = null;
}
}
}
/// <summary>
/// Dispose method in IDisposable.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Finalizer.
/// </summary>
~OutGridViewCommand()
{
Dispose(false);
}
}
}
| |
using System;
using System.Threading.Tasks;
using Abp.Authorization;
using Abp.Collections.Extensions;
using Abp.Runtime.Session;
using Abp.Threading;
namespace Abp.Application.Features
{
/// <summary>
/// Some extension methods for <see cref="IFeatureChecker"/>.
/// </summary>
public static class FeatureCheckerExtensions
{
/// <summary>
/// Gets value of a feature by it's name. This is sync version of <see cref="IFeatureChecker.GetValueAsync(string)"/>
///
/// This is a shortcut for <see cref="GetValue(IFeatureChecker, int, string)"/> that uses <see cref="IAbpSession.TenantId"/> as tenantId.
/// So, this method should be used only if TenantId can be obtained from the session.
/// </summary>
/// <param name="featureChecker"><see cref="IFeatureChecker"/> instance</param>
/// <param name="featureName">Unique feature name</param>
/// <returns>Feature's current value</returns>
public static string GetValue(this IFeatureChecker featureChecker, string featureName)
{
return AsyncHelper.RunSync(() => featureChecker.GetValueAsync(featureName));
}
/// <summary>
/// Gets value of a feature by it's name. This is sync version of <see cref="IFeatureChecker.GetValueAsync(int, string)"/>
/// </summary>
/// <param name="featureChecker"><see cref="IFeatureChecker"/> instance</param>
/// <param name="tenantId">Tenant's Id</param>
/// <param name="featureName">Unique feature name</param>
/// <returns>Feature's current value</returns>
public static string GetValue(this IFeatureChecker featureChecker, int tenantId, string featureName)
{
return AsyncHelper.RunSync(() => featureChecker.GetValueAsync(tenantId, featureName));
}
/// <summary>
/// Checks if given feature is enabled.
/// This should be used for boolean-value features.
///
/// This is a shortcut for <see cref="IsEnabledAsync(IFeatureChecker, int, string)"/> that uses <see cref="IAbpSession.TenantId"/> as tenantId.
/// So, this method should be used only if TenantId can be obtained from the session.
/// </summary>
/// <param name="featureChecker"><see cref="IFeatureChecker"/> instance</param>
/// <param name="featureName">Unique feature name</param>
/// <returns>True, if current feature's value is "true".</returns>
public static async Task<bool> IsEnabledAsync(this IFeatureChecker featureChecker, string featureName)
{
return string.Equals(await featureChecker.GetValueAsync(featureName), "true", StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Checks if given feature is enabled.
/// This should be used for boolean-value features.
/// </summary>
/// <param name="featureChecker"><see cref="IFeatureChecker"/> instance</param>
/// <param name="tenantId">Tenant's Id</param>
/// <param name="featureName">Unique feature name</param>
/// <returns>True, if current feature's value is "true".</returns>
public static async Task<bool> IsEnabledAsync(this IFeatureChecker featureChecker, int tenantId, string featureName)
{
return string.Equals(await featureChecker.GetValueAsync(tenantId, featureName), "true", StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Checks if given feature is enabled.
/// This should be used for boolean-value features.
///
/// This is a shortcut for <see cref="IsEnabled(IFeatureChecker, int, string)"/> that uses <see cref="IAbpSession.TenantId"/> as tenantId.
/// So, this method should be used only if TenantId can be obtained from the session.
/// </summary>
/// <param name="featureChecker"><see cref="IFeatureChecker"/> instance</param>
/// <param name="name">Unique feature name</param>
/// <returns>True, if current feature's value is "true".</returns>
public static bool IsEnabled(this IFeatureChecker featureChecker, string name)
{
return AsyncHelper.RunSync(() => featureChecker.IsEnabledAsync(name));
}
/// <summary>
/// Checks if given feature is enabled.
/// This should be used for boolean-value features.
/// </summary>
/// <param name="featureChecker"><see cref="IFeatureChecker"/> instance</param>
/// <param name="tenantId">Tenant's Id</param>
/// <param name="featureName">Unique feature name</param>
/// <returns>True, if current feature's value is "true".</returns>
public static bool IsEnabled(this IFeatureChecker featureChecker, int tenantId, string featureName)
{
return AsyncHelper.RunSync(() => featureChecker.IsEnabledAsync(tenantId, featureName));
}
/// <summary>
/// Used to check if one of all given features are enabled.
/// </summary>
/// <param name="featureChecker"><see cref="IFeatureChecker"/> instance</param>
/// <param name="requiresAll">True, to require all given features are enabled. False, to require one or more.</param>
/// <param name="featureNames">Name of the features</param>
public static async Task<bool> IsEnabledAsync(this IFeatureChecker featureChecker, bool requiresAll, params string[] featureNames)
{
if (featureNames.IsNullOrEmpty())
{
return true;
}
if (requiresAll)
{
foreach (var featureName in featureNames)
{
if (!(await featureChecker.IsEnabledAsync(featureName)))
{
return false;
}
}
return true;
}
else
{
foreach (var featureName in featureNames)
{
if (await featureChecker.IsEnabledAsync(featureName))
{
return true;
}
}
return false;
}
}
/// <summary>
/// Used to check if one of all given features are enabled.
/// </summary>
/// <param name="featureChecker"><see cref="IFeatureChecker"/> instance</param>
/// <param name="tenantId">Tenant id</param>
/// <param name="requiresAll">True, to require all given features are enabled. False, to require one or more.</param>
/// <param name="featureNames">Name of the features</param>
public static async Task<bool> IsEnabledAsync(this IFeatureChecker featureChecker, int tenantId, bool requiresAll, params string[] featureNames)
{
if (featureNames.IsNullOrEmpty())
{
return true;
}
if (requiresAll)
{
foreach (var featureName in featureNames)
{
if (!(await featureChecker.IsEnabledAsync(tenantId, featureName)))
{
return false;
}
}
return true;
}
else
{
foreach (var featureName in featureNames)
{
if (await featureChecker.IsEnabledAsync(tenantId, featureName))
{
return true;
}
}
return false;
}
}
/// <summary>
/// Used to check if one of all given features are enabled.
/// </summary>
/// <param name="featureChecker"><see cref="IFeatureChecker"/> instance</param>
/// <param name="requiresAll">True, to require all given features are enabled. False, to require one or more.</param>
/// <param name="featureNames">Name of the features</param>
public static bool IsEnabled(this IFeatureChecker featureChecker, bool requiresAll, params string[] featureNames)
{
return AsyncHelper.RunSync(() => featureChecker.IsEnabledAsync(requiresAll, featureNames));
}
/// <summary>
/// Used to check if one of all given features are enabled.
/// </summary>
/// <param name="featureChecker"><see cref="IFeatureChecker"/> instance</param>
/// <param name="tenantId">Tenant id</param>
/// <param name="requiresAll">True, to require all given features are enabled. False, to require one or more.</param>
/// <param name="featureNames">Name of the features</param>
public static bool IsEnabled(this IFeatureChecker featureChecker, int tenantId, bool requiresAll, params string[] featureNames)
{
return AsyncHelper.RunSync(() => featureChecker.IsEnabledAsync(tenantId, requiresAll, featureNames));
}
/// <summary>
/// Checks if given feature is enabled. Throws <see cref="AbpAuthorizationException"/> if not.
/// </summary>
/// <param name="featureChecker"><see cref="IFeatureChecker"/> instance</param>
/// <param name="featureName">Unique feature name</param>
public static async Task CheckEnabledAsync(this IFeatureChecker featureChecker, string featureName)
{
if (!(await featureChecker.IsEnabledAsync(featureName)))
{
throw new AbpAuthorizationException("Feature is not enabled: " + featureName);
}
}
/// <summary>
/// Checks if given feature is enabled. Throws <see cref="AbpAuthorizationException"/> if not.
/// </summary>
/// <param name="featureChecker"><see cref="IFeatureChecker"/> instance</param>
/// <param name="featureName">Unique feature name</param>
public static void CheckEnabled(this IFeatureChecker featureChecker, string featureName)
{
if (!featureChecker.IsEnabled(featureName))
{
throw new AbpAuthorizationException("Feature is not enabled: " + featureName);
}
}
/// <summary>
/// Checks if one of all given features are enabled. Throws <see cref="AbpAuthorizationException"/> if not.
/// </summary>
/// <param name="featureChecker"><see cref="IFeatureChecker"/> instance</param>
/// <param name="requiresAll">True, to require all given features are enabled. False, to require one or more.</param>
/// <param name="featureNames">Name of the features</param>
public static async Task CheckEnabledAsync(this IFeatureChecker featureChecker, bool requiresAll, params string[] featureNames)
{
if (featureNames.IsNullOrEmpty())
{
return;
}
if (requiresAll)
{
foreach (var featureName in featureNames)
{
if (!(await featureChecker.IsEnabledAsync(featureName)))
{
throw new AbpAuthorizationException(
"Required features are not enabled. All of these features must be enabled: " +
string.Join(", ", featureNames)
);
}
}
}
else
{
foreach (var featureName in featureNames)
{
if (await featureChecker.IsEnabledAsync(featureName))
{
return;
}
}
throw new AbpAuthorizationException(
"Required features are not enabled. At least one of these features must be enabled: " +
string.Join(", ", featureNames)
);
}
}
/// <summary>
/// Checks if one of all given features are enabled. Throws <see cref="AbpAuthorizationException"/> if not.
/// </summary>
/// <param name="featureChecker"><see cref="IFeatureChecker"/> instance</param>
/// <param name="tenantId">Tenant id</param>
/// <param name="requiresAll">True, to require all given features are enabled. False, to require one or more.</param>
/// <param name="featureNames">Name of the features</param>
public static async Task CheckEnabledAsync(this IFeatureChecker featureChecker, int tenantId, bool requiresAll, params string[] featureNames)
{
if (featureNames.IsNullOrEmpty())
{
return;
}
if (requiresAll)
{
foreach (var featureName in featureNames)
{
if (!(await featureChecker.IsEnabledAsync(tenantId, featureName)))
{
throw new AbpAuthorizationException(
"Required features are not enabled. All of these features must be enabled: " +
string.Join(", ", featureNames)
);
}
}
}
else
{
foreach (var featureName in featureNames)
{
if (await featureChecker.IsEnabledAsync(tenantId, featureName))
{
return;
}
}
throw new AbpAuthorizationException(
"Required features are not enabled. At least one of these features must be enabled: " +
string.Join(", ", featureNames)
);
}
}
/// <summary>
/// Checks if one of all given features are enabled. Throws <see cref="AbpAuthorizationException"/> if not.
/// </summary>
/// <param name="featureChecker"><see cref="IFeatureChecker"/> instance</param>
/// <param name="requiresAll">True, to require all given features are enabled. False, to require one or more.</param>
/// <param name="featureNames">Name of the features</param>
public static void CheckEnabled(this IFeatureChecker featureChecker, bool requiresAll, params string[] featureNames)
{
AsyncHelper.RunSync(() => featureChecker.CheckEnabledAsync(requiresAll, featureNames));
}
/// <summary>
/// Checks if one of all given features are enabled. Throws <see cref="AbpAuthorizationException"/> if not.
/// </summary>
/// <param name="featureChecker"><see cref="IFeatureChecker"/> instance</param>
/// <param name="tenantId">Tenant id</param>
/// <param name="requiresAll">True, to require all given features are enabled. False, to require one or more.</param>
/// <param name="featureNames">Name of the features</param>
public static void CheckEnabled(this IFeatureChecker featureChecker, int tenantId, bool requiresAll, params string[] featureNames)
{
AsyncHelper.RunSync(() => featureChecker.CheckEnabledAsync(tenantId, requiresAll, featureNames));
}
}
}
| |
// ReSharper disable All
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Frapid.ApplicationState.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Frapid.WebsiteBuilder.DataAccess;
using Frapid.WebsiteBuilder.Api.Fakes;
using Frapid.DataAccess;
using Frapid.DataAccess.Models;
using Xunit;
namespace Frapid.WebsiteBuilder.Api.Tests
{
public class MenuItemTests
{
public static MenuItemController Fixture()
{
MenuItemController controller = new MenuItemController(new MenuItemRepository(), "", new LoginView());
return controller;
}
[Fact]
[Conditional("Debug")]
public void CountEntityColumns()
{
EntityView entityView = Fixture().GetEntityView();
Assert.Null(entityView.Columns);
}
[Fact]
[Conditional("Debug")]
public void Count()
{
long count = Fixture().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetAll()
{
int count = Fixture().GetAll().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void Export()
{
int count = Fixture().Export().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void Get()
{
Frapid.WebsiteBuilder.Entities.MenuItem menuItem = Fixture().Get(0);
Assert.NotNull(menuItem);
}
[Fact]
[Conditional("Debug")]
public void First()
{
Frapid.WebsiteBuilder.Entities.MenuItem menuItem = Fixture().GetFirst();
Assert.NotNull(menuItem);
}
[Fact]
[Conditional("Debug")]
public void Previous()
{
Frapid.WebsiteBuilder.Entities.MenuItem menuItem = Fixture().GetPrevious(0);
Assert.NotNull(menuItem);
}
[Fact]
[Conditional("Debug")]
public void Next()
{
Frapid.WebsiteBuilder.Entities.MenuItem menuItem = Fixture().GetNext(0);
Assert.NotNull(menuItem);
}
[Fact]
[Conditional("Debug")]
public void Last()
{
Frapid.WebsiteBuilder.Entities.MenuItem menuItem = Fixture().GetLast();
Assert.NotNull(menuItem);
}
[Fact]
[Conditional("Debug")]
public void GetMultiple()
{
IEnumerable<Frapid.WebsiteBuilder.Entities.MenuItem> menuItems = Fixture().Get(new int[] { });
Assert.NotNull(menuItems);
}
[Fact]
[Conditional("Debug")]
public void GetPaginatedResult()
{
int count = Fixture().GetPaginatedResult().Count();
Assert.Equal(1, count);
count = Fixture().GetPaginatedResult(1).Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void CountWhere()
{
long count = Fixture().CountWhere(new JArray());
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetWhere()
{
int count = Fixture().GetWhere(1, new JArray()).Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void CountFiltered()
{
long count = Fixture().CountFiltered("");
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetFiltered()
{
int count = Fixture().GetFiltered(1, "").Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetDisplayFields()
{
int count = Fixture().GetDisplayFields().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetCustomFields()
{
int count = Fixture().GetCustomFields().Count();
Assert.Equal(1, count);
count = Fixture().GetCustomFields("").Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void AddOrEdit()
{
try
{
var form = new JArray { null, null };
Fixture().AddOrEdit(form);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode);
}
}
[Fact]
[Conditional("Debug")]
public void Add()
{
try
{
Fixture().Add(null);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode);
}
}
[Fact]
[Conditional("Debug")]
public void Edit()
{
try
{
Fixture().Edit(0, null);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode);
}
}
[Fact]
[Conditional("Debug")]
public void BulkImport()
{
var collection = new JArray { null, null, null, null };
var actual = Fixture().BulkImport(collection);
Assert.NotNull(actual);
}
[Fact]
[Conditional("Debug")]
public void Delete()
{
try
{
Fixture().Delete(0);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.InternalServerError, ex.Response.StatusCode);
}
}
}
}
| |
using System;
using Microsoft.Xna.Framework;
// Advanced Camera2D implementation
// Thanks to: http://blog.roboblob.com/2013/07/27/solving-resolution-independent-rendering-and-2d-camera-using-monogame/
// Modified and enhanced by PantheR (http://www.panthernet.ru)
// Simple usage:
// 1. Create camera
// 2. Call Camera2D.Update() method in your update method
// 3. Provide Camera2D.GetViewTransformationMatrix() to all nedded SpriteBatch.Begin() calls to draw using camera
// 4. Setup camera input that deals with such props as Zoom and Position
namespace Examples.Classes
{
public class Camera2D: IDisposable
{
#region Variables
private float _zoom;
private float _rotation;
private Vector2 _position;
private Matrix _transform = Matrix.Identity;
private bool _isViewTransformationDirty = true;
private Matrix _camTranslationMatrix = Matrix.Identity;
private Matrix _camRotationMatrix = Matrix.Identity;
private Matrix _camScaleMatrix = Matrix.Identity;
private Matrix _resTranslationMatrix = Matrix.Identity;
protected ResolutionRenderer Irr;
private Vector3 _camTranslationVector = Vector3.Zero;
private Vector3 _camScaleVector = Vector3.Zero;
private Vector3 _resTranslationVector = Vector3.Zero;
/// <summary>
/// Current camera position
/// </summary>
public Vector2 Position
{
get { return _position; }
set
{
_position = value;
_isViewTransformationDirty = true;
}
}
/// <summary>
/// Minimum zoom value (can be no less than 0.1f)
/// </summary>
public float MinZoom { get; set; }
/// <summary>
/// Maximum zoom value
/// </summary>
public float MaxZoom { get; set; }
/// <summary>
/// Gets or sets camera zoom value
/// </summary>
public float Zoom
{
get { return _zoom; }
set
{
_zoom = value;
if (_zoom < 0.1f)
_zoom = 0.1f;
if (_zoom < MinZoom) _zoom = MinZoom;
if (_zoom > MaxZoom) _zoom = MaxZoom;
_isViewTransformationDirty = true;
}
}
/// <summary>
/// Gets or sets camera rotation value
/// </summary>
public float Rotation
{
get
{
return _rotation;
}
set
{
_rotation = value;
_isViewTransformationDirty = true;
}
}
#endregion
public Camera2D(ResolutionRenderer irr)
{
Irr = irr;
_zoom = 0.1f;
_rotation = 0.0f;
_position = Vector2.Zero;
MinZoom = 0.1f;
MaxZoom = 999f;
}
/// <summary>
/// Center camera and fit the area of specified rectangle
/// </summary>
/// <param name="rec">Rectange</param>
public void CenterOnTarget(Rectangle rec)
{
Position = new Vector2(rec.Center.X, rec.Center.Y);
var fat1 = Irr.VirtualWidth / (float)Irr.VirtualHeight;
var fat2 = rec.Width / (float)rec.Height;
float ratio;
if (fat2 >= fat1) ratio = Irr.VirtualWidth / (float)rec.Width;
else ratio = Irr.VirtualHeight / (float)rec.Height;
Zoom = ratio;
}
/// <summary>
/// Move camera by specified vector
/// </summary>
/// <param name="amount">Vector movement</param>
public void Move(Vector2 amount)
{
Position += amount;
}
/// <summary>
/// Set camera position
/// </summary>
/// <param name="position">Position</param>
public void SetPosition(Vector2 position)
{
Position = position;
}
/// <summary>
/// Get camera transformation matrix
/// </summary>
public Matrix GetViewTransformationMatrix()
{
if (_isViewTransformationDirty)
{
_camTranslationVector.X = -_position.X;
_camTranslationVector.Y = -_position.Y;
Matrix.CreateTranslation(ref _camTranslationVector, out _camTranslationMatrix);
Matrix.CreateRotationZ(_rotation, out _camRotationMatrix);
_camScaleVector.X = _zoom;
_camScaleVector.Y = _zoom;
_camScaleVector.Z = 1;
Matrix.CreateScale(ref _camScaleVector, out _camScaleMatrix);
_resTranslationVector.X = Irr.VirtualWidth * 0.5f;
_resTranslationVector.Y = Irr.VirtualHeight * 0.5f;
_resTranslationVector.Z = 0;
Matrix.CreateTranslation(ref _resTranslationVector, out _resTranslationMatrix);
_transform = _camTranslationMatrix *
_camRotationMatrix *
_camScaleMatrix *
_resTranslationMatrix *
Irr.GetTransformationMatrix();
_isViewTransformationDirty = false;
}
return _transform;
}
public void RecalculateTransformationMatrices()
{
_isViewTransformationDirty = true;
}
/// <summary>
/// Convert screen coordinates to virtual
/// </summary>
/// <param name="coord">Coordinates</param>
/// <param name="useIrr"></param>
public Vector2 ToVirtual(Vector2 coord, bool useIrr = true)
{
if (useIrr) coord = coord - new Vector2(Irr.Viewport.X, Irr.Viewport.Y);
return Vector2.Transform(coord, Matrix.Invert(GetViewTransformationMatrix()));
}
/// <summary>
/// Convert virtual coordinates to screen
/// </summary>
/// <param name="coord">Coordinates</param>
public Vector2 ToDisplay(Vector2 coord)
{
return Vector2.Transform(coord, GetViewTransformationMatrix());
}
public void Dispose()
{
Irr = null;
}
#region SmoothTransition Logic
private int _trDuration;
public bool IsTransitionActive { get; private set; }
private float _trElapsedTime;
private Vector2 _trTargetPosition;
/// <summary>
/// Start camera transition to specified position
/// </summary>
/// <param name="targetPos">Target position</param>
/// <param name="duration">Expected transition duration</param>
public void StartTransition(Vector2 targetPos, int duration = 5000)
{
if (IsTransitionActive)
ResetTransition();
_trTargetPosition = targetPos;
IsTransitionActive = true;
_trDuration = duration;
}
/// <summary>
/// Start camera transition to specified position
/// </summary>
/// <param name="targetPos">Target position</param>
/// <param name="duration">Expected transition duration</param>
public void StartTransition(Point targetPos, int duration = 5000)
{
StartTransition(new Vector2(targetPos.X, targetPos.Y), duration);
}
/// <summary>
/// Update transition target position without cancelling current transition
/// </summary>
/// <param name="targetPos">Target position</param>
public void UpdateTransitionTarget(Vector2 targetPos)
{
_trTargetPosition = targetPos;
}
/// <summary>
/// Update transition target position without cancelling current transition
/// </summary>
/// <param name="targetPos">Target position</param>
public void UpdateTransitionTarget(Point targetPos)
{
_trTargetPosition = new Vector2(targetPos.X, targetPos.Y);
}
/// <summary>
/// Stop and reset transition
/// </summary>
public void StopTransition()
{
ResetTransition();
IsTransitionActive = false;
}
/// <summary>
/// Reset current transition
/// </summary>
public void ResetTransition()
{
_trElapsedTime = 0f;
}
private void UpdateTransition(GameTime gt)
{
_trElapsedTime += (float)gt.ElapsedGameTime.TotalMilliseconds;
var amount = MathHelper.Clamp(_trElapsedTime / _trDuration, 0, 1);
Vector2 result;
Vector2 cpos = Position;
Vector2.Lerp(ref cpos, ref _trTargetPosition, amount, out result);
SetPosition(result);
if (amount >= 1f)
StopTransition();
}
#endregion
/// <summary>
/// Update logic (must be called within main update method)
/// </summary>
/// <param name="gt">Game time</param>
public void Update(GameTime gt)
{
if(IsTransitionActive)
UpdateTransition(gt);
}
}
}
| |
// 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.Net.NetworkInformation;
using System.Net.Sockets;
using Xunit;
namespace System.Net.Tests
{
public class WebProxyTest
{
public static IEnumerable<object[]> Ctor_ExpectedPropertyValues_MemberData()
{
yield return new object[] { new WebProxy(), null, false, false, Array.Empty<string>(), null };
yield return new object[] { new WebProxy("http://anything"), new Uri("http://anything"), false, false, Array.Empty<string>(), null };
yield return new object[] { new WebProxy("anything", 42), new Uri("http://anything:42"), false, false, Array.Empty<string>(), null };
yield return new object[] { new WebProxy(new Uri("http://anything")), new Uri("http://anything"), false, false, Array.Empty<string>(), null };
yield return new object[] { new WebProxy("http://anything", true), new Uri("http://anything"), false, true, Array.Empty<string>(), null };
yield return new object[] { new WebProxy(new Uri("http://anything"), true), new Uri("http://anything"), false, true, Array.Empty<string>(), null };
yield return new object[] { new WebProxy("http://anything.com", true, new[] { ".*.com" }), new Uri("http://anything.com"), false, true, new[] { ".*.com" }, null };
yield return new object[] { new WebProxy(new Uri("http://anything.com"), true, new[] { ".*.com" }), new Uri("http://anything.com"), false, true, new[] { ".*.com" }, null };
var c = new DummyCredentials();
yield return new object[] { new WebProxy("http://anything.com", true, new[] { ".*.com" }, c), new Uri("http://anything.com"), false, true, new[] { ".*.com" }, c };
yield return new object[] { new WebProxy(new Uri("http://anything.com"), true, new[] { ".*.com" }, c), new Uri("http://anything.com"), false, true, new[] { ".*.com" }, c };
}
[Theory]
[MemberData(nameof(Ctor_ExpectedPropertyValues_MemberData))]
public static void WebProxy_Ctor_ExpectedPropertyValues(
WebProxy p, Uri address, bool useDefaultCredentials, bool bypassLocal, string[] bypassedAddresses, ICredentials creds)
{
Assert.Equal(address, p.Address);
Assert.Equal(useDefaultCredentials, p.UseDefaultCredentials);
Assert.Equal(bypassLocal, p.BypassProxyOnLocal);
Assert.Equal(bypassedAddresses, p.BypassList);
Assert.Equal(bypassedAddresses, (string[])p.BypassArrayList.ToArray(typeof(string)));
Assert.Equal(creds, p.Credentials);
}
[Fact]
public static void WebProxy_BypassList_Roundtrip()
{
var p = new WebProxy();
Assert.Empty(p.BypassList);
Assert.Empty(p.BypassArrayList);
string[] strings;
strings = new string[] { "hello", "world" };
p.BypassList = strings;
Assert.Equal(strings, p.BypassList);
Assert.Equal(strings, (string[])p.BypassArrayList.ToArray(typeof(string)));
strings = new string[] { "hello" };
p.BypassList = strings;
Assert.Equal(strings, p.BypassList);
Assert.Equal(strings, (string[])p.BypassArrayList.ToArray(typeof(string)));
}
[Fact]
public static void WebProxy_UseDefaultCredentials_Roundtrip()
{
var p = new WebProxy();
Assert.False(p.UseDefaultCredentials);
Assert.Null(p.Credentials);
p.UseDefaultCredentials = true;
Assert.True(p.UseDefaultCredentials);
Assert.NotNull(p.Credentials);
p.UseDefaultCredentials = false;
Assert.False(p.UseDefaultCredentials);
Assert.Null(p.Credentials);
}
[Fact]
public static void WebProxy_BypassProxyOnLocal_Roundtrip()
{
var p = new WebProxy();
Assert.False(p.BypassProxyOnLocal);
p.BypassProxyOnLocal = true;
Assert.True(p.BypassProxyOnLocal);
p.BypassProxyOnLocal = false;
Assert.False(p.BypassProxyOnLocal);
}
[Fact]
public static void WebProxy_Address_Roundtrip()
{
var p = new WebProxy();
Assert.Null(p.Address);
p.Address = new Uri("http://hello");
Assert.Equal(new Uri("http://hello"), p.Address);
p.Address = null;
Assert.Null(p.Address);
}
[Fact]
public static void WebProxy_InvalidArgs_Throws()
{
var p = new WebProxy();
AssertExtensions.Throws<ArgumentNullException>("destination", () => p.GetProxy(null));
AssertExtensions.Throws<ArgumentNullException>("host", () => p.IsBypassed(null));
AssertExtensions.Throws<ArgumentNullException>("c", () => p.BypassList = null);
AssertExtensions.Throws<ArgumentException>(null, () => p.BypassList = new string[] { "*.com" });
}
[Fact]
public static void WebProxy_InvalidBypassUrl_AddedDirectlyToList_SilentlyEaten()
{
var p = new WebProxy("http://bing.com");
p.BypassArrayList.Add("*.com");
p.IsBypassed(new Uri("http://microsoft.com")); // exception should be silently eaten
}
[Fact]
public static void WebProxy_BypassList_DoesntContainUrl_NotBypassed()
{
var p = new WebProxy("http://microsoft.com");
Assert.Equal(new Uri("http://microsoft.com"), p.GetProxy(new Uri("http://bing.com")));
}
[Fact]
public static void WebProxy_BypassList_ContainsUrl_IsBypassed()
{
var p = new WebProxy("http://microsoft.com", false, new[] { "hello", "bing.*", "world" });
Assert.Equal(new Uri("http://bing.com"), p.GetProxy(new Uri("http://bing.com")));
}
public static IEnumerable<object[]> BypassOnLocal_MemberData()
{
// Local
yield return new object[] { new Uri($"http://nodotinhostname"), true };
yield return new object[] { new Uri($"http://{Guid.NewGuid().ToString("N")}"), true };
foreach (IPAddress address in Dns.GetHostEntryAsync(Dns.GetHostName()).GetAwaiter().GetResult().AddressList)
{
if (address.AddressFamily == AddressFamily.InterNetwork)
{
Uri uri;
try { uri = new Uri($"http://{address}"); }
catch (UriFormatException) { continue; }
yield return new object[] { uri, true };
}
}
string domain = IPGlobalProperties.GetIPGlobalProperties().DomainName;
if (!string.IsNullOrWhiteSpace(domain))
{
Uri uri = null;
try { uri = new Uri($"http://{Guid.NewGuid().ToString("N")}.{domain}"); }
catch (UriFormatException) { }
if (uri != null)
{
yield return new object[] { uri, true };
}
}
// Non-local
yield return new object[] { new Uri($"http://{Guid.NewGuid().ToString("N")}.com"), false };
yield return new object[] { new Uri($"http://{IPAddress.None}"), false };
}
[Theory]
[MemberData(nameof(BypassOnLocal_MemberData))]
public static void WebProxy_BypassOnLocal_MatchesExpected(Uri destination, bool isLocal)
{
Uri proxyUri = new Uri("http://microsoft.com");
Assert.Equal(isLocal, new WebProxy(proxyUri, true).IsBypassed(destination));
Assert.False(new WebProxy(proxyUri, false).IsBypassed(destination));
Assert.Equal(isLocal ? destination : proxyUri, new WebProxy(proxyUri, true).GetProxy(destination));
Assert.Equal(proxyUri, new WebProxy(proxyUri, false).GetProxy(destination));
}
[Fact]
public static void WebProxy_BypassOnLocal_SpecialCases()
{
Assert.True(new WebProxy().IsBypassed(new Uri("http://anything.com")));
Assert.True(new WebProxy((string)null).IsBypassed(new Uri("http://anything.com")));
Assert.True(new WebProxy((Uri)null).IsBypassed(new Uri("http://anything.com")));
Assert.True(new WebProxy("microsoft", true).IsBypassed(new Uri($"http://{IPAddress.Loopback}")));
Assert.True(new WebProxy("microsoft", false).IsBypassed(new Uri($"http://{IPAddress.Loopback}")));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public static void WebProxy_GetDefaultProxy_NotSupported()
{
#pragma warning disable 0618 // obsolete method
Assert.Throws<PlatformNotSupportedException>(() => WebProxy.GetDefaultProxy());
#pragma warning restore 0618
}
private class DummyCredentials : ICredentials
{
public NetworkCredential GetCredential(Uri uri, string authType) => null;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace Northwind.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);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.IO.PortsTests;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Legacy.Support;
using Xunit;
namespace System.IO.Ports.Tests
{
public class ReadChar : PortsTest
{
//The number of random bytes to receive for large input buffer testing
// This was 4096, but the largest buffer setting on FTDI USB-Serial devices is "4096", which actually only allows a read of 4094 or 4095 bytes
// The test code assumes that we will be able to do this transfer as a single read, so 4000 is safer and would seem to be about
// as rigourous a test
private const int largeNumRndBytesToRead = 4000;
//The number of random characters to receive
private const int numRndChar = 8;
private enum ReadDataFromEnum { NonBuffered, Buffered, BufferedAndNonBuffered };
#region Test Cases
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void ASCIIEncoding()
{
Debug.WriteLine("Verifying read with bytes encoded with ASCIIEncoding");
VerifyRead(new ASCIIEncoding());
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void UTF8Encoding()
{
Debug.WriteLine("Verifying read with bytes encoded with UTF8Encoding");
VerifyRead(new UTF8Encoding());
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void UTF32Encoding()
{
Debug.WriteLine("Verifying read with bytes encoded with UTF32Encoding");
VerifyRead(new UTF32Encoding());
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void SerialPort_ReadBufferedData()
{
VerifyRead(Encoding.ASCII, ReadDataFromEnum.Buffered);
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void SerialPort_IterativeReadBufferedData()
{
VerifyRead(Encoding.ASCII, ReadDataFromEnum.Buffered);
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void SerialPort_ReadBufferedAndNonBufferedData()
{
VerifyRead(Encoding.ASCII, ReadDataFromEnum.BufferedAndNonBuffered);
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void SerialPort_IterativeReadBufferedAndNonBufferedData()
{
VerifyRead(Encoding.ASCII, ReadDataFromEnum.BufferedAndNonBuffered);
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void ReadTimeout_Zero_ResizeBuffer()
{
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
byte[] byteXmitBuffer = new byte[1024];
char utf32Char = 'A';
byte[] utf32CharBytes = Encoding.UTF32.GetBytes(new[] { utf32Char });
char[] charXmitBuffer = TCSupport.GetRandomChars(16, false);
char[] expectedChars = new char[charXmitBuffer.Length + 1];
Debug.WriteLine("Verifying Read method with zero timeout that resizes SerialPort's buffer");
expectedChars[0] = utf32Char;
Array.Copy(charXmitBuffer, 0, expectedChars, 1, charXmitBuffer.Length);
//Put the first byte of the utf32 encoder char in the last byte of this buffer
//when we read this later the buffer will have to be resized
byteXmitBuffer[byteXmitBuffer.Length - 1] = utf32CharBytes[0];
com1.ReadTimeout = 0;
com1.Open();
if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
com2.Open();
com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length);
TCSupport.WaitForReadBufferToLoad(com1, byteXmitBuffer.Length);
//Read Every Byte except the last one. The last bye should be left in the last position of SerialPort's
//internal buffer. When we try to read this char as UTF32 the buffer should have to be resized so
//the other 3 bytes of the ut32 encoded char can be in the buffer
com1.Read(new char[1023], 0, 1023);
Assert.Equal(1, com1.BytesToRead);
com1.Encoding = Encoding.UTF32;
byteXmitBuffer = Encoding.UTF32.GetBytes(charXmitBuffer);
Assert.Throws<TimeoutException>(() => com1.ReadChar());
Assert.Equal(1, com1.BytesToRead);
com2.Write(utf32CharBytes, 1, 3);
com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length);
TCSupport.WaitForReadBufferToLoad(com1, 4 + byteXmitBuffer.Length);
PerformReadOnCom1FromCom2(com1, com2, expectedChars);
}
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void ReadTimeout_NonZero_ResizeBuffer()
{
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
byte[] byteXmitBuffer = new byte[1024];
char utf32Char = 'A';
byte[] utf32CharBytes = Encoding.UTF32.GetBytes(new[] { utf32Char });
char[] charXmitBuffer = TCSupport.GetRandomChars(16, false);
char[] expectedChars = new char[charXmitBuffer.Length + 1];
Debug.WriteLine("Verifying Read method with non zero timeout that resizes SerialPort's buffer");
expectedChars[0] = utf32Char;
Array.Copy(charXmitBuffer, 0, expectedChars, 1, charXmitBuffer.Length);
//Put the first byte of the utf32 encoder char in the last byte of this buffer
//when we read this later the buffer will have to be resized
byteXmitBuffer[byteXmitBuffer.Length - 1] = utf32CharBytes[0];
com1.ReadTimeout = 500;
com1.Open();
if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
com2.Open();
com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length);
TCSupport.WaitForReadBufferToLoad(com1, byteXmitBuffer.Length);
//Read Every Byte except the last one. The last bye should be left in the last position of SerialPort's
//internal buffer. When we try to read this char as UTF32 the buffer should have to be resized so
//the other 3 bytes of the ut32 encoded char can be in the buffer
com1.Read(new char[1023], 0, 1023);
Assert.Equal(1, com1.BytesToRead);
com1.Encoding = Encoding.UTF32;
byteXmitBuffer = Encoding.UTF32.GetBytes(charXmitBuffer);
Assert.Throws<TimeoutException>(() => com1.ReadChar());
Assert.Equal(1, com1.BytesToRead);
com2.Write(utf32CharBytes, 1, 3);
com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length);
TCSupport.WaitForReadBufferToLoad(com1, 4 + byteXmitBuffer.Length);
PerformReadOnCom1FromCom2(com1, com2, expectedChars);
}
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void GreedyRead()
{
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
byte[] byteXmitBuffer = new byte[1024];
char utf32Char = TCSupport.GenerateRandomCharNonSurrogate();
byte[] utf32CharBytes = Encoding.UTF32.GetBytes(new[] { utf32Char });
int charRead;
Debug.WriteLine("Verifying that ReadChar() will read everything from internal buffer and drivers buffer");
//Put the first byte of the utf32 encoder char in the last byte of this buffer
//when we read this later the buffer will have to be resized
byteXmitBuffer[byteXmitBuffer.Length - 1] = utf32CharBytes[0];
TCSupport.SetHighSpeed(com1, com2);
com1.Open();
if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
com2.Open();
com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length);
TCSupport.WaitForReadBufferToLoad(com1, byteXmitBuffer.Length);
//Read Every Byte except the last one. The last bye should be left in the last position of SerialPort's
//internal buffer. When we try to read this char as UTF32 the buffer should have to be resized so
//the other 3 bytes of the ut32 encoded char can be in the buffer
com1.Read(new char[1023], 0, 1023);
Assert.Equal(1, com1.BytesToRead);
com1.Encoding = Encoding.UTF32;
com2.Write(utf32CharBytes, 1, 3);
TCSupport.WaitForReadBufferToLoad(com1, 4);
if (utf32Char != (charRead = com1.ReadChar()))
{
Fail("Err_6481sfadw ReadChar() returned={0} expected={1}", charRead, utf32Char);
}
Assert.Equal(0, com1.BytesToRead);
}
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void LargeInputBuffer()
{
Debug.WriteLine("Verifying read with large input buffer");
VerifyRead(Encoding.ASCII, largeNumRndBytesToRead);
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void ReadTimeout_Zero_Bytes()
{
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
char utf32Char = (char)0x254b; //Box drawing char
byte[] utf32CharBytes = Encoding.UTF32.GetBytes(new[] { utf32Char });
int readChar;
Debug.WriteLine("Verifying Read method with zero timeout that resizes SerialPort's buffer");
com1.Encoding = Encoding.UTF32;
com1.ReadTimeout = 0;
com1.Open();
if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
com2.Open();
//[] Try ReadChar with no bytes available
Assert.Throws<TimeoutException>(() => com1.ReadChar());
Assert.Equal(0, com1.BytesToRead);
//[] Try ReadChar with 1 byte available
com2.Write(utf32CharBytes, 0, 1);
TCSupport.WaitForPredicate(() => com1.BytesToRead == 1, 2000,
"Err_28292aheid Expected BytesToRead to be 1");
Assert.Throws<TimeoutException>(() => com1.ReadChar());
Assert.Equal(1, com1.BytesToRead);
//[] Try ReadChar with the bytes in the buffer and in available in the SerialPort
com2.Write(utf32CharBytes, 1, 3);
TCSupport.WaitForPredicate(() => com1.BytesToRead == 4, 2000,
"Err_415568haikpas Expected BytesToRead to be 4");
readChar = com1.ReadChar();
Assert.Equal(utf32Char, readChar);
}
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void Read_DataReceivedBeforeTimeout()
{
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
char[] charXmitBuffer = TCSupport.GetRandomChars(512, TCSupport.CharacterOptions.None);
char[] charRcvBuffer = new char[charXmitBuffer.Length];
ASyncRead asyncRead = new ASyncRead(com1);
var asyncReadTask = new Task(asyncRead.Read);
Debug.WriteLine(
"Verifying that ReadChar will read characters that have been received after the call to Read was made");
com1.Encoding = Encoding.UTF8;
com2.Encoding = Encoding.UTF8;
com1.ReadTimeout = 20000; // 20 seconds
com1.Open();
if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
com2.Open();
asyncReadTask.Start();
asyncRead.ReadStartedEvent.WaitOne();
//This only tells us that the thread has started to execute code in the method
Thread.Sleep(2000); //We need to wait to guarentee that we are executing code in SerialPort
com2.Write(charXmitBuffer, 0, charXmitBuffer.Length);
asyncRead.ReadCompletedEvent.WaitOne();
Assert.Null(asyncRead.Exception);
if (asyncRead.Result != charXmitBuffer[0])
{
Fail("Err_0158ahei Expected ReadChar to read {0}({0:X}) actual {1}({1:X})", charXmitBuffer[0], asyncRead.Result);
}
else
{
charRcvBuffer[0] = (char)asyncRead.Result;
int receivedLength = 1;
while (receivedLength < charXmitBuffer.Length)
{
receivedLength += com1.Read(charRcvBuffer, receivedLength, charRcvBuffer.Length - receivedLength);
}
Assert.Equal(receivedLength, charXmitBuffer.Length);
Assert.Equal(charXmitBuffer, charRcvBuffer);
}
TCSupport.WaitForTaskCompletion(asyncReadTask);
}
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void Read_Timeout()
{
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
char[] charXmitBuffer = TCSupport.GetRandomChars(512, TCSupport.CharacterOptions.None);
byte[] byteXmitBuffer = new UTF32Encoding().GetBytes(charXmitBuffer);
char[] charRcvBuffer = new char[charXmitBuffer.Length];
int result;
Debug.WriteLine(
"Verifying that Read(char[], int, int) works appropriately after TimeoutException has been thrown");
com1.Encoding = new UTF32Encoding();
com2.Encoding = new UTF32Encoding();
com1.ReadTimeout = 500; // 20 seconds
com1.Open();
if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
com2.Open();
//Write the first 3 bytes of a character
com2.Write(byteXmitBuffer, 0, 3);
Assert.Throws<TimeoutException>(() => com1.ReadChar());
Assert.Equal(3, com1.BytesToRead);
com2.Write(byteXmitBuffer, 3, byteXmitBuffer.Length - 3);
TCSupport.WaitForExpected(() => com1.BytesToRead, byteXmitBuffer.Length,
5000, "Err_91818aheid BytesToRead");
result = com1.ReadChar();
if (result != charXmitBuffer[0])
{
Fail("Err_0158ahei Expected ReadChar to read {0}({0:X}) actual {1}({1:X})", charXmitBuffer[0], result);
}
else
{
charRcvBuffer[0] = (char)result;
int readResult = com1.Read(charRcvBuffer, 1, charRcvBuffer.Length - 1);
if (readResult + 1 != charXmitBuffer.Length)
{
Fail("Err_051884ajoedo Expected Read to read {0} characters actually read {1}", charXmitBuffer.Length - 1, readResult);
}
else
{
for (int i = 0; i < charXmitBuffer.Length; ++i)
{
if (charRcvBuffer[i] != charXmitBuffer[i])
{
Fail("Err_05188ahed Characters differ at {0} expected:{1}({1:X}) actual:{2}({2:X})", i, charXmitBuffer[i], charRcvBuffer[i]);
}
}
}
}
VerifyBytesReadOnCom1FromCom2(com1, com2, byteXmitBuffer, charXmitBuffer);
}
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void Read_Surrogate()
{
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
char[] surrogateChars = { (char)0xDB26, (char)0xDC49 };
char[] additionalChars = TCSupport.GetRandomChars(32, TCSupport.CharacterOptions.None);
char[] charRcvBuffer = new char[2];
Debug.WriteLine("Verifying that ReadChar works correctly when trying to read surrogate characters");
com1.Encoding = new UTF32Encoding();
com2.Encoding = new UTF32Encoding();
com1.ReadTimeout = 500; // 20 seconds
com1.Open();
if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
com2.Open();
int numBytes = com2.Encoding.GetByteCount(surrogateChars);
numBytes += com2.Encoding.GetByteCount(additionalChars);
com2.Write(surrogateChars, 0, 2);
com2.Write(additionalChars, 0, additionalChars.Length);
TCSupport.WaitForExpected(() => com1.BytesToRead, numBytes,
5000, "Err_91818aheid BytesToRead");
// We expect this to fail, because it can't read a surrogate
AssertExtensions.Throws<ArgumentException>(null, () => com1.ReadChar());
int result = com1.Read(charRcvBuffer, 0, 2);
Assert.Equal(2, result);
if (charRcvBuffer[0] != surrogateChars[0])
{
Fail("Err_12929anied Expected first char read={0}({1:X}) actually read={2}({3:X})",
surrogateChars[0], (int)surrogateChars[0], charRcvBuffer[0], (int)charRcvBuffer[0]);
}
else if (charRcvBuffer[1] != surrogateChars[1])
{
Fail("Err_12929anied Expected second char read={0}({1:X}) actually read={2}({3:X})",
surrogateChars[1], (int)surrogateChars[1], charRcvBuffer[1], (int)charRcvBuffer[1]);
}
PerformReadOnCom1FromCom2(com1, com2, additionalChars);
}
}
#endregion
#region Verification for Test Cases
private void VerifyRead(Encoding encoding)
{
VerifyRead(encoding, ReadDataFromEnum.NonBuffered);
}
private void VerifyRead(Encoding encoding, int bufferSize)
{
VerifyRead(encoding, ReadDataFromEnum.NonBuffered, bufferSize);
}
private void VerifyRead(Encoding encoding, ReadDataFromEnum readDataFrom)
{
VerifyRead(encoding, readDataFrom, numRndChar);
}
private void VerifyRead(Encoding encoding, ReadDataFromEnum readDataFrom, int bufferSize)
{
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
char[] charXmitBuffer = TCSupport.GetRandomChars(bufferSize, false);
byte[] byteXmitBuffer = encoding.GetBytes(charXmitBuffer);
com1.ReadTimeout = 500;
com1.Encoding = encoding;
TCSupport.SetHighSpeed(com1, com2);
com1.Open();
if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
com2.Open();
switch (readDataFrom)
{
case ReadDataFromEnum.NonBuffered:
VerifyReadNonBuffered(com1, com2, byteXmitBuffer);
break;
case ReadDataFromEnum.Buffered:
VerifyReadBuffered(com1, com2, byteXmitBuffer);
break;
case ReadDataFromEnum.BufferedAndNonBuffered:
VerifyReadBufferedAndNonBuffered(com1, com2, byteXmitBuffer);
break;
default:
throw new ArgumentOutOfRangeException(nameof(readDataFrom), readDataFrom, null);
}
}
}
private void VerifyReadNonBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite)
{
char[] expectedChars = com1.Encoding.GetChars(bytesToWrite, 0, bytesToWrite.Length);
VerifyBytesReadOnCom1FromCom2(com1, com2, bytesToWrite, expectedChars);
}
private void VerifyReadBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite)
{
char[] expectedChars = com1.Encoding.GetChars(bytesToWrite, 0, bytesToWrite.Length);
BufferData(com1, com2, bytesToWrite);
PerformReadOnCom1FromCom2(com1, com2, expectedChars);
}
private void VerifyReadBufferedAndNonBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite)
{
char[] expectedChars = new char[com1.Encoding.GetCharCount(bytesToWrite, 0, bytesToWrite.Length) * 2];
char[] encodedChars = com1.Encoding.GetChars(bytesToWrite, 0, bytesToWrite.Length);
Array.Copy(encodedChars, 0, expectedChars, 0, bytesToWrite.Length);
Array.Copy(encodedChars, 0, expectedChars, encodedChars.Length, encodedChars.Length);
BufferData(com1, com2, bytesToWrite);
VerifyBytesReadOnCom1FromCom2(com1, com2, bytesToWrite, expectedChars);
}
private void BufferData(SerialPort com1, SerialPort com2, byte[] bytesToWrite)
{
com2.Write(bytesToWrite, 0, 1); // Write one byte at the begining because we are going to read this to buffer the rest of the data
com2.Write(bytesToWrite, 0, bytesToWrite.Length);
TCSupport.WaitForReadBufferToLoad(com1, bytesToWrite.Length);
com1.Read(new char[1], 0, 1); // This should put the rest of the bytes in SerialPorts own internal buffer
Assert.Equal(bytesToWrite.Length, com1.BytesToRead);
}
private void VerifyBytesReadOnCom1FromCom2(SerialPort com1, SerialPort com2, byte[] bytesToWrite, char[] expectedChars)
{
com2.Write(bytesToWrite, 0, bytesToWrite.Length);
com1.ReadTimeout = 500;
Thread.Sleep((int)(((bytesToWrite.Length * 10.0) / com1.BaudRate) * 1000) + 250);
PerformReadOnCom1FromCom2(com1, com2, expectedChars);
}
private void PerformReadOnCom1FromCom2(SerialPort com1, SerialPort com2, char[] expectedChars)
{
int bytesToRead = com1.Encoding.GetByteCount(expectedChars);
char[] charRcvBuffer = new char[expectedChars.Length];
int rcvBufferSize = 0;
int i;
i = 0;
while (true)
{
int readInt;
try
{
readInt = com1.ReadChar();
}
catch (TimeoutException)
{
Assert.Equal(expectedChars.Length, i);
break;
}
//While there are more characters to be read
if (expectedChars.Length <= i)
{
//If we have read in more characters then were actually sent
Fail("ERROR!!!: We have received more characters then were sent");
}
charRcvBuffer[i] = (char)readInt;
rcvBufferSize += com1.Encoding.GetByteCount(charRcvBuffer, i, 1);
int com1ToRead = com1.BytesToRead;
if (bytesToRead - rcvBufferSize != com1ToRead)
{
Fail("ERROR!!!: Expected BytesToRead={0} actual={1} at {2}", bytesToRead - rcvBufferSize, com1ToRead, i);
}
if (readInt != expectedChars[i])
{
//If the character read is not the expected character
Fail("ERROR!!!: Expected to read {0} actual read char {1} at {2}", (int)expectedChars[i], readInt, i);
}
i++;
}
Assert.Equal(0, com1.BytesToRead);
}
public class ASyncRead
{
private readonly SerialPort _com;
private int _result;
private readonly AutoResetEvent _readCompletedEvent;
private readonly AutoResetEvent _readStartedEvent;
private Exception _exception;
public ASyncRead(SerialPort com)
{
_com = com;
_result = int.MinValue;
_readCompletedEvent = new AutoResetEvent(false);
_readStartedEvent = new AutoResetEvent(false);
_exception = null;
}
public void Read()
{
try
{
_readStartedEvent.Set();
_result = _com.ReadChar();
}
catch (Exception e)
{
_exception = e;
}
finally
{
_readCompletedEvent.Set();
}
}
public AutoResetEvent ReadStartedEvent => _readStartedEvent;
public AutoResetEvent ReadCompletedEvent => _readCompletedEvent;
public int Result => _result;
public Exception Exception => _exception;
}
#endregion
}
}
| |
// The MIT License (MIT)
//
// Copyright (c) 2015-2016 Microsoft
//
// 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.
namespace Microsoft.Diagnostics.Tracing.Logging
{
using System;
using System.Diagnostics.Tracing;
using System.Globalization;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
[JsonObject(MemberSerialization = MemberSerialization.OptIn), JsonConverter(typeof(Converter))]
public sealed class EventProviderSubscription
{
public const EventLevel DefaultMinimumLevel = EventLevel.Informational;
public const EventKeywords DefaultKeywords = EventKeywords.None;
private EventProviderSubscription(string name, EventSource source, Guid providerID, EventLevel minimuLevel,
EventKeywords keywords)
{
if (source != null)
{
this.UpdateSource(source);
}
else if (providerID != Guid.Empty)
{
this.ProviderID = providerID;
if (this.Source == null)
{
var eventSource = LogManager.FindEventSource(providerID);
if (eventSource != null)
{
this.UpdateSource(eventSource);
}
}
}
else if (!string.IsNullOrWhiteSpace(name))
{
this.Name = name;
if (this.Source == null && this.ProviderID == Guid.Empty)
{
var eventSource = LogManager.FindEventSource(name);
if (eventSource != null)
{
this.UpdateSource(eventSource);
}
}
}
else
{
throw new ArgumentException(
"Must provider at least one of name / EventSource / ProviderID for subscription.");
}
this.MinimumLevel = minimuLevel;
this.Keywords = keywords;
}
/// <summary>
/// Construct a new EventSourceSubscription object based on a provided EventSource.
/// </summary>
/// <param name="source">Source object to use.</param>
public EventProviderSubscription(EventSource source)
: this(null, source, Guid.Empty, DefaultMinimumLevel, DefaultKeywords) { }
/// <summary>
/// Construct a new EventSourceSubscription object based on a provided EventSource.
/// </summary>
/// <param name="source">Source object to use.</param>
/// <param name="minimumLevel">Minimum severity level of events to subscribe to.</param>
public EventProviderSubscription(EventSource source, EventLevel minimumLevel)
: this(null, source, source.Guid, minimumLevel, EventKeywords.None) { }
/// <summary>
/// Construct a new EventSourceSubscription object based on a provided EventSource.
/// </summary>
/// <param name="source">Source object to use.</param>
/// <param name="minimumLevel">Minimum severity level of events to subscribe to.</param>
/// <param name="keywords">Keywords to match events against.</param>
public EventProviderSubscription(EventSource source, EventLevel minimumLevel, EventKeywords keywords)
: this(null, source, source.Guid, minimumLevel, keywords) { }
/// <summary>
/// Construct a new EventSourceSubscription object based on a provided EventSource.
/// </summary>
/// <param name="source">Source object to use.</param>
/// <param name="minimumLevel">Minimum severity level of events to subscribe to.</param>
/// <param name="keywords">Keywords to match events against.</param>
public EventProviderSubscription(EventSource source, EventLevel minimumLevel, ulong keywords)
: this(null, source, source.Guid, minimumLevel, (EventKeywords)keywords) { }
/// <summary>
/// Construct a new EventSourceSubscription object based on an ETW provider GUID.
/// </summary>
/// <param name="providerID">GUID of the desired event provider.</param>
public EventProviderSubscription(Guid providerID)
: this(null, null, providerID, DefaultMinimumLevel, DefaultKeywords) { }
/// <summary>
/// Construct a new EventSourceSubscription object based on an ETW provider GUID.
/// </summary>
/// <param name="providerID">GUID of the desired event provider.</param>
/// <param name="minimumLevel">Minimum severity level of events to subscribe to.</param>
public EventProviderSubscription(Guid providerID, EventLevel minimumLevel)
: this(null, null, providerID, minimumLevel, EventKeywords.None) { }
/// <summary>
/// Construct a new EventSourceSubscription object based on an ETW provider GUID.
/// </summary>
/// <param name="providerID">GUID of the desired event provider.</param>
/// <param name="minimumLevel">Minimum severity level of events to subscribe to.</param>
/// <param name="keywords">Keywords to match events against.</param>
public EventProviderSubscription(Guid providerID, EventLevel minimumLevel, EventKeywords keywords)
: this(null, null, providerID, minimumLevel, keywords) { }
/// <summary>
/// Construct a new EventSourceSubscription object based on an ETW provider GUID.
/// </summary>
/// <param name="providerID">GUID of the desired event provider.</param>
/// <param name="minimumLevel">Minimum severity level of events to subscribe to.</param>
/// <param name="keywords">Keywords to match events against.</param>
public EventProviderSubscription(Guid providerID, EventLevel minimumLevel, ulong keywords)
: this(null, null, providerID, minimumLevel, (EventKeywords)keywords) { }
/// <summary>
/// Construct a new EventSourceSubscription object based on the name of an EventSource provider.
/// </summary>
/// <param name="name">Name of the EventSource provider.</param>
public EventProviderSubscription(string name)
: this(name, null, Guid.Empty, DefaultMinimumLevel, DefaultKeywords) { }
/// <summary>
/// Construct a new EventSourceSubscription object based on the name of an EventSource provider.
/// </summary>
/// <param name="name">Name of the EventSource provider.</param>
/// <param name="minimumLevel">Minimum severity level of events to subscribe to.</param>
public EventProviderSubscription(string name, EventLevel minimumLevel)
: this(name, null, Guid.Empty, minimumLevel, EventKeywords.None) { }
/// <summary>
/// Construct a new EventSourceSubscription object based on the name of an EventSource provider.
/// </summary>
/// <param name="name">Name of the EventSource provider.</param>
/// <param name="minimumLevel">Minimum severity level of events to subscribe to.</param>
/// <param name="keywords">Keywords to match events against.</param>
public EventProviderSubscription(string name, EventLevel minimumLevel, EventKeywords keywords)
: this(name, null, Guid.Empty, minimumLevel, keywords) { }
/// <summary>
/// Construct a new EventSourceSubscription object based on the name of an EventSource provider.
/// </summary>
/// <param name="name">Name of the EventSource provider.</param>
/// <param name="minimumLevel">Minimum severity level of events to subscribe to.</param>
/// <param name="keywords">Keywords to match events against.</param>
public EventProviderSubscription(string name, EventLevel minimumLevel, ulong keywords)
: this(name, null, Guid.Empty, minimumLevel, (EventKeywords)keywords) { }
/// <summary>
/// Keywords to match.
/// </summary>
public EventKeywords Keywords { get; set; }
/// <summary>
/// Minimum event level to record.
/// </summary>
public EventLevel MinimumLevel { get; set; }
/// <summary>
/// EventSource to subscribe to. May be null if ProviderID is provided.
/// </summary>
public EventSource Source { get; private set; }
/// <summary>
/// Guid to subscribe to. May be empty if Source is provided.
/// </summary>
public Guid ProviderID { get; private set; }
/// <summary>
/// Name of the EventSource to subscribe to. May be empty if ProviderID is provided.
/// </summary>
public string Name { get; private set; }
/// <summary>
/// True if the subscription is considered "resolved" (i.e. if either the EventSource is known or a GUID is provided).
/// </summary>
public bool IsResolved => this.Source != null || this.ProviderID != Guid.Empty;
internal void UpdateSource(EventSource source)
{
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}
if (this.Source != null)
{
throw new InvalidOperationException("Multiple updates to source are not allowed.");
}
this.Source = source;
this.Name = source.Name;
this.ProviderID = source.Guid;
}
public override bool Equals(object obj)
{
var other = obj as EventProviderSubscription;
return other != null && this.Equals(other);
}
private bool Equals(EventProviderSubscription other)
{
return this.ProviderID.Equals(other.ProviderID) &&
string.Equals(this.Name, other.Name, StringComparison.OrdinalIgnoreCase);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = this.ProviderID.GetHashCode();
hashCode = (hashCode * 397) ^ (this.Name?.ToLower(CultureInfo.InvariantCulture).GetHashCode() ?? 0);
return hashCode;
}
}
public override string ToString()
{
var serializer = new JsonSerializer();
using (var writer = new StringWriter())
{
serializer.Serialize(writer, this);
return writer.ToString();
}
}
private sealed class Converter : JsonConverter
{
private const string NameProperty = "name";
private const string ProviderIDProperty = "providerID";
private const string MinimumLevelProperty = "minimumLevel";
private const string KeywordsProperty = "keywords";
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var subscription = value as EventProviderSubscription;
if (subscription == null)
{
throw new ArgumentNullException(nameof(value));
}
writer.WriteStartObject();
if (subscription.Name != null)
{
writer.WritePropertyName(NameProperty);
writer.WriteValue(subscription.Name);
}
else
{
if (subscription.ProviderID == Guid.Empty)
{
throw new ArgumentException("Source without name or valid ProviderID provided.", nameof(value));
}
writer.WritePropertyName(ProviderIDProperty);
writer.WriteValue(subscription.ProviderID);
}
if (subscription.MinimumLevel != DefaultMinimumLevel)
{
writer.WritePropertyName(MinimumLevelProperty);
writer.WriteValue(subscription.MinimumLevel.ToString());
}
if (subscription.Keywords != DefaultKeywords)
{
writer.WritePropertyName(KeywordsProperty);
writer.WriteValue("0x" + ((ulong)subscription.Keywords).ToString("x"));
}
writer.WriteEndObject();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
JsonSerializer serializer)
{
var jObject = JObject.Load(reader);
JToken token;
string name = null;
Guid providerID = Guid.Empty;
EventLevel minimumLevel = DefaultMinimumLevel;
EventKeywords keywords = DefaultKeywords;
if (jObject.TryGetValue(NameProperty, StringComparison.OrdinalIgnoreCase, out token))
{
name = token.Value<string>();
}
if (jObject.TryGetValue(ProviderIDProperty, StringComparison.OrdinalIgnoreCase, out token))
{
providerID = token.Value<Guid>();
}
if (jObject.TryGetValue(MinimumLevelProperty, StringComparison.OrdinalIgnoreCase, out token))
{
minimumLevel = (EventLevel)Enum.Parse(typeof(EventLevel), token.Value<string>(), true);
}
if (jObject.TryGetValue(KeywordsProperty, StringComparison.OrdinalIgnoreCase, out token))
{
var value = token.Value<string>().Trim();
if (value.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
{
value = value.Substring(2);
}
keywords = (EventKeywords)ulong.Parse(value, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
}
return new EventProviderSubscription(name, null, providerID, minimumLevel, keywords);
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(EventProviderSubscription);
}
}
}
}
| |
using System;
using System.Text;
/// <summary>
/// GetByteCount(System.Char[],System.Int32,System.Int32) [v-jianq]
/// </summary>
public class UTF8EncodingGetCharCount
{
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
//
// TODO: Add your negative test cases here
//
// TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
retVal = NegTest4() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest1: Verify method GetByteCount with a non-null Byte[]");
try
{
Byte[] bytes = new Byte[] {
85, 84, 70, 56, 32, 69, 110,
99, 111, 100, 105, 110, 103, 32,
69, 120, 97, 109, 112, 108, 101};
UTF8Encoding utf8 = new UTF8Encoding();
int charCount = utf8.GetCharCount(bytes, 2, 8);
if (charCount != 8)
{
TestLibrary.TestFramework.LogError("001.1", "Method GetByteCount Err.");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest2: Verify method GetByteCount with a null Byte[]");
try
{
Byte[] bytes = new Byte[] { };
UTF8Encoding utf8 = new UTF8Encoding();
int charCount = utf8.GetCharCount(bytes, 0, 0);
if (charCount != 0)
{
TestLibrary.TestFramework.LogError("002.1", "Method GetByteCount Err.");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: ArgumentNullException is not thrown when bytes is a null reference");
try
{
Byte[] bytes = null;
UTF8Encoding utf8 = new UTF8Encoding();
int charCount = utf8.GetCharCount(bytes, 2, 8);
TestLibrary.TestFramework.LogError("101.1", "ArgumentNullException is not thrown when bytes is a null reference.");
retVal = false;
}
catch (ArgumentNullException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("101.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: ArgumentOutOfRangeException is not thrown when index is less than zero.");
try
{
Byte[] bytes = new Byte[] {
85, 84, 70, 56, 32, 69, 110,
99, 111, 100, 105, 110, 103, 32,
69, 120, 97, 109, 112, 108, 101};
UTF8Encoding utf8 = new UTF8Encoding();
int charCount = utf8.GetCharCount(bytes, -1, 8);
TestLibrary.TestFramework.LogError("102.1", "ArgumentNullException is not thrown when index is less than zero..");
retVal = false;
}
catch (ArgumentOutOfRangeException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest3: ArgumentOutOfRangeException is not thrown when count is less than zero.");
try
{
Byte[] bytes = new Byte[] {
85, 84, 70, 56, 32, 69, 110,
99, 111, 100, 105, 110, 103, 32,
69, 120, 97, 109, 112, 108, 101};
UTF8Encoding utf8 = new UTF8Encoding();
int charCount = utf8.GetCharCount(bytes, 2, -1);
TestLibrary.TestFramework.LogError("103.1", "ArgumentNullException is not thrown when count is less than zero..");
retVal = false;
}
catch (ArgumentOutOfRangeException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("103.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest4: ArgumentOutOfRangeException is not thrown when index and count do not denote a valid range in bytes.");
try
{
Byte[] bytes = new Byte[] {
85, 84, 70, 56, 32, 69, 110,
99, 111, 100, 105, 110, 103, 32,
69, 120, 97, 109, 112, 108, 101};
UTF8Encoding utf8 = new UTF8Encoding();
int charCount = utf8.GetCharCount(bytes, 2, bytes.Length);
TestLibrary.TestFramework.LogError("104.1", "ArgumentNullException is not thrown whenindex and count do not denote a valid range in bytes.");
retVal = false;
}
catch (ArgumentOutOfRangeException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("104.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
UTF8EncodingGetCharCount test = new UTF8EncodingGetCharCount();
TestLibrary.TestFramework.BeginTestCase("UTF8EncodingGetCharCount");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Windows.Controls.MediaElement.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Windows.Controls
{
public partial class MediaElement : System.Windows.FrameworkElement, System.Windows.Markup.IUriContext
{
#region Methods and constructors
protected override System.Windows.Size ArrangeOverride(System.Windows.Size finalSize)
{
return default(System.Windows.Size);
}
public void Close()
{
}
protected override System.Windows.Size MeasureOverride(System.Windows.Size availableSize)
{
return default(System.Windows.Size);
}
public MediaElement()
{
}
protected override System.Windows.Automation.Peers.AutomationPeer OnCreateAutomationPeer()
{
return default(System.Windows.Automation.Peers.AutomationPeer);
}
protected override void OnRender(System.Windows.Media.DrawingContext drawingContext)
{
}
public void Pause()
{
}
public void Play()
{
}
public void Stop()
{
}
#endregion
#region Properties and indexers
public double Balance
{
get
{
return default(double);
}
set
{
}
}
public double BufferingProgress
{
get
{
return default(double);
}
}
public bool CanPause
{
get
{
return default(bool);
}
}
public System.Windows.Media.MediaClock Clock
{
get
{
return default(System.Windows.Media.MediaClock);
}
set
{
}
}
public double DownloadProgress
{
get
{
return default(double);
}
}
public bool HasAudio
{
get
{
return default(bool);
}
}
public bool HasVideo
{
get
{
return default(bool);
}
}
public bool IsBuffering
{
get
{
return default(bool);
}
}
public bool IsMuted
{
get
{
return default(bool);
}
set
{
}
}
public MediaState LoadedBehavior
{
get
{
return default(MediaState);
}
set
{
}
}
public System.Windows.Duration NaturalDuration
{
get
{
return default(System.Windows.Duration);
}
}
public int NaturalVideoHeight
{
get
{
return default(int);
}
}
public int NaturalVideoWidth
{
get
{
return default(int);
}
}
public TimeSpan Position
{
get
{
return default(TimeSpan);
}
set
{
}
}
public bool ScrubbingEnabled
{
get
{
return default(bool);
}
set
{
}
}
public Uri Source
{
get
{
return default(Uri);
}
set
{
}
}
public double SpeedRatio
{
get
{
return default(double);
}
set
{
}
}
public System.Windows.Media.Stretch Stretch
{
get
{
return default(System.Windows.Media.Stretch);
}
set
{
}
}
public StretchDirection StretchDirection
{
get
{
return default(StretchDirection);
}
set
{
}
}
Uri System.Windows.Markup.IUriContext.BaseUri
{
get
{
return default(Uri);
}
set
{
}
}
public MediaState UnloadedBehavior
{
get
{
return default(MediaState);
}
set
{
}
}
public double Volume
{
get
{
return default(double);
}
set
{
}
}
#endregion
#region Events
public event System.Windows.RoutedEventHandler BufferingEnded
{
add
{
}
remove
{
}
}
public event System.Windows.RoutedEventHandler BufferingStarted
{
add
{
}
remove
{
}
}
public event System.Windows.RoutedEventHandler MediaEnded
{
add
{
}
remove
{
}
}
public event EventHandler<System.Windows.ExceptionRoutedEventArgs> MediaFailed
{
add
{
}
remove
{
}
}
public event System.Windows.RoutedEventHandler MediaOpened
{
add
{
}
remove
{
}
}
public event EventHandler<System.Windows.MediaScriptCommandRoutedEventArgs> ScriptCommand
{
add
{
}
remove
{
}
}
#endregion
#region Fields
public readonly static System.Windows.DependencyProperty BalanceProperty;
public readonly static System.Windows.RoutedEvent BufferingEndedEvent;
public readonly static System.Windows.RoutedEvent BufferingStartedEvent;
public readonly static System.Windows.DependencyProperty IsMutedProperty;
public readonly static System.Windows.DependencyProperty LoadedBehaviorProperty;
public readonly static System.Windows.RoutedEvent MediaEndedEvent;
public readonly static System.Windows.RoutedEvent MediaFailedEvent;
public readonly static System.Windows.RoutedEvent MediaOpenedEvent;
public readonly static System.Windows.RoutedEvent ScriptCommandEvent;
public readonly static System.Windows.DependencyProperty ScrubbingEnabledProperty;
public readonly static System.Windows.DependencyProperty SourceProperty;
public readonly static System.Windows.DependencyProperty StretchDirectionProperty;
public readonly static System.Windows.DependencyProperty StretchProperty;
public readonly static System.Windows.DependencyProperty UnloadedBehaviorProperty;
public readonly static System.Windows.DependencyProperty VolumeProperty;
#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.Linq;
using System.Reflection;
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "LocalSimulationConnectorModule")]
public class LocalSimulationConnectorModule : ISharedRegionModule, ISimulationService
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Version of this service
/// </summary>
private const string m_Version = "SIMULATION/0.1";
/// <summary>
/// Map region ID to scene.
/// </summary>
private Dictionary<UUID, Scene> m_scenes = new Dictionary<UUID, Scene>();
/// <summary>
/// Is this module enabled?
/// </summary>
private bool m_ModuleEnabled = false;
#region Region Module interface
public void Initialise(IConfigSource config)
{
IConfig moduleConfig = config.Configs["Modules"];
if (moduleConfig != null)
{
string name = moduleConfig.GetString("SimulationServices", "");
if (name == Name)
{
//IConfig userConfig = config.Configs["SimulationService"];
//if (userConfig == null)
//{
// m_log.Error("[AVATAR CONNECTOR]: SimulationService missing from OpenSim.ini");
// return;
//}
m_ModuleEnabled = true;
m_log.Info("[SIMULATION CONNECTOR]: Local simulation enabled");
}
}
}
public void PostInitialise()
{
}
public void AddRegion(Scene scene)
{
if (!m_ModuleEnabled)
return;
Init(scene);
scene.RegisterModuleInterface<ISimulationService>(this);
}
public void RemoveRegion(Scene scene)
{
if (!m_ModuleEnabled)
return;
RemoveScene(scene);
scene.UnregisterModuleInterface<ISimulationService>(this);
}
public void RegionLoaded(Scene scene)
{
}
public void Close()
{
}
public Type ReplaceableInterface
{
get { return null; }
}
public string Name
{
get { return "LocalSimulationConnectorModule"; }
}
/// <summary>
/// Can be called from other modules.
/// </summary>
/// <param name="scene"></param>
public void RemoveScene(Scene scene)
{
lock (m_scenes)
{
if (m_scenes.ContainsKey(scene.RegionInfo.RegionID))
m_scenes.Remove(scene.RegionInfo.RegionID);
else
m_log.WarnFormat(
"[LOCAL SIMULATION CONNECTOR]: Tried to remove region {0} but it was not present",
scene.RegionInfo.RegionName);
}
}
/// <summary>
/// Can be called from other modules.
/// </summary>
/// <param name="scene"></param>
public void Init(Scene scene)
{
lock (m_scenes)
{
if (!m_scenes.ContainsKey(scene.RegionInfo.RegionID))
m_scenes[scene.RegionInfo.RegionID] = scene;
else
m_log.WarnFormat(
"[LOCAL SIMULATION CONNECTOR]: Tried to add region {0} but it is already present",
scene.RegionInfo.RegionName);
}
}
#endregion
#region ISimulation
public IScene GetScene(UUID regionId)
{
if (m_scenes.ContainsKey(regionId))
{
return m_scenes[regionId];
}
else
{
// FIXME: This was pre-existing behaviour but possibly not a good idea, since it hides an error rather
// than making it obvious and fixable. Need to see if the error message comes up in practice.
Scene s = m_scenes.Values.ToArray()[0];
m_log.ErrorFormat(
"[LOCAL SIMULATION CONNECTOR]: Region with id {0} not found. Returning {1} {2} instead",
regionId, s.RegionInfo.RegionName, s.RegionInfo.RegionID);
return s;
}
}
public ISimulationService GetInnerService()
{
return this;
}
/**
* Agent-related communications
*/
public bool CreateAgent(GridRegion destination, AgentCircuitData aCircuit, uint teleportFlags, out string reason)
{
if (destination == null)
{
reason = "Given destination was null";
m_log.DebugFormat("[LOCAL SIMULATION CONNECTOR]: CreateAgent was given a null destination");
return false;
}
if (m_scenes.ContainsKey(destination.RegionID))
{
// m_log.DebugFormat("[LOCAL SIMULATION CONNECTOR]: Found region {0} to send SendCreateChildAgent", destination.RegionName);
return m_scenes[destination.RegionID].NewUserConnection(aCircuit, teleportFlags, out reason);
}
reason = "Did not find region " + destination.RegionName;
return false;
}
public bool UpdateAgent(GridRegion destination, AgentData cAgentData)
{
if (destination == null)
return false;
if (m_scenes.ContainsKey(destination.RegionID))
{
// m_log.DebugFormat(
// "[LOCAL SIMULATION CONNECTOR]: Found region {0} {1} to send AgentUpdate",
// destination.RegionName, destination.RegionID);
return m_scenes[destination.RegionID].IncomingChildAgentDataUpdate(cAgentData);
}
// m_log.DebugFormat(
// "[LOCAL COMMS]: Did not find region {0} {1} for ChildAgentUpdate",
// destination.RegionName, destination.RegionID);
return false;
}
public bool UpdateAgent(GridRegion destination, AgentPosition cAgentData)
{
if (destination == null)
return false;
// We limit the number of messages sent for a position change to just one per
// simulator so when we receive the update we need to hand it to each of the
// scenes; scenes each check to see if the is a scene presence for the avatar
// note that we really don't need the GridRegion for this call
foreach (Scene s in m_scenes.Values)
{
// m_log.Debug("[LOCAL COMMS]: Found region to send ChildAgentUpdate");
s.IncomingChildAgentDataUpdate(cAgentData);
}
//m_log.Debug("[LOCAL COMMS]: region not found for ChildAgentUpdate");
return true;
}
public bool RetrieveAgent(GridRegion destination, UUID id, out IAgentData agent)
{
agent = null;
if (destination == null)
return false;
if (m_scenes.ContainsKey(destination.RegionID))
{
// m_log.DebugFormat(
// "[LOCAL SIMULATION CONNECTOR]: Found region {0} {1} to send AgentUpdate",
// s.RegionInfo.RegionName, destination.RegionHandle);
return m_scenes[destination.RegionID].IncomingRetrieveRootAgent(id, out agent);
}
//m_log.Debug("[LOCAL COMMS]: region not found for ChildAgentUpdate");
return false;
}
public bool QueryAccess(GridRegion destination, UUID id, Vector3 position, out string version, out string reason)
{
reason = "Communications failure";
version = m_Version;
if (destination == null)
return false;
if (m_scenes.ContainsKey(destination.RegionID))
{
// m_log.DebugFormat(
// "[LOCAL SIMULATION CONNECTOR]: Found region {0} {1} to send AgentUpdate",
// s.RegionInfo.RegionName, destination.RegionHandle);
return m_scenes[destination.RegionID].QueryAccess(id, position, out reason);
}
//m_log.Debug("[LOCAL COMMS]: region not found for QueryAccess");
return false;
}
public bool ReleaseAgent(UUID originId, UUID agentId, string uri)
{
if (m_scenes.ContainsKey(originId))
{
// m_log.DebugFormat(
// "[LOCAL SIMULATION CONNECTOR]: Found region {0} {1} to send AgentUpdate",
// s.RegionInfo.RegionName, destination.RegionHandle);
m_scenes[originId].EntityTransferModule.AgentArrivedAtDestination(agentId);
return true;
}
//m_log.Debug("[LOCAL COMMS]: region not found in SendReleaseAgent " + origin);
return false;
}
public bool CloseAgent(GridRegion destination, UUID id)
{
if (destination == null)
return false;
if (m_scenes.ContainsKey(destination.RegionID))
{
// m_log.DebugFormat(
// "[LOCAL SIMULATION CONNECTOR]: Found region {0} {1} to send AgentUpdate",
// s.RegionInfo.RegionName, destination.RegionHandle);
Util.FireAndForget(delegate { m_scenes[destination.RegionID].IncomingCloseAgent(id, false); });
return true;
}
//m_log.Debug("[LOCAL COMMS]: region not found in SendCloseAgent");
return false;
}
/**
* Object-related communications
*/
public bool CreateObject(GridRegion destination, Vector3 newPosition, ISceneObject sog, bool isLocalCall)
{
if (destination == null)
return false;
if (m_scenes.ContainsKey(destination.RegionID))
{
// m_log.DebugFormat(
// "[LOCAL SIMULATION CONNECTOR]: Found region {0} {1} to send AgentUpdate",
// s.RegionInfo.RegionName, destination.RegionHandle);
Scene s = m_scenes[destination.RegionID];
if (isLocalCall)
{
// We need to make a local copy of the object
ISceneObject sogClone = sog.CloneForNewScene();
sogClone.SetState(sog.GetStateSnapshot(), s);
return s.IncomingCreateObject(newPosition, sogClone);
}
else
{
// Use the object as it came through the wire
return s.IncomingCreateObject(newPosition, sog);
}
}
return false;
}
#endregion /* IInterregionComms */
#region Misc
public bool IsLocalRegion(ulong regionhandle)
{
foreach (Scene s in m_scenes.Values)
if (s.RegionInfo.RegionHandle == regionhandle)
return true;
return false;
}
public bool IsLocalRegion(UUID id)
{
return m_scenes.ContainsKey(id);
}
#endregion
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
/// <summary>
/// UsageRecordResource
/// </summary>
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
using Twilio.Types;
namespace Twilio.Rest.Wireless.V1
{
public class UsageRecordResource : Resource
{
public sealed class GranularityEnum : StringEnum
{
private GranularityEnum(string value) : base(value) {}
public GranularityEnum() {}
public static implicit operator GranularityEnum(string value)
{
return new GranularityEnum(value);
}
public static readonly GranularityEnum Hourly = new GranularityEnum("hourly");
public static readonly GranularityEnum Daily = new GranularityEnum("daily");
public static readonly GranularityEnum All = new GranularityEnum("all");
}
private static Request BuildReadRequest(ReadUsageRecordOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Wireless,
"/v1/UsageRecords",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// read
/// </summary>
/// <param name="options"> Read UsageRecord parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of UsageRecord </returns>
public static ResourceSet<UsageRecordResource> Read(ReadUsageRecordOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildReadRequest(options, client));
var page = Page<UsageRecordResource>.FromJson("usage_records", response.Content);
return new ResourceSet<UsageRecordResource>(page, options, client);
}
#if !NET35
/// <summary>
/// read
/// </summary>
/// <param name="options"> Read UsageRecord parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of UsageRecord </returns>
public static async System.Threading.Tasks.Task<ResourceSet<UsageRecordResource>> ReadAsync(ReadUsageRecordOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildReadRequest(options, client));
var page = Page<UsageRecordResource>.FromJson("usage_records", response.Content);
return new ResourceSet<UsageRecordResource>(page, options, client);
}
#endif
/// <summary>
/// read
/// </summary>
/// <param name="end"> Only include usage that has occurred on or before this date </param>
/// <param name="start"> Only include usage that has occurred on or after this date </param>
/// <param name="granularity"> The time-based grouping that results are aggregated by </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of UsageRecord </returns>
public static ResourceSet<UsageRecordResource> Read(DateTime? end = null,
DateTime? start = null,
UsageRecordResource.GranularityEnum granularity = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadUsageRecordOptions(){End = end, Start = start, Granularity = granularity, PageSize = pageSize, Limit = limit};
return Read(options, client);
}
#if !NET35
/// <summary>
/// read
/// </summary>
/// <param name="end"> Only include usage that has occurred on or before this date </param>
/// <param name="start"> Only include usage that has occurred on or after this date </param>
/// <param name="granularity"> The time-based grouping that results are aggregated by </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of UsageRecord </returns>
public static async System.Threading.Tasks.Task<ResourceSet<UsageRecordResource>> ReadAsync(DateTime? end = null,
DateTime? start = null,
UsageRecordResource.GranularityEnum granularity = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadUsageRecordOptions(){End = end, Start = start, Granularity = granularity, PageSize = pageSize, Limit = limit};
return await ReadAsync(options, client);
}
#endif
/// <summary>
/// Fetch the target page of records
/// </summary>
/// <param name="targetUrl"> API-generated URL for the requested results page </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The target page of records </returns>
public static Page<UsageRecordResource> GetPage(string targetUrl, ITwilioRestClient client)
{
client = client ?? TwilioClient.GetRestClient();
var request = new Request(
HttpMethod.Get,
targetUrl
);
var response = client.Request(request);
return Page<UsageRecordResource>.FromJson("usage_records", response.Content);
}
/// <summary>
/// Fetch the next page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The next page of records </returns>
public static Page<UsageRecordResource> NextPage(Page<UsageRecordResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetNextPageUrl(Rest.Domain.Wireless)
);
var response = client.Request(request);
return Page<UsageRecordResource>.FromJson("usage_records", response.Content);
}
/// <summary>
/// Fetch the previous page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The previous page of records </returns>
public static Page<UsageRecordResource> PreviousPage(Page<UsageRecordResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetPreviousPageUrl(Rest.Domain.Wireless)
);
var response = client.Request(request);
return Page<UsageRecordResource>.FromJson("usage_records", response.Content);
}
/// <summary>
/// Converts a JSON string into a UsageRecordResource object
/// </summary>
/// <param name="json"> Raw JSON string </param>
/// <returns> UsageRecordResource object represented by the provided JSON </returns>
public static UsageRecordResource FromJson(string json)
{
// Convert all checked exceptions to Runtime
try
{
return JsonConvert.DeserializeObject<UsageRecordResource>(json);
}
catch (JsonException e)
{
throw new ApiException(e.Message, e);
}
}
/// <summary>
/// The SID of the Account that created the resource
/// </summary>
[JsonProperty("account_sid")]
public string AccountSid { get; private set; }
/// <summary>
/// The time period for which usage is reported
/// </summary>
[JsonProperty("period")]
public object Period { get; private set; }
/// <summary>
/// An object that describes the aggregated Commands usage for all SIMs during the specified period
/// </summary>
[JsonProperty("commands")]
public object Commands { get; private set; }
/// <summary>
/// An object that describes the aggregated Data usage for all SIMs over the period
/// </summary>
[JsonProperty("data")]
public object Data { get; private set; }
private UsageRecordResource()
{
}
}
}
| |
/********************************************************************
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.
*********************************************************************/
#region license
/*
DirectShowLib - Provide access to DirectShow interfaces via .NET
Copyright (C) 2006
http://sourceforge.net/projects/directshownet/
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#endregion
using System;
using System.Runtime.InteropServices;
namespace DirectShowLib
{
#region Declarations
/// <summary>
/// From AM_GBF_* defines
/// </summary>
[Flags]
public enum AMGBF
{
None = 0,
PrevFrameSkipped = 1,
NotAsyncPoint = 2,
NoWait = 4,
NoDDSurfaceLock = 8
}
/// <summary>
/// From AM_VIDEO_FLAG_* defines
/// </summary>
[Flags]
public enum AMVideoFlag
{
FieldMask = 0x0003,
InterleavedFrame = 0x0000,
Field1 = 0x0001,
Field2 = 0x0002,
Field1First = 0x0004,
Weave = 0x0008,
IPBMask = 0x0030,
ISample = 0x0000,
PSample = 0x0010,
BSample = 0x0020,
RepeatField = 0x0040
}
/// <summary>
/// From AM_SAMPLE_PROPERTY_FLAGS
/// </summary>
[Flags]
public enum AMSamplePropertyFlags
{
SplicePoint = 0x01,
PreRoll = 0x02,
DataDiscontinuity = 0x04,
TypeChanged = 0x08,
TimeValid = 0x10,
MediaTimeValid = 0x20,
TimeDiscontinuity = 0x40,
FlushOnPause = 0x80,
StopValid = 0x100,
EndOfStream = 0x200,
Media = 0,
Control = 1
}
/// <summary>
/// From PIN_INFO
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack=1, CharSet=CharSet.Unicode)]
public struct PinInfo
{
[MarshalAs(UnmanagedType.Interface)] public IBaseFilter filter;
public PinDirection dir;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=128)] public string name;
}
/// <summary>
/// From AM_MEDIA_TYPE - When you are done with an instance of this class,
/// it should be released with FreeAMMediaType() to avoid leaking
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack=1)]
public class AMMediaType
{
public Guid majorType;
public Guid subType;
[MarshalAs(UnmanagedType.Bool)] public bool fixedSizeSamples;
[MarshalAs(UnmanagedType.Bool)] public bool temporalCompression;
public int sampleSize;
public Guid formatType;
public IntPtr unkPtr; // IUnknown Pointer
public int formatSize;
public IntPtr formatPtr; // Pointer to a buff determined by formatType
}
/// <summary>
/// From PIN_DIRECTION
/// </summary>
public enum PinDirection
{
Input,
Output
}
/// <summary>
/// From AM_SEEKING_SeekingCapabilities
/// </summary>
[Flags]
public enum AMSeekingSeekingCapabilities
{
None = 0,
CanSeekAbsolute = 0x001,
CanSeekForwards = 0x002,
CanSeekBackwards = 0x004,
CanGetCurrentPos = 0x008,
CanGetStopPos = 0x010,
CanGetDuration = 0x020,
CanPlayBackwards = 0x040,
CanDoSegments = 0x080,
Source = 0x100
}
/// <summary>
/// From FILTER_STATE
/// </summary>
public enum FilterState
{
Stopped,
Paused,
Running
}
/// <summary>
/// From FILTER_INFO
/// </summary>
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
public struct FilterInfo
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=128)] public string achName;
[MarshalAs(UnmanagedType.Interface)] public IFilterGraph pGraph;
}
/// <summary>
/// From AM_SEEKING_SeekingFlags
/// </summary>
[Flags]
public enum AMSeekingSeekingFlags
{
NoPositioning = 0x00,
AbsolutePositioning = 0x01,
RelativePositioning = 0x02,
IncrementalPositioning = 0x03,
PositioningBitsMask = 0x03,
SeekToKeyFrame = 0x04,
ReturnTime = 0x08,
Segment = 0x10,
NoFlush = 0x20
}
/// <summary>
/// From ALLOCATOR_PROPERTIES
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public class AllocatorProperties
{
public int cBuffers;
public int cbBuffer;
public int cbAlign;
public int cbPrefix;
}
/// <summary>
/// From AM_SAMPLE2_PROPERTIES
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public class AMSample2Properties
{
public int cbData;
public AMVideoFlag dwTypeSpecificFlags;
public AMSamplePropertyFlags dwSampleFlags;
public int lActual;
public long tStart;
public long tStop;
public int dwStreamId;
public IntPtr pMediaType;
public IntPtr pbBuffer; // BYTE *
public int cbBuffer;
}
#endregion
#region Interfaces
#if ALLOW_UNTESTED_INTERFACES
[ComImport,
Guid("36b73885-c2c8-11cf-8b46-00805f6cef60"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IReferenceClock2 : IReferenceClock
{
#region IReferenceClock Methods
[PreserveSig]
new int GetTime([Out] out long pTime);
[PreserveSig]
new int AdviseTime(
[In] long baseTime,
[In] long streamTime,
[In] IntPtr hEvent, // System.Threading.WaitHandle?
[Out] out int pdwAdviseCookie
);
[PreserveSig]
new int AdvisePeriodic(
[In] long startTime,
[In] long periodTime,
[In] IntPtr hSemaphore, // System.Threading.WaitHandle?
[Out] out int pdwAdviseCookie
);
[PreserveSig]
new int Unadvise([In] int dwAdviseCookie);
#endregion
}
[ComImport,
Guid("56a8689d-0ad4-11ce-b03a-0020af0ba770"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IMemInputPin
{
[PreserveSig]
int GetAllocator([Out] out IMemAllocator ppAllocator);
[PreserveSig]
int NotifyAllocator(
[In] IMemAllocator pAllocator,
[In, MarshalAs(UnmanagedType.Bool)] bool bReadOnly
);
[PreserveSig]
int GetAllocatorRequirements([Out] out AllocatorProperties pProps);
[PreserveSig]
int Receive([In] IMediaSample pSample);
[PreserveSig]
int ReceiveMultiple(
[In] IntPtr pSamples, // IMediaSample[]
[In] int nSamples,
[Out] out int nSamplesProcessed
);
[PreserveSig]
int ReceiveCanBlock();
}
[ComImport,
Guid("a3d8cec0-7e5a-11cf-bbc5-00805f6cef20"),
Obsolete("This interface has been deprecated.", false),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IAMovieSetup
{
[PreserveSig]
int Register();
[PreserveSig]
int Unregister();
}
#endif
[ComImport,
Guid("56a86891-0ad4-11ce-b03a-0020af0ba770"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IPin
{
[PreserveSig]
int Connect(
[In] IPin pReceivePin,
[In, MarshalAs(UnmanagedType.LPStruct)] AMMediaType pmt
);
[PreserveSig]
int ReceiveConnection(
[In] IPin pReceivePin,
[In, MarshalAs(UnmanagedType.LPStruct)] AMMediaType pmt
);
[PreserveSig]
int Disconnect();
[PreserveSig]
int ConnectedTo(
[Out] out IPin ppPin);
/// <summary>
/// Release returned parameter with DsUtils.FreeAMMediaType
/// </summary>
[PreserveSig]
int ConnectionMediaType(
[Out, MarshalAs(UnmanagedType.LPStruct)] AMMediaType pmt);
/// <summary>
/// Release returned parameter with DsUtils.FreePinInfo
/// </summary>
[PreserveSig]
int QueryPinInfo([Out] out PinInfo pInfo);
[PreserveSig]
int QueryDirection(out PinDirection pPinDir);
[PreserveSig]
int QueryId([Out, MarshalAs(UnmanagedType.LPWStr)] out string Id);
[PreserveSig]
int QueryAccept([In, MarshalAs(UnmanagedType.LPStruct)] AMMediaType pmt);
[PreserveSig]
int EnumMediaTypes([Out] out IEnumMediaTypes ppEnum);
[PreserveSig]
int QueryInternalConnections(
[Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex=1)] IPin[] ppPins,
[In, Out] ref int nPin
);
[PreserveSig]
int EndOfStream();
[PreserveSig]
int BeginFlush();
[PreserveSig]
int EndFlush();
[PreserveSig]
int NewSegment(
[In] long tStart,
[In] long tStop,
[In] double dRate
);
}
[ComImport,
Guid("36b73880-c2c8-11cf-8b46-00805f6cef60"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IMediaSeeking
{
[PreserveSig]
int GetCapabilities([Out] out AMSeekingSeekingCapabilities pCapabilities);
[PreserveSig]
int CheckCapabilities([In, Out] ref AMSeekingSeekingCapabilities pCapabilities);
[PreserveSig]
int IsFormatSupported([In, MarshalAs(UnmanagedType.LPStruct)] Guid pFormat);
[PreserveSig]
int QueryPreferredFormat([Out] out Guid pFormat);
[PreserveSig]
int GetTimeFormat([Out] out Guid pFormat);
[PreserveSig]
int IsUsingTimeFormat([In, MarshalAs(UnmanagedType.LPStruct)] Guid pFormat);
[PreserveSig]
int SetTimeFormat([In, MarshalAs(UnmanagedType.LPStruct)] Guid pFormat);
[PreserveSig]
int GetDuration([Out] out long pDuration);
[PreserveSig]
int GetStopPosition([Out] out long pStop);
[PreserveSig]
int GetCurrentPosition([Out] out long pCurrent);
[PreserveSig]
int ConvertTimeFormat(
[Out] out long pTarget,
[In, MarshalAs(UnmanagedType.LPStruct)] DsGuid pTargetFormat,
[In] long Source,
[In, MarshalAs(UnmanagedType.LPStruct)] DsGuid pSourceFormat
);
[PreserveSig]
int SetPositions(
[In, Out, MarshalAs(UnmanagedType.LPStruct)] DsLong pCurrent,
[In] AMSeekingSeekingFlags dwCurrentFlags,
[In, Out, MarshalAs(UnmanagedType.LPStruct)] DsLong pStop,
[In] AMSeekingSeekingFlags dwStopFlags
);
[PreserveSig]
int GetPositions(
[Out] out long pCurrent,
[Out] out long pStop
);
[PreserveSig]
int GetAvailable(
[Out] out long pEarliest,
[Out] out long pLatest
);
[PreserveSig]
int SetRate([In] double dRate);
[PreserveSig]
int GetRate([Out] out double pdRate);
[PreserveSig]
int GetPreroll([Out] out long pllPreroll);
}
[ComImport,
Guid("56a8689a-0ad4-11ce-b03a-0020af0ba770"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IMediaSample
{
[PreserveSig]
int GetPointer([Out] out IntPtr ppBuffer); // BYTE **
[PreserveSig]
int GetSize();
[PreserveSig]
int GetTime(
[Out] out long pTimeStart,
[Out] out long pTimeEnd
);
[PreserveSig]
int SetTime(
[In, MarshalAs(UnmanagedType.LPStruct)] DsLong pTimeStart,
[In, MarshalAs(UnmanagedType.LPStruct)] DsLong pTimeEnd
);
[PreserveSig]
int IsSyncPoint();
[PreserveSig]
int SetSyncPoint([In, MarshalAs(UnmanagedType.Bool)] bool bIsSyncPoint);
[PreserveSig]
int IsPreroll();
[PreserveSig]
int SetPreroll([In, MarshalAs(UnmanagedType.Bool)] bool bIsPreroll);
[PreserveSig]
int GetActualDataLength();
[PreserveSig]
int SetActualDataLength([In] int len);
/// <summary>
/// Returned object must be released with DsUtils.FreeAMMediaType()
/// </summary>
[PreserveSig]
int GetMediaType([Out, MarshalAs(UnmanagedType.LPStruct)] out AMMediaType ppMediaType);
[PreserveSig]
int SetMediaType([In, MarshalAs(UnmanagedType.LPStruct)] AMMediaType pMediaType);
[PreserveSig]
int IsDiscontinuity();
[PreserveSig]
int SetDiscontinuity([In, MarshalAs(UnmanagedType.Bool)] bool bDiscontinuity);
[PreserveSig]
int GetMediaTime(
[Out] out long pTimeStart,
[Out] out long pTimeEnd
);
[PreserveSig]
int SetMediaTime(
[In, MarshalAs(UnmanagedType.LPStruct)] DsLong pTimeStart,
[In, MarshalAs(UnmanagedType.LPStruct)] DsLong pTimeEnd
);
}
[ComImport,
Guid("56a86899-0ad4-11ce-b03a-0020af0ba770"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IMediaFilter : IPersist
{
#region IPersist Methods
[PreserveSig]
new int GetClassID(
[Out] out Guid pClassID);
#endregion
[PreserveSig]
int Stop();
[PreserveSig]
int Pause();
[PreserveSig]
int Run([In] long tStart);
[PreserveSig]
int GetState(
[In] int dwMilliSecsTimeout,
[Out] out FilterState filtState
);
[PreserveSig]
int SetSyncSource([In] IReferenceClock pClock);
[PreserveSig]
int GetSyncSource([Out] out IReferenceClock pClock);
}
[ComImport,
Guid("56a86895-0ad4-11ce-b03a-0020af0ba770"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IBaseFilter : IMediaFilter
{
#region IPersist Methods
[PreserveSig]
new int GetClassID(
[Out] out Guid pClassID);
#endregion
#region IMediaFilter Methods
[PreserveSig]
new int Stop();
[PreserveSig]
new int Pause();
[PreserveSig]
new int Run(long tStart);
[PreserveSig]
new int GetState([In] int dwMilliSecsTimeout, [Out] out FilterState filtState);
[PreserveSig]
new int SetSyncSource([In] IReferenceClock pClock);
[PreserveSig]
new int GetSyncSource([Out] out IReferenceClock pClock);
#endregion
[PreserveSig]
int EnumPins([Out] out IEnumPins ppEnum);
[PreserveSig]
int FindPin(
[In, MarshalAs(UnmanagedType.LPWStr)] string Id,
[Out] out IPin ppPin
);
[PreserveSig]
int QueryFilterInfo([Out] out FilterInfo pInfo);
[PreserveSig]
int JoinFilterGraph(
[In] IFilterGraph pGraph,
[In, MarshalAs(UnmanagedType.LPWStr)] string pName
);
[PreserveSig]
int QueryVendorInfo([Out, MarshalAs(UnmanagedType.LPWStr)] out string pVendorInfo);
}
[ComImport,
Guid("56a8689f-0ad4-11ce-b03a-0020af0ba770"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IFilterGraph
{
[PreserveSig]
int AddFilter(
[In] IBaseFilter pFilter,
[In, MarshalAs(UnmanagedType.LPWStr)] string pName
);
[PreserveSig]
int RemoveFilter([In] IBaseFilter pFilter);
[PreserveSig]
int EnumFilters([Out] out IEnumFilters ppEnum);
[PreserveSig]
int FindFilterByName(
[In, MarshalAs(UnmanagedType.LPWStr)] string pName,
[Out] out IBaseFilter ppFilter
);
[PreserveSig]
int ConnectDirect(
[In] IPin ppinOut,
[In] IPin ppinIn,
[In, MarshalAs(UnmanagedType.LPStruct)] AMMediaType pmt
);
[PreserveSig]
[Obsolete("This method is obsolete; use the IFilterGraph2.ReconnectEx method instead.")]
int Reconnect([In] IPin ppin);
[PreserveSig]
int Disconnect([In] IPin ppin);
[PreserveSig]
int SetDefaultSyncSource();
}
[ComImport,
Guid("56a86893-0ad4-11ce-b03a-0020af0ba770"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IEnumFilters
{
[PreserveSig]
int Next(
[In] int cFilters,
[Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)] IBaseFilter[] ppFilter,
[Out] out int pcFetched
);
[PreserveSig]
int Skip([In] int cFilters);
[PreserveSig]
int Reset();
[PreserveSig]
int Clone([Out] out IEnumFilters ppEnum);
}
[ComImport,
Guid("56a86892-0ad4-11ce-b03a-0020af0ba770"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IEnumPins
{
[PreserveSig]
int Next(
[In] int cPins,
[Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)] IPin[] ppPins,
[Out] out int pcFetched
);
[PreserveSig]
int Skip([In] int cPins);
[PreserveSig]
int Reset();
[PreserveSig]
int Clone([Out] out IEnumPins ppEnum);
}
[ComImport,
Guid("56a86897-0ad4-11ce-b03a-0020af0ba770"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IReferenceClock
{
[PreserveSig]
int GetTime([Out] out long pTime);
[PreserveSig]
int AdviseTime(
[In] long baseTime,
[In] long streamTime,
[In] IntPtr hEvent, // System.Threading.WaitHandle?
[Out] out int pdwAdviseCookie
);
[PreserveSig]
int AdvisePeriodic(
[In] long startTime,
[In] long periodTime,
[In] IntPtr hSemaphore, // System.Threading.WaitHandle?
[Out] out int pdwAdviseCookie
);
[PreserveSig]
int Unadvise([In] int dwAdviseCookie);
}
[ComImport,
Guid("89c31040-846b-11ce-97d3-00aa0055595a"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IEnumMediaTypes
{
[PreserveSig]
int Next(
[In] int cMediaTypes,
// SizeParamIndex may have to be 1 because of the [PreserveSig] att
//[In, Out, MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(EMTMarshaler))] AMMediaType[] ppMediaTypes,
//[In, Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] AMMediaType[] ppMediaTypes,
[In, Out] IntPtr ppMediaTypes,
[Out] out int pcFetched
);
[PreserveSig]
int Skip([In] int cMediaTypes);
[PreserveSig]
int Reset();
[PreserveSig]
int Clone([Out] out IEnumMediaTypes ppEnum);
}
[ComImport,
Guid("36b73884-c2c8-11cf-8b46-00805f6cef60"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IMediaSample2 : IMediaSample
{
#region IMediaSample Methods
[PreserveSig]
new int GetPointer([Out] out IntPtr ppBuffer); // BYTE **
[PreserveSig]
new int GetSize();
[PreserveSig]
new int GetTime(
[Out] out long pTimeStart,
[Out] out long pTimeEnd
);
[PreserveSig]
new int SetTime(
[In, MarshalAs(UnmanagedType.LPStruct)] DsLong pTimeStart,
[In, MarshalAs(UnmanagedType.LPStruct)] DsLong pTimeEnd
);
[PreserveSig]
new int IsSyncPoint();
[PreserveSig]
new int SetSyncPoint([In, MarshalAs(UnmanagedType.Bool)] bool bIsSyncPoint);
[PreserveSig]
new int IsPreroll();
[PreserveSig]
new int SetPreroll([In, MarshalAs(UnmanagedType.Bool)] bool bIsPreroll);
[PreserveSig]
new int GetActualDataLength();
[PreserveSig]
new int SetActualDataLength([In] int len);
[PreserveSig]
new int GetMediaType([Out] out AMMediaType ppMediaType);
[PreserveSig]
new int SetMediaType([In] AMMediaType pMediaType);
[PreserveSig]
new int IsDiscontinuity();
[PreserveSig]
new int SetDiscontinuity([In, MarshalAs(UnmanagedType.Bool)] bool bDiscontinuity);
[PreserveSig]
new int GetMediaTime(
[Out] out long pTimeStart,
[Out] out long pTimeEnd
);
[PreserveSig]
new int SetMediaTime(
[In, MarshalAs(UnmanagedType.LPStruct)] DsLong pTimeStart,
[In, MarshalAs(UnmanagedType.LPStruct)] DsLong pTimeEnd
);
#endregion
[PreserveSig]
int GetProperties(
[In] int cbProperties,
[In] IntPtr pbProperties // BYTE *
);
[PreserveSig]
int SetProperties(
[In] int cbProperties,
[In] IntPtr pbProperties // BYTE *
);
}
[ComImport,
Guid("92980b30-c1de-11d2-abf5-00a0c905f375"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IMemAllocatorNotifyCallbackTemp
{
[PreserveSig]
int NotifyRelease();
}
[ComImport,
Guid("379a0cf0-c1de-11d2-abf5-00a0c905f375"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IMemAllocatorCallbackTemp : IMemAllocator
{
#region IMemAllocator Methods
[PreserveSig]
new int SetProperties(
[In] AllocatorProperties pRequest,
[Out, MarshalAs(UnmanagedType.LPStruct)] AllocatorProperties pActual
);
[PreserveSig]
new int GetProperties([Out] AllocatorProperties pProps);
[PreserveSig]
new int Commit();
[PreserveSig]
new int Decommit();
[PreserveSig]
new int GetBuffer(
[Out] out IMediaSample ppBuffer,
[In, MarshalAs(UnmanagedType.LPStruct)] DsLong pStartTime,
[In, MarshalAs(UnmanagedType.LPStruct)] DsLong pEndTime,
[In] AMGBF dwFlags
);
[PreserveSig]
new int ReleaseBuffer([In] IMediaSample pBuffer);
#endregion
[PreserveSig]
int SetNotify([In] IMemAllocatorNotifyCallbackTemp pNotify);
[PreserveSig]
int GetFreeCount([Out] out int plBuffersFree);
}
[ComImport,
Guid("56a8689c-0ad4-11ce-b03a-0020af0ba770"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IMemAllocator
{
[PreserveSig]
int SetProperties(
[In, MarshalAs(UnmanagedType.LPStruct)] AllocatorProperties pRequest,
[Out, MarshalAs(UnmanagedType.LPStruct)] AllocatorProperties pActual
);
[PreserveSig]
int GetProperties(
[Out, MarshalAs(UnmanagedType.LPStruct)] AllocatorProperties pProps
);
[PreserveSig]
int Commit();
[PreserveSig]
int Decommit();
[PreserveSig]
int GetBuffer(
[Out] out IMediaSample ppBuffer,
[In, MarshalAs(UnmanagedType.LPStruct)] DsLong pStartTime,
[In, MarshalAs(UnmanagedType.LPStruct)] DsLong pEndTime,
[In] AMGBF dwFlags
);
[PreserveSig]
int ReleaseBuffer(
[In] IMediaSample pBuffer
);
}
#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.Globalization;
using System.Diagnostics;
using System.Text;
using System.Runtime.CompilerServices;
namespace System
{
// A Version object contains four hierarchical numeric components: major, minor,
// build and revision. Build and revision may be unspecified, which is represented
// internally as a -1. By definition, an unspecified component matches anything
// (both unspecified and specified), and an unspecified component is "less than" any
// specified component.
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public sealed class Version : ICloneable, IComparable, IComparable<Version>, IEquatable<Version>, ISpanFormattable
{
// AssemblyName depends on the order staying the same
private readonly int _Major; // Do not rename (binary serialization)
private readonly int _Minor; // Do not rename (binary serialization)
private readonly int _Build = -1; // Do not rename (binary serialization)
private readonly int _Revision = -1; // Do not rename (binary serialization)
public Version(int major, int minor, int build, int revision)
{
if (major < 0)
throw new ArgumentOutOfRangeException(nameof(major), SR.ArgumentOutOfRange_Version);
if (minor < 0)
throw new ArgumentOutOfRangeException(nameof(minor), SR.ArgumentOutOfRange_Version);
if (build < 0)
throw new ArgumentOutOfRangeException(nameof(build), SR.ArgumentOutOfRange_Version);
if (revision < 0)
throw new ArgumentOutOfRangeException(nameof(revision), SR.ArgumentOutOfRange_Version);
_Major = major;
_Minor = minor;
_Build = build;
_Revision = revision;
}
public Version(int major, int minor, int build)
{
if (major < 0)
throw new ArgumentOutOfRangeException(nameof(major), SR.ArgumentOutOfRange_Version);
if (minor < 0)
throw new ArgumentOutOfRangeException(nameof(minor), SR.ArgumentOutOfRange_Version);
if (build < 0)
throw new ArgumentOutOfRangeException(nameof(build), SR.ArgumentOutOfRange_Version);
_Major = major;
_Minor = minor;
_Build = build;
}
public Version(int major, int minor)
{
if (major < 0)
throw new ArgumentOutOfRangeException(nameof(major), SR.ArgumentOutOfRange_Version);
if (minor < 0)
throw new ArgumentOutOfRangeException(nameof(minor), SR.ArgumentOutOfRange_Version);
_Major = major;
_Minor = minor;
}
public Version(string version)
{
Version v = Version.Parse(version);
_Major = v.Major;
_Minor = v.Minor;
_Build = v.Build;
_Revision = v.Revision;
}
public Version()
{
_Major = 0;
_Minor = 0;
}
private Version(Version version)
{
Debug.Assert(version != null);
_Major = version._Major;
_Minor = version._Minor;
_Build = version._Build;
_Revision = version._Revision;
}
public object Clone()
{
return new Version(this);
}
// Properties for setting and getting version numbers
public int Major
{
get { return _Major; }
}
public int Minor
{
get { return _Minor; }
}
public int Build
{
get { return _Build; }
}
public int Revision
{
get { return _Revision; }
}
public short MajorRevision
{
get { return (short)(_Revision >> 16); }
}
public short MinorRevision
{
get { return (short)(_Revision & 0xFFFF); }
}
public int CompareTo(object version)
{
if (version == null)
{
return 1;
}
Version v = version as Version;
if (v == null)
{
throw new ArgumentException(SR.Arg_MustBeVersion);
}
return CompareTo(v);
}
public int CompareTo(Version value)
{
return
object.ReferenceEquals(value, this) ? 0 :
value is null ? 1 :
_Major != value._Major ? (_Major > value._Major ? 1 : -1) :
_Minor != value._Minor ? (_Minor > value._Minor ? 1 : -1) :
_Build != value._Build ? (_Build > value._Build ? 1 : -1) :
_Revision != value._Revision ? (_Revision > value._Revision ? 1 : -1) :
0;
}
public override bool Equals(object obj)
{
return Equals(obj as Version);
}
public bool Equals(Version obj)
{
return object.ReferenceEquals(obj, this) ||
(!(obj is null) &&
_Major == obj._Major &&
_Minor == obj._Minor &&
_Build == obj._Build &&
_Revision == obj._Revision);
}
public override int GetHashCode()
{
// Let's assume that most version numbers will be pretty small and just
// OR some lower order bits together.
int accumulator = 0;
accumulator |= (_Major & 0x0000000F) << 28;
accumulator |= (_Minor & 0x000000FF) << 20;
accumulator |= (_Build & 0x000000FF) << 12;
accumulator |= (_Revision & 0x00000FFF);
return accumulator;
}
public override string ToString() =>
ToString(DefaultFormatFieldCount);
public string ToString(int fieldCount) =>
fieldCount == 0 ? string.Empty :
fieldCount == 1 ? _Major.ToString() :
StringBuilderCache.GetStringAndRelease(ToCachedStringBuilder(fieldCount));
public bool TryFormat(Span<char> destination, out int charsWritten) =>
TryFormat(destination, DefaultFormatFieldCount, out charsWritten);
public bool TryFormat(Span<char> destination, int fieldCount, out int charsWritten)
{
if (fieldCount == 0)
{
charsWritten = 0;
return true;
}
else if (fieldCount == 1)
{
return _Major.TryFormat(destination, out charsWritten);
}
StringBuilder sb = ToCachedStringBuilder(fieldCount);
if (sb.Length <= destination.Length)
{
sb.CopyTo(0, destination, sb.Length);
StringBuilderCache.Release(sb);
charsWritten = sb.Length;
return true;
}
StringBuilderCache.Release(sb);
charsWritten = 0;
return false;
}
bool ISpanFormattable.TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format, IFormatProvider provider)
{
// format and provider are ignored.
return TryFormat(destination, out charsWritten);
}
private int DefaultFormatFieldCount =>
_Build == -1 ? 2 :
_Revision == -1 ? 3 :
4;
private StringBuilder ToCachedStringBuilder(int fieldCount)
{
// Note: As we always have positive numbers then it is safe to convert the number to string
// regardless of the current culture as we'll not have any punctuation marks in the number.
if (fieldCount == 2)
{
StringBuilder sb = StringBuilderCache.Acquire();
sb.Append(_Major);
sb.Append('.');
sb.Append(_Minor);
return sb;
}
else
{
if (_Build == -1)
{
throw new ArgumentException(SR.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, "0", "2"), nameof(fieldCount));
}
if (fieldCount == 3)
{
StringBuilder sb = StringBuilderCache.Acquire();
sb.Append(_Major);
sb.Append('.');
sb.Append(_Minor);
sb.Append('.');
sb.Append(_Build);
return sb;
}
if (_Revision == -1)
{
throw new ArgumentException(SR.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, "0", "3"), nameof(fieldCount));
}
if (fieldCount == 4)
{
StringBuilder sb = StringBuilderCache.Acquire();
sb.Append(_Major);
sb.Append('.');
sb.Append(_Minor);
sb.Append('.');
sb.Append(_Build);
sb.Append('.');
sb.Append(_Revision);
return sb;
}
throw new ArgumentException(SR.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, "0", "4"), nameof(fieldCount));
}
}
public static Version Parse(string input)
{
if (input == null)
{
throw new ArgumentNullException(nameof(input));
}
return ParseVersion(input.AsSpan(), throwOnFailure: true);
}
public static Version Parse(ReadOnlySpan<char> input) =>
ParseVersion(input, throwOnFailure: true);
public static bool TryParse(string input, out Version result)
{
if (input == null)
{
result = null;
return false;
}
return (result = ParseVersion(input.AsSpan(), throwOnFailure: false)) != null;
}
public static bool TryParse(ReadOnlySpan<char> input, out Version result) =>
(result = ParseVersion(input, throwOnFailure: false)) != null;
private static Version ParseVersion(ReadOnlySpan<char> input, bool throwOnFailure)
{
// Find the separator between major and minor. It must exist.
int majorEnd = input.IndexOf('.');
if (majorEnd < 0)
{
if (throwOnFailure) throw new ArgumentException(SR.Arg_VersionString, nameof(input));
return null;
}
// Find the ends of the optional minor and build portions.
// We musn't have any separators after build.
int buildEnd = -1;
int minorEnd = input.Slice(majorEnd + 1).IndexOf('.');
if (minorEnd != -1)
{
minorEnd += (majorEnd + 1);
buildEnd = input.Slice(minorEnd + 1).IndexOf('.');
if (buildEnd != -1)
{
buildEnd += (minorEnd + 1);
if (input.Slice(buildEnd + 1).Contains('.'))
{
if (throwOnFailure) throw new ArgumentException(SR.Arg_VersionString, nameof(input));
return null;
}
}
}
int minor, build, revision;
// Parse the major version
if (!TryParseComponent(input.Slice(0, majorEnd), nameof(input), throwOnFailure, out int major))
{
return null;
}
if (minorEnd != -1)
{
// If there's more than a major and minor, parse the minor, too.
if (!TryParseComponent(input.Slice(majorEnd + 1, minorEnd - majorEnd - 1), nameof(input), throwOnFailure, out minor))
{
return null;
}
if (buildEnd != -1)
{
// major.minor.build.revision
return
TryParseComponent(input.Slice(minorEnd + 1, buildEnd - minorEnd - 1), nameof(build), throwOnFailure, out build) &&
TryParseComponent(input.Slice(buildEnd + 1), nameof(revision), throwOnFailure, out revision) ?
new Version(major, minor, build, revision) :
null;
}
else
{
// major.minor.build
return TryParseComponent(input.Slice(minorEnd + 1), nameof(build), throwOnFailure, out build) ?
new Version(major, minor, build) :
null;
}
}
else
{
// major.minor
return TryParseComponent(input.Slice(majorEnd + 1), nameof(input), throwOnFailure, out minor) ?
new Version(major, minor) :
null;
}
}
private static bool TryParseComponent(ReadOnlySpan<char> component, string componentName, bool throwOnFailure, out int parsedComponent)
{
if (throwOnFailure)
{
if ((parsedComponent = int.Parse(component, NumberStyles.Integer, CultureInfo.InvariantCulture)) < 0)
{
throw new ArgumentOutOfRangeException(componentName, SR.ArgumentOutOfRange_Version);
}
return true;
}
return int.TryParse(component, NumberStyles.Integer, CultureInfo.InvariantCulture, out parsedComponent) && parsedComponent >= 0;
}
// Force inline as the true/false ternary takes it above ALWAYS_INLINE size even though the asm ends up smaller
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(Version v1, Version v2)
{
// Test "right" first to allow branch elimination when inlined for null checks (== null)
// so it can become a simple test
if (v2 is null)
{
// return true/false not the test result https://github.com/dotnet/coreclr/issues/914
return (v1 is null) ? true : false;
}
// Quick reference equality test prior to calling the virtual Equality
return ReferenceEquals(v2, v1) ? true : v2.Equals(v1);
}
public static bool operator !=(Version v1, Version v2)
{
return !(v1 == v2);
}
public static bool operator <(Version v1, Version v2)
{
if ((object)v1 == null)
throw new ArgumentNullException(nameof(v1));
return (v1.CompareTo(v2) < 0);
}
public static bool operator <=(Version v1, Version v2)
{
if ((object)v1 == null)
throw new ArgumentNullException(nameof(v1));
return (v1.CompareTo(v2) <= 0);
}
public static bool operator >(Version v1, Version v2)
{
return (v2 < v1);
}
public static bool operator >=(Version v1, Version v2)
{
return (v2 <= v1);
}
}
}
| |
using Castle.Core.Logging;
namespace Castle.Transactions.IO
{
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Transactions;
using Castle.IO;
using Castle.IO.FileSystems.Local.Win32.Interop;
using Castle.Transactions.IO.Internal;
using NativeMethods = Castle.Transactions.IO.Interop.NativeMethods;
using Path = Castle.IO.Path;
using Transaction = Castle.Transactions.Transaction;
using TransactionException = Castle.Transactions.TransactionException;
///<summary>
/// Represents a transaction on transactional kernels
/// like the Vista kernel or Server 2008 kernel and newer.
///</summary>
///<remarks>
/// Good information for dealing with the peculiarities of the runtime:
/// http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.safehandle.aspx
///</remarks>
internal sealed class FileTransaction : IFileAdapter, IDirectoryAdapter, IFileTransaction
{
private readonly ITransaction _Inner;
private readonly string _Name;
private SafeKernelTransactionHandle _TransactionHandle;
private TransactionState _State;
#region Constructors
public FileTransaction()
: this(null)
{
}
public FileTransaction(string name)
{
_Name = name;
InnerBegin();
_State = TransactionState.Active;
}
public FileTransaction(string name, CommittableTransaction inner, uint stackDepth, ITransactionOptions creationOptions,
Action onDispose)
{
Contract.Requires(inner != null);
Contract.Requires(creationOptions != null);
_Inner = new Transaction(inner, stackDepth, creationOptions, onDispose, NullLogger.Instance);
_Name = name;
InnerBegin();
}
public FileTransaction(string name, DependentTransaction inner, uint stackDepth, ITransactionOptions creationOptions,
Action onDispose)
{
Contract.Requires(inner != null);
Contract.Requires(creationOptions != null);
_Inner = new Transaction(inner, stackDepth, creationOptions, onDispose, NullLogger.Instance);
_Name = name;
InnerBegin();
}
[ContractInvariantMethod]
private void Invariant()
{
Contract.Invariant(_Inner == null || _State == _Inner.State);
}
#endregion
///<summary>
/// Gets the name of the transaction.
///</summary>
public string Name
{
get { return _Name ?? string.Format("FileTransaction#{0}", GetHashCode()); }
}
private void InnerBegin()
{
Contract.Ensures(_State == TransactionState.Active);
// we have a ongoing current transaction, join it!
if (System.Transactions.Transaction.Current != null)
{
var ktx = (IKernelTransaction) TransactionInterop.GetDtcTransaction(System.Transactions.Transaction.Current);
SafeKernelTransactionHandle handle;
ktx.GetHandle(out handle);
// even though _TransactionHandle can already contain a handle if this thread
// had been yielded just before setting this reference, the "safe"-ness of the wrapper should
// not dispose the other handle which is now removed
_TransactionHandle = handle;
//IsAmbient = true; // TODO: Perhaps we created this item and we need to notify the transaction manager...
}
else _TransactionHandle = NativeMethods.CreateTransaction(string.Format("{0} Transaction", _Name));
if (!_TransactionHandle.IsInvalid)
{
_State = TransactionState.Active;
return;
}
throw new TransactionException(
"Cannot begin file transaction. CreateTransaction failed and there's no ambient transaction.",
LastEx());
}
TransactionState ITransaction.State
{
get { return _Inner != null ? _Inner.State : _State; }
}
ITransactionOptions ITransaction.CreationOptions
{
get { return _Inner != null ? _Inner.CreationOptions : new DefaultTransactionOptions(); }
}
System.Transactions.Transaction ITransaction.Inner
{
get { return _Inner != null ? _Inner.Inner : null; }
}
//Maybe<SafeKernelTransactionHandle> ITransaction.KernelTransactionHandle
//{
// get
// {
// return _TransactionHandle != null && !_TransactionHandle.IsInvalid
// ? Maybe.Some(_TransactionHandle)
// : Maybe.None<SafeKernelTransactionHandle>();
// }
//}
//Maybe<IRetryPolicy> ITransaction.FailedPolicy
//{
// get { return _Inner != null ? _Inner.FailedPolicy : Maybe.None<IRetryPolicy>(); }
//}
string ITransaction.LocalIdentifier
{
get { return _Inner != null ? _Inner.LocalIdentifier : _Name; }
}
void ITransaction.Rollback()
{
try
{
if (!NativeMethods.RollbackTransaction(_TransactionHandle))
throw new TransactionException("Rollback failed.", LastEx());
if (_Inner != null)
_Inner.Rollback();
}
finally
{
_State = TransactionState.Aborted;
}
}
void ITransaction.Complete()
{
try
{
if (_Inner != null && _Inner.State == TransactionState.Active)
_Inner.Complete();
if (!NativeMethods.CommitTransaction(_TransactionHandle))
throw new TransactionException("Commit failed.", LastEx());
_State = TransactionState.CommittedOrCompleted;
}
finally
{
_State = _State != TransactionState.CommittedOrCompleted
? TransactionState.Aborted
: TransactionState.CommittedOrCompleted;
}
}
#region State - defensive programming
private void AssertState(TransactionState status, string msg = null)
{
if (status == _State)
return;
if (!string.IsNullOrEmpty(msg))
throw new TransactionException(msg);
throw new TransactionException(string.Format("State failure; should have been {0} but was {1}",
status, _State));
}
#endregion
Maybe<SafeKernelTransactionHandle> IFileTransaction.Handle
{
get { return _TransactionHandle; }
}
#region IFileAdapter members
FileStream IFileAdapter.Create(string path)
{
AssertState(TransactionState.Active);
return Open(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None);
}
void IFileAdapter.Delete(string filePath)
{
AssertState(TransactionState.Active);
if (!NativeMethods.DeleteFileTransactedW(filePath, _TransactionHandle))
throw new TransactionException("Unable to perform transacted file delete.", LastEx());
}
FileStream IFileAdapter.Open(string filePath, FileMode mode)
{
return Open(filePath, mode, FileAccess.ReadWrite, FileShare.None);
}
FileStream IFileAdapter.OpenWrite(string path)
{
return Open(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read);
}
//int IFileAdapter.WriteStream(string targetPath, Stream sourceStream)
//{
// throw new NotSupportedException("Use the file adapter instead!");
//}
//string IFileAdapter.ReadAllText(string path, Encoding encoding)
//{
// AssertState(TransactionState.Active);
// using (var reader = new StreamReader(Open(path, FileMode.Open, FileAccess.Read, FileShare.Read), encoding))
// {
// return reader.ReadToEnd();
// }
//}
void IFileAdapter.Move(string originalFilePath, string newFilePath)
{
// case 1, the new file path is a folder
if (((IDirectoryAdapter) this).Exists(newFilePath))
{
var fileName = Path.GetFileName(originalFilePath);
Contract.Assume(fileName.Length > 0, "by pre-condition of IFileAdapterContract.Move");
NativeMethods.MoveFileTransacted(originalFilePath, System.IO.Path.Combine(newFilePath, fileName), IntPtr.Zero,
IntPtr.Zero, MoveFileFlags.CopyAllowed,
_TransactionHandle);
return;
}
// case 2, its not a folder, so assume it's a file.
NativeMethods.MoveFileTransacted(originalFilePath, newFilePath, IntPtr.Zero, IntPtr.Zero,
MoveFileFlags.CopyAllowed,
_TransactionHandle);
}
public void Move(string originalPath, string newPath, bool overwrite)
{
var flags = MoveFileFlags.CopyAllowed;
if (overwrite)
flags |= MoveFileFlags.ReplaceExisting;
NativeMethods.MoveFileTransacted(originalPath, newPath, IntPtr.Zero, IntPtr.Zero, flags, _TransactionHandle);
}
bool IFileAdapter.Exists(string filePath)
{
AssertState(TransactionState.Active);
using (var handle = NativeMethods.FindFirstFileTransacted(filePath, false, _TransactionHandle))
return !handle.IsInvalid;
}
//string IFileAdapter.ReadAllText(string path)
//{
// AssertState(TransactionState.Active);
// using (var reader = new StreamReader(Open(path, FileMode.Open, FileAccess.Read, FileShare.Read)))
// return reader.ReadToEnd();
//}
//void IFileAdapter.WriteAllText(string targetPath, string contents)
//{
// AssertState(TransactionState.Active);
// var exists = ((IFileAdapter) this).Exists(targetPath);
// var fileMode = exists ? FileMode.Truncate : FileMode.OpenOrCreate;
// using (var writer = new StreamWriter(Open(targetPath, fileMode, FileAccess.Write, FileShare.None)))
// writer.Write(contents);
//}
//IEnumerable<string> IFileAdapter.ReadAllLines(string filePath)
//{
// throw new NotImplementedException();
//}
StreamWriter IFileAdapter.CreateText(string filePath)
{
throw new NotImplementedException();
}
#endregion
#region IDirectoryAdapter members
///<summary>
/// Creates a directory at the path given.
///</summary>
///<param name = "path">The path to create the directory at.</param>
// TODO: Move this method to Create() on IDirectory.
bool IDirectoryAdapter.Create(string path)
{
AssertState(TransactionState.Active);
path = Path.NormDirSepChars(CleanPathEnd(path));
// we don't need to re-create existing folders.
if (((IDirectoryAdapter) this).Exists(path))
return true;
var nonExistent = new Stack<string>();
nonExistent.Push(path);
var curr = path;
while (!((IDirectoryAdapter) this).Exists(curr)
&& (curr.Contains(Path.DirectorySeparatorChar)
|| curr.Contains(Path.AltDirectorySeparatorChar)))
{
curr = Path.GetPathWithoutLastBit(curr).ToString();
if (!((IDirectoryAdapter) this).Exists(curr))
nonExistent.Push(curr);
}
while (nonExistent.Count > 0)
{
if (!CreateDirectoryTransacted(nonExistent.Pop()))
{
throw new TransactionException(string.Format("Failed to create directory \"{1}\" at path \"{0}\". "
+ "See inner exception for more details.", path, curr),
LastEx());
}
}
return false;
}
/// <summary>
/// Deletes a folder recursively.
/// </summary>
/// <param name = "path">The directory path to start deleting at!</param>
void IDirectoryAdapter.Delete(string path)
{
AssertState(TransactionState.Active);
if (!NativeMethods.RemoveDirectoryTransactedW(path, _TransactionHandle))
throw new TransactionException("Unable to delete folder. See inner exception for details.",
LastEx());
}
/// <summary>
/// Checks whether the path exists.
/// </summary>
/// <param name = "path">Path to check.</param>
/// <returns>True if it exists, false otherwise.</returns>
bool IDirectoryAdapter.Exists(string path)
{
AssertState(TransactionState.Active);
path = CleanPathEnd(path);
using (var handle = NativeMethods.FindFirstFileTransacted(path, true, _TransactionHandle))
return !handle.IsInvalid;
}
string IDirectoryAdapter.GetFullPath(string relativePath)
{
AssertState(TransactionState.Active);
return GetFullPathNameTransacted(relativePath);
}
string IDirectoryAdapter.MapPath(string path)
{
throw new NotSupportedException("Implemented on the directory adapter.");
}
void IDirectoryAdapter.Move(string originalPath, string newPath)
{
var da = ((IDirectoryAdapter) this);
if (!da.Exists(originalPath))
throw new DirectoryNotFoundException(
string.Format("The path \"{0}\" could not be found. The source directory needs to exist.",
originalPath));
if (!da.Exists(newPath))
da.Create(newPath);
if (!NativeMethods.MoveFileTransacted(originalPath, newPath, IntPtr.Zero, IntPtr.Zero,
MoveFileFlags.ReplaceExisting, _TransactionHandle))
throw new TransactionException("Could not move directory", LastEx());
//RecurseFiles(originalPath, f => { Console.WriteLine("file: {0}", f); return true; },
// d => { Console.WriteLine("dir: {0}", d); return true; });
}
/// <summary>
/// Deletes an empty directory
/// </summary>
/// <param name = "path">The path to the folder to delete.</param>
/// <param name = "recursively">
/// Whether to delete recursively or not.
/// When recursive, we delete all subfolders and files in the given
/// directory as well.
/// </param>
bool IDirectoryAdapter.Delete(string path, bool recursively)
{
AssertState(TransactionState.Active);
return recursively
? DeleteRecursive(path)
: NativeMethods.RemoveDirectoryTransactedW(path, _TransactionHandle);
}
#endregion
#region Dispose-pattern
void ITransaction.Dispose()
{
Dispose();
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
/// <filterpriority>2</filterpriority>
public void Dispose()
{
Dispose(true);
// the base transaction dispose all resources active, so we must be careful
// and call our own resources first, thereby having to call this afterwards.
//base.Dispose();
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
// no unmanaged code here, just return.
if (!disposing) return;
if (_State == TransactionState.Disposed) return;
// called via the Dispose() method on IDisposable,
// can use private object references.
try
{
if (_State == TransactionState.Active)
((ITransaction) this).Rollback();
if (_TransactionHandle != null)
_TransactionHandle.Dispose();
if (_Inner != null)
_Inner.Dispose();
}
finally
{
_State = TransactionState.Disposed;
}
}
#endregion
#region Helper methods
/// <summary>
/// Creates a file handle with the current ongoing transaction.
/// </summary>
/// <param name = "path">The path of the file.</param>
/// <param name = "mode">The file mode, i.e. what is going to be done if it exists etc.</param>
/// <param name = "access">The access rights this handle has.</param>
/// <param name = "share">What other handles may be opened; sharing settings.</param>
/// <returns>A safe file handle. Not null, but may be invalid.</returns>
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope",
Justification = "This method's aim IS to provide a disposable resource.")]
private FileStream Open(string path, FileMode mode, FileAccess access, FileShare share)
{
// Future: Support System.IO.FileOptions which is the dwFlagsAndAttribute parameter.
var fileHandle = NativeMethods.CreateFileTransactedW(path,
access.ToNative(),
share.ToNative(),
IntPtr.Zero,
mode.ToNative(),
0, IntPtr.Zero,
_TransactionHandle,
IntPtr.Zero, IntPtr.Zero);
var error = Marshal.GetLastWin32Error();
if (fileHandle.IsInvalid)
{
var baseStr = string.Format("Transaction \"{1}\": Unable to open a file descriptor to \"{0}\".", path,
Name ?? "[no name]");
if (error == TxFCodes.ERROR_TRANSACTIONAL_CONFLICT)
throw new TransactionalConflictException(baseStr
+
" You will get this error if you are accessing the transacted file from a non-transacted API before the transaction has "
+ "committed. See HelperLink for details.",
new Uri("http://msdn.microsoft.com/en-us/library/aa365536%28VS.85%29.aspx"));
throw new TransactionException(baseStr + "Please see the inner exceptions for details.",
LastEx());
}
return new FileStream(fileHandle, access);
}
private bool CreateDirectoryTransacted(string templatePath,
string dirPath)
{
return NativeMethods.CreateDirectoryTransactedW(templatePath,
dirPath,
IntPtr.Zero,
_TransactionHandle);
}
private bool CreateDirectoryTransacted(string dirPath)
{
return CreateDirectoryTransacted(null, dirPath);
}
private bool DeleteRecursive(string path)
{
Contract.Requires(!string.IsNullOrEmpty(path));
return RecurseFiles(path,
file => NativeMethods.DeleteFileTransactedW(file, _TransactionHandle),
dir => NativeMethods.RemoveDirectoryTransactedW(dir, _TransactionHandle));
}
private bool RecurseFiles(string path,
Func<string, bool> operationOnFiles,
Func<string, bool> operationOnDirectories)
{
Contract.Requires(!string.IsNullOrEmpty(path));
WIN32_FIND_DATA findData;
var addPrefix = !path.StartsWith(@"\\?\");
var ok = true;
var pathWithoutSufflix = addPrefix ? @"\\?\" + Path.GetFullPath(path) : Path.GetFullPath(path);
path = pathWithoutSufflix + "\\*";
using (var findHandle = NativeMethods.FindFirstFileTransactedW(path, _TransactionHandle, out findData))
{
if (findHandle.IsInvalid) return false;
do
{
Contract.Assume(!string.IsNullOrEmpty(findData.cFileName) && findData.cFileName.Length > 0,
"or otherwise FindNextFile should have returned false");
var subPath = System.IO.Path.Combine(pathWithoutSufflix, findData.cFileName);
if ((findData.dwFileAttributes & FileAttributes.Directory) != 0)
{
if (findData.cFileName != "." && findData.cFileName != "..")
ok &= DeleteRecursive(subPath);
}
else
ok = ok && operationOnFiles(subPath);
} while (Castle.IO.FileSystems.Local.Win32.Interop.NativeMethods.FindNextFile(findHandle, out findData));
}
return ok && operationOnDirectories(pathWithoutSufflix);
}
private string GetFullPathNameTransacted(string dirOrFilePath)
{
var sb = new StringBuilder(512);
retry:
var p = IntPtr.Zero;
var res = NativeMethods.GetFullPathNameTransactedW(dirOrFilePath,
sb.Capacity,
sb,
ref p, // here we can check if it's a file or not.
_TransactionHandle);
if (res == 0) // failure
{
throw new TransactionException(
string.Format("Could not get full path for \"{0}\", see inner exception for details.",
dirOrFilePath), LastEx());
}
if (res > sb.Capacity)
{
sb.Capacity = res; // update capacity
goto retry; // handle edge case if the path.Length > 512.
}
return sb.ToString();
}
// more examples in C++:
// http://msdn.microsoft.com/en-us/library/aa364963(VS.85).aspx
// http://msdn.microsoft.com/en-us/library/x3txb6xc.aspx
#endregion
// ReSharper restore UnusedMember.Local
// ReSharper restore InconsistentNaming
#pragma warning restore 1591
private static string CleanPathEnd(string path)
{
return path.TrimEnd('/', '\\');
}
private static Exception LastEx()
{
return Marshal.GetExceptionForHR(Marshal.GetLastWin32Error());
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.CSharp;
using OpenSim.Region.ScriptEngine.Shared.CodeTools;
using System.CodeDom.Compiler;
namespace OpenSim.Tools.LSL.Compiler
{
class Program
{
// Commented out because generated warning since m_positionMap could never be anything other than null
// private static Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> m_positionMap;
private static CSharpCodeProvider CScodeProvider = new CSharpCodeProvider();
static void Main(string[] args)
{
string source = null;
if (args.Length == 0)
{
Console.WriteLine("No input file specified");
Environment.Exit(1);
}
if (!File.Exists(args[0]))
{
Console.WriteLine("Input file does not exist");
Environment.Exit(1);
}
try
{
ICodeConverter cvt = (ICodeConverter) new CSCodeGenerator();
source = cvt.Convert(File.ReadAllText(args[0]));
}
catch(Exception e)
{
Console.WriteLine("Conversion failed:\n"+e.Message);
Environment.Exit(1);
}
source = CreateCSCompilerScript(source);
try
{
Console.WriteLine(CompileFromDotNetText(source,"a.out"));
}
catch(Exception e)
{
Console.WriteLine("Conversion failed: "+e.Message);
Environment.Exit(1);
}
Environment.Exit(0);
}
private static string CreateCSCompilerScript(string compileScript)
{
compileScript = String.Empty +
"using OpenSim.Region.ScriptEngine.Shared; using System.Collections.Generic;\r\n" +
String.Empty + "namespace SecondLife { " +
String.Empty + "public class Script : OpenSim.Region.ScriptEngine.Shared.ScriptBase.ScriptBaseClass { \r\n" +
@"public Script() { } " +
compileScript +
"} }\r\n";
return compileScript;
}
private static string CompileFromDotNetText(string Script, string asset)
{
string OutFile = asset;
string disp ="OK";
try
{
File.Delete(OutFile);
}
catch (Exception e) // NOTLEGIT - Should be just FileIOException
{
throw new Exception("Unable to delete old existing "+
"script-file before writing new. Compile aborted: " +
e.ToString());
}
// Do actual compile
CompilerParameters parameters = new CompilerParameters();
parameters.IncludeDebugInformation = true;
string rootPath =
Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory);
parameters.ReferencedAssemblies.Add(Path.Combine(rootPath,
"OpenSim.Region.ScriptEngine.Shared.dll"));
parameters.ReferencedAssemblies.Add(Path.Combine(rootPath,
"OpenSim.Region.ScriptEngine.Shared.Api.Runtime.dll"));
parameters.GenerateExecutable = false;
parameters.OutputAssembly = OutFile;
parameters.IncludeDebugInformation = true;
parameters.WarningLevel = 1;
parameters.TreatWarningsAsErrors = false;
CompilerResults results = CScodeProvider.CompileAssemblyFromSource(parameters, Script);
if (results.Errors.Count > 0)
{
string errtext = String.Empty;
foreach (CompilerError CompErr in results.Errors)
{
string severity = CompErr.IsWarning ? "Warning" : "Error";
KeyValuePair<int, int> lslPos;
lslPos = FindErrorPosition(CompErr.Line, CompErr.Column);
string text = CompErr.ErrorText;
text = ReplaceTypes(CompErr.ErrorText);
// The Second Life viewer's script editor begins
// countingn lines and columns at 0, so we subtract 1.
errtext += String.Format("Line ({0},{1}): {4} {2}: {3}\n",
lslPos.Key - 1, lslPos.Value - 1,
CompErr.ErrorNumber, text, severity);
}
disp = "Completed with errors";
if (!File.Exists(OutFile))
{
throw new Exception(errtext);
}
}
if (!File.Exists(OutFile))
{
string errtext = String.Empty;
errtext += "No compile error. But not able to locate compiled file.";
throw new Exception(errtext);
}
// Because windows likes to perform exclusive locks, we simply
// write out a textual representation of the file here
//
// Read the binary file into a buffer
//
FileInfo fi = new FileInfo(OutFile);
if (fi == null)
{
string errtext = String.Empty;
errtext += "No compile error. But not able to stat file.";
throw new Exception(errtext);
}
Byte[] data = new Byte[fi.Length];
try
{
FileStream fs = File.Open(OutFile, FileMode.Open, FileAccess.Read);
fs.Read(data, 0, data.Length);
fs.Close();
}
catch (Exception)
{
string errtext = String.Empty;
errtext += "No compile error. But not able to open file.";
throw new Exception(errtext);
}
// Convert to base64
//
string filetext = System.Convert.ToBase64String(data);
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
Byte[] buf = enc.GetBytes(filetext);
FileStream sfs = File.Create(OutFile+".text");
sfs.Write(buf, 0, buf.Length);
sfs.Close();
string posmap = String.Empty;
// if (m_positionMap != null)
// {
// foreach (KeyValuePair<KeyValuePair<int, int>, KeyValuePair<int, int>> kvp in m_positionMap)
// {
// KeyValuePair<int, int> k = kvp.Key;
// KeyValuePair<int, int> v = kvp.Value;
// posmap += String.Format("{0},{1},{2},{3}\n",
// k.Key, k.Value, v.Key, v.Value);
// }
// }
buf = enc.GetBytes(posmap);
FileStream mfs = File.Create(OutFile+".map");
mfs.Write(buf, 0, buf.Length);
mfs.Close();
return disp;
}
private static string ReplaceTypes(string message)
{
message = message.Replace(
"OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString",
"string");
message = message.Replace(
"OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger",
"integer");
message = message.Replace(
"OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat",
"float");
message = message.Replace(
"OpenSim.Region.ScriptEngine.Shared.LSL_Types.list",
"list");
return message;
}
private static KeyValuePair<int, int> FindErrorPosition(int line, int col)
{
//return FindErrorPosition(line, col, m_positionMap);
return FindErrorPosition(line, col, null);
}
private class kvpSorter : IComparer<KeyValuePair<int,int>>
{
public int Compare(KeyValuePair<int,int> a,
KeyValuePair<int,int> b)
{
return a.Key.CompareTo(b.Key);
}
}
public static KeyValuePair<int, int> FindErrorPosition(int line,
int col, Dictionary<KeyValuePair<int, int>,
KeyValuePair<int, int>> positionMap)
{
if (positionMap == null || positionMap.Count == 0)
return new KeyValuePair<int, int>(line, col);
KeyValuePair<int, int> ret = new KeyValuePair<int, int>();
if (positionMap.TryGetValue(new KeyValuePair<int, int>(line, col),
out ret))
return ret;
List<KeyValuePair<int,int>> sorted =
new List<KeyValuePair<int,int>>(positionMap.Keys);
sorted.Sort(new kvpSorter());
int l = 1;
int c = 1;
foreach (KeyValuePair<int, int> cspos in sorted)
{
if (cspos.Key >= line)
{
if (cspos.Key > line)
return new KeyValuePair<int, int>(l, c);
if (cspos.Value > col)
return new KeyValuePair<int, int>(l, c);
c = cspos.Value;
if (c == 0)
c++;
}
else
{
l = cspos.Key;
}
}
return new KeyValuePair<int, int>(l, c);
}
}
}
| |
//
// GeneratedCode\SimpleAPIClient.cs
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Test
{
using System.Linq;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
public partial class SimpleAPIClient : Microsoft.Rest.ServiceClient<SimpleAPIClient>, ISimpleAPIClient, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
public Microsoft.Rest.ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Initializes a new instance of the SimpleAPIClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected SimpleAPIClient(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the SimpleAPIClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected SimpleAPIClient(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the SimpleAPIClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected SimpleAPIClient(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the SimpleAPIClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected SimpleAPIClient(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the SimpleAPIClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public SimpleAPIClient(Microsoft.Rest.ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the SimpleAPIClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public SimpleAPIClient(Microsoft.Rest.ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the SimpleAPIClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public SimpleAPIClient(System.Uri baseUri, Microsoft.Rest.ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the SimpleAPIClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public SimpleAPIClient(System.Uri baseUri, Microsoft.Rest.ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
this.BaseUri = new System.Uri("http://localhost");
this.AcceptLanguage = "en-US";
this.LongRunningOperationRetryTimeout = 30;
this.GenerateClientRequestId = true;
SerializationSettings = new Newtonsoft.Json.JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(),
Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter>
{
new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new Newtonsoft.Json.JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(),
Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter>
{
new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter()
}
};
CustomInitialize();
DeserializationSettings.Converters.Add(new Microsoft.Rest.Azure.CloudErrorJsonConverter());
}
/// <summary>
/// Gets those integers.
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<int?>>> ListWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "getIntegers").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.GenerateClientRequestId != null && this.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.DeserializationSettings);
if (_errorBody != null)
{
ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<int?>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<int?>>(_responseContent, this.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets those integers.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<int?>>> ListNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (nextPageLink == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.GenerateClientRequestId != null && this.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.DeserializationSettings);
if (_errorBody != null)
{
ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<int?>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<int?>>(_responseContent, this.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
//
// GeneratedCode\ISimpleAPIClient.cs
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Test
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// </summary>
public partial interface ISimpleAPIClient : System.IDisposable
{
/// <summary>
/// The base URI of the service.
/// </summary>
System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
Microsoft.Rest.ServiceClientCredentials Credentials { get; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running
/// Operations. Default value is 30.
/// </summary>
int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated
/// and included in each request. Default is true.
/// </summary>
bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets those integers.
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<int?>>> ListWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Gets those integers.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<int?>>> ListNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
}
}
//
// GeneratedCode\SimpleAPIClientExtensions.cs
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Test
{
using System.Threading.Tasks;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for SimpleAPIClient.
/// </summary>
public static partial class SimpleAPIClientExtensions
{
/// <summary>
/// Gets those integers.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static Microsoft.Rest.Azure.IPage<int?> List(this ISimpleAPIClient operations)
{
return ((ISimpleAPIClient)operations).ListAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Gets those integers.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<int?>> ListAsync(this ISimpleAPIClient operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets those integers.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static Microsoft.Rest.Azure.IPage<int?> ListNext(this ISimpleAPIClient operations, string nextPageLink)
{
return ((ISimpleAPIClient)operations).ListNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets those integers.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<int?>> ListNextAsync(this ISimpleAPIClient operations, string nextPageLink, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
//
// GeneratedCode\Models\Page.cs
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Test.Models
{
/// <summary>
/// Defines a page in Azure responses.
/// </summary>
/// <typeparam name="T">Type of the page content items</typeparam>
[Newtonsoft.Json.JsonObject]
public class Page<T> : Microsoft.Rest.Azure.IPage<T>
{
/// <summary>
/// Gets the link to the next page.
/// </summary>
[Newtonsoft.Json.JsonProperty("nextLink")]
public System.String NextPageLink { get; private set; }
[Newtonsoft.Json.JsonProperty("value")]
private System.Collections.Generic.IList<T> Items{ get; set; }
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>A an enumerator that can be used to iterate through the collection.</returns>
public System.Collections.Generic.IEnumerator<T> GetEnumerator()
{
return (Items == null) ? System.Linq.Enumerable.Empty<T>().GetEnumerator() : Items.GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>A an enumerator that can be used to iterate through the collection.</returns>
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
| |
//
// TraceTest.cs - NUnit Test Cases for System.Diagnostics.Trace
//
// Authors:
// Jonathan Pryor (jonpryor@vt.edu)
// Martin Willemoes Hansen (mwh@sysrq.dk)
//
// (C) Jonathan Pryor
// (C) 2003 Martin Willemoes Hansen
//
// We want tracing enabled, so...
#define TRACE
using NUnit.Framework;
using System;
using System.IO;
using System.Diagnostics;
using System.Threading;
namespace MonoTests.System.Diagnostics {
[TestFixture]
public class TraceTest {
private StringWriter buffer;
private TraceListener listener;
[SetUp]
public void GetReady ()
{
// We don't want to deal with the default listener, which can send the
// output to various places (Debug stream, Console.Out, ...)
// Trace.Listeners.Remove ("Default");
buffer = new StringWriter ();
listener = new TextWriterTraceListener (buffer, "TestOutput");
Trace.Listeners.Clear ();
Trace.Listeners.Add (listener);
Trace.AutoFlush = true;
}
[TearDown]
public void Clear ()
{
// Trace.Listeners.Add (new DefaultTraceListener ());
Trace.Listeners.Remove (listener);
}
// Make sure that when we get the output we expect....
[Test]
public void Tracing ()
{
Trace.IndentLevel = 0;
Trace.IndentSize = 4;
string value =
"Entering Main" + Environment.NewLine +
"Exiting Main" + Environment.NewLine;
Trace.WriteLine ("Entering Main");
Trace.WriteLine ("Exiting Main");
Assertion.AssertEquals ("#Tr01", value, buffer.ToString ());
}
// Make sure we get the output we expect in the presence of indenting...
[Test]
public void Indent ()
{
Trace.IndentLevel = 0;
Trace.IndentSize = 4;
string value =
"List of errors:" + Environment.NewLine +
" Error 1: File not found" + Environment.NewLine +
" Error 2: Directory not found" + Environment.NewLine +
"End of list of errors" + Environment.NewLine;
Trace.WriteLine ("List of errors:");
Trace.Indent ();
Trace.WriteLine ("Error 1: File not found");
Trace.WriteLine ("Error 2: Directory not found");
Trace.Unindent ();
Trace.WriteLine ("End of list of errors");
Assertion.AssertEquals ("#In01", value, buffer.ToString());
}
// Make sure that TraceListener properties (IndentLevel, IndentSize) are
// modified when the corresponding Trace properties are changed.
[Test]
public void AddedTraceListenerProperties ()
{
TraceListener t1 = new TextWriterTraceListener (Console.Out);
TraceListener t2 = new TextWriterTraceListener (Console.Error);
Trace.Listeners.Add(t1);
Trace.Listeners.Add(t2);
const int ExpectedSize = 5;
const int ExpectedLevel = 2;
Trace.IndentSize = ExpectedSize;
Trace.IndentLevel = ExpectedLevel;
foreach (TraceListener t in Trace.Listeners) {
string ids = "#TATLP-S-" + t.Name;
string idl = "#TATLP-L-" + t.Name;
Assertion.AssertEquals (ids, ExpectedSize, t.IndentSize);
Assertion.AssertEquals (idl, ExpectedLevel, t.IndentLevel);
}
Trace.Listeners.Remove(t1);
Trace.Listeners.Remove(t2);
}
// Make sure that the TraceListener properties (IndentLevel, IndentSize)
// are properly modified when the TraceListener is added to the
// collection.
[Test]
public void Listeners_Add_Values()
{
const int ExpectedLevel = 0;
const int ExpectedSize = 4;
Trace.IndentLevel = ExpectedLevel;
Trace.IndentSize = ExpectedSize;
TraceListener tl = new TextWriterTraceListener(Console.Out);
tl.IndentLevel = 2*ExpectedLevel;
tl.IndentSize = 2*ExpectedSize;
Trace.Listeners.Add(tl);
// Assertion.Assert that the listener we added has been set to the correct indent
// level.
Assertion.AssertEquals ("#LATL-L", ExpectedLevel, tl.IndentLevel);
Assertion.AssertEquals ("#LATL-S", ExpectedSize, tl.IndentSize);
// Assertion.Assert that all listeners in the collection have the same level.
foreach (TraceListener t in Trace.Listeners)
{
string idl = "#LATL-L:" + t.Name;
string ids = "#LATL-S:" + t.Name;
Assertion.AssertEquals(idl, ExpectedLevel, t.IndentLevel);
Assertion.AssertEquals(ids, ExpectedSize, t.IndentSize);
}
}
// IndentSize, IndentLevel are thread-static
class MyTraceListener : TraceListener
{
public int Writes;
public int WriteLines;
public MyTraceListener ()
: base ("mt-test")
{
}
public override void Write (string msg)
{
++Writes;
}
public override void WriteLine (string msg)
{
++WriteLines;
}
}
class MultiThreadModify
{
public MyTraceListener listener = new MyTraceListener ();
public const int MaxIterations = 10000;
public String Exception = null;
public MultiThreadModify ()
{
Trace.Listeners.Add (listener);
}
public void Write ()
{
try {
for (int i = 0; i < MaxIterations; ++i)
Trace.WriteLine ("message " + i + "... ");
}
catch (Exception e) {
Exception = string.Format (
"#MTMW: Exception emitted from Trace.WriteLine: {0}", e);
}
}
public void Remove ()
{
try {
Trace.Listeners.Remove (listener);
}
catch (Exception e) {
Exception = string.Format (
"#MTMR: Exception emitted from Trace.Listeners.Remove: {0}", e);
}
}
}
[Test]
public void TestMultiThreadModify ()
{
MultiThreadModify m = new MultiThreadModify ();
Thread t1 = new Thread (new ThreadStart (m.Write));
Thread t2 = new Thread (new ThreadStart (m.Remove));
t1.Start ();
t2.Start ();
t1.Join ();
t2.Join ();
Assert.IsTrue (m.Exception == null, m.Exception);
Assert.AreEqual (MultiThreadModify.MaxIterations, m.listener.WriteLines,
"#tmtm: listener was removed before iterations were completed");
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics;
using System.IO.Pipelines;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
#nullable enable
namespace System.Buffers
{
internal static class BufferExtensions
{
private const int _maxULongByteLength = 20;
[ThreadStatic]
private static byte[]? _numericBytesScratch;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ReadOnlySpan<byte> ToSpan(in this ReadOnlySequence<byte> buffer)
{
if (buffer.IsSingleSegment)
{
return buffer.FirstSpan;
}
return buffer.ToArray();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void CopyTo(in this ReadOnlySequence<byte> buffer, PipeWriter pipeWriter)
{
if (buffer.IsSingleSegment)
{
pipeWriter.Write(buffer.FirstSpan);
}
else
{
CopyToMultiSegment(buffer, pipeWriter);
}
}
private static void CopyToMultiSegment(in ReadOnlySequence<byte> buffer, PipeWriter pipeWriter)
{
foreach (var item in buffer)
{
pipeWriter.Write(item.Span);
}
}
public static ArraySegment<byte> GetArray(this Memory<byte> buffer)
{
return ((ReadOnlyMemory<byte>)buffer).GetArray();
}
public static ArraySegment<byte> GetArray(this ReadOnlyMemory<byte> memory)
{
if (!MemoryMarshal.TryGetArray(memory, out var result))
{
throw new InvalidOperationException("Buffer backed by array was expected");
}
return result;
}
/// <summary>
/// Returns position of first occurrence of item in the <see cref="ReadOnlySequence{T}"/>
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static SequencePosition? PositionOfAny<T>(in this ReadOnlySequence<T> source, T value0, T value1) where T : IEquatable<T>
{
if (source.IsSingleSegment)
{
int index = source.First.Span.IndexOfAny(value0, value1);
if (index != -1)
{
return source.GetPosition(index);
}
return null;
}
else
{
return PositionOfAnyMultiSegment(source, value0, value1);
}
}
private static SequencePosition? PositionOfAnyMultiSegment<T>(in ReadOnlySequence<T> source, T value0, T value1) where T : IEquatable<T>
{
SequencePosition position = source.Start;
SequencePosition result = position;
while (source.TryGet(ref position, out ReadOnlyMemory<T> memory))
{
int index = memory.Span.IndexOfAny(value0, value1);
if (index != -1)
{
return source.GetPosition(index, result);
}
else if (position.GetObject() == null)
{
break;
}
result = position;
}
return null;
}
internal static void WriteAscii(ref this BufferWriter<PipeWriter> buffer, string data)
{
if (string.IsNullOrEmpty(data))
{
return;
}
var dest = buffer.Span;
var sourceLength = data.Length;
// Fast path, try encoding to the available memory directly
if (sourceLength <= dest.Length)
{
Encoding.ASCII.GetBytes(data, dest);
buffer.Advance(sourceLength);
}
else
{
WriteEncodedMultiWrite(ref buffer, data, sourceLength, Encoding.ASCII);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static unsafe void WriteNumeric(ref this BufferWriter<PipeWriter> buffer, ulong number)
{
const byte AsciiDigitStart = (byte)'0';
var span = buffer.Span;
var bytesLeftInBlock = span.Length;
// Fast path, try copying to the available memory directly
var simpleWrite = true;
fixed (byte* output = span)
{
var start = output;
if (number < 10 && bytesLeftInBlock >= 1)
{
*(start) = (byte)(((uint)number) + AsciiDigitStart);
buffer.Advance(1);
}
else if (number < 100 && bytesLeftInBlock >= 2)
{
var val = (uint)number;
var tens = (byte)((val * 205u) >> 11); // div10, valid to 1028
*(start) = (byte)(tens + AsciiDigitStart);
*(start + 1) = (byte)(val - (tens * 10) + AsciiDigitStart);
buffer.Advance(2);
}
else if (number < 1000 && bytesLeftInBlock >= 3)
{
var val = (uint)number;
var digit0 = (byte)((val * 41u) >> 12); // div100, valid to 1098
var digits01 = (byte)((val * 205u) >> 11); // div10, valid to 1028
*(start) = (byte)(digit0 + AsciiDigitStart);
*(start + 1) = (byte)(digits01 - (digit0 * 10) + AsciiDigitStart);
*(start + 2) = (byte)(val - (digits01 * 10) + AsciiDigitStart);
buffer.Advance(3);
}
else
{
simpleWrite = false;
}
}
if (!simpleWrite)
{
WriteNumericMultiWrite(ref buffer, number);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void WriteNumericMultiWrite(ref this BufferWriter<PipeWriter> buffer, ulong number)
{
const byte AsciiDigitStart = (byte)'0';
var value = number;
var position = _maxULongByteLength;
var byteBuffer = NumericBytesScratch;
do
{
// Consider using Math.DivRem() if available
var quotient = value / 10;
byteBuffer[--position] = (byte)(AsciiDigitStart + (value - quotient * 10)); // 0x30 = '0'
value = quotient;
}
while (value != 0);
var length = _maxULongByteLength - position;
buffer.Write(new ReadOnlySpan<byte>(byteBuffer, position, length));
}
internal static void WriteEncoded(ref this BufferWriter<PipeWriter> buffer, string data, Encoding encoding)
{
if (string.IsNullOrEmpty(data))
{
return;
}
var dest = buffer.Span;
var sourceLength = encoding.GetByteCount(data);
// Fast path, try encoding to the available memory directly
if (sourceLength <= dest.Length)
{
encoding.GetBytes(data, dest);
buffer.Advance(sourceLength);
}
else
{
WriteEncodedMultiWrite(ref buffer, data, sourceLength, encoding);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void WriteEncodedMultiWrite(ref this BufferWriter<PipeWriter> buffer, string data, int encodedLength, Encoding encoding)
{
var source = data.AsSpan();
var totalBytesUsed = 0;
var encoder = encoding.GetEncoder();
var minBufferSize = encoding.GetMaxByteCount(1);
buffer.Ensure(minBufferSize);
var bytes = buffer.Span;
var completed = false;
// This may be a bug, but encoder.Convert returns completed = true for UTF7 too early.
// Therefore, we check encodedLength - totalBytesUsed too.
while (!completed || encodedLength - totalBytesUsed != 0)
{
// Zero length spans are possible, though unlikely.
// encoding.Convert and .Advance will both handle them so we won't special case for them.
encoder.Convert(source, bytes, flush: true, out var charsUsed, out var bytesUsed, out completed);
buffer.Advance(bytesUsed);
totalBytesUsed += bytesUsed;
if (totalBytesUsed >= encodedLength)
{
Debug.Assert(totalBytesUsed == encodedLength);
// Encoded everything
break;
}
source = source.Slice(charsUsed);
// Get new span, more to encode.
buffer.Ensure(minBufferSize);
bytes = buffer.Span;
}
}
private static byte[] NumericBytesScratch => _numericBytesScratch ?? CreateNumericBytesScratch();
[MethodImpl(MethodImplOptions.NoInlining)]
private static byte[] CreateNumericBytesScratch()
{
var bytes = new byte[_maxULongByteLength];
_numericBytesScratch = bytes;
return bytes;
}
}
}
| |
using System;
using System.Collections;
using Server;
using Server.Network;
using Server.Mobiles;
using Server.Targeting;
using Server.Engines.Craft;
namespace Server.Items
{
public delegate void InstrumentPickedCallback( Mobile from, BaseInstrument instrument );
public enum InstrumentQuality
{
Low,
Regular,
Exceptional
}
public abstract class BaseInstrument : Item, ICraftable, ISlayer
{
private int m_WellSound, m_BadlySound;
private SlayerName m_Slayer, m_Slayer2;
private InstrumentQuality m_Quality;
private Mobile m_Crafter;
private int m_UsesRemaining;
[CommandProperty( AccessLevel.GameMaster )]
public int SuccessSound
{
get{ return m_WellSound; }
set{ m_WellSound = value; }
}
[CommandProperty( AccessLevel.GameMaster )]
public int FailureSound
{
get{ return m_BadlySound; }
set{ m_BadlySound = value; }
}
[CommandProperty( AccessLevel.GameMaster )]
public SlayerName Slayer
{
get{ return m_Slayer; }
set{ m_Slayer = value; InvalidateProperties(); }
}
[CommandProperty( AccessLevel.GameMaster )]
public SlayerName Slayer2
{
get{ return m_Slayer2; }
set{ m_Slayer2 = value; InvalidateProperties(); }
}
[CommandProperty( AccessLevel.GameMaster )]
public InstrumentQuality Quality
{
get{ return m_Quality; }
set{ UnscaleUses(); m_Quality = value; InvalidateProperties(); ScaleUses(); }
}
[CommandProperty( AccessLevel.GameMaster )]
public Mobile Crafter
{
get{ return m_Crafter; }
set{ m_Crafter = value; InvalidateProperties(); }
}
public virtual int InitMinUses{ get{ return 350; } }
public virtual int InitMaxUses{ get{ return 450; } }
public virtual TimeSpan ChargeReplenishRate { get { return TimeSpan.FromMinutes( 5.0 ); } }
[CommandProperty( AccessLevel.GameMaster )]
public int UsesRemaining
{
get{ CheckReplenishUses(); return m_UsesRemaining; }
set{ m_UsesRemaining = value; InvalidateProperties(); }
}
private DateTime m_LastReplenished;
[CommandProperty( AccessLevel.GameMaster )]
public DateTime LastReplenished
{
get { return m_LastReplenished; }
set { m_LastReplenished = value; CheckReplenishUses(); }
}
private bool m_ReplenishesCharges;
[CommandProperty( AccessLevel.GameMaster )]
public bool ReplenishesCharges
{
get { return m_ReplenishesCharges; }
set
{
if( value != m_ReplenishesCharges && value )
m_LastReplenished = DateTime.Now;
m_ReplenishesCharges = value;
}
}
public void CheckReplenishUses()
{
CheckReplenishUses( true );
}
public void CheckReplenishUses( bool invalidate )
{
if( !m_ReplenishesCharges || m_UsesRemaining >= InitMaxUses )
return;
if( m_LastReplenished + ChargeReplenishRate < DateTime.Now )
{
TimeSpan timeDifference = DateTime.Now - m_LastReplenished;
m_UsesRemaining = Math.Min( m_UsesRemaining + (int)( timeDifference.Ticks / ChargeReplenishRate.Ticks), InitMaxUses ); //How rude of TimeSpan to not allow timespan division.
m_LastReplenished = DateTime.Now;
if( invalidate )
InvalidateProperties();
}
}
public void ScaleUses()
{
UsesRemaining = (UsesRemaining * GetUsesScalar()) / 100;
//InvalidateProperties();
}
public void UnscaleUses()
{
UsesRemaining = (UsesRemaining * 100) / GetUsesScalar();
}
public int GetUsesScalar()
{
if ( m_Quality == InstrumentQuality.Exceptional )
return 200;
return 100;
}
public void ConsumeUse( Mobile from )
{
// TODO: Confirm what must happen here?
if ( UsesRemaining > 1 )
{
--UsesRemaining;
}
else
{
if ( from != null )
from.SendLocalizedMessage( 502079 ); // The instrument played its last tune.
Delete();
}
}
private static Hashtable m_Instruments = new Hashtable();
public static BaseInstrument GetInstrument( Mobile from )
{
BaseInstrument item = m_Instruments[from] as BaseInstrument;
if ( item == null )
return null;
if ( !item.IsChildOf( from.Backpack ) )
{
m_Instruments.Remove( from );
return null;
}
return item;
}
public static int GetBardRange( Mobile bard, SkillName skill )
{
return 8 + (int)(bard.Skills[skill].Value / 15);
}
public static void PickInstrument( Mobile from, InstrumentPickedCallback callback )
{
BaseInstrument instrument = GetInstrument( from );
if ( instrument != null )
{
if ( callback != null )
callback( from, instrument );
}
else
{
from.SendLocalizedMessage( 500617 ); // What instrument shall you play?
from.BeginTarget( 1, false, TargetFlags.None, new TargetStateCallback( OnPickedInstrument ), callback );
}
}
public static void OnPickedInstrument( Mobile from, object targeted, object state )
{
BaseInstrument instrument = targeted as BaseInstrument;
if ( instrument == null )
{
from.SendLocalizedMessage( 500619 ); // That is not a musical instrument.
}
else
{
SetInstrument( from, instrument );
InstrumentPickedCallback callback = state as InstrumentPickedCallback;
if ( callback != null )
callback( from, instrument );
}
}
public static bool IsMageryCreature( BaseCreature bc )
{
return ( bc != null && bc.AI == AIType.AI_Mage && bc.Skills[SkillName.Magery].Base > 5.0 );
}
public static bool IsFireBreathingCreature( BaseCreature bc )
{
if ( bc == null )
return false;
return bc.HasBreath;
}
public static bool IsPoisonImmune( BaseCreature bc )
{
return ( bc != null && bc.PoisonImmune != null );
}
public static int GetPoisonLevel( BaseCreature bc )
{
if ( bc == null )
return 0;
Poison p = bc.HitPoison;
if ( p == null )
return 0;
return p.Level + 1;
}
public static double GetBaseDifficulty( Mobile targ )
{
/* Difficulty TODO: Add another 100 points for each of the following abilities:
- Radiation or Aura Damage (Heat, Cold etc.)
- Summoning Undead
*/
double val = (targ.HitsMax * 1.6) + targ.StamMax + targ.ManaMax;
val += targ.SkillsTotal / 10;
if ( val > 700 )
val = 700 + (int)((val - 700) * (3.0 / 11));
BaseCreature bc = targ as BaseCreature;
if ( IsMageryCreature( bc ) )
val += 100;
if ( IsFireBreathingCreature( bc ) )
val += 100;
if ( IsPoisonImmune( bc ) )
val += 100;
if ( targ is VampireBat || targ is VampireBatFamiliar )
val += 100;
val += GetPoisonLevel( bc ) * 20;
val /= 10;
if ( bc != null && bc.IsParagon )
val += 40.0;
if ( Core.SE && val > 160.0 )
val = 160.0;
return val;
}
public double GetDifficultyFor( Mobile targ )
{
double val = GetBaseDifficulty( targ );
if ( m_Quality == InstrumentQuality.Exceptional )
val -= 5.0; // 10%
if ( m_Slayer != SlayerName.None )
{
SlayerEntry entry = SlayerGroup.GetEntryByName( m_Slayer );
if ( entry != null )
{
if ( entry.Slays( targ ) )
val -= 10.0; // 20%
else if ( entry.Group.OppositionSuperSlays( targ ) )
val += 10.0; // -20%
}
}
if ( m_Slayer2 != SlayerName.None )
{
SlayerEntry entry = SlayerGroup.GetEntryByName( m_Slayer2 );
if ( entry != null )
{
if ( entry.Slays( targ ) )
val -= 10.0; // 20%
else if ( entry.Group.OppositionSuperSlays( targ ) )
val += 10.0; // -20%
}
}
return val;
}
public static void SetInstrument( Mobile from, BaseInstrument item )
{
m_Instruments[from] = item;
}
public BaseInstrument( int itemID, int wellSound, int badlySound ) : base( itemID )
{
m_WellSound = wellSound;
m_BadlySound = badlySound;
UsesRemaining = Utility.RandomMinMax( InitMinUses, InitMaxUses );
}
public override void GetProperties( ObjectPropertyList list )
{
int oldUses = m_UsesRemaining;
CheckReplenishUses( false );
base.GetProperties( list );
if ( m_Crafter != null )
list.Add( 1050043, m_Crafter.Name ); // crafted by ~1_NAME~
if ( m_Quality == InstrumentQuality.Exceptional )
list.Add( 1060636 ); // exceptional
list.Add( 1060584, m_UsesRemaining.ToString() ); // uses remaining: ~1_val~
if( m_ReplenishesCharges )
list.Add( 1070928 ); // Replenish Charges
if( m_Slayer != SlayerName.None )
{
SlayerEntry entry = SlayerGroup.GetEntryByName( m_Slayer );
if( entry != null )
list.Add( entry.Title );
}
if( m_Slayer2 != SlayerName.None )
{
SlayerEntry entry = SlayerGroup.GetEntryByName( m_Slayer2 );
if( entry != null )
list.Add( entry.Title );
}
if( m_UsesRemaining != oldUses )
Timer.DelayCall( TimeSpan.Zero, new TimerCallback( InvalidateProperties ) );
}
public override void OnSingleClick( Mobile from )
{
ArrayList attrs = new ArrayList();
if ( DisplayLootType )
{
if ( LootType == LootType.Blessed )
attrs.Add( new EquipInfoAttribute( 1038021 ) ); // blessed
else if ( LootType == LootType.Cursed )
attrs.Add( new EquipInfoAttribute( 1049643 ) ); // cursed
}
if ( m_Quality == InstrumentQuality.Exceptional )
attrs.Add( new EquipInfoAttribute( 1018305 - (int)m_Quality ) );
if( m_ReplenishesCharges )
attrs.Add( new EquipInfoAttribute( 1070928 ) ); // Replenish Charges
// TODO: Must this support item identification?
if( m_Slayer != SlayerName.None )
{
SlayerEntry entry = SlayerGroup.GetEntryByName( m_Slayer );
if( entry != null )
attrs.Add( new EquipInfoAttribute( entry.Title ) );
}
if( m_Slayer2 != SlayerName.None )
{
SlayerEntry entry = SlayerGroup.GetEntryByName( m_Slayer2 );
if( entry != null )
attrs.Add( new EquipInfoAttribute( entry.Title ) );
}
int number;
if ( Name == null )
{
number = LabelNumber;
}
else
{
this.LabelTo( from, Name );
number = 1041000;
}
if ( attrs.Count == 0 && Crafter == null && Name != null )
return;
EquipmentInfo eqInfo = new EquipmentInfo( number, m_Crafter, false, (EquipInfoAttribute[])attrs.ToArray( typeof( EquipInfoAttribute ) ) );
from.Send( new DisplayEquipmentInfo( this, eqInfo ) );
}
public BaseInstrument( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 3 ); // version
writer.Write( m_ReplenishesCharges );
if( m_ReplenishesCharges )
writer.Write( m_LastReplenished );
writer.Write( m_Crafter );
writer.WriteEncodedInt( (int) m_Quality );
writer.WriteEncodedInt( (int) m_Slayer );
writer.WriteEncodedInt( (int) m_Slayer2 );
writer.WriteEncodedInt( (int)UsesRemaining );
writer.WriteEncodedInt( (int) m_WellSound );
writer.WriteEncodedInt( (int) m_BadlySound );
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
switch ( version )
{
case 3:
{
m_ReplenishesCharges = reader.ReadBool();
if( m_ReplenishesCharges )
m_LastReplenished = reader.ReadDateTime();
goto case 2;
}
case 2:
{
m_Crafter = reader.ReadMobile();
m_Quality = (InstrumentQuality)reader.ReadEncodedInt();
m_Slayer = (SlayerName)reader.ReadEncodedInt();
m_Slayer2 = (SlayerName)reader.ReadEncodedInt();
UsesRemaining = reader.ReadEncodedInt();
m_WellSound = reader.ReadEncodedInt();
m_BadlySound = reader.ReadEncodedInt();
break;
}
case 1:
{
m_Crafter = reader.ReadMobile();
m_Quality = (InstrumentQuality)reader.ReadEncodedInt();
m_Slayer = (SlayerName)reader.ReadEncodedInt();
UsesRemaining = reader.ReadEncodedInt();
m_WellSound = reader.ReadEncodedInt();
m_BadlySound = reader.ReadEncodedInt();
break;
}
case 0:
{
m_WellSound = reader.ReadInt();
m_BadlySound = reader.ReadInt();
UsesRemaining = Utility.RandomMinMax( InitMinUses, InitMaxUses );
break;
}
}
CheckReplenishUses();
}
public override void OnDoubleClick( Mobile from )
{
if ( !from.InRange( GetWorldLocation(), 1 ) )
{
from.SendLocalizedMessage( 500446 ); // That is too far away.
}
else if ( from.BeginAction( typeof( BaseInstrument ) ) )
{
SetInstrument( from, this );
// Delay of 7 second before beign able to play another instrument again
new InternalTimer( from ).Start();
if ( CheckMusicianship( from ) )
PlayInstrumentWell( from );
else
PlayInstrumentBadly( from );
}
else
{
from.SendLocalizedMessage( 500119 ); // You must wait to perform another action
}
}
public static bool CheckMusicianship( Mobile m )
{
m.CheckSkill( SkillName.Musicianship, 0.0, 120.0 );
return ( (m.Skills[SkillName.Musicianship].Value / 100) > Utility.RandomDouble() );
}
public void PlayInstrumentWell( Mobile from )
{
from.PlaySound( m_WellSound );
}
public void PlayInstrumentBadly( Mobile from )
{
from.PlaySound( m_BadlySound );
}
private class InternalTimer : Timer
{
private Mobile m_From;
public InternalTimer( Mobile from ) : base( TimeSpan.FromSeconds( 6.0 ) )
{
m_From = from;
Priority = TimerPriority.TwoFiftyMS;
}
protected override void OnTick()
{
m_From.EndAction( typeof( BaseInstrument ) );
}
}
#region ICraftable Members
public int OnCraft( int quality, bool makersMark, Mobile from, CraftSystem craftSystem, Type typeRes, BaseTool tool, CraftItem craftItem, int resHue )
{
Quality = (InstrumentQuality)quality;
if ( makersMark )
Crafter = from;
return quality;
}
#endregion
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.