context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
/*
* 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 OpenSim.Framework;
using OpenSim.Framework.Client;
using OpenSim.Region.Framework.Scenes;
using OpenMetaverse;
using Nini.Config;
using log4net;
namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
{
public class InventoryCache
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
protected BaseInventoryConnector m_Connector;
protected List<Scene> m_Scenes;
// The cache proper
protected Dictionary<UUID, Dictionary<AssetType, InventoryFolderBase>> m_InventoryCache;
// A cache of userIDs --> ServiceURLs, for HGBroker only
protected Dictionary<UUID, string> m_InventoryURLs =
new Dictionary<UUID, string>();
public virtual void Init(IConfigSource source, BaseInventoryConnector connector)
{
m_Scenes = new List<Scene>();
m_InventoryCache = new Dictionary<UUID, Dictionary<AssetType, InventoryFolderBase>>();
m_Connector = connector;
}
public virtual void AddRegion(Scene scene)
{
m_Scenes.Add(scene);
scene.EventManager.OnMakeRootAgent += OnMakeRootAgent;
scene.EventManager.OnClientClosed += OnClientClosed;
}
public virtual void RemoveRegion(Scene scene)
{
if ((m_Scenes != null) && m_Scenes.Contains(scene))
{
m_Scenes.Remove(scene);
}
}
void OnMakeRootAgent(ScenePresence presence)
{
// Get system folders
// First check if they're here already
lock (m_InventoryCache)
{
if (m_InventoryCache.ContainsKey(presence.UUID))
{
m_log.DebugFormat("[INVENTORY CACHE]: OnMakeRootAgent, system folders for {0} {1} already in cache", presence.Firstname, presence.Lastname);
return;
}
}
// If not, go get them and place them in the cache
Dictionary<AssetType, InventoryFolderBase> folders = CacheSystemFolders(presence.UUID);
CacheInventoryServiceURL(presence.Scene, presence.UUID);
m_log.DebugFormat("[INVENTORY CACHE]: OnMakeRootAgent in {0}, fetched system folders for {1} {2}: count {3}",
presence.Scene.RegionInfo.RegionName, presence.Firstname, presence.Lastname, folders.Count);
}
void OnClientClosed(UUID clientID, Scene scene)
{
if (m_InventoryCache.ContainsKey(clientID)) // if it's still in cache
{
ScenePresence sp = null;
foreach (Scene s in m_Scenes)
{
s.TryGetScenePresence(clientID, out sp);
if ((sp != null) && !sp.IsChildAgent && (s != scene))
{
m_log.DebugFormat("[INVENTORY CACHE]: OnClientClosed in {0}, but user {1} still in sim. Keeping system folders in cache",
scene.RegionInfo.RegionName, clientID);
return;
}
}
m_log.DebugFormat(
"[INVENTORY CACHE]: OnClientClosed in {0}, user {1} out of sim. Dropping system folders",
scene.RegionInfo.RegionName, clientID);
DropCachedSystemFolders(clientID);
DropInventoryServiceURL(clientID);
}
}
/// <summary>
/// Cache a user's 'system' folders.
/// </summary>
/// <param name="userID"></param>
/// <returns>Folders cached</returns>
protected Dictionary<AssetType, InventoryFolderBase> CacheSystemFolders(UUID userID)
{
// If not, go get them and place them in the cache
Dictionary<AssetType, InventoryFolderBase> folders = m_Connector.GetSystemFolders(userID);
if (folders.Count > 0)
lock (m_InventoryCache)
m_InventoryCache.Add(userID, folders);
return folders;
}
/// <summary>
/// Drop a user's cached 'system' folders
/// </summary>
/// <param name="userID"></param>
protected void DropCachedSystemFolders(UUID userID)
{
// Drop system folders
lock (m_InventoryCache)
if (m_InventoryCache.ContainsKey(userID))
m_InventoryCache.Remove(userID);
}
/// <summary>
/// Get the system folder for a particular asset type
/// </summary>
/// <param name="userID"></param>
/// <param name="type"></param>
/// <returns></returns>
public InventoryFolderBase GetFolderForType(UUID userID, AssetType type)
{
Dictionary<AssetType, InventoryFolderBase> folders = null;
lock (m_InventoryCache)
{
m_InventoryCache.TryGetValue(userID, out folders);
// In some situations (such as non-secured standalones), system folders can be requested without
// the user being logged in. So we need to try caching them here if we don't already have them.
if (null == folders)
CacheSystemFolders(userID);
m_InventoryCache.TryGetValue(userID, out folders);
}
if ((folders != null) && folders.ContainsKey(type))
{
return folders[type];
}
return null;
}
/// <summary>
/// Gets the user's inventory URL from its serviceURLs, if the user is foreign,
/// and sticks it in the cache
/// </summary>
/// <param name="userID"></param>
private void CacheInventoryServiceURL(Scene scene, UUID userID)
{
if (scene.UserAccountService.GetUserAccount(scene.RegionInfo.ScopeID, userID) == null)
{
// The user does not have a local account; let's cache its service URL
string inventoryURL = string.Empty;
ScenePresence sp = null;
scene.TryGetScenePresence(userID, out sp);
if (sp != null)
{
AgentCircuitData aCircuit = scene.AuthenticateHandler.GetAgentCircuitData(sp.ControllingClient.CircuitCode);
if (aCircuit.ServiceURLs.ContainsKey("InventoryServerURI"))
{
inventoryURL = aCircuit.ServiceURLs["InventoryServerURI"].ToString();
if (inventoryURL != null && inventoryURL != string.Empty)
{
inventoryURL = inventoryURL.Trim(new char[] { '/' });
m_InventoryURLs.Add(userID, inventoryURL);
}
}
}
}
}
private void DropInventoryServiceURL(UUID userID)
{
lock (m_InventoryURLs)
if (m_InventoryURLs.ContainsKey(userID))
m_InventoryURLs.Remove(userID);
}
public string GetInventoryServiceURL(UUID userID)
{
if (m_InventoryURLs.ContainsKey(userID))
return m_InventoryURLs[userID];
return null;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using JimBobBennett.JimLib.Events;
using JimBobBennett.JimLib.Xamarin.Contacts;
using JimBobBennett.JimLib.Xamarin.ios.Images;
using JimBobBennett.JimLib.Xamarin.ios.Navigation;
using JimBobBennett.JimLib.Xamarin.Network;
using JimBobBennett.JimLib.Xamarin.SocialMedia;
using AddressBook;
using AddressBookUI;
using Foundation;
using UIKit;
using Newtonsoft.Json;
using Xamarin.Contacts;
using Address = Xamarin.Contacts.Address;
using Email = Xamarin.Contacts.Email;
using InstantMessagingAccount = Xamarin.Contacts.InstantMessagingAccount;
using InstantMessagingService = JimBobBennett.JimLib.Xamarin.Contacts.InstantMessagingService;
using Phone = Xamarin.Contacts.Phone;
using Website = Xamarin.Contacts.Website;
namespace JimBobBennett.JimLib.Xamarin.ios.Contacts
{
public class Contacts : IContacts
{
private readonly INavigation _navigation;
private readonly IUriHelper _uriHelper;
private AuthorizationStatus _authorizationStatus;
public Contacts(INavigation navigation, IUriHelper uriHelper)
{
_navigation = navigation;
_uriHelper = uriHelper;
AuthorizationStatus = GetStatus();
}
public async Task<bool> AuthoriseContactsAsync()
{
return await GetAddressBookAsync() != null;
}
public AuthorizationStatus AuthorizationStatus
{
get
{
AuthorizationStatus = GetStatus();
return _authorizationStatus;
}
private set
{
if (_authorizationStatus == value) return;
_authorizationStatus = value;
OnAuthorizationStatusChanged();
}
}
private static AuthorizationStatus GetStatus()
{
var status = ABAddressBook.GetAuthorizationStatus();
switch (status)
{
case ABAuthorizationStatus.Authorized:
return AuthorizationStatus.Authorized;
case ABAuthorizationStatus.Restricted:
return AuthorizationStatus.Restricted;
case ABAuthorizationStatus.NotDetermined:
return AuthorizationStatus.NotDetermined;
default:
return AuthorizationStatus.Denied;
}
}
public void AddContact(ContactOverview contactOverview)
{
var person = new ABPerson
{
FirstName = contactOverview.FirstName,
MiddleName = contactOverview.MiddleName,
LastName = contactOverview.LastName,
Image = new NSData(contactOverview.ThumbBase64, NSDataBase64DecodingOptions.None),
Nickname = contactOverview.NickName,
Prefix = contactOverview.Prefix,
Suffix = contactOverview.Suffix,
Organization = contactOverview.Organization
};
AddPhones(contactOverview, person);
AddEmails(contactOverview, person);
AddAddresses(contactOverview, person);
AddWebsites(contactOverview, person);
AddSocialProfiles(contactOverview, person);
var vc = new ABUnknownPersonViewController {DisplayedPerson = person};
vc.PersonCreated += (s, e) =>
{
if (e.Person != null)
contactOverview.AddressBookId = e.Person.Id.ToString(CultureInfo.InvariantCulture);
};
var rootController = _navigation.NavigationController.VisibleViewController;
var nc = new UINavigationController(vc);
vc.NavigationItem.LeftBarButtonItem = new UIBarButtonItem("Done",
UIBarButtonItemStyle.Plain,
(s, e) => nc.DismissViewController(true, null));
rootController.PresentViewController(nc, true, null);
}
private static void AddWebsites(ContactOverview contactOverview, ABPerson person)
{
var websites = new ABMutableStringMultiValue();
foreach (var website in contactOverview.Websites)
websites.Add(website.Address, ABPersonUrlLabel.HomePage);
if (websites.Any())
person.SetUrls(websites);
}
private static void AddSocialProfiles(ContactOverview contactOverview, ABPerson person)
{
var profiles = new ABMutableDictionaryMultiValue();
foreach (var socialMediaUser in contactOverview.SocialMediaUsers
.Where(c => c.Type == Account.Twitter || c.Type == Account.Facebook))
{
var socialProfile = new SocialProfile
{
UserIdentifier = socialMediaUser.UserId,
Username = socialMediaUser.Name
};
switch (socialMediaUser.Type)
{
case Account.Twitter:
socialProfile.ServiceName = ABPersonSocialProfileService.Twitter;
break;
case Account.Facebook:
socialProfile.ServiceName = ABPersonSocialProfileService.Facebook;
break;
}
profiles.Add(socialProfile.Dictionary, new NSString(socialProfile.ServiceName));
}
if (profiles.Any())
person.SetSocialProfile(profiles);
}
public event EventHandler AuthorizationStatusChanged
{
add { WeakEventManager.GetWeakEventManager(this).AddEventHandler("AuthorizationStatusChanged", value); }
remove { WeakEventManager.GetWeakEventManager(this).RemoveEventHandler("AuthorizationStatusChanged", value); }
}
public void OnAuthorizationStatusChanged()
{
WeakEventManager.GetWeakEventManager(this).RaiseEvent(this, EventArgs.Empty, "AuthorizationStatusChanged");
}
private static void AddAddresses(ContactOverview contactOverview, ABPerson person)
{
var addresses = new ABMutableDictionaryMultiValue();
foreach (var address in contactOverview.Addresses)
{
var a = new NSMutableDictionary
{
{new NSString(ABPersonAddressKey.City), new NSString(address.City)},
{new NSString(ABPersonAddressKey.Country), new NSString(address.Country)},
{new NSString(ABPersonAddressKey.Zip), new NSString(address.PostalCode)},
{new NSString(ABPersonAddressKey.State), new NSString(address.Region)},
{new NSString(ABPersonAddressKey.Street), new NSString(address.StreetAddress)}
};
addresses.Add(a, new NSString(address.Label));
}
if (addresses.Any())
person.SetAddresses(addresses);
}
private static void AddPhones(ContactOverview contactOverview, ABPerson person)
{
ABMutableMultiValue<string> phones = new ABMutableStringMultiValue();
foreach (var phone in contactOverview.Phones)
phones.Add(phone.Number, new NSString(phone.Label));
if (phones.Any())
person.SetPhones(phones);
}
private static void AddEmails(ContactOverview contactOverview, ABPerson person)
{
ABMutableMultiValue<string> emails = new ABMutableStringMultiValue();
foreach (var email in contactOverview.Emails)
emails.Add(email.Address, new NSString(email.Label));
if (emails.Any())
person.SetEmails(emails);
}
public async Task<IEnumerable<ContactOverview>> GetContactOverviewsAsync()
{
var addressBook = await GetAddressBookAsync();
return await Task<List<ContactOverview>>.Factory.StartNew(() => GetContactsListAsync(addressBook));
}
public string Serialize(ContactOverview contact)
{
return JsonConvert.SerializeObject(contact, Formatting.None,
new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
}
public ContactOverview Deserialize(string contact)
{
return JsonConvert.DeserializeObject<ContactOverview>(contact);
}
private static List<ContactOverview> GetContactsListAsync(IEnumerable<Contact> addressBook)
{
return addressBook.Select(CreateContact).ToList();
}
private static ContactOverview CreateContact(Contact c)
{
var thumb = c.GetThumbnail();
var scaled = ImageHelper.MaxResizeImage(thumb, 128, 128);
var contactOverview = new ContactOverview
{
DisplayName = c.DisplayName,
FirstName = c.FirstName,
MiddleName = c.MiddleName,
LastName = c.LastName,
NickName = c.Nickname,
Prefix = c.Prefix,
Suffix = c.Suffix,
AddressBookId = c.Id
};
var organization = c.Organizations.FirstOrDefault();
if (organization != null)
contactOverview.Organization = organization.Name;
contactOverview.SetThumbImageSource(ImageHelper.GetImageSourceFromUIImage(scaled));
if (scaled != null)
{
var data = scaled.AsPNG();
contactOverview.ThumbBase64 = data.GetBase64EncodedString(NSDataBase64EncodingOptions.None);
}
contactOverview.Emails.AddRange(c.Emails.Select(CreateEmail));
contactOverview.Phones.AddRange(c.Phones.Select(CreatePhone));
contactOverview.Addresses.AddRange(c.Addresses.Select(CreateAddress));
contactOverview.InstantMessagingAccounts.AddRange(c.InstantMessagingAccounts.Select(CreateInstantMessagingAccount));
contactOverview.Websites.AddRange(c.Websites.Select(CreateWebsites));
return contactOverview;
}
private static Xamarin.Contacts.InstantMessagingAccount CreateInstantMessagingAccount(InstantMessagingAccount arg)
{
return new Xamarin.Contacts.InstantMessagingAccount
{
Account = arg.Account,
Service = (InstantMessagingService) arg.Service,
ServiceLabel = arg.ServiceLabel
};
}
private static Xamarin.Contacts.Address CreateAddress(Address arg)
{
return new Xamarin.Contacts.Address
{
City = arg.City,
Label = arg.Label,
Type = (Xamarin.Contacts.AddressType)arg.Type,
Country = arg.Country,
PostalCode = arg.PostalCode,
Region = arg.Region,
StreetAddress = arg.StreetAddress
};
}
private static Xamarin.Contacts.Website CreateWebsites(Website arg)
{
return new Xamarin.Contacts.Website
{
Address = arg.Address
};
}
private static Xamarin.Contacts.Phone CreatePhone(Phone arg)
{
return new Xamarin.Contacts.Phone
{
Number = arg.Number,
Type = (Xamarin.Contacts.PhoneType) arg.Type,
Label = arg.Label
};
}
private static Xamarin.Contacts.Email CreateEmail(Email arg)
{
return new Xamarin.Contacts.Email
{
Address = arg.Address,
AddressType = (Xamarin.Contacts.AddressType) arg.Type,
Label = arg.Label
};
}
private async Task<global::Xamarin.Contacts.AddressBook> GetAddressBookAsync()
{
var addressBook = new global::Xamarin.Contacts.AddressBook();
var t = addressBook.RequestPermission();
await t;
AuthorizationStatus = GetStatus();
return !t.Result ? null : addressBook;
}
public void MakePhoneCall(Xamarin.Contacts.Phone phone)
{
_uriHelper.OpenSchemeUri(new System.Uri("tel:" + phone.Number));
}
public void SendEmail(Xamarin.Contacts.Email email)
{
_uriHelper.OpenSchemeUri(new System.Uri("mailto:" + email.Address));
}
}
}
| |
//
// Copyright (c) 2010-2012 Frank A. Krueger
//
// 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.Drawing;
namespace CrossGraphics
{
public interface IGraphics
{
void BeginEntity(object entity);
void SetFont(Font f);
void SetColor(Color c);
void FillRect(float x,float y,float width, float height);
void DrawRect(float x, float y, float width, float height, float w);
void FillRoundedRect(float x, float y, float width, float height, float radius);
void DrawRoundedRect(float x, float y, float width, float height, float radius, float w);
void FillOval(float x, float y, float width, float height);
void DrawOval(float x, float y, float width, float height, float w);
void BeginLines(bool rounded);
void DrawLine(float sx, float sy, float ex, float ey, float w);
void EndLines();
void FillArc(float cx, float cy, float radius, float startAngle, float endAngle);
void DrawArc(float cx, float cy, float radius, float startAngle, float endAngle, float w);
void DrawImage(IImage img, float x, float y);
void DrawImage(IImage img, float x, float y, float width, float height);
void DrawString(string s,
float x,
float y,
float width,
float height,
LineBreakMode lineBreak,
TextAlignment horizontal_align,
TextAlignment vertical_align
);
void SaveState();
void SetClippingRect (float x, float y, float width, float height);
void Translate(float dx, float dy);
void Scale(float sx, float sy);
void RestoreState();
void BeginOffscreen (float width, float height, IImage prev);
IImage EndOffscreen ();
}
public enum LineBreakMode {
None,
Clip,
WordWrap,
}
public enum TextAlignment {
Start,
Center,
End,
//Justified
}
public interface IImage
{
void Destroy();
}
[Flags]
public enum FontOptions
{
None = 0,
Bold = 1,
Italic = 2, // TODO
}
public class Font
{
public string FontFamily { get; private set; }
public FontOptions Options { get; private set; }
public int Size { get; private set; } // TODO why is this an int?
public object Tag { get; set; }
public bool IsBold { get { return (Options & FontOptions.Bold) != 0; } }
public Font (string fontFamily, FontOptions options, int size)
{
FontFamily = fontFamily;
Options = options;
Size = size;
}
static Font[] _boldSystemFonts = new Font[0];
static Font[] _systemFonts = new Font[0];
static Font[] _userFixedPitchFonts = new Font[0];
static Font[] _boldUserFixedPitchFonts = new Font[0];
public static Font BoldSystemFontOfSize (int size) {
if (size >= _boldSystemFonts.Length) {
return new Font ("SystemFont", FontOptions.Bold, size);
}
else {
var f = _boldSystemFonts[size];
if (f == null) {
f = new Font ("SystemFont", FontOptions.Bold, size);
_boldSystemFonts[size] = f;
}
return f;
}
}
public static Font SystemFontOfSize (int size) {
if (size >= _systemFonts.Length) {
return new Font ("SystemFont", FontOptions.None, size);
}
else {
var f = _systemFonts[size];
if (f == null) {
f = new Font ("SystemFont", FontOptions.None, size);
_systemFonts[size] = f;
}
return f;
}
}
public static Font UserFixedPitchFontOfSize (int size) {
if (size >= _userFixedPitchFonts.Length) {
return new Font ("Monospace", FontOptions.None, size);
}
else {
var f = _userFixedPitchFonts[size];
if (f == null) {
f = new Font ("Monospace", FontOptions.None, size);
_userFixedPitchFonts[size] = f;
}
return f;
}
}
public static Font BoldUserFixedPitchFontOfSize (int size) {
if (size >= _boldUserFixedPitchFonts.Length) {
return new Font ("Monospace", FontOptions.Bold, size);
}
else {
var f = _boldUserFixedPitchFonts[size];
if (f == null) {
f = new Font ("Monospace", FontOptions.Bold, size);
_boldUserFixedPitchFonts[size] = f;
}
return f;
}
}
public static Font FromName (string name, int size) {
return new Font (name, FontOptions.None, size);
}
public override string ToString()
{
return string.Format ("[Font: FontFamily={0}, Options={1}, Size={2}, Tag={3}]", FontFamily, Options, Size, Tag);
}
}
public class Color
{
public readonly int Red, Green, Blue, Alpha;
public object Tag;
public float RedValue {
get { return Red / 255.0f; }
}
public float GreenValue {
get { return Green / 255.0f; }
}
public float BlueValue {
get { return Blue / 255.0f; }
}
public float AlphaValue {
get { return Alpha / 255.0f; }
}
public Color (int red, int green, int blue)
{
Red = red;
Green = green;
Blue = blue;
Alpha = 255;
}
public Color (int red, int green, int blue, int alpha)
{
Red = red;
Green = green;
Blue = blue;
Alpha = alpha;
}
public Color (double red, double green, double blue)
{
Red = (int) (red * 255);
Green = (int) (green * 255);
Blue = (int) (blue * 255);
Alpha = 255;
}
public Color (double red, double green, double blue, double alpha)
{
Red = (int) (red * 255);
Green = (int) (green * 255);
Blue = (int) (blue * 255);
Alpha = (int) (alpha * 255);
}
public int Intensity { get { return (Red + Green + Blue) / 3; } }
public Color GetInvertedColor()
{
return new Color (255 - Red, 255 - Green, 255 - Blue, Alpha);
}
public static bool AreEqual(Color a, Color b)
{
if (a == null && b == null)
return true;
if (a == null && b != null)
return false;
if (a != null && b == null)
return false;
return (a.Red == b.Red && a.Green == b.Green && a.Blue == b.Blue && a.Alpha == b.Alpha);
}
public bool IsWhite {
get { return (Red == 255) && (Green == 255) && (Blue == 255); }
}
public bool IsBlack {
get { return (Red == 0) && (Green == 0) && (Blue == 0); }
}
public Color WithAlpha(int aa)
{
return new Color (Red, Green, Blue, aa);
}
public override bool Equals (object obj)
{
var o = obj as Color;
return (o != null) && (o.Red == Red) && (o.Green == Green) && (o.Blue == Blue) && (o.Alpha == Alpha);
}
public override int GetHashCode ()
{
return (Red + Green + Blue + Alpha).GetHashCode ();
}
public override string ToString()
{
return string.Format ("[Color: RedValue={0}, GreenValue={1}, BlueValue={2}, AlphaValue={3}]", RedValue, GreenValue, BlueValue, AlphaValue);
}
}
public static class Colors
{
public static readonly Color Yellow = new Color (255, 255, 0);
public static readonly Color Red = new Color (255, 0, 0);
public static readonly Color Green = new Color (0, 255, 0);
public static readonly Color Blue = new Color (0, 0, 255);
public static readonly Color White = new Color (255, 255, 255);
public static readonly Color Cyan = new Color (0, 255, 255);
public static readonly Color Black = new Color (0, 0, 0);
public static readonly Color LightGray = new Color (212, 212, 212);
public static readonly Color Gray = new Color (127, 127, 127);
public static readonly Color DarkGray = new Color (64, 64, 64);
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.ResourceManager
{
using System.Linq;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// SubscriptionsOperations operations.
/// </summary>
internal partial class SubscriptionsOperations : Microsoft.Rest.IServiceOperations<SubscriptionClient>, ISubscriptionsOperations
{
/// <summary>
/// Initializes a new instance of the SubscriptionsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal SubscriptionsOperations(SubscriptionClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the SubscriptionClient
/// </summary>
public SubscriptionClient Client { get; private set; }
/// <summary>
/// Gets all available geo-locations.
/// </summary>
/// <remarks>
/// This operation provides all the locations that are available for resource
/// providers; however, each resource provider may support a subset of this
/// list.
/// </remarks>
/// <param name='subscriptionId'>
/// The ID of the target subscription.
/// </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>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<System.Collections.Generic.IEnumerable<Location>>> ListLocationsWithHttpMessagesAsync(string subscriptionId, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (subscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "subscriptionId");
}
if (this.Client.ApiVersion == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// 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("subscriptionId", subscriptionId);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "ListLocations", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/locations").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(subscriptionId));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _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.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.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.Client.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<System.Collections.Generic.IEnumerable<Location>>();
_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<Location>>(_responseContent, this.Client.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 details about a specified subscription.
/// </summary>
/// <param name='subscriptionId'>
/// The ID of the target subscription.
/// </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>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Subscription>> GetWithHttpMessagesAsync(string subscriptionId, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (subscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "subscriptionId");
}
if (this.Client.ApiVersion == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// 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("subscriptionId", subscriptionId);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(subscriptionId));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _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.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.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.Client.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<Subscription>();
_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<Subscription>(_responseContent, this.Client.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 all subscriptions for a tenant.
/// </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>
/// <exception cref="Microsoft.Rest.ValidationException">
/// 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<Subscription>>> ListWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (this.Client.ApiVersion == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// 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.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _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.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.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.Client.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<Subscription>>();
_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<Subscription>>(_responseContent, this.Client.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 all subscriptions for a tenant.
/// </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>
/// <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<Subscription>>> 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
System.Net.Http.HttpRequestMessage _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.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.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.Client.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<Subscription>>();
_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<Subscription>>(_responseContent, this.Client.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;
}
}
}
| |
// 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.Net.Sockets;
using System.Runtime.CompilerServices;
namespace System.Net
{
/// <devdoc>
/// <para>
/// Provides an Internet Protocol (IP) address.
/// </para>
/// </devdoc>
public class IPAddress
{
public static readonly IPAddress Any = new IPAddress(0x0000000000000000);
public static readonly IPAddress Loopback = new IPAddress(0x000000000100007F);
public static readonly IPAddress Broadcast = new IPAddress(0x00000000FFFFFFFF);
public static readonly IPAddress None = Broadcast;
internal const long LoopbackMask = 0x00000000000000FF;
public static readonly IPAddress IPv6Any = new IPAddress(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 0);
public static readonly IPAddress IPv6Loopback = new IPAddress(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }, 0);
public static readonly IPAddress IPv6None = new IPAddress(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 0);
/// <summary>
/// For IPv4 addresses, this field stores the Address.
/// For IPv6 addresses, this field stores the ScopeId.
/// Instead of accessing this field directly, use the <see cref="PrivateAddress"/> or <see cref="PrivateScopeId"/> properties.
/// </summary>
private uint _addressOrScopeId;
/// <summary>
/// This field is only used for IPv6 addresses. A null value indicates that this instance is an IPv4 address.
/// </summary>
private readonly ushort[] _numbers;
/// <summary>
/// A lazily initialized cache of the result of calling <see cref="ToString"/>.
/// </summary>
private string _toString;
/// <summary>
/// This field is only used for IPv6 addresses. A lazily initialized cache of the <see cref="GetHashCode"/> value.
/// </summary>
private int _hashCode;
// Maximum length of address literals (potentially including a port number)
// generated by any address-to-string conversion routine. This length can
// be used when declaring buffers used with getnameinfo, WSAAddressToString,
// inet_ntoa, etc. We just provide one define, rather than one per api,
// to avoid confusion.
//
// The totals are derived from the following data:
// 15: IPv4 address
// 45: IPv6 address including embedded IPv4 address
// 11: Scope Id
// 2: Brackets around IPv6 address when port is present
// 6: Port (including colon)
// 1: Terminating null byte
internal const int NumberOfLabels = IPAddressParserStatics.IPv6AddressBytes / 2;
private bool IsIPv4
{
get { return _numbers == null; }
}
private bool IsIPv6
{
get { return _numbers != null; }
}
private uint PrivateAddress
{
get
{
Debug.Assert(IsIPv4);
return _addressOrScopeId;
}
set
{
Debug.Assert(IsIPv4);
_addressOrScopeId = value;
}
}
private uint PrivateScopeId
{
get
{
Debug.Assert(IsIPv6);
return _addressOrScopeId;
}
set
{
Debug.Assert(IsIPv6);
_addressOrScopeId = value;
}
}
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Net.IPAddress'/>
/// class with the specified address.
/// </para>
/// </devdoc>
public IPAddress(long newAddress)
{
if (newAddress < 0 || newAddress > 0x00000000FFFFFFFF)
{
throw new ArgumentOutOfRangeException(nameof(newAddress));
}
PrivateAddress = (uint)newAddress;
}
/// <devdoc>
/// <para>
/// Constructor for an IPv6 Address with a specified Scope.
/// </para>
/// </devdoc>
public IPAddress(byte[] address, long scopeid) :
this(new ReadOnlySpan<byte>(address ?? ThrowAddressNullException()), scopeid)
{
}
public IPAddress(ReadOnlySpan<byte> address, long scopeid)
{
if (address.Length != IPAddressParserStatics.IPv6AddressBytes)
{
throw new ArgumentException(SR.dns_bad_ip_address, nameof(address));
}
// Consider: Since scope is only valid for link-local and site-local
// addresses we could implement some more robust checking here
if (scopeid < 0 || scopeid > 0x00000000FFFFFFFF)
{
throw new ArgumentOutOfRangeException(nameof(scopeid));
}
_numbers = new ushort[NumberOfLabels];
for (int i = 0; i < NumberOfLabels; i++)
{
_numbers[i] = (ushort)(address[i * 2] * 256 + address[i * 2 + 1]);
}
PrivateScopeId = (uint)scopeid;
}
internal unsafe IPAddress(ushort* numbers, int numbersLength, uint scopeid)
{
Debug.Assert(numbers != null);
Debug.Assert(numbersLength == NumberOfLabels);
var arr = new ushort[NumberOfLabels];
for (int i = 0; i < arr.Length; i++)
{
arr[i] = numbers[i];
}
_numbers = arr;
PrivateScopeId = scopeid;
}
private IPAddress(ushort[] numbers, uint scopeid)
{
Debug.Assert(numbers != null);
Debug.Assert(numbers.Length == NumberOfLabels);
_numbers = numbers;
PrivateScopeId = scopeid;
}
/// <devdoc>
/// <para>
/// Constructor for IPv4 and IPv6 Address.
/// </para>
/// </devdoc>
public IPAddress(byte[] address) :
this(new ReadOnlySpan<byte>(address ?? ThrowAddressNullException()))
{
}
public IPAddress(ReadOnlySpan<byte> address)
{
if (address.Length == IPAddressParserStatics.IPv4AddressBytes)
{
PrivateAddress = (uint)((address[3] << 24 | address[2] << 16 | address[1] << 8 | address[0]) & 0x0FFFFFFFF);
}
else if (address.Length == IPAddressParserStatics.IPv6AddressBytes)
{
_numbers = new ushort[NumberOfLabels];
for (int i = 0; i < NumberOfLabels; i++)
{
_numbers[i] = (ushort)(address[i * 2] * 256 + address[i * 2 + 1]);
}
}
else
{
throw new ArgumentException(SR.dns_bad_ip_address, nameof(address));
}
}
// We need this internally since we need to interface with winsock,
// and winsock only understands Int32.
internal IPAddress(int newAddress)
{
PrivateAddress = (uint)newAddress;
}
/// <devdoc>
/// <para>
/// Converts an IP address string to an <see cref='System.Net.IPAddress'/> instance.
/// </para>
/// </devdoc>
public static bool TryParse(string ipString, out IPAddress address)
{
if (ipString == null)
{
address = null;
return false;
}
address = IPAddressParser.Parse(ipString.AsReadOnlySpan(), tryParse: true);
return (address != null);
}
public static bool TryParse(ReadOnlySpan<char> ipSpan, out IPAddress address)
{
address = IPAddressParser.Parse(ipSpan, tryParse: true);
return (address != null);
}
public static IPAddress Parse(string ipString)
{
if (ipString == null)
{
throw new ArgumentNullException(nameof(ipString));
}
return IPAddressParser.Parse(ipString.AsReadOnlySpan(), tryParse: false);
}
public static IPAddress Parse(ReadOnlySpan<char> ipSpan)
{
return IPAddressParser.Parse(ipSpan, tryParse: false);
}
public bool TryWriteBytes(Span<byte> destination, out int bytesWritten)
{
if (IsIPv6)
{
if (destination.Length < IPAddressParserStatics.IPv6AddressBytes)
{
bytesWritten = 0;
return false;
}
WriteIPv6Bytes(destination);
bytesWritten = IPAddressParserStatics.IPv6AddressBytes;
}
else
{
if (destination.Length < IPAddressParserStatics.IPv4AddressBytes)
{
bytesWritten = 0;
return false;
}
WriteIPv4Bytes(destination);
bytesWritten = IPAddressParserStatics.IPv4AddressBytes;
}
return true;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void WriteIPv6Bytes(Span<byte> destination)
{
Debug.Assert(_numbers != null && _numbers.Length == NumberOfLabels);
int j = 0;
for (int i = 0; i < NumberOfLabels; i++)
{
destination[j++] = (byte)((_numbers[i] >> 8) & 0xFF);
destination[j++] = (byte)((_numbers[i]) & 0xFF);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void WriteIPv4Bytes(Span<byte> destination)
{
uint address = PrivateAddress;
destination[0] = (byte)(address);
destination[1] = (byte)(address >> 8);
destination[2] = (byte)(address >> 16);
destination[3] = (byte)(address >> 24);
}
/// <devdoc>
/// <para>
/// Provides a copy of the IPAddress internals as an array of bytes.
/// </para>
/// </devdoc>
public byte[] GetAddressBytes()
{
if (IsIPv6)
{
Debug.Assert(_numbers != null && _numbers.Length == NumberOfLabels);
byte[] bytes = new byte[IPAddressParserStatics.IPv6AddressBytes];
WriteIPv6Bytes(bytes);
return bytes;
}
else
{
byte[] bytes = new byte[IPAddressParserStatics.IPv4AddressBytes];
WriteIPv4Bytes(bytes);
return bytes;
}
}
public AddressFamily AddressFamily
{
get
{
return IsIPv4 ? AddressFamily.InterNetwork : AddressFamily.InterNetworkV6;
}
}
/// <devdoc>
/// <para>
/// IPv6 Scope identifier. This is really a uint32, but that isn't CLS compliant
/// </para>
/// </devdoc>
public long ScopeId
{
get
{
// Not valid for IPv4 addresses
if (IsIPv4)
{
throw new SocketException(SocketError.OperationNotSupported);
}
return PrivateScopeId;
}
set
{
// Not valid for IPv4 addresses
if (IsIPv4)
{
throw new SocketException(SocketError.OperationNotSupported);
}
// Consider: Since scope is only valid for link-local and site-local
// addresses we could implement some more robust checking here
if (value < 0 || value > 0x00000000FFFFFFFF)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
PrivateScopeId = (uint)value;
}
}
/// <devdoc>
/// <para>
/// Converts the Internet address to either standard dotted quad format
/// or standard IPv6 representation.
/// </para>
/// </devdoc>
public override string ToString()
{
if (_toString == null)
{
_toString = IsIPv4 ?
IPAddressParser.IPv4AddressToString(PrivateAddress) :
IPAddressParser.IPv6AddressToString(_numbers, PrivateScopeId);
}
return _toString;
}
public bool TryFormat(Span<char> destination, out int charsWritten)
{
return IsIPv4 ?
IPAddressParser.IPv4AddressToString(PrivateAddress, destination, out charsWritten) :
IPAddressParser.IPv6AddressToString(_numbers, PrivateScopeId, destination, out charsWritten);
}
public static long HostToNetworkOrder(long host)
{
#if BIGENDIAN
return host;
#else
return (((long)HostToNetworkOrder(unchecked((int)host)) & 0xFFFFFFFF) << 32)
| ((long)HostToNetworkOrder(unchecked((int)(host >> 32))) & 0xFFFFFFFF);
#endif
}
public static int HostToNetworkOrder(int host)
{
#if BIGENDIAN
return host;
#else
return (((int)HostToNetworkOrder(unchecked((short)host)) & 0xFFFF) << 16)
| ((int)HostToNetworkOrder(unchecked((short)(host >> 16))) & 0xFFFF);
#endif
}
public static short HostToNetworkOrder(short host)
{
#if BIGENDIAN
return host;
#else
return unchecked((short)((((int)host & 0xFF) << 8) | (int)((host >> 8) & 0xFF)));
#endif
}
public static long NetworkToHostOrder(long network)
{
return HostToNetworkOrder(network);
}
public static int NetworkToHostOrder(int network)
{
return HostToNetworkOrder(network);
}
public static short NetworkToHostOrder(short network)
{
return HostToNetworkOrder(network);
}
public static bool IsLoopback(IPAddress address)
{
if (address == null)
{
ThrowAddressNullException();
}
if (address.IsIPv6)
{
// Do Equals test for IPv6 addresses
return address.Equals(IPv6Loopback);
}
else
{
return ((address.PrivateAddress & LoopbackMask) == (Loopback.PrivateAddress & LoopbackMask));
}
}
/// <devdoc>
/// <para>
/// Determines if an address is an IPv6 Multicast address
/// </para>
/// </devdoc>
public bool IsIPv6Multicast
{
get
{
return IsIPv6 && ((_numbers[0] & 0xFF00) == 0xFF00);
}
}
/// <devdoc>
/// <para>
/// Determines if an address is an IPv6 Link Local address
/// </para>
/// </devdoc>
public bool IsIPv6LinkLocal
{
get
{
return IsIPv6 && ((_numbers[0] & 0xFFC0) == 0xFE80);
}
}
/// <devdoc>
/// <para>
/// Determines if an address is an IPv6 Site Local address
/// </para>
/// </devdoc>
public bool IsIPv6SiteLocal
{
get
{
return IsIPv6 && ((_numbers[0] & 0xFFC0) == 0xFEC0);
}
}
public bool IsIPv6Teredo
{
get
{
return IsIPv6 &&
(_numbers[0] == 0x2001) &&
(_numbers[1] == 0);
}
}
// 0:0:0:0:0:FFFF:x.x.x.x
public bool IsIPv4MappedToIPv6
{
get
{
if (IsIPv4)
{
return false;
}
for (int i = 0; i < 5; i++)
{
if (_numbers[i] != 0)
{
return false;
}
}
return (_numbers[5] == 0xFFFF);
}
}
[Obsolete("This property has been deprecated. It is address family dependent. Please use IPAddress.Equals method to perform comparisons. http://go.microsoft.com/fwlink/?linkid=14202")]
public long Address
{
get
{
//
// IPv6 Changes: Can't do this for IPv6, so throw an exception.
//
//
if (AddressFamily == AddressFamily.InterNetworkV6)
{
throw new SocketException(SocketError.OperationNotSupported);
}
else
{
return PrivateAddress;
}
}
set
{
//
// IPv6 Changes: Can't do this for IPv6 addresses
if (AddressFamily == AddressFamily.InterNetworkV6)
{
throw new SocketException(SocketError.OperationNotSupported);
}
else
{
if (PrivateAddress != value)
{
_toString = null;
PrivateAddress = unchecked((uint)value);
}
}
}
}
internal bool Equals(object comparandObj, bool compareScopeId)
{
IPAddress comparand = comparandObj as IPAddress;
if (comparand == null)
{
return false;
}
// Compare families before address representations
if (AddressFamily != comparand.AddressFamily)
{
return false;
}
if (IsIPv6)
{
// For IPv6 addresses, we must compare the full 128-bit representation.
for (int i = 0; i < NumberOfLabels; i++)
{
if (comparand._numbers[i] != _numbers[i])
{
return false;
}
}
// The scope IDs must also match
return comparand.PrivateScopeId == PrivateScopeId || !compareScopeId;
}
else
{
// For IPv4 addresses, compare the integer representation.
return comparand.PrivateAddress == PrivateAddress;
}
}
/// <devdoc>
/// <para>
/// Compares two IP addresses.
/// </para>
/// </devdoc>
public override bool Equals(object comparand)
{
return Equals(comparand, true);
}
public override int GetHashCode()
{
// For IPv6 addresses, we cannot simply return the integer
// representation as the hashcode. Instead, we calculate
// the hashcode from the string representation of the address.
if (IsIPv6)
{
if (_hashCode == 0)
{
_hashCode = StringComparer.OrdinalIgnoreCase.GetHashCode(ToString());
}
return _hashCode;
}
else
{
// For IPv4 addresses, we can simply use the integer representation.
return unchecked((int)PrivateAddress);
}
}
// For security, we need to be able to take an IPAddress and make a copy that's immutable and not derived.
internal IPAddress Snapshot()
{
return IsIPv4 ?
new IPAddress(PrivateAddress) :
new IPAddress(_numbers, PrivateScopeId);
}
// IPv4 192.168.1.1 maps as ::FFFF:192.168.1.1
public IPAddress MapToIPv6()
{
if (IsIPv6)
{
return this;
}
uint address = PrivateAddress;
ushort[] labels = new ushort[NumberOfLabels];
labels[5] = 0xFFFF;
labels[6] = (ushort)(((address & 0x0000FF00) >> 8) | ((address & 0x000000FF) << 8));
labels[7] = (ushort)(((address & 0xFF000000) >> 24) | ((address & 0x00FF0000) >> 8));
return new IPAddress(labels, 0);
}
// Takes the last 4 bytes of an IPv6 address and converts it to an IPv4 address.
// This does not restrict to address with the ::FFFF: prefix because other types of
// addresses display the tail segments as IPv4 like Terado.
public IPAddress MapToIPv4()
{
if (IsIPv4)
{
return this;
}
// Cast the ushort values to a uint and mask with unsigned literal before bit shifting.
// Otherwise, we can end up getting a negative value for any IPv4 address that ends with
// a byte higher than 127 due to sign extension of the most significant 1 bit.
long address = ((((uint)_numbers[6] & 0x0000FF00u) >> 8) | (((uint)_numbers[6] & 0x000000FFu) << 8)) |
(((((uint)_numbers[7] & 0x0000FF00u) >> 8) | (((uint)_numbers[7] & 0x000000FFu) << 8)) << 16);
return new IPAddress(address);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static byte[] ThrowAddressNullException() => throw new ArgumentNullException("address");
}
}
| |
using System.Collections.Generic;
using System.Reflection;
namespace CobaltAHK
{
public abstract class Token
{
#region any state
public static readonly Token EOF = new PunctuationToken(unchecked ((char)-1));
public static readonly Token Newline = new PunctuationToken('\n');
public static readonly Token Comma = new PunctuationToken(',');
#endregion
// State.Traditional
public static readonly Token ForceExpression = new PunctuationToken('%');
#region State.Expression (and others)
public static readonly Token Colon = new PunctuationToken(':');
public static readonly Token OpenParenthesis = new PunctuationToken('(');
public static readonly Token CloseParenthesis = new PunctuationToken(')');
public static readonly Token OpenBrace = new PunctuationToken('{'); // blocks or object literals
public static readonly Token CloseBrace = new PunctuationToken('}');
public static readonly Token OpenBracket = new PunctuationToken('['); // object access or array literals
public static readonly Token CloseBracket = new PunctuationToken(']');
#endregion
}
public abstract class PositionedToken : Token
{
protected PositionedToken(SourcePosition pos)
{
position = pos;
}
private readonly SourcePosition position;
public SourcePosition Position { get { return position; } }
}
public class PunctuationToken : Token
{
public PunctuationToken(char ch)
{
character = ch;
}
private readonly char character;
public char Character { get { return character; } }
}
#region TextToken
public abstract class TextToken : PositionedToken
{
protected TextToken(SourcePosition pos, string str)
: base(pos)
{
text = str;
}
private string text;
public string Text { get { return text; } }
#if DEBUG
public override string ToString()
{
return string.Format("[" + GetType() + ": Text='{0}']", Text.Escape());
}
#endif
}
#region comments
public abstract class CommentToken : TextToken
{
public CommentToken(SourcePosition pos, string comment) : base(pos, comment) { }
}
public class SingleCommentToken : CommentToken
{
public SingleCommentToken(SourcePosition pos, string comment) : base(pos, comment) { }
}
public class MultiLineCommentToken : CommentToken
{
public MultiLineCommentToken(SourcePosition pos, string comment) : base(pos, comment) { }
}
#endregion
public class QuotedStringToken : TextToken
{
public QuotedStringToken(SourcePosition pos, string str) : base(pos, str) { }
}
public class TraditionalStringToken : TextToken
{
public TraditionalStringToken(SourcePosition pos, string str) : base(pos, str) { }
}
public class NumberToken : TextToken
{
public NumberToken(SourcePosition pos, string str, Syntax.NumberType t)
: base(pos, str)
{
type = t;
}
private Syntax.NumberType type;
public Syntax.NumberType Type { get { return type; } }
}
public class VariableToken : TextToken // for variables in traditional mode
{
public VariableToken(SourcePosition pos, string var) : base(pos, var) { }
}
public class IdToken : TextToken // for variables, command names, ...
{
public IdToken(SourcePosition pos, string id) : base(pos, id) { }
}
public class FunctionToken : TextToken // for function calls or definitions (id followed by opening parenthese)
{
public FunctionToken(SourcePosition pos, string name) : base(pos, name) { }
}
#endregion
public class HotkeyToken : PositionedToken
{
public HotkeyToken(SourcePosition pos) : base(pos) { }
}
public class HotstringToken : PositionedToken
{
public HotstringToken(SourcePosition pos) : base(pos) { }
}
#region EnumToken
public abstract class EnumToken<T, TToken> : Token where TToken : EnumToken<T, TToken>
{
protected EnumToken(T val)
{
value = val;
}
protected T value;
private static IDictionary<T, TToken> map = new Dictionary<T, TToken>();
public static TToken GetToken(T key)
{
if (!map.ContainsKey(key)) {
map[key] = CreateInstance(key);
}
return map[key];
}
private static TToken CreateInstance(T val)
{
var c = typeof(TToken).GetConstructor(
BindingFlags.NonPublic|BindingFlags.Instance,
null,
new[] { typeof(T) },
default(ParameterModifier[])
);
return (TToken)c.Invoke(new object[] { val });
}
}
public class DirectiveToken : EnumToken<Syntax.Directive, DirectiveToken>
{
protected DirectiveToken(Syntax.Directive dir) : base(dir) { }
public Syntax.Directive Directive { get { return value; } }
}
public class OperatorToken : EnumToken<Operator, OperatorToken>
{
protected OperatorToken(Operator op) : base(op) { }
public Operator Operator { get { return value; } }
#if DEBUG
public override string ToString()
{
return string.Format("[OperatorToken: Operator='{0}' Type={1}]", Operator.Code, Operator.GetType());
}
#endif
}
public class KeywordToken : EnumToken<Syntax.Keyword, KeywordToken>
{
protected KeywordToken(Syntax.Keyword kw) : base(kw) { }
public Syntax.Keyword Keyword { get { return value; } }
}
public class ValueKeywordToken : EnumToken<Syntax.ValueKeyword, ValueKeywordToken>
{
protected ValueKeywordToken(Syntax.ValueKeyword kw) : base(kw) { }
public Syntax.ValueKeyword Keyword { get { return value; } }
}
#endregion
}
| |
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using BTDB.KVDBLayer.BTree;
namespace BTDB.KVDBLayer;
class KeyValueDBTransaction : IKeyValueDBTransaction
{
readonly KeyValueDB _keyValueDB;
IBTreeRootNode? _btreeRoot;
readonly List<NodeIdxPair> _stack = new List<NodeIdxPair>();
bool _writing;
readonly bool _readOnly;
bool _preapprovedWriting;
bool _temporaryCloseTransactionLog;
long _keyIndex;
long _cursorMovedCounter;
public DateTime CreatedTime { get; } = DateTime.UtcNow;
public KeyValueDBTransaction(KeyValueDB keyValueDB, IBTreeRootNode btreeRoot, bool writing, bool readOnly)
{
_preapprovedWriting = writing;
_readOnly = readOnly;
_keyValueDB = keyValueDB;
_btreeRoot = btreeRoot;
_keyIndex = -1;
_cursorMovedCounter = 0;
_keyValueDB.StartedUsingBTreeRoot(_btreeRoot);
}
~KeyValueDBTransaction()
{
if (_btreeRoot != null || _writing || _preapprovedWriting)
{
Dispose();
_keyValueDB.Logger?.ReportTransactionLeak(this);
}
}
internal IBTreeRootNode? BtreeRoot => _btreeRoot;
public bool FindFirstKey(in ReadOnlySpan<byte> prefix)
{
_cursorMovedCounter++;
if (_btreeRoot!.FindKey(_stack, out _keyIndex, prefix, (uint)prefix.Length) !=
FindResult.NotFound) return true;
InvalidateCurrentKey();
return false;
}
public bool FindLastKey(in ReadOnlySpan<byte> prefix)
{
_cursorMovedCounter++;
_keyIndex = _btreeRoot!.FindLastWithPrefix(prefix);
if (_keyIndex == -1) return false;
_btreeRoot.FillStackByIndex(_stack, _keyIndex);
return true;
}
public bool FindPreviousKey(in ReadOnlySpan<byte> prefix)
{
if (_keyIndex == -1) return FindLastKey(prefix);
_cursorMovedCounter++;
if (_btreeRoot!.FindPreviousKey(_stack))
{
if (CheckPrefixIn(prefix, GetCurrentKeyFromStack()))
{
_keyIndex--;
return true;
}
}
InvalidateCurrentKey();
return false;
}
public bool FindNextKey(in ReadOnlySpan<byte> prefix)
{
if (_keyIndex == -1) return FindFirstKey(prefix);
_cursorMovedCounter++;
if (_btreeRoot!.FindNextKey(_stack))
{
if (CheckPrefixIn(prefix, GetCurrentKeyFromStack()))
{
_keyIndex++;
return true;
}
}
InvalidateCurrentKey();
return false;
}
public FindResult Find(in ReadOnlySpan<byte> key, uint prefixLen)
{
_cursorMovedCounter++;
return _btreeRoot!.FindKey(_stack, out _keyIndex, key, prefixLen);
}
public bool CreateOrUpdateKeyValue(in ReadOnlySpan<byte> key, in ReadOnlySpan<byte> value)
{
_cursorMovedCounter++;
MakeWritable();
_keyValueDB.WriteCreateOrUpdateCommand(key, value, out var valueFileId, out var valueOfs, out var valueSize);
var ctx = new CreateOrUpdateCtx
{
Key = key,
ValueFileId = valueFileId,
ValueOfs = valueOfs,
ValueSize = valueSize,
Stack = _stack
};
_btreeRoot!.CreateOrUpdate(ref ctx);
_keyIndex = ctx.KeyIndex;
return ctx.Created;
}
void MakeWritable()
{
if (_writing) return;
if (_preapprovedWriting)
{
_writing = true;
_preapprovedWriting = false;
_keyValueDB.WriteStartTransaction();
return;
}
if (_readOnly)
{
throw new BTDBTransactionRetryException("Cannot write from readOnly transaction");
}
var oldBTreeRoot = _btreeRoot;
_btreeRoot = _keyValueDB.MakeWritableTransaction(this, oldBTreeRoot!);
_keyValueDB.StartedUsingBTreeRoot(_btreeRoot);
_keyValueDB.FinishedUsingBTreeRoot(oldBTreeRoot);
_btreeRoot.DescriptionForLeaks = _descriptionForLeaks;
_writing = true;
InvalidateCurrentKey();
_keyValueDB.WriteStartTransaction();
}
public long GetKeyValueCount() => _btreeRoot!.CalcKeyCount();
public long GetKeyIndex() => _keyIndex;
public bool SetKeyIndex(long index)
{
_cursorMovedCounter++;
if (index < 0 || index >= _btreeRoot!.CalcKeyCount())
{
InvalidateCurrentKey();
return false;
}
_keyIndex = index;
_btreeRoot!.FillStackByIndex(_stack, _keyIndex);
return true;
}
public bool SetKeyIndex(in ReadOnlySpan<byte> prefix, long index)
{
_cursorMovedCounter++;
if (_btreeRoot!.FindKey(_stack, out _keyIndex, prefix, (uint)prefix.Length) ==
FindResult.NotFound)
{
InvalidateCurrentKey();
return false;
}
index += _keyIndex;
if (index < _btreeRoot!.CalcKeyCount())
{
_keyIndex = index;
_btreeRoot!.FillStackByIndex(_stack, _keyIndex);
if (CheckPrefixIn(prefix, GetCurrentKeyFromStack()))
return true;
}
InvalidateCurrentKey();
return false;
}
static bool CheckPrefixIn(in ReadOnlySpan<byte> prefix, in ReadOnlySpan<byte> key)
{
return BTreeRoot.KeyStartsWithPrefix(prefix, key);
}
ReadOnlySpan<byte> GetCurrentKeyFromStack()
{
var nodeIdxPair = _stack[^1];
return ((IBTreeLeafNode)nodeIdxPair.Node).GetKey(nodeIdxPair.Idx);
}
public void InvalidateCurrentKey()
{
_cursorMovedCounter++;
_keyIndex = -1;
_stack.Clear();
}
public bool IsValidKey()
{
return _keyIndex >= 0;
}
public ReadOnlySpan<byte> GetKey()
{
if (!IsValidKey()) return new ReadOnlySpan<byte>();
return GetCurrentKeyFromStack();
}
public byte[] GetKeyToArray()
{
var nodeIdxPair = _stack[^1];
return ((IBTreeLeafNode)nodeIdxPair.Node).GetKey(nodeIdxPair.Idx).ToArray();
}
public ReadOnlySpan<byte> GetKey(ref byte buffer, int bufferLength)
{
if (!IsValidKey()) return new ReadOnlySpan<byte>();
return GetCurrentKeyFromStack();
}
public ReadOnlySpan<byte> GetClonedValue(ref byte buffer, int bufferLength)
{
if (!IsValidKey()) return ReadOnlySpan<byte>.Empty;
var nodeIdxPair = _stack[^1];
var leafMember = ((IBTreeLeafNode)nodeIdxPair.Node).GetMemberValue(nodeIdxPair.Idx);
try
{
return _keyValueDB.ReadValue(leafMember.ValueFileId, leafMember.ValueOfs, leafMember.ValueSize, ref buffer, bufferLength);
}
catch (BTDBException ex)
{
var oldestRoot = (IBTreeRootNode)_keyValueDB.ReferenceAndGetOldestRoot();
var lastCommitted = (IBTreeRootNode)_keyValueDB.ReferenceAndGetLastCommitted();
// no need to dereference roots because we know it is managed
throw new BTDBException($"GetValue failed in TrId:{_btreeRoot!.TransactionId},TRL:{_btreeRoot!.TrLogFileId},Ofs:{_btreeRoot!.TrLogOffset},ComUlong:{_btreeRoot!.CommitUlong} and LastTrId:{lastCommitted.TransactionId},ComUlong:{lastCommitted.CommitUlong} OldestTrId:{oldestRoot.TransactionId},TRL:{oldestRoot.TrLogFileId},ComUlong:{oldestRoot.CommitUlong} innerMessage:{ex.Message}", ex);
}
}
public ReadOnlySpan<byte> GetValue()
{
return GetClonedValue(ref Unsafe.AsRef((byte)0), 0);
}
void EnsureValidKey()
{
if (_keyIndex < 0)
{
throw new InvalidOperationException("Current key is not valid");
}
}
public void SetValue(in ReadOnlySpan<byte> value)
{
EnsureValidKey();
var keyIndexBackup = _keyIndex;
MakeWritable();
if (_keyIndex != keyIndexBackup)
{
_keyIndex = keyIndexBackup;
_btreeRoot!.FillStackByIndex(_stack, _keyIndex);
}
var nodeIdxPair = _stack[^1];
var memberValue = ((IBTreeLeafNode)nodeIdxPair.Node).GetMemberValue(nodeIdxPair.Idx);
var memberKey = ((IBTreeLeafNode)nodeIdxPair.Node).GetKey(nodeIdxPair.Idx);
_keyValueDB.WriteCreateOrUpdateCommand(memberKey, value, out memberValue.ValueFileId, out memberValue.ValueOfs, out memberValue.ValueSize);
((IBTreeLeafNode)nodeIdxPair.Node).SetMemberValue(nodeIdxPair.Idx, memberValue);
}
public void EraseCurrent()
{
_cursorMovedCounter++;
EnsureValidKey();
var keyIndex = _keyIndex;
MakeWritable();
if (_keyIndex != keyIndex)
{
_keyIndex = keyIndex;
_btreeRoot!.FillStackByIndex(_stack, keyIndex);
}
_keyValueDB.WriteEraseOneCommand(GetCurrentKeyFromStack());
InvalidateCurrentKey();
_btreeRoot!.EraseOne(keyIndex);
}
public bool EraseCurrent(in ReadOnlySpan<byte> exactKey)
{
_cursorMovedCounter++;
if (_btreeRoot!.FindKey(_stack, out _keyIndex, exactKey, 0) != FindResult.Exact)
{
InvalidateCurrentKey();
return false;
}
var keyIndex = _keyIndex;
MakeWritable();
_keyValueDB.WriteEraseOneCommand(exactKey);
InvalidateCurrentKey();
_btreeRoot!.EraseOne(keyIndex);
return true;
}
public bool EraseCurrent(in ReadOnlySpan<byte> exactKey, ref byte buffer, int bufferLength, out ReadOnlySpan<byte> value)
{
_cursorMovedCounter++;
if (_btreeRoot!.FindKey(_stack, out _keyIndex, exactKey, 0) != FindResult.Exact)
{
InvalidateCurrentKey();
value = ReadOnlySpan<byte>.Empty;
return false;
}
var keyIndex = _keyIndex;
value = GetClonedValue(ref buffer, bufferLength);
MakeWritable();
_keyValueDB.WriteEraseOneCommand(exactKey);
InvalidateCurrentKey();
_btreeRoot!.EraseOne(keyIndex);
return true;
}
public void EraseAll()
{
EraseRange(0, GetKeyValueCount() - 1);
}
public void EraseRange(long firstKeyIndex, long lastKeyIndex)
{
if (firstKeyIndex < 0) firstKeyIndex = 0;
if (lastKeyIndex >= GetKeyValueCount()) lastKeyIndex = GetKeyValueCount() - 1;
if (lastKeyIndex < firstKeyIndex) return;
_cursorMovedCounter++;
MakeWritable();
InvalidateCurrentKey();
_btreeRoot!.FillStackByIndex(_stack, firstKeyIndex);
if (firstKeyIndex == lastKeyIndex)
{
_keyValueDB.WriteEraseOneCommand(GetCurrentKeyFromStack());
}
else
{
var firstKey = GetCurrentKeyFromStack();
_btreeRoot!.FillStackByIndex(_stack, lastKeyIndex);
_keyValueDB.WriteEraseRangeCommand(firstKey, GetCurrentKeyFromStack());
}
_btreeRoot!.EraseRange(firstKeyIndex, lastKeyIndex);
}
public bool IsWriting()
{
return _writing || _preapprovedWriting;
}
public bool IsReadOnly()
{
return _readOnly;
}
public bool IsDisposed()
{
return BtreeRoot == null;
}
public ulong GetCommitUlong()
{
return _btreeRoot!.CommitUlong;
}
public void SetCommitUlong(ulong value)
{
if (_btreeRoot!.CommitUlong != value)
{
MakeWritable();
_btreeRoot!.CommitUlong = value;
}
}
public void NextCommitTemporaryCloseTransactionLog()
{
MakeWritable();
_temporaryCloseTransactionLog = true;
}
public void Commit()
{
if (BtreeRoot == null) throw new BTDBException("Transaction already committed or disposed");
InvalidateCurrentKey();
var currentBtreeRoot = _btreeRoot;
_keyValueDB.FinishedUsingBTreeRoot(_btreeRoot!);
_btreeRoot = null;
GC.SuppressFinalize(this);
if (_preapprovedWriting)
{
_preapprovedWriting = false;
_keyValueDB.RevertWritingTransaction(true);
}
else if (_writing)
{
_keyValueDB.CommitWritingTransaction(currentBtreeRoot!, _temporaryCloseTransactionLog);
_writing = false;
}
}
public void Dispose()
{
if (_writing || _preapprovedWriting)
{
_keyValueDB.RevertWritingTransaction(_preapprovedWriting);
_writing = false;
_preapprovedWriting = false;
}
if (_btreeRoot == null) return;
_keyValueDB.FinishedUsingBTreeRoot(_btreeRoot);
_btreeRoot = null;
GC.SuppressFinalize(this);
}
public long GetTransactionNumber()
{
return _btreeRoot!.TransactionId;
}
public long CursorMovedCounter => _cursorMovedCounter;
public KeyValuePair<uint, uint> GetStorageSizeOfCurrentKey()
{
if (!IsValidKey()) return new KeyValuePair<uint, uint>();
var nodeIdxPair = _stack[^1];
var leafMember = ((IBTreeLeafNode)nodeIdxPair.Node).GetMemberValue(nodeIdxPair.Idx);
return new KeyValuePair<uint, uint>(
(uint)((IBTreeLeafNode)nodeIdxPair.Node).GetKey(nodeIdxPair.Idx).Length,
KeyValueDB.CalcValueSize(leafMember.ValueFileId, leafMember.ValueOfs, leafMember.ValueSize));
}
public ulong GetUlong(uint idx)
{
return _btreeRoot!.GetUlong(idx);
}
public void SetUlong(uint idx, ulong value)
{
if (_btreeRoot!.GetUlong(idx) != value)
{
MakeWritable();
_btreeRoot!.SetUlong(idx, value);
}
}
public uint GetUlongCount()
{
return _btreeRoot!.UlongsArray == null ? 0U : (uint)_btreeRoot!.UlongsArray.Length;
}
string? _descriptionForLeaks;
public IKeyValueDB Owner => _keyValueDB;
public string? DescriptionForLeaks
{
get => _descriptionForLeaks;
set
{
_descriptionForLeaks = value;
if (_preapprovedWriting || _writing) _btreeRoot!.DescriptionForLeaks = value;
}
}
public bool RollbackAdvised { get; set; }
}
| |
//
// AudioType.cs:
//
// Authors:
// Miguel de Icaza (miguel@novell.com)
// AKIHIRO Uehara (u-akihiro@reinforce-lab.com)
// Marek Safar (marek.safar@gmail.com)
//
// Copyright 2009, 2010 Novell, Inc
// Copyright 2010, Reinforce Lab.
// Copyright 2011, 2012 Xamarin Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Text;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Diagnostics;
using MonoMac.CoreFoundation;
using MonoMac.ObjCRuntime;
using MonoMac.Foundation;
namespace MonoMac.AudioToolbox {
public enum AudioFormatType {
LinearPCM = 0x6c70636d,
AC3 = 0x61632d33,
CAC3 = 0x63616333,
AppleIMA4 = 0x696d6134,
MPEG4AAC = 0x61616320,
MPEG4CELP = 0x63656c70,
MPEG4HVXC = 0x68767863,
MPEG4TwinVQ = 0x74777671,
MACE3 = 0x4d414333,
MACE6 = 0x4d414336,
ULaw = 0x756c6177,
ALaw = 0x616c6177,
QDesign = 0x51444d43,
QDesign2 = 0x51444d32,
QUALCOMM = 0x51636c70,
MPEGLayer1 = 0x2e6d7031,
MPEGLayer2 = 0x2e6d7032,
MPEGLayer3 = 0x2e6d7033,
TimeCode = 0x74696d65,
MIDIStream = 0x6d696469,
ParameterValueStream = 0x61707673,
AppleLossless = 0x616c6163,
MPEG4AAC_HE = 0x61616368,
MPEG4AAC_LD = 0x6161636c,
MPEG4AAC_ELD = 0x61616365, // 'aace'
MPEG4AAC_ELD_SBR = 0x61616366, // 'aacf',
MPEG4AAC_ELD_V2 = 0x61616367, // 'aacg',
MPEG4AAC_HE_V2 = 0x61616370,
MPEG4AAC_Spatial = 0x61616373,
AMR = 0x73616d72,
Audible = 0x41554442,
iLBC = 0x696c6263,
DVIIntelIMA = 0x6d730011,
MicrosoftGSM = 0x6d730031,
AES3 = 0x61657333,
}
[Flags]
public enum AudioFormatFlags : uint
{
IsFloat = (1 << 0), // 0x1
IsBigEndian = (1 << 1), // 0x2
IsSignedInteger = (1 << 2), // 0x4
IsPacked = (1 << 3), // 0x8
IsAlignedHigh = (1 << 4), // 0x10
IsNonInterleaved = (1 << 5), // 0x20
IsNonMixable = (1 << 6), // 0x40
FlagsAreAllClear = unchecked((uint)(1 << 31)),
LinearPCMIsFloat = (1 << 0), // 0x1
LinearPCMIsBigEndian = (1 << 1), // 0x2
LinearPCMIsSignedInteger = (1 << 2), // 0x4
LinearPCMIsPacked = (1 << 3), // 0x8
LinearPCMIsAlignedHigh = (1 << 4), // 0x10
LinearPCMIsNonInterleaved = (1 << 5), // 0x20
LinearPCMIsNonMixable = (1 << 6), // 0x40
LinearPCMSampleFractionShift = 7,
LinearPCMSampleFractionMask = 0x3F << (int)LinearPCMSampleFractionShift,
LinearPCMFlagsAreAllClear = FlagsAreAllClear,
AppleLossless16BitSourceData = 1,
AppleLossless20BitSourceData = 2,
AppleLossless24BitSourceData = 3,
AppleLossless32BitSourceData = 4
}
[StructLayout (LayoutKind.Sequential)]
unsafe struct AudioFormatInfo
{
public AudioStreamBasicDescription AudioStreamBasicDescription;
public byte* MagicCookieWeak;
public int MagicCookieSize;
}
[DebuggerDisplay ("{FormatName}")]
[StructLayout(LayoutKind.Sequential)]
public struct AudioStreamBasicDescription {
public double SampleRate;
public AudioFormatType Format;
public AudioFormatFlags FormatFlags;
public int BytesPerPacket; // uint
public int FramesPerPacket; // uint
public int BytesPerFrame; // uint
public int ChannelsPerFrame; // uint
public int BitsPerChannel; // uint
public int Reserved; // uint
public const double AudioStreamAnyRate = 0;
const int AudioUnitSampleFractionBits = 24;
const AudioFormatFlags AudioFormatFlagIsBigEndian = 0;
public static readonly AudioFormatFlags AudioFormatFlagsAudioUnitCanonical = AudioFormatFlags.IsSignedInteger | AudioFormatFlagIsBigEndian |
AudioFormatFlags.IsPacked | AudioFormatFlags.IsNonInterleaved | (AudioFormatFlags) (AudioUnitSampleFractionBits << (int)AudioFormatFlags.LinearPCMSampleFractionShift);
public AudioStreamBasicDescription (AudioFormatType formatType)
: this ()
{
Format = formatType;
}
public static AudioStreamBasicDescription CreateLinearPCM (double sampleRate = 44100, uint channelsPerFrame = 2, uint bitsPerChannel = 16, bool bigEndian = false)
{
var desc = new AudioStreamBasicDescription (AudioFormatType.LinearPCM);
desc.SampleRate = sampleRate;
desc.ChannelsPerFrame = (int) channelsPerFrame;
desc.BitsPerChannel = (int) bitsPerChannel;
desc.BytesPerPacket = desc.BytesPerFrame = (int) channelsPerFrame * sizeof (Int16);
desc.FramesPerPacket = 1;
desc.FormatFlags = AudioFormatFlags.IsSignedInteger | AudioFormatFlags.IsPacked;
if (bigEndian)
desc.FormatFlags |= AudioFormatFlags.IsBigEndian;
return desc;
}
public unsafe static AudioChannelLayoutTag[] GetAvailableEncodeChannelLayoutTags (AudioStreamBasicDescription format)
{
var type_size = Marshal.SizeOf (format);
uint size;
if (AudioFormatPropertyNative.AudioFormatGetPropertyInfo (AudioFormatProperty.AvailableEncodeChannelLayoutTags, type_size, ref format, out size) != 0)
return null;
var data = new AudioChannelLayoutTag[size / sizeof (AudioChannelLayoutTag)];
fixed (AudioChannelLayoutTag* ptr = data) {
var res = AudioFormatPropertyNative.AudioFormatGetProperty (AudioFormatProperty.AvailableEncodeChannelLayoutTags, type_size, ref format, ref size, (int*)ptr);
if (res != 0)
return null;
return data;
}
}
public unsafe static int[] GetAvailableEncodeNumberChannels (AudioStreamBasicDescription format)
{
uint size;
if (AudioFormatPropertyNative.AudioFormatGetPropertyInfo (AudioFormatProperty.AvailableEncodeNumberChannels, Marshal.SizeOf (format), ref format, out size) != 0)
return null;
var data = new int[size / sizeof (int)];
fixed (int* ptr = data) {
var res = AudioFormatPropertyNative.AudioFormatGetProperty (AudioFormatProperty.AvailableEncodeNumberChannels, Marshal.SizeOf (format), ref format, ref size, ptr);
if (res != 0)
return null;
return data;
}
}
public unsafe AudioFormat[] GetOutputFormatList (byte[] magicCookie = null)
{
var afi = new AudioFormatInfo ();
afi.AudioStreamBasicDescription = this;
var type_size = Marshal.SizeOf (typeof (AudioFormat));
uint size;
if (AudioFormatPropertyNative.AudioFormatGetPropertyInfo (AudioFormatProperty.OutputFormatList, type_size, ref afi, out size) != 0)
return null;
Debug.Assert (sizeof (AudioFormat) == type_size);
var data = new AudioFormat[size / type_size];
fixed (AudioFormat* ptr = &data[0]) {
var res = AudioFormatPropertyNative.AudioFormatGetProperty (AudioFormatProperty.OutputFormatList, type_size, ref afi, ref size, ptr);
if (res != 0)
return null;
Array.Resize (ref data, (int) size / type_size);
return data;
}
}
public unsafe AudioFormat[] GetFormatList (byte[] magicCookie)
{
if (magicCookie == null)
throw new ArgumentNullException ("magicCookie");
var afi = new AudioFormatInfo ();
afi.AudioStreamBasicDescription = this;
fixed (byte* b = magicCookie)
{
afi.MagicCookieWeak = b;
afi.MagicCookieSize = magicCookie.Length;
var type_size = Marshal.SizeOf (typeof (AudioFormat));
uint size;
if (AudioFormatPropertyNative.AudioFormatGetPropertyInfo (AudioFormatProperty.FormatList, type_size, ref afi, out size) != 0)
return null;
Debug.Assert (sizeof (AudioFormat) == type_size);
var data = new AudioFormat[size / type_size];
fixed (AudioFormat* ptr = &data[0]) {
var res = AudioFormatPropertyNative.AudioFormatGetProperty (AudioFormatProperty.FormatList, type_size, ref afi, ref size, ptr);
if (res != 0)
return null;
Array.Resize (ref data, (int)size / type_size);
return data;
}
}
}
public static AudioFormatError GetFormatInfo (ref AudioStreamBasicDescription format)
{
var size = Marshal.SizeOf (format);
return AudioFormatPropertyNative.AudioFormatGetProperty (AudioFormatProperty.FormatInfo, 0, IntPtr.Zero, ref size, ref format);
}
public unsafe string FormatName {
get {
IntPtr ptr;
var size = Marshal.SizeOf (typeof (IntPtr));
if (AudioFormatPropertyNative.AudioFormatGetProperty (AudioFormatProperty.FormatName, Marshal.SizeOf (this), ref this, ref size, out ptr) != 0)
return null;
return new CFString (ptr, true);
}
}
public unsafe bool IsEncrypted {
get {
uint data;
var size = sizeof (uint);
if (AudioFormatPropertyNative.AudioFormatGetProperty (AudioFormatProperty.FormatIsEncrypted, Marshal.SizeOf (this), ref this, ref size, out data) != 0)
return false;
return data != 0;
}
}
public unsafe bool IsExternallyFramed {
get {
uint data;
var size = sizeof (uint);
if (AudioFormatPropertyNative.AudioFormatGetProperty (AudioFormatProperty.FormatIsExternallyFramed, Marshal.SizeOf (this), ref this, ref size, out data) != 0)
return false;
return data != 0;
}
}
public unsafe bool IsVariableBitrate {
get {
uint data;
var size = sizeof (uint);
if (AudioFormatPropertyNative.AudioFormatGetProperty (AudioFormatProperty.FormatName, Marshal.SizeOf (this), ref this, ref size, out data) != 0)
return false;
return data != 0;
}
}
public override string ToString ()
{
return String.Format ("[SampleRate={0} FormatID={1} FormatFlags={2} BytesPerPacket={3} FramesPerPacket={4} BytesPerFrame={5} ChannelsPerFrame={6} BitsPerChannel={7}]",
SampleRate, Format, FormatFlags, BytesPerPacket, FramesPerPacket, BytesPerFrame, ChannelsPerFrame, BitsPerChannel);
}
}
[StructLayout(LayoutKind.Sequential)]
public struct AudioStreamPacketDescription {
public long StartOffset;
public int VariableFramesInPacket;
public int DataByteSize;
public override string ToString ()
{
return String.Format ("StartOffset={0} VariableFramesInPacket={1} DataByteSize={2}", StartOffset, VariableFramesInPacket, DataByteSize);
}
}
[Flags]
public enum AudioChannelFlags {
AllOff = 0,
RectangularCoordinates = 1 << 0,
SphericalCoordinates = 1 << 1,
Meters = 1 << 2
}
public enum AudioChannelLabel {
Unknown = -1,
Unused = 0,
UseCoordinates = 100,
Left = 1,
Right = 2,
Center = 3,
LFEScreen = 4,
LeftSurround = 5,
RightSurround = 6,
LeftCenter = 7,
RightCenter = 8,
CenterSurround = 9,
LeftSurroundDirect = 10,
RightSurroundDirect = 11,
TopCenterSurround = 12,
VerticalHeightLeft = 13,
VerticalHeightCenter = 14,
VerticalHeightRight = 15,
TopBackLeft = 16,
TopBackCenter = 17,
TopBackRight = 18,
RearSurroundLeft = 33,
RearSurroundRight = 34,
LeftWide = 35,
RightWide = 36,
LFE2 = 37,
LeftTotal = 38,
RightTotal = 39,
HearingImpaired = 40,
Narration = 41,
Mono = 42,
DialogCentricMix = 43,
CenterSurroundDirect = 44,
Haptic = 45,
// first order ambisonic channels
Ambisonic_W = 200,
Ambisonic_X = 201,
Ambisonic_Y = 202,
Ambisonic_Z = 203,
// Mid/Side Recording
MS_Mid = 204,
MS_Side = 205,
// X-Y Recording
XY_X = 206,
XY_Y = 207,
// other
HeadphonesLeft = 301,
HeadphonesRight = 302,
ClickTrack = 304,
ForeignLanguage = 305,
// generic discrete channel
Discrete = 400,
// numbered discrete channel
Discrete_0 = (1<<16) | 0,
Discrete_1 = (1<<16) | 1,
Discrete_2 = (1<<16) | 2,
Discrete_3 = (1<<16) | 3,
Discrete_4 = (1<<16) | 4,
Discrete_5 = (1<<16) | 5,
Discrete_6 = (1<<16) | 6,
Discrete_7 = (1<<16) | 7,
Discrete_8 = (1<<16) | 8,
Discrete_9 = (1<<16) | 9,
Discrete_10 = (1<<16) | 10,
Discrete_11 = (1<<16) | 11,
Discrete_12 = (1<<16) | 12,
Discrete_13 = (1<<16) | 13,
Discrete_14 = (1<<16) | 14,
Discrete_15 = (1<<16) | 15,
Discrete_65535 = (1<<16) | 65535
}
[Flags]
public enum AudioChannelBit
{
Left = 1<<0,
Right = 1<<1,
Center = 1<<2,
LFEScreen = 1<<3,
LeftSurround = 1<<4,
RightSurround = 1<<5,
LeftCenter = 1<<6,
RightCenter = 1<<7,
CenterSurround = 1<<8,
LeftSurroundDirect = 1<<9,
RightSurroundDirect = 1<<10,
TopCenterSurround = 1<<11,
VerticalHeightLeft = 1<<12,
VerticalHeightCenter = 1<<13,
VerticalHeightRight = 1<<14,
TopBackLeft = 1<<15,
TopBackCenter = 1<<16,
TopBackRight = 1<<17
}
[StructLayout (LayoutKind.Sequential)]
public struct AudioChannelDescription
{
public AudioChannelLabel Label;
public AudioChannelFlags Flags;
[MarshalAs (UnmanagedType.ByValArray, SizeConst = 3)]
public float[] Coords; // = new float[3];
public unsafe string Name {
get {
IntPtr sptr;
int size = Marshal.SizeOf (typeof (IntPtr));
int ptr_size = Marshal.SizeOf (this);
var ptr = ToPointer ();
var res = AudioFormatPropertyNative.AudioFormatGetProperty (AudioFormatProperty.ChannelName, ptr_size, ptr, ref size, out sptr);
Marshal.FreeHGlobal (ptr);
if (res != 0)
return null;
return new CFString (sptr, true);
}
}
public unsafe string ShortName {
get {
IntPtr sptr;
int size = Marshal.SizeOf (typeof (IntPtr));
int ptr_size = Marshal.SizeOf (this);
var ptr = ToPointer ();
var res = AudioFormatPropertyNative.AudioFormatGetProperty (AudioFormatProperty.ChannelShortName, ptr_size, ptr, ref size, out sptr);
Marshal.FreeHGlobal (ptr);
if (res != 0)
return null;
return new CFString (sptr, true);
}
}
internal IntPtr ToPointer ()
{
var ptr = Marshal.AllocHGlobal (sizeof (AudioChannelLabel) + sizeof (AudioChannelFlags) + 3 * sizeof (float));
Marshal.StructureToPtr (this, ptr, false);
return ptr;
}
public override string ToString ()
{
return String.Format ("[id={0} {1} - {2},{3},{4}", Label, Flags, Coords [0], Coords[1], Coords[2]);
}
}
public enum AudioChannelLayoutTag {
UseChannelDescriptions = (0<<16) | 0,
UseChannelBitmap = (1<<16) | 0,
Mono = (100<<16) | 1,
Stereo = (101<<16) | 2,
StereoHeadphones = (102<<16) | 2,
MatrixStereo = (103<<16) | 2,
MidSide = (104<<16) | 2,
XY = (105<<16) | 2,
Binaural = (106<<16) | 2,
Ambisonic_B_Format = (107<<16) | 4,
Quadraphonic = (108<<16) | 4,
Pentagonal = (109<<16) | 5,
Hexagonal = (110<<16) | 6,
Octagonal = (111<<16) | 8,
Cube = (112<<16) | 8,
MPEG_1_0 = Mono,
MPEG_2_0 = Stereo,
MPEG_3_0_A = (113<<16) | 3,
MPEG_3_0_B = (114<<16) | 3,
MPEG_4_0_A = (115<<16) | 4,
MPEG_4_0_B = (116<<16) | 4,
MPEG_5_0_A = (117<<16) | 5,
MPEG_5_0_B = (118<<16) | 5,
MPEG_5_0_C = (119<<16) | 5,
MPEG_5_0_D = (120<<16) | 5,
MPEG_5_1_A = (121<<16) | 6,
MPEG_5_1_B = (122<<16) | 6,
MPEG_5_1_C = (123<<16) | 6,
MPEG_5_1_D = (124<<16) | 6,
MPEG_6_1_A = (125<<16) | 7,
MPEG_7_1_A = (126<<16) | 8,
MPEG_7_1_B = (127<<16) | 8,
MPEG_7_1_C = (128<<16) | 8,
Emagic_Default_7_1 = (129<<16) | 8,
SMPTE_DTV = (130<<16) | 8,
ITU_1_0 = Mono,
ITU_2_0 = Stereo,
ITU_2_1 = (131<<16) | 3,
ITU_2_2 = (132<<16) | 4,
ITU_3_0 = MPEG_3_0_A,
ITU_3_1 = MPEG_4_0_A,
ITU_3_2 = MPEG_5_0_A,
ITU_3_2_1 = MPEG_5_1_A,
ITU_3_4_1 = MPEG_7_1_C,
DVD_0 = Mono,
DVD_1 = Stereo,
DVD_2 = ITU_2_1,
DVD_3 = ITU_2_2,
DVD_4 = (133<<16) | 3,
DVD_5 = (134<<16) | 4,
DVD_6 = (135<<16) | 5,
DVD_7 = MPEG_3_0_A,
DVD_8 = MPEG_4_0_A,
DVD_9 = MPEG_5_0_A,
DVD_10 = (136<<16) | 4,
DVD_11 = (137<<16) | 5,
DVD_12 = MPEG_5_1_A,
DVD_13 = DVD_8,
DVD_14 = DVD_9,
DVD_15 = DVD_10,
DVD_16 = DVD_11,
DVD_17 = DVD_12,
DVD_18 = (138<<16) | 5,
DVD_19 = MPEG_5_0_B,
DVD_20 = MPEG_5_1_B,
AudioUnit_4 = Quadraphonic,
AudioUnit_5 = Pentagonal,
AudioUnit_6 = Hexagonal,
AudioUnit_8 = Octagonal,
AudioUnit_5_0 = MPEG_5_0_B,
AudioUnit_6_0 = (139<<16) | 6,
AudioUnit_7_0 = (140<<16) | 7,
AudioUnit_7_0_Front = (148<<16) | 7,
AudioUnit_5_1 = MPEG_5_1_A,
AudioUnit_6_1 = MPEG_6_1_A,
AudioUnit_7_1 = MPEG_7_1_C,
AudioUnit_7_1_Front = MPEG_7_1_A,
AAC_3_0 = MPEG_3_0_B,
AAC_Quadraphonic = Quadraphonic,
AAC_4_0 = MPEG_4_0_B,
AAC_5_0 = MPEG_5_0_D,
AAC_5_1 = MPEG_5_1_D,
AAC_6_0 = (141<<16) | 6,
AAC_6_1 = (142<<16) | 7,
AAC_7_0 = (143<<16) | 7,
AAC_7_1 = MPEG_7_1_B,
AAC_Octagonal = (144<<16) | 8,
TMH_10_2_std = (145<<16) | 16,
TMH_10_2_full = (146<<16) | 21,
AC3_1_0_1 = (149<<16) | 2,
AC3_3_0 = (150<<16) | 3,
AC3_3_1 = (151<<16) | 4,
AC3_3_0_1 = (152<<16) | 4,
AC3_2_1_1 = (153<<16) | 4,
AC3_3_1_1 = (154<<16) | 5,
EAC_6_0_A = (155<<16) | 6,
EAC_7_0_A = (156<<16) | 7,
EAC3_6_1_A = (157<<16) | 7,
EAC3_6_1_B = (158<<16) | 7,
EAC3_6_1_C = (159<<16) | 7,
EAC3_7_1_A = (160<<16) | 8,
EAC3_7_1_B = (161<<16) | 8,
EAC3_7_1_C = (162<<16) | 8,
EAC3_7_1_D = (163<<16) | 8,
EAC3_7_1_E = (164<<16) | 8,
EAC3_7_1_F = (165<<16) | 8,
EAC3_7_1_G = (166<<16) | 8,
EAC3_7_1_H = (167<<16) | 8,
DTS_3_1 = (168<<16) | 4,
DTS_4_1 = (169<<16) | 5,
DTS_6_0_A = (170<<16) | 6,
DTS_6_0_B = (171<<16) | 6,
DTS_6_0_C = (172<<16) | 6,
DTS_6_1_A = (173<<16) | 7,
DTS_6_1_B = (174<<16) | 7,
DTS_6_1_C = (175<<16) | 7,
DTS_7_0 = (176<<16) | 7,
DTS_7_1 = (177<<16) | 8,
DTS_8_0_A = (178<<16) | 8,
DTS_8_0_B = (179<<16) | 8,
DTS_8_1_A = (180<<16) | 9,
DTS_8_1_B = (181<<16) | 9,
DTS_6_1_D = (182<<16) | 7,
DiscreteInOrder = (147<<16) | 0, // needs to be ORed with the actual number of channels
Unknown = unchecked ((int)(0xFFFF0000)) // needs to be ORed with the actual number of channels
}
public static class AudioChannelLayoutTagExtensions
{
public static AudioChannelBit? ToAudioChannel (this AudioChannelLayoutTag layoutTag)
{
int value;
int size = sizeof (uint);
int layout = (int) layoutTag;
if (AudioFormatPropertyNative.AudioFormatGetProperty (AudioFormatProperty.BitmapForLayoutTag, sizeof (AudioChannelLayoutTag), ref layout, ref size, out value) != 0)
return null;
return (AudioChannelBit) value;
}
}
[DebuggerDisplay ("{Name}")]
public class AudioChannelLayout
{
public AudioChannelLayout ()
{
}
internal unsafe AudioChannelLayout (IntPtr h)
{
AudioTag = (AudioChannelLayoutTag) Marshal.ReadInt32 (h, 0);
ChannelUsage = (AudioChannelBit) Marshal.ReadInt32 (h, 4);
Channels = new AudioChannelDescription [Marshal.ReadInt32 (h, 8)];
int p = 12;
for (int i = 0; i < Channels.Length; i++){
Channels [i] = (AudioChannelDescription) Marshal.PtrToStructure((IntPtr) (unchecked (((byte *) h) + p)), typeof(AudioChannelDescription));
p += Marshal.SizeOf (typeof (AudioChannelDescription));
}
}
[Obsolete ("Use the strongly typed AudioTag instead")]
public int Tag {
get {
return (int) AudioTag;
}
set {
AudioTag = (AudioChannelLayoutTag) value;
}
}
[Obsolete ("Use ChannelUsage instead")]
public int Bitmap {
get {
return (int) ChannelUsage;
}
set {
ChannelUsage = (AudioChannelBit) value;
}
}
public AudioChannelLayoutTag AudioTag;
public AudioChannelBit ChannelUsage;
public AudioChannelDescription[] Channels;
public unsafe string Name {
get {
IntPtr sptr;
int size = Marshal.SizeOf (typeof (IntPtr));
int ptr_size;
var ptr = ToBlock (out ptr_size);
var res = AudioFormatPropertyNative.AudioFormatGetProperty (AudioFormatProperty.ChannelLayoutName, ptr_size, ptr, ref size, out sptr);
Marshal.FreeHGlobal (ptr);
if (res != 0)
return null;
return new CFString (sptr, true);
}
}
public unsafe string SimpleName {
get {
IntPtr sptr;
int size = Marshal.SizeOf (typeof (IntPtr));
int ptr_size;
var ptr = ToBlock (out ptr_size);
var res = AudioFormatPropertyNative.AudioFormatGetProperty (AudioFormatProperty.ChannelLayoutSimpleName, ptr_size, ptr, ref size, out sptr);
Marshal.FreeHGlobal (ptr);
if (res != 0)
return null;
return new CFString (sptr, true);
}
}
public static AudioChannelLayout FromAudioChannelBitmap (AudioChannelBit channelBitmap)
{
return GetChannelLayout (AudioFormatProperty.ChannelLayoutForBitmap, (int) channelBitmap);
}
public static AudioChannelLayout FromAudioChannelLayoutTag (AudioChannelLayoutTag channelLayoutTag)
{
return GetChannelLayout (AudioFormatProperty.ChannelLayoutForTag, (int) channelLayoutTag);
}
static AudioChannelLayout GetChannelLayout (AudioFormatProperty property, int value)
{
int size;
AudioFormatPropertyNative.AudioFormatGetPropertyInfo (property, sizeof (AudioFormatProperty), ref value, out size);
AudioChannelLayout layout;
IntPtr ptr = Marshal.AllocHGlobal (size);
if (AudioFormatPropertyNative.AudioFormatGetProperty (property, sizeof (AudioFormatProperty), ref value, ref size, ptr) == 0)
layout = new AudioChannelLayout (ptr);
else
layout = null;
Marshal.FreeHGlobal (ptr);
return layout;
}
internal static AudioChannelLayout FromHandle (IntPtr handle)
{
if (handle == IntPtr.Zero)
return null;
return new AudioChannelLayout (handle);
}
public override string ToString ()
{
return String.Format ("AudioChannelLayout: Tag={0} Bitmap={1} Channels={2}", AudioTag, ChannelUsage, Channels.Length);
}
// The returned block must be released with FreeHGlobal
internal unsafe IntPtr ToBlock (out int size)
{
if (Channels == null)
throw new ArgumentNullException ("Channels");
var desc_size = Marshal.SizeOf (typeof (AudioChannelDescription));
size = 12 + Channels.Length * desc_size;
IntPtr buffer = Marshal.AllocHGlobal (size);
int p;
Marshal.WriteInt32 (buffer, (int) AudioTag);
Marshal.WriteInt32 (buffer, 4, (int) ChannelUsage);
Marshal.WriteInt32 (buffer, 8, Channels.Length);
p = 12;
foreach (var desc in Channels){
Marshal.StructureToPtr (desc, (IntPtr) (unchecked (((byte *) buffer) + p)), false);
p += desc_size;
}
return buffer;
}
public static AudioFormatError Validate (AudioChannelLayout layout)
{
if (layout == null)
throw new ArgumentNullException ("layout");
int ptr_size;
var ptr = layout.ToBlock (out ptr_size);
var res = AudioFormatPropertyNative.AudioFormatGetProperty (AudioFormatProperty.ValidateChannelLayout, ptr_size, ptr, IntPtr.Zero, IntPtr.Zero);
Marshal.FreeHGlobal (ptr);
return res;
}
public unsafe static int[] GetChannelMap (AudioChannelLayout inputLayout, AudioChannelLayout outputLayout)
{
if (inputLayout == null)
throw new ArgumentNullException ("inputLayout");
if (outputLayout == null)
throw new ArgumentNullException ("outputLayout");
var channels_count = GetNumberOfChannels (outputLayout);
if (channels_count == null)
throw new ArgumentException ("outputLayout");
int ptr_size;
var input_ptr = inputLayout.ToBlock (out ptr_size);
var output_ptr = outputLayout.ToBlock (out ptr_size);
var array = new IntPtr[] { input_ptr, output_ptr };
ptr_size = Marshal.SizeOf (typeof (IntPtr)) * array.Length;
int[] value;
AudioFormatError res;
fixed (IntPtr* ptr = &array[0]) {
value = new int[channels_count.Value];
var size = sizeof (int) * value.Length;
fixed (int* value_ptr = &value[0]) {
res = AudioFormatPropertyNative.AudioFormatGetProperty (AudioFormatProperty.ChannelMap, ptr_size, ptr, ref size, value_ptr);
}
}
Marshal.FreeHGlobal (input_ptr);
Marshal.FreeHGlobal (output_ptr);
return res == 0 ? value : null;
}
public unsafe static float[,] GetMatrixMixMap (AudioChannelLayout inputLayout, AudioChannelLayout outputLayout)
{
if (inputLayout == null)
throw new ArgumentNullException ("inputLayout");
if (outputLayout == null)
throw new ArgumentNullException ("outputLayout");
var channels_count_output = GetNumberOfChannels (outputLayout);
if (channels_count_output == null)
throw new ArgumentException ("outputLayout");
var channels_count_input = GetNumberOfChannels (inputLayout);
if (channels_count_input == null)
throw new ArgumentException ("inputLayout");
int ptr_size;
var input_ptr = inputLayout.ToBlock (out ptr_size);
var output_ptr = outputLayout.ToBlock (out ptr_size);
var array = new IntPtr[] { input_ptr, output_ptr };
ptr_size = Marshal.SizeOf (typeof (IntPtr)) * array.Length;
float[,] value;
AudioFormatError res;
fixed (IntPtr* ptr = &array[0]) {
value = new float[channels_count_input.Value, channels_count_output.Value];
var size = sizeof (float) * channels_count_input.Value * channels_count_output.Value;
fixed (float* value_ptr = &value[0, 0]) {
res = AudioFormatPropertyNative.AudioFormatGetProperty (AudioFormatProperty.MatrixMixMap, ptr_size, ptr, ref size, value_ptr);
}
}
Marshal.FreeHGlobal (input_ptr);
Marshal.FreeHGlobal (output_ptr);
return res == 0 ? value : null;
}
public static int? GetNumberOfChannels (AudioChannelLayout layout)
{
if (layout == null)
throw new ArgumentNullException ("layout");
int ptr_size;
var ptr = layout.ToBlock (out ptr_size);
int size = sizeof (int);
int value;
var res = AudioFormatPropertyNative.AudioFormatGetProperty (AudioFormatProperty.NumberOfChannelsForLayout, ptr_size, ptr, ref size, out value);
Marshal.FreeHGlobal (ptr);
return res != 0 ? null : (int?) value;
}
public static AudioChannelLayoutTag? GetTagForChannelLayout (AudioChannelLayout layout)
{
if (layout == null)
throw new ArgumentNullException ("layout");
int ptr_size;
var ptr = layout.ToBlock (out ptr_size);
int size = sizeof (AudioChannelLayoutTag);
int value;
var res = AudioFormatPropertyNative.AudioFormatGetProperty (AudioFormatProperty.TagForChannelLayout, ptr_size, ptr, ref size, out value);
Marshal.FreeHGlobal (ptr);
return res != 0 ? null : (AudioChannelLayoutTag?) value;
}
public unsafe static AudioChannelLayoutTag[] GetTagsForNumberOfChannels (int count)
{
const int type_size = sizeof (uint);
int size;
if (AudioFormatPropertyNative.AudioFormatGetPropertyInfo (AudioFormatProperty.TagsForNumberOfChannels, type_size, ref count, out size) != 0)
return null;
var data = new AudioChannelLayoutTag[size / type_size];
fixed (AudioChannelLayoutTag* ptr = data) {
var res = AudioFormatPropertyNative.AudioFormatGetProperty (AudioFormatProperty.TagsForNumberOfChannels, type_size, ref count, ref size, (int*)ptr);
if (res != 0)
return null;
return data;
}
}
#if !COREBUILD
public NSData AsData ()
{
int size;
var p = ToBlock (out size);
var result = NSData.FromBytes (p, (uint) size);
Marshal.FreeHGlobal (p);
return result;
}
#endif
}
[StructLayout(LayoutKind.Sequential)]
public struct SmpteTime {
public short Subframes;
public short SubframeDivisor;
public uint Counter;
public uint Type;
public uint Flags;
public short Hours;
public short Minutes;
public short Seconds;
public short Frames;
public override string ToString ()
{
return String.Format ("[Subframes={0},Divisor={1},Counter={2},Type={3},Flags={4},Hours={5},Minutes={6},Seconds={7},Frames={8}]",
Subframes, SubframeDivisor, Counter, Type, Flags, Hours, Minutes, Seconds, Frames);
}
}
public enum SmpteTimeType
{
None = 0,
Type24 = 1,
Type25 = 2,
Type30Drop = 3,
Type30 = 4,
Type2997 = 5,
Type2997Drop = 6,
Type60 = 7,
Type5994 = 8,
Type60Drop = 9,
Type5994Drop = 10,
Type50 = 11,
Type2398 = 12
}
[StructLayout(LayoutKind.Sequential)]
public struct AudioTimeStamp {
[Flags]
public enum AtsFlags {
SampleTimeValid = (1 << 0),
HostTimeValid = (1 << 1),
RateScalarValid = (1 << 2),
WordClockTimeValid = (1 << 3),
SmpteTimeValid = (1 << 4),
SampleHostTimeValid = SampleTimeValid | HostTimeValid
}
public double SampleTime;
public ulong HostTime;
public double RateScalar;
public ulong WordClockTime;
public SmpteTime SMPTETime;
public AtsFlags Flags;
public uint Reserved;
public override string ToString ()
{
var sb = new StringBuilder ("{");
if ((Flags & AtsFlags.SampleTimeValid) != 0)
sb.Append ("SampleTime=" + SampleTime.ToString ());
if ((Flags & AtsFlags.HostTimeValid) != 0){
if (sb.Length > 0)
sb.Append (',');
sb.Append ("HostTime=" + HostTime.ToString ());
}
if ((Flags & AtsFlags.RateScalarValid) != 0){
if (sb.Length > 0)
sb.Append (',');
sb.Append ("RateScalar=" + RateScalar.ToString ());
}
if ((Flags & AtsFlags.WordClockTimeValid) != 0){
if (sb.Length > 0)
sb.Append (',');
sb.Append ("WordClock=" + HostTime.ToString () + ",");
}
if ((Flags & AtsFlags.SmpteTimeValid) != 0){
if (sb.Length > 0)
sb.Append (',');
sb.Append ("SmpteTime=" + SMPTETime.ToString ());
}
sb.Append ("}");
return sb.ToString ();
}
}
[StructLayout(LayoutKind.Sequential)]
public struct AudioBuffer {
public int NumberChannels;
public int DataByteSize;
public IntPtr Data;
public override string ToString ()
{
return string.Format ("[channels={0},dataByteSize={1},ptrData=0x{2:x}]", NumberChannels, DataByteSize, Data);
}
}
}
| |
namespace PrimitiveEngine
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
/// <summary>
/// Class SystemManager.
/// </summary>
public sealed class SystemManager
{
private readonly EntityWorld entityWorld;
private readonly IDictionary<Type, IList> systems;
private readonly SystemBitManager systemBitManager;
private readonly Bag<EntitySystem> mergedBag;
private IDictionary<int, SystemLayer> fixedUpdateLayers;
private IDictionary<int, SystemLayer> frameUpdateLayers;
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="SystemManager" /> class.
/// </summary>
/// <param name="entityWorld">The entity world.</param>
internal SystemManager(EntityWorld entityWorld)
{
this.mergedBag = new Bag<EntitySystem>();
this.frameUpdateLayers = new Dictionary<int, SystemLayer>();
this.fixedUpdateLayers = new Dictionary<int, SystemLayer>();
this.systemBitManager = new SystemBitManager();
this.systems = new Dictionary<Type, IList>();
this.entityWorld = entityWorld;
}
#endregion
#region Properties
/// <summary>
/// Gets the systems.
/// </summary>
/// <value>The systems.</value>
public Bag<EntitySystem> Systems
{
get { return this.mergedBag; }
}
#endregion
/// <summary>
/// Gets the system.
/// </summary>
/// <typeparam name="T">The EntitySystem</typeparam>
/// <returns>The system instance</returns>
/// <exception cref="InvalidOperationException">There are more or none systems of the type passed</exception>
public T GetSystem<T>() where T : EntitySystem
{
this.systems.TryGetValue(typeof(T), out IList foundSystems);
if (foundSystems == null)
return null;
if (foundSystems.Count > 1)
{
throw new InvalidOperationException(
$"System list contains more than one element of type {typeof(T)}");
}
return (T)foundSystems[0];
}
/// <summary>
/// Gets the systems.
/// </summary>
/// <typeparam name="T">The EntitySystem</typeparam>
/// <returns>A List of System Instances</returns>
public List<T> GetSystems<T>() where T : EntitySystem
{
this.systems.TryGetValue(typeof(T), out IList system);
return (List<T>)system;
}
/// <summary>
/// Sets the system.
/// </summary>
/// <typeparam name="T">The <see langword="Type" /> T.</typeparam>
/// <param name="system">The system.</param>
/// <param name="updateType">Type of the game loop.</param>
/// <param name="layer">The layer.</param>
/// <param name="executionType">Type of the execution.</param>
/// <returns>The set system.</returns>
public T SetSystem<T>(
T system,
UpdateType updateType,
int layer = 0,
ExecutionType executionType = ExecutionType.Synchronous) where T : EntitySystem
{
return (T)SetSystem(system.GetType(), system, updateType, layer, executionType);
}
/// <summary>
/// Creates the instance.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The specified ComponentPool-able instance.</returns>
private static ComponentPoolable CreateInstance(Type type)
{
return (ComponentPoolable)Activator.CreateInstance(type);
}
/// <summary>
/// Processes the specified systems to process.
/// </summary>
/// <param name="systemsToProcess">The systems to process.</param>
private static void Process(IDictionary<int, SystemLayer> systemsToProcess)
{
foreach (int item in systemsToProcess.Keys)
{
if (systemsToProcess[item].SynchronousSystems.Count > 0)
ProcessBagSynchronous(systemsToProcess[item].SynchronousSystems);
if (systemsToProcess[item].AsynchronousSystems.Count > 0)
ProcessBagAsynchronous(systemsToProcess[item].AsynchronousSystems);
}
}
/// <summary>
/// Updates the bag asynchronous.
/// </summary>
/// <param name="entitySystems">The entity systems.</param>
private static void ProcessBagAsynchronous(IEnumerable<EntitySystem> entitySystems)
{
Parallel.ForEach(
source: entitySystems,
body: (EntitySystem entitySystem) =>
{
entitySystem.Process();
});
}
/// <summary>
/// Updates the bag synchronous.
/// </summary>
/// <param name="entitySystems">The entitySystems.</param>
private static void ProcessBagSynchronous(Bag<EntitySystem> entitySystems)
{
for (int index = 0, j = entitySystems.Count; index < j; ++index)
{
entitySystems.Get(index).Process();
}
}
/// <summary>
/// Sets the system.
/// </summary>
/// <param name="layers">The layers.</param>
/// <param name="system">The system.</param>
/// <param name="layer">The layer.</param>
/// <param name="executionType">Type of the execution.</param>
private static void SetSystem(
ref IDictionary<int, SystemLayer> layers,
EntitySystem system,
int layer,
ExecutionType executionType)
{
if (!layers.ContainsKey(layer))
layers[layer] = new SystemLayer();
Bag<EntitySystem> updateBag = layers[layer][executionType];
if (!updateBag.Contains(system))
updateBag.Add(system);
layers = (from d in layers orderby d.Key ascending select d).ToDictionary(keySelector: pair => pair.Key, elementSelector: pair => pair.Value);
}
/// <summary>
/// Creates the pool.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="attributes">The attributes.</param>
/// <exception cref="NullReferenceException">propertyComponentPool is null.</exception>
private void CreatePool(Type type, IEnumerable<Attribute> attributes)
{
ComponentPoolAttribute propertyComponentPool = null;
foreach (ComponentPoolAttribute artemisComponentPool in attributes.OfType<ComponentPoolAttribute>())
{
propertyComponentPool = artemisComponentPool;
}
MethodInfo[] methods = type.GetMethods();
IEnumerable<MethodInfo> methodInfos = from methodInfo in methods
let methodAttributes = methodInfo.GetCustomAttributes(false)
from attribute in methodAttributes.OfType<ComponentCreate>()
select methodInfo;
Func<Type, ComponentPoolable> create = null;
foreach (MethodInfo methodInfo in methodInfos)
{
create = (Func<Type, ComponentPoolable>)Delegate.CreateDelegate(typeof(Func<Type, ComponentPoolable>), methodInfo);
}
if (create == null)
create = CreateInstance;
IComponentPool<ComponentPoolable> pool;
if (propertyComponentPool == null)
throw new NullReferenceException("propertyComponentPool is null.");
if (!propertyComponentPool.IsSupportMultiThread)
{
pool = new ComponentPool<ComponentPoolable>(
propertyComponentPool.InitialSize,
propertyComponentPool.ResizeSize,
propertyComponentPool.IsResizable,
create,
type);
}
else
{
pool = new ComponentPoolMultiThread<ComponentPoolable>(
propertyComponentPool.InitialSize,
propertyComponentPool.ResizeSize,
propertyComponentPool.IsResizable,
create,
type);
}
this.entityWorld.SetPool(type, pool);
}
/// <summary>
/// Sets the system.
/// </summary>
/// <param name="systemType">Type of the system.</param>
/// <param name="system">The system.</param>
/// <param name="updateType">Type of the game loop.</param>
/// <param name="layer">The layer.</param>
/// <param name="executionType">Type of the execution.</param>
/// <returns>The EntitySystem.</returns>
private EntitySystem SetSystem(
Type systemType,
EntitySystem system,
UpdateType updateType,
int layer = 0,
ExecutionType executionType = ExecutionType.Synchronous)
{
system.EntityWorld = this.entityWorld;
if (this.systems.ContainsKey(systemType))
this.systems[systemType].Add(system);
else
{
Type genericType = typeof(List<>);
Type listType = genericType.MakeGenericType(systemType);
this.systems[systemType] = (IList)Activator.CreateInstance(listType);
this.systems[systemType].Add(system);
}
switch (updateType)
{
case UpdateType.FrameUpdate:
SetSystem(ref this.frameUpdateLayers, system, layer, executionType);
break;
case UpdateType.FixedUpdate:
SetSystem(ref this.fixedUpdateLayers, system, layer, executionType);
break;
}
if (!this.mergedBag.Contains(system))
this.mergedBag.Add(system);
system.Bit = this.systemBitManager.GetBitFor(system);
return system;
}
/// <summary>
/// The system layer class.
/// </summary>
private sealed class SystemLayer
{
/// <summary>
/// The synchronous systems.
/// </summary>
public readonly Bag<EntitySystem> SynchronousSystems;
/// <summary>
/// The asynchronous systems.
/// </summary>
public readonly Bag<EntitySystem> AsynchronousSystems;
#region Constructors
/// <summary>Initializes a new instance of the <see cref="SystemLayer"/> class.</summary>
public SystemLayer()
{
this.AsynchronousSystems = new Bag<EntitySystem>();
this.SynchronousSystems = new Bag<EntitySystem>();
}
#endregion
#region Properties
/// <summary>
/// Gets the <see cref="Bag{EntitySystem}"/> with the specified execution type.
/// </summary>
/// <param name="executionType">Type of the execution.</param>
/// <returns>The Bag{EntitySystem}.</returns>
public Bag<EntitySystem> this[ExecutionType executionType]
{
get
{
switch (executionType)
{
case ExecutionType.Synchronous:
return this.SynchronousSystems;
case ExecutionType.Asynchronous:
return this.AsynchronousSystems;
default:
throw new ArgumentOutOfRangeException(nameof(executionType));
}
}
}
#endregion
}
/// <summary>
/// Initialize a system.
/// </summary>
/// <param name="type">Type of the system, inheriting from EntitySystem.</param>
/// <param name="updateType">Update type of the system (default: FrameUpdate).</param>
/// <param name="order">Order the system processes (default: 0).</param>
/// <param name="executionType">System execution type (default: Synchronous).</param>
public void InitializeSystem(
Type type,
UpdateType updateType = UpdateType.FrameUpdate,
int order = 0,
ExecutionType executionType = ExecutionType.Synchronous)
{
if (typeof(EntitySystem).IsAssignableFrom(type))
{
EntitySystem instance = (EntitySystem)Activator.CreateInstance(type);
SetSystem(
instance,
updateType,
order,
executionType);
instance.LoadContent();
}
}
/// <summary>
/// Initializes all systems.
/// </summary>
/// <param name="processAttributes">if set to <see langword="true" /> [process attributes].</param>
/// <param name="assembliesToScan">The assemblies to scan.</param>
/// <exception cref="Exception">propertyComponentPool is null.</exception>
internal void InitializeAll(
bool processAttributes,
IEnumerable<Assembly> assembliesToScan = null)
{
if (processAttributes)
{
IDictionary<Type, List<Attribute>> types;
if (assembliesToScan == null)
types = AttributesProcessor.Process(
supportedAttributes: AttributesProcessor.SupportedAttributes,
assembliesToScan: null);
else
types = AttributesProcessor.Process(
supportedAttributes: AttributesProcessor.SupportedAttributes,
assembliesToScan: assembliesToScan);
foreach (KeyValuePair<Type, List<Attribute>> item in types)
{
Type type = item.Key;
List<Attribute> attributes = item.Value;
if (typeof(EntitySystem).IsAssignableFrom(type))
{
EntitySystemAttribute entitySystemAttribute = (EntitySystemAttribute)attributes[0];
EntitySystem instance = (EntitySystem)Activator.CreateInstance(type);
SetSystem(
instance,
entitySystemAttribute.UpdateType,
entitySystemAttribute.Layer,
entitySystemAttribute.ExecutionType);
}
else if (typeof(IEntityTemplate).IsAssignableFrom(type))
{
EntityTemplateAttribute entitySystemAttribute = (EntityTemplateAttribute)attributes[0];
IEntityTemplate instance = (IEntityTemplate)Activator.CreateInstance(type);
this.entityWorld.SetEntityTemplate(entitySystemAttribute.Name, instance);
}
else if (typeof(ComponentPoolable).IsAssignableFrom(type))
CreatePool(type, attributes);
}
}
for (int index = 0, j = this.mergedBag.Count; index < j; ++index)
{
this.mergedBag.Get(index).LoadContent();
}
}
/// <summary>
/// Terminates all systems.
/// </summary>
internal void TerminateAll()
{
for (int index = 0; index < this.Systems.Count; ++index)
{
EntitySystem entitySystem = this.Systems.Get(index);
entitySystem.UnloadContent();
}
this.Systems.Clear();
}
/// <summary>
/// Updates the specified execution type.
/// </summary>
internal void FixedUpdate()
{
Process(this.fixedUpdateLayers);
}
/// <summary>
/// Updates the specified execution type.
/// </summary>
internal void FrameUpdate()
{
Process(this.frameUpdateLayers);
}
}
}
| |
/////////////////////////////////////////////////////////////////////////////////
//
// vp_Timer.cs
// ?VisionPunk. All Rights Reserved.
// https://twitter.com/VisionPunk
// http://www.visionpunk.com
//
// description: vp_Timer is a script extension for delaying (scheduling) methods
// in Unity. it supports arguments, delegates, repetition with
// intervals, infinite repetition, pausing and canceling, and uses
// an object pool in order to feed the garbage collector with an
// absolute minimum amount of data
//
// NOTE: this class is also part of the 'visionTimer' package, a
// complete time scripting framework for Unity. check it out if you
// want to do things like time bombs, stopwatches, analog clocks etc.
// http://u3d.as/content/vision-punk/vision-timer/3xc
//
/////////////////////////////////////////////////////////////////////////////////
//#define DEBUG // uncomment to display timers in the Unity Editor Hierarchy
using UnityEngine;
using System;
using System.Collections.Generic;
#if (UNITY_EDITOR && DEBUG)
using System.Diagnostics;
#endif
public class vp_Timer : MonoBehaviour
{
private static GameObject m_MainObject = null;
private static List<Event> m_Active = new List<Event>();
private static List<Event> m_Pool = new List<Event>();
private static Event m_NewEvent = null;
private static int m_EventCount = 0;
// variables for the Update method
private static int m_EventBatch = 0;
private static int m_EventIterator = 0;
// this flag prevents timer scheduling when application is about to quit (which may cause errors)
static bool m_AppQuitting = false;
/// <summary>
/// the maximum amount of callbacks that the timer system will be
/// allowed to execute in one frame. reducing this may improve
/// performance with extreme amounts (hundreds) of active timers
/// but may also lead to some events getting delayed for a few
/// frames
/// </summary>
public static int MaxEventsPerFrame = 500;
/// <summary>
/// timer event callback for methods with no parameters
/// </summary>
public delegate void Callback();
/// <summary>
/// timer event callback for methods with parameters
/// </summary>
public delegate void ArgCallback(object args);
/// <summary>
/// data struct for use by the editor class
/// </summary>
public struct Stats
{
public int Created;
public int Inactive;
public int Active;
}
/// <summary>
/// returns false if this script was not added via the 'vp_Timer.In'
/// method - e.g. you may have dragged it to a gameobject in
/// the Inspector which won't work
/// </summary>
public bool WasAddedCorrectly
{
get
{
if (!Application.isPlaying)
return false;
if (gameObject != m_MainObject)
return false;
return true;
}
}
/// <summary>
/// in Awake a check is made to see if the vp_Timer component
/// was added correctly. if not it will be destroyed
/// </summary>
private void Awake()
{
if (!WasAddedCorrectly)
{
Destroy(this);
return;
}
}
/// <summary>
/// in Update the active list is looped every frame, executing
/// any timer events for which time is up. Update also detects
/// paused and canceled events
/// </summary>
private void Update()
{
// NOTE: this method never processes more than 'MaxEventsPerFrame',
// in order to avoid performance problems with excessive amounts of
// timers. this may lead to events being delayed a few frames.
// if experiencing delayed events 1) try to cut back on the amount
// of timers created simultaneously, and 2) increase 'MaxEventsPerFrame'
// execute any active events that are due, but only check
// up to max events per frame for performance
m_EventBatch = 0;
while ((vp_Timer.m_Active.Count > 0) && m_EventBatch < MaxEventsPerFrame)
{
// if we reached beginning of list, halt until next frame
if (m_EventIterator < 0)
{
// this has two purposes: 1) preventing multiple iterations
// per frame if our event count is below the maximum, and
// 2) preventing reaching index -1
m_EventIterator = vp_Timer.m_Active.Count - 1;
break;
}
// prevent index out of bounds
if (m_EventIterator > vp_Timer.m_Active.Count - 1)
m_EventIterator = vp_Timer.m_Active.Count - 1;
// execute all due events
if (Time.time >= vp_Timer.m_Active[m_EventIterator].DueTime || // time is up
vp_Timer.m_Active[m_EventIterator].Id == 0) // event has been canceled ('Execute' will kill it)
vp_Timer.m_Active[m_EventIterator].Execute();
else
{
// handle pausing
if (vp_Timer.m_Active[m_EventIterator].Paused)
vp_Timer.m_Active[m_EventIterator].DueTime += Time.deltaTime;
else
// log lifetime
vp_Timer.m_Active[m_EventIterator].LifeTime += Time.deltaTime;
}
// going backwards since 'Execute' will remove items from the list
m_EventIterator--;
m_EventBatch++;
}
}
///////////////////////////////////////////////////////////
// the "In" method is used for scheduling events. it always takes a
// delay along with a callback (method or delegate) to be triggered
// at the end of the delay. the overloads support arguments, iterations
// and intervals. an optional "Event.Handle" object can also be passed
// as the last parameter. this will be associated to the scheduled
// event and will enable interaction with the event post-initiation,
// along with extraction of a number of useful parameters
///////////////////////////////////////////////////////////
/// <summary>
/// schedules an event by time + callback + [timer handle]
/// <summary>
public static void In(float delay, Callback callback, Handle timerHandle = null)
{ Schedule(delay, callback, null, null, timerHandle, 1, -1.0f); }
/// <summary>
/// schedules an event by time + callback + iterations + [timer handle]
/// <summary>
public static void In(float delay, Callback callback, int iterations, Handle timerHandle = null)
{ Schedule(delay, callback, null, null, timerHandle, iterations, -1.0f); }
/// <summary>
/// schedules an event by time + callback + iterations + interval + [timer handle]
/// <summary>
public static void In(float delay, Callback callback, int iterations, float interval, Handle timerHandle = null)
{ Schedule(delay, callback, null, null, timerHandle, iterations, interval); }
/// <summary>
/// schedules an event by time + callback + arguments + [timer handle]
/// <summary>
public static void In(float delay, ArgCallback callback, object arguments, Handle timerHandle = null)
{ Schedule(delay, null, callback, arguments, timerHandle, 1, -1.0f); }
/// <summary>
/// schedules an event by time + callback + arguments + iterations + [timer handle]
/// <summary>
public static void In(float delay, ArgCallback callback, object arguments, int iterations, Handle timerHandle = null)
{ Schedule(delay, null, callback, arguments, timerHandle, iterations, -1.0f); }
/// <summary>
/// schedules an event by time + callback + arguments + iterations + interval + [timer handle]
/// <summary>
public static void In(float delay, ArgCallback callback, object arguments, int iterations, float interval, Handle timerHandle = null)
{ Schedule(delay, null, callback, arguments, timerHandle, iterations, interval); }
/// <summary>
/// the "Start" method is used to run a timer for the sole
/// purpose of measuring time (useful for e.g. stopwatches).
/// it takes a mandatory timer handle as only input argument,
/// has no callback method and will run practically forever.
/// the timer handle can then be used to pause, resume and
/// poll all sorts of info from the timer event
/// </summary>
public static void Start(Handle timerHandle)
{
Schedule(315360000.0f, /* ten years, yo ;) */ delegate() { }, null, null, timerHandle, 1, -1.0f);
}
/// <summary>
/// the 'Schedule' method sets everything in order for the
/// timer event to be fired. it also creates a hidden
/// gameobject upon the first time called (for purposes of
/// running the Update loop and drawing editor debug info)
/// </summary>
private static void Schedule(float time, Callback func, ArgCallback argFunc, object args, Handle timerHandle, int iterations, float interval)
{
if (func == null && argFunc == null)
{
UnityEngine.Debug.LogError("Error: (vp_Timer) Aborted event because function is null.");
return;
}
// setup main gameobject
if (m_MainObject == null)
{
if (!m_AppQuitting)
{
m_MainObject = new GameObject("Timers");
m_MainObject.AddComponent<vp_Timer>();
UnityEngine.Object.DontDestroyOnLoad(m_MainObject);
}
else
return;
#if (UNITY_EDITOR && !DEBUG)
m_MainObject.gameObject.hideFlags = HideFlags.HideInHierarchy;
#endif
}
// force healthy time values
time = Mathf.Max(0.0f, time);
iterations = Mathf.Max(0, iterations);
interval = (interval == -1.0f) ? time : Mathf.Max(0.0f, interval);
// recycle an event - or create a new one if the pool is empty
m_NewEvent = null;
if (m_Pool.Count > 0)
{
m_NewEvent = m_Pool[0];
m_Pool.Remove(m_NewEvent);
}
else
m_NewEvent = new Event();
// iterate the event counter and store the id for this event
vp_Timer.m_EventCount++;
m_NewEvent.Id = vp_Timer.m_EventCount;
// set up the event with its function, arguments and times
if (func != null)
m_NewEvent.Function = func;
else if (argFunc != null)
{
m_NewEvent.ArgFunction = argFunc;
m_NewEvent.Arguments = args;
}
m_NewEvent.StartTime = Time.time;
m_NewEvent.DueTime = Time.time + time;
m_NewEvent.Iterations = iterations;
m_NewEvent.Interval = interval;
m_NewEvent.LifeTime = 0.0f;
m_NewEvent.Paused = false;
// add event to the Active list
vp_Timer.m_Active.Add(m_NewEvent);
// if a timer handle was provided, associate it to this event,
// but first cancel any already active event using the same
// handle: there can be only one ...
if (timerHandle != null)
{
if (timerHandle.Active)
timerHandle.Cancel();
// setting the 'Id' property associates this handle with
// the currently active event with the corresponding id
timerHandle.Id = m_NewEvent.Id;
}
#if (UNITY_EDITOR && DEBUG)
m_NewEvent.StoreCallingMethod();
EditorRefresh();
#endif
}
/// <summary>
/// cancels a timer if the passed timer handle is still active
/// </summary>
private static void Cancel(vp_Timer.Handle handle)
{
if (handle == null)
return;
// NOTE: the below Active check is super-important for verifying timer
// handle integrity. recycling 'handle.Event' if 'handle.Active' is false
// will cancel the wrong event and lead to some other timer never firing
// (this is because timer events are recycled but not their timer handles).
if (handle.Active)
{
// setting the 'Id' property to zero will result in DueTime also
// becoming zero, sending the event to 'Execute' in the next frame
// where it will be recycled instead of executed
handle.Id = 0;
return;
}
}
/// <summary>
/// cancels every currently active timer
/// </summary>
public static void CancelAll()
{
for (int t = vp_Timer.m_Active.Count - 1; t > -1; t--)
{
vp_Timer.m_Active[t].Id = 0;
}
}
/// <summary>
/// cancels every currently active timer that points to a
/// certain method
/// </summary>
public static void CancelAll(string methodName)
{
for (int t = vp_Timer.m_Active.Count - 1; t > -1; t--)
{
if (vp_Timer.m_Active[t].MethodName == methodName)
vp_Timer.m_Active[t].Id = 0;
}
}
/// <summary>
/// clears all currently active timers along with the object
/// pool, that is: disposes of every timer event, releasing
/// memory to the garbage collector
/// </summary>
public static void DestroyAll()
{
vp_Timer.m_Active.Clear();
vp_Timer.m_Pool.Clear();
#if (UNITY_EDITOR && DEBUG)
EditorRefresh();
#endif
}
/// <summary>
/// upon level load, cancels every currently active timer
/// whose 'CancelOnLoad' parameter is true (default)
/// </summary>
private void OnLevelWasLoaded()
{
for (int t = vp_Timer.m_Active.Count - 1; t > -1; t--)
{
if (vp_Timer.m_Active[t].CancelOnLoad)
vp_Timer.m_Active[t].Id = 0;
}
}
/// <summary>
/// provides the custom vp_Timer editor class with debug info
/// </summary>
public static Stats EditorGetStats()
{
Stats stats;
stats.Created = m_Active.Count + m_Pool.Count;
stats.Inactive = m_Pool.Count;
stats.Active = m_Active.Count;
return stats;
}
/// <summary>
/// provides the custom vp_Timer editor class with the name of a
/// specific method in the Active list along with any arguments,
/// plus a stack trace (if compiling with the DEBUG define)
/// </summary>
public static string EditorGetMethodInfo(int eventIndex)
{
if (eventIndex < 0 || eventIndex > m_Active.Count - 1)
return "Argument out of range.";
return m_Active[eventIndex].MethodInfo;
}
/// <summary>
/// provides the custom vp_Timer editor class with the id of a
/// specific event in the Active list
/// </summary>
public static int EditorGetMethodId(int eventIndex)
{
if (eventIndex < 0 || eventIndex > m_Active.Count - 1)
return 0;
return m_Active[eventIndex].Id;
}
#if (DEBUG && UNITY_EDITOR)
/// <summary>
/// updates the name of the main gamobject, visible in the
/// hierarchy view during runtime (if compiling with the
/// DEBUG define)
/// </summary>
private static void EditorRefresh()
{
if (!m_AppQuitting)
m_MainObject.name = "Timers (" + m_Active.Count + " / " + (m_Pool.Count + m_Active.Count).ToString() + ")";
}
#endif
/////////////////////////////////////////////////////////////////////////////////
//
// vp_Timer.Event
//
// description: this class is the internal representation of an event object.
// it is not to be manipulated directly since events are recycled
// and references to them would be unreliable. to interact with
// an event post initiation, schedule it with a 'vp_Timer.Handle'
//
/////////////////////////////////////////////////////////////////////////////////
private class Event
{
public int Id;
public Callback Function = null;
public ArgCallback ArgFunction = null;
public object Arguments = null;
public int Iterations = 1;
public float Interval = -1.0f;
public float DueTime = 0.0f;
public float StartTime = 0.0f;
public float LifeTime = 0.0f;
public bool Paused = false;
public bool CancelOnLoad = true;
#if (DEBUG && UNITY_EDITOR)
private string m_CallingMethod = "";
#endif
/// <summary>
/// runs an event function, taking care of iterations, intervals
/// canceling and recycling
/// </summary>
public void Execute()
{
// if either 'Id' or 'DueTime' is zero, this timer has been
// canceled: recycle it!
if (Id == 0 || DueTime == 0.0f)
{
Recycle();
return;
}
// attempt to execute the callback function
if (Function != null)
{
Function();
//UnityEngine.Debug.Log(Function.Method + ", " + (Function.Target ?? "none"));
}
else if (ArgFunction != null)
ArgFunction(Arguments);
else
{
// function was null: nothing to do so abort
Error("Aborted event because function is null.");
Recycle();
return;
}
// count down to recycling
if (Iterations > 0)
{
Iterations--;
// usually a timer has one default iteration and will
// enter the below scope to get recycled right away ...
if (Iterations < 1)
{
Recycle();
return;
}
}
// ... but if we end up here the timer either has atleast one
// iteration left, or user set iterations to zero for infinite
// repetition. either way: update due time with the interval
DueTime = Time.time + Interval;
}
/// <summary>
/// performs internal recycling of the vp_Timer
/// </summary>
private void Recycle()
{
Id = 0;
DueTime = 0.0f;
StartTime = 0.0f;
CancelOnLoad = true;
Function = null;
ArgFunction = null;
Arguments = null;
if (vp_Timer.m_Active.Remove(this))
m_Pool.Add(this);
#if (UNITY_EDITOR && DEBUG)
EditorRefresh();
#endif
}
/// <summary>
/// destroys this timer event forever, releasing its memory
/// to the garbage collector
/// </summary>
private void Destroy()
{
vp_Timer.m_Active.Remove(this);
vp_Timer.m_Pool.Remove(this);
}
#if (UNITY_EDITOR && DEBUG)
/// <summary>
/// used by the debug mode to fetch the callstack
/// </summary>
public void StoreCallingMethod()
{
StackTrace stackTrace = new StackTrace();
string result = "";
string declaringType = "";
for (int v = 3; v < stackTrace.FrameCount; v++)
{
StackFrame stackFrame = stackTrace.GetFrame(v);
declaringType = stackFrame.GetMethod().DeclaringType.ToString();
result += " <- " + declaringType + ":" + stackFrame.GetMethod().Name.ToString();
}
m_CallingMethod = result;
}
#endif
/// <summary>
/// standard event error method
/// </summary>
private void Error(string message)
{
string msg = "Error: (" + this + ") " + message;
#if (UNITY_EDITOR && DEBUG)
msg += MethodInfo;
#endif
UnityEngine.Debug.LogError(msg);
}
/// <summary>
/// returns the name of the scheduled method, or 'delegate'
/// </summary>
public string MethodName
{
get
{
if (Function != null)
{
if (Function.Method != null)
{
if (Function.Method.Name[0] == '<')
return "delegate";
else return Function.Method.Name;
}
}
else if (ArgFunction != null)
{
if (ArgFunction.Method != null)
{
if (ArgFunction.Method.Name[0] == '<')
return "delegate";
else return ArgFunction.Method.Name;
}
}
return null;
}
}
/// <summary>
/// returns the name of the scheduled method along with any arguments,
/// plus a stack trace (if compiling with the DEBUG define)
/// </summary>
public string MethodInfo
{
get
{
string s = MethodName;
if (!string.IsNullOrEmpty(s))
{
s += "(";
if (Arguments != null)
{
if (Arguments.GetType().IsArray)
{
object[] array = (object[])Arguments;
foreach (object o in array)
{
s += o.ToString();
if (Array.IndexOf(array, o) < array.Length - 1)
s += ", ";
}
}
else
s += Arguments;
}
s += ")";
}
else
s = "(function = null)";
#if (DEBUG && UNITY_EDITOR)
s += m_CallingMethod;
#endif
return s;
}
}
}
/////////////////////////////////////////////////////////////////////////////////
//
// vp_Timer.Handle
//
// description: this class is used to keep track of a currently running event.
// it is most commonly used to cancel an event or to see if it's
// still active, but it also has many properties to analyze the
// state of an event. the editor uses it to display debug info
//
/////////////////////////////////////////////////////////////////////////////////
public class Handle
{
private vp_Timer.Event m_Event = null; // timer we're pointing at
private int m_Id = 0; // id associated with timer upon creation of this handle
private int m_StartIterations = 1; // the amount of iterations of the event when started
private float m_FirstDueTime = 0.0f; // the initial execution delay of the event
/// <summary>
/// pauses or unpauses this timer event
/// </summary>
public bool Paused
{
get
{
return Active && m_Event.Paused;
}
set
{
if (Active)
m_Event.Paused = value;
}
}
//////// fixed times ////////
/// <summary>
/// returns the time of initial scheduling
/// </summary>
public float TimeOfInitiation
{
get
{
if (Active)
return m_Event.StartTime;
else return 0.0f;
}
}
/// <summary>
/// returns the time of first execution
/// </summary>
public float TimeOfFirstIteration
{
get
{
if (Active)
return m_FirstDueTime;
return 0.0f;
}
}
/// <summary>
/// returns the expected due time of the next iteration of an event
/// </summary>
public float TimeOfNextIteration
{
get
{
if (Active)
return m_Event.DueTime;
return 0.0f;
}
}
/// <summary>
/// returns the expected due time of the last iteration of an event
/// </summary>
public float TimeOfLastIteration
{
get
{
if (Active)
return Time.time + DurationLeft;
return 0.0f;
}
}
//////// timespans ////////
/// <summary>
/// returns the delay before first execution
/// </summary>
public float Delay
{
get
{
return (Mathf.Round((m_FirstDueTime - TimeOfInitiation) * 1000.0f) / 1000.0f);
}
}
/// <summary>
/// returns the repeat interval of an event
/// </summary>
public float Interval
{
get
{
if (Active)
return m_Event.Interval;
return 0.0f;
}
}
/// <summary>
/// returns the time left until the next iteration of an event
/// </summary>
public float TimeUntilNextIteration
{
get
{
if (Active)
return m_Event.DueTime - Time.time;
return 0.0f;
}
}
/// <summary>
/// returns the current total time left (all iterations) of an event
/// </summary>
public float DurationLeft
{
get
{
if (Active)
return TimeUntilNextIteration + ((m_Event.Iterations - 1) * m_Event.Interval);
return 0.0f;
}
}
/// <summary>
/// returns the total expected duration (due time + all iterations) of an event.
/// NOTE: this does not take pausing into account.
/// </summary>
public float DurationTotal
{
get
{
if (Active)
{
return Delay +
((m_StartIterations) * ((m_StartIterations > 1) ? Interval : 0.0f));
}
return 0.0f;
}
}
/// <summary>
/// returns the current age of an event (lifetime since initiation)
/// </summary>
public float Duration
{
get
{
if (Active)
return m_Event.LifeTime;
return 0.0f;
}
}
//////// iterations ////////
/// <summary>
/// returns the total expected amount of iterations of an event upon initiation
/// </summary>
public int IterationsTotal
{
get
{
return m_StartIterations;
}
}
/// <summary>
/// returns the number of iterations left of an event
/// </summary>
public int IterationsLeft
{
get
{
if (Active)
return m_Event.Iterations;
return 0;
}
}
//////// main data ////////
/// <summary>
/// returns the id of this event handle, which is also the id of
/// the associated event (if not, the handle is considered inactive).
/// Setting this property directly is not recommended
/// </summary>
public int Id
{
get
{
return m_Id;
}
set
{
// setting the property associates this handle with a
// currently active event with the same id, or null.
m_Id = value;
// if 'Id' is being set to zero, cancel the event immediately
// by setting due time to zero and return
if (m_Id == 0)
{
m_Event.DueTime = 0.0f;
return;
}
// find the associated event. most likely it is the last created one in
// the active list, which is instantly found by looping backwards.
// if not, it might be some other event that a brave user wishes to
// find and hook up manually (this is OK, though not recommended)
m_Event = null;
for (int t = vp_Timer.m_Active.Count - 1; t > -1; t--)
{
if (vp_Timer.m_Active[t].Id == m_Id)
{
m_Event = vp_Timer.m_Active[t];
break;
}
}
if (m_Event == null)
UnityEngine.Debug.LogError("Error: (" + this + ") Failed to assign event with Id '" + m_Id + "'.");
// store some initial event info
m_StartIterations = m_Event.Iterations;
m_FirstDueTime = m_Event.DueTime;
}
}
/// <summary>
/// returns true if the timer event of this handle is active
/// (running or paused). rReturns false if not, or if this
/// timer handle is no longer valid
/// </summary>
public bool Active
{
// NOTE: this property verifies timer handle integrity.
// if 'Event.Id' and 'Id' differ, the timer handle is no
// longer valid and using its event may cause bugs
get
{
if (m_Event == null || Id == 0 || m_Event.Id == 0)
return false;
return m_Event.Id == Id;
}
}
/// <summary>
/// returns the name of the scheduled method, or 'delegate'
/// </summary>
public string MethodName
{
get
{
if (Active)
return m_Event.MethodName;
return "";
}
}
/// <summary>
/// returns the name of the scheduled method along with any arguments,
/// plus a stack trace (if compiling with the DEBUG define)
/// </summary>
public string MethodInfo
{
get
{
if (Active)
return m_Event.MethodInfo;
return "";
}
}
/// <summary>
/// sets whether the event associated with this handle should be
/// canceled upon level load (default: true)
/// </summary>
public bool CancelOnLoad
{
get
{
if (Active)
return m_Event.CancelOnLoad;
return true;
}
set
{
if (Active)
{
m_Event.CancelOnLoad = value;
return;
}
UnityEngine.Debug.LogWarning("Warning: (" + this + ") Tried to set CancelOnLoad on inactive timer handle.");
}
}
/// <summary>
/// cancels the event associated with this handle, if active
/// </summary>
public void Cancel()
{
vp_Timer.Cancel(this);
}
/// <summary>
/// executes the event associated with this handle early, if active
/// </summary>
public void Execute()
{
m_Event.DueTime = Time.time;
}
}
/// <summary>
/// sets a flag preventing timer scheduling when application is about
/// to quit (prevents memory leaks in the editor)
/// </summary>
void OnApplicationQuit()
{
m_AppQuitting = true;
}
}
| |
// Copyright (C) 2012-2017 Luca Piccioni
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
namespace OpenGL.Objects.State
{
/// <summary>
/// Class describing a partial uniform state of a <see cref="ShaderProgram"/>
/// </summary>
/// <remarks>
/// This class is able to setup <see cref="ShaderProgram"/> uniform state by detecting fields and properties of derived
/// classes having the <see cref="ShaderUniformStateAttribute"/> attribute.
/// </remarks>
public abstract class ShaderUniformStateBase : GraphicsState
{
#region Uniform State (via Reflection)
/// <summary>
/// Attribute applied to those fields that are bound to a shader program uniform state.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
protected class ShaderUniformStateAttribute : Attribute
{
#region Constructors
/// <summary>
/// Assumes that the name is prefixes with a prefix framework-reserved ("glo_").
/// </summary>
internal ShaderUniformStateAttribute()
{
}
/// <summary>
/// Assumes that the name is prefixes with a prefix framework-reserved ("glo_").
/// </summary>
public ShaderUniformStateAttribute(string uniformName)
{
UniformName = uniformName;
}
#endregion
#region Parameters
/// <summary>
/// A specific name of the uniform variable. If null, the name is implicit.
/// </summary>
public readonly string UniformName;
#endregion
}
/// <summary>
/// Delegate used for getting the uniform variable value.
/// </summary>
/// <param name="instance">
/// The <see cref="Object"/> that specify the instance defining <paramref name="memberInfo"/>.
/// </param>
/// <param name="memberInfo">
/// The <see cref="MemberInfo"/> that is used to get the uniform value.
/// </param>
/// <returns>
/// It returns an object that specify the value of the underlying uniform variable.
/// </returns>
protected delegate object GetUniformValueDelegate(object instance, MemberInfo memberInfo);
/// <summary>
/// The <see cref="GetUniformValueDelegate"/> implementation for fields.
/// </summary>
/// <param name="instance">
/// The <see cref="Object"/> that specify the instance defining <paramref name="memberInfo"/>.
/// </param>
/// <param name="memberInfo">
/// The <see cref="MemberInfo"/> that is used to get the uniform value.
/// </param>
/// <returns>
/// It returns an object that specify the value of the underlying uniform variable.
/// </returns>
private static object GetFieldUniformValue(object instance, MemberInfo memberInfo)
{
if (memberInfo == null)
throw new ArgumentNullException("memberInfo");
if (memberInfo.MemberType != MemberTypes.Field)
throw new ArgumentException("not a field member", "memberInfo");
FieldInfo fieldInfo = (FieldInfo)memberInfo;
return (fieldInfo.GetValue(instance));
}
/// <summary>
/// The <see cref="GetUniformValueDelegate"/> implementation for properties.
/// </summary>
/// <param name="instance">
/// The <see cref="Object"/> that specify the instance defining <paramref name="memberInfo"/>.
/// </param>
/// <param name="memberInfo">
/// The <see cref="MemberInfo"/> that is used to get the uniform value.
/// </param>
/// <returns>
/// It returns an object that specify the value of the underlying uniform variable.
/// </returns>
private static object GetPropertyUniformValue(object instance, MemberInfo memberInfo)
{
if (memberInfo == null)
throw new ArgumentNullException("memberInfo");
if (memberInfo.MemberType != MemberTypes.Property)
throw new ArgumentException("not a property member", "memberInfo");
PropertyInfo propertyInfo = (PropertyInfo)memberInfo;
return (propertyInfo.GetValue(instance, null));
}
/// <summary>
/// Context used for compositing all information required for getting the uniform state.
/// </summary>
protected class UniformStateMember
{
/// <summary>
/// Basic constructor.
/// </summary>
/// <param name="uniformName"></param>
protected UniformStateMember(string uniformName)
{
if (uniformName == null)
throw new ArgumentNullException("uniformName");
UniformName = uniformName;
}
/// <summary>
/// Construct a UniformStateMember.
/// </summary>
/// <param name="uniformName">
/// A <see cref="String"/> that specifies the name of the uniform variable.
/// </param>
/// <param name="memberInfo">
/// The <see cref="MemberInfo"/> that specify the uniform state variable.
/// </param>
/// <param name="getUniformValueDelegate">
/// The <see cref="GetUniformValueDelegate"/> used for getting the uniform state from <paramref name="memberInfo"/>.
/// </param>
public UniformStateMember(string uniformName, MemberInfo memberInfo, GetUniformValueDelegate getUniformValueDelegate) :
this(uniformName)
{
if (memberInfo == null)
throw new ArgumentNullException("memberInfo");
if (getUniformValueDelegate == null)
throw new ArgumentNullException("getUniformValueDelegate");
UniformName = uniformName;
_Member = memberInfo;
GetValueDelegate = getUniformValueDelegate;
}
/// <summary>
/// The name of the uniform variable.
/// </summary>
public readonly string UniformName;
/// <summary>
/// The underlying member that specify the uniform state variable.
/// </summary>
private readonly MemberInfo _Member;
/// <summary>
/// The <see cref="GetUniformValueDelegate"/> used for getting the uniform state from <see cref="_Member"/>.
/// </summary>
public readonly GetUniformValueDelegate GetValueDelegate;
/// <summary>
/// Get the <see cref="Type"/> of the uniform value.
/// </summary>
/// <returns>
/// It returns the <see cref="Type"/> corresponding to the uniform value.
/// </returns>
public virtual Type GetUniformType()
{
switch (_Member.MemberType) {
case MemberTypes.Field:
return (((FieldInfo)_Member).FieldType);
case MemberTypes.Property:
return (((PropertyInfo)_Member).PropertyType);
default:
throw new NotImplementedException();
}
}
/// <summary>
/// Get the uniform variable value.
/// </summary>
/// <param name="instance">
/// The <see cref="Object"/> that specify the instance defining <paramref name="memberInfo"/>.
/// </param>
/// <returns></returns>
public virtual object GetUniformValue(object instance) { return (GetValueDelegate(instance, _Member)); }
}
/// <summary>
/// Utility routine for detecting fields and properties which value is bound to a shader program uniform
/// state.
/// </summary>
/// <param name="shaderUniformStateType">
/// The <see cref="Type"/> that is defining the fields and properties to be linked with the uniform state.
/// </param>
/// <returns>
/// It returns a <see cref="Dictionary{String, UniformStateMember}"/> that associate uniform variable names with
/// the relative <see cref="UniformStateMember"/>, which define access to backing properties for getting uniform
/// variable values.
/// </returns>
protected static Dictionary<string, UniformStateMember> DetectUniformProperties(Type shaderUniformStateType)
{
DetectTypeUniformProperties(shaderUniformStateType);
List<UniformStateMember> uniformState = _TypeUniformState[shaderUniformStateType];
Dictionary<string, UniformStateMember> uniformMembers = new Dictionary<string, UniformStateMember>();
foreach (UniformStateMember uniformStateMember in uniformState)
uniformMembers.Add(uniformStateMember.UniformName, uniformStateMember);
return (uniformMembers);
}
private static void DetectTypeUniformProperties(Type shaderUniformStateType)
{
if (shaderUniformStateType == null)
throw new ArgumentNullException("shaderUniformStateType");
if (_TypeUniformState.ContainsKey(shaderUniformStateType))
return;
List<UniformStateMember> typeMembers = new List<UniformStateMember>();
// Fields
FieldInfo[] uniformFields = shaderUniformStateType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
foreach (FieldInfo uniformField in uniformFields) {
ShaderUniformStateAttribute attribute = (ShaderUniformStateAttribute)Attribute.GetCustomAttribute(uniformField, typeof(ShaderUniformStateAttribute));
if (attribute == null)
continue;
// If the uniform name is unspecified, it's implictly defined with the "glo_" 'namespace'
string uniformName = attribute.UniformName != null ? attribute.UniformName : "glo_" + uniformField.Name;
typeMembers.Add(new UniformStateMember(uniformName, uniformField, GetFieldUniformValue));
// Recurse on uniform type
CheckUniformType(uniformField.FieldType);
}
// Properties
PropertyInfo[] uniformProperties = shaderUniformStateType.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
foreach (PropertyInfo uniformProperty in uniformProperties) {
if (uniformProperty.CanRead == false)
continue;
if (uniformProperty.GetIndexParameters().Length > 0)
continue;
ShaderUniformStateAttribute attribute = (ShaderUniformStateAttribute)Attribute.GetCustomAttribute(uniformProperty, typeof(ShaderUniformStateAttribute));
if (attribute == null)
continue;
// If the uniform name is unspecified, it's implictly defined with the "glo_" 'namespace'
string uniformName = attribute.UniformName != null ? attribute.UniformName : "glo_" + uniformProperty.Name;
typeMembers.Add(new UniformStateMember(uniformName, uniformProperty, GetPropertyUniformValue));
// Recurse on uniform type
CheckUniformType(uniformProperty.PropertyType);
}
// Nested types (and because this it's not possible to support public ShaderUniformStateAttribute)
foreach (Type nestedType in shaderUniformStateType.GetNestedTypes(BindingFlags.Public)) {
CheckUniformType(nestedType);
}
_TypeUniformState.Add(shaderUniformStateType, typeMembers);
}
private static void CheckUniformType(Type uniformType)
{
if (uniformType == null)
throw new ArgumentNullException("uniformType");
if (uniformType.IsAbstract)
return;
if (uniformType.IsArray)
uniformType = uniformType.GetElementType();
ShaderUniformStateAttribute typeAttribute = (ShaderUniformStateAttribute)Attribute.GetCustomAttribute(uniformType, typeof(ShaderUniformStateAttribute));
if (typeAttribute != null)
DetectTypeUniformProperties(uniformType);
}
/// <summary>
/// Get the uniform state associated with this instance.
/// </summary>
protected abstract Dictionary<string, UniformStateMember> UniformState { get; }
/// <summary>
///
/// </summary>
private static readonly Dictionary<Type, List<UniformStateMember>> _TypeUniformState = new Dictionary<Type, List<UniformStateMember>>();
/// <summary>
/// Apply this state to a shader program.
/// </summary>
/// <param name="ctx">
/// A <see cref="GraphicsContext"/> used to share common state between shaders.
/// </param>
/// <param name="shaderProgram">
/// A <see cref="ShaderProgram"/> that specify this uniform state.
/// </param>
/// <param name="uniformScope">
/// A <see cref="String"/> that specify the scope the uniform variable.
/// </param>
private void ApplyState(GraphicsContext ctx, ShaderProgram shaderProgram, string uniformScope)
{
if (shaderProgram == null)
throw new ArgumentNullException("shaderProgram");
GraphicsResource.CheckCurrentContext(ctx);
if (UniformBlockTag != null && UniformBuffer != null && shaderProgram.IsActiveUniformBlock(UniformBlockTag)) {
// Update uniform buffer
UniformBuffer.Map(ctx, BufferAccess.WriteOnly);
try {
ApplyState(ctx, UniformBuffer, null, UniformState.Values, this);
} finally {
UniformBuffer.Unmap(ctx);
}
// All uniforms at once
shaderProgram.SetUniformBlock(ctx, UniformBlockTag, UniformBuffer);
} else {
ApplyState(ctx, shaderProgram, null, UniformState.Values, this);
}
}
/// <summary>
/// Apply this state to a shader program.
/// </summary>
/// <param name="ctx">
/// A <see cref="GraphicsContext"/> used to share common state between shaders.
/// </param>
/// <param name="uniformContainer">
/// A <see cref="IShaderUniformContainer"/> that specify this uniform state.
/// </param>
/// <param name="uniformScope">
/// A <see cref="String"/> that specify the scope the uniform variable.
/// </param>
private void ApplyState(GraphicsContext ctx, IShaderUniformContainer uniformContainer, string uniformScope, IEnumerable<UniformStateMember> uniforms, object instance)
{
if (uniformContainer == null)
throw new ArgumentNullException("shaderProgram");
if (uniforms == null)
throw new ArgumentNullException("uniforms");
if (instance == null)
throw new ArgumentNullException("instance");
foreach (UniformStateMember uniform in uniforms) {
// Set the program uniform
string uniformPattern = uniformScope != null ? String.Format("{0}.{1}", uniformScope, uniform.UniformName) : uniform.UniformName;
// Matches also partial uniform variables (i.e. glo_Struct[0] or glo_Struct while glo_Struct[0].Member is active)
// Indeed quite efficient when structures are not active (skip all members)
if (uniformContainer.IsActiveUniform(uniformPattern) == false)
continue;
object uniformValue = uniform.GetUniformValue(instance);
// Silently skip null references
if (uniformValue == null)
continue;
Type uniformValueType = uniformValue.GetType();
if (uniformValueType.IsArray) {
Array uniformArray = (Array)uniformValue;
for (int i = 0; i < uniformArray.Length; i++) {
string uniformArrayPattern = String.Format("{0}[{1}]", uniformPattern, i);
if (uniformContainer.IsActiveUniform(uniformArrayPattern) == false)
continue;
object uniformArrayValue = uniformArray.GetValue(i);
// Silently skip null references
if (uniformArrayValue == null)
continue;
ApplyUniform(ctx, uniformContainer, uniformArrayPattern, uniformArrayValue);
}
} else
ApplyUniform(ctx, uniformContainer, uniformPattern, uniformValue);
}
}
/// <summary>
/// Set a single uniform, optionally structured.
/// </summary>
/// <param name="ctx">
/// A <see cref="GraphicsContext"/> used to share common state between shaders.
/// </param>
/// <param name="uniformContainer">
/// A <see cref="IShaderUniformContainer"/> that specify this uniform state.
/// </param>
/// <param name="uniformPattern"></param>
/// <param name="uniformValue"></param>
private void ApplyUniform(GraphicsContext ctx, IShaderUniformContainer uniformContainer, string uniformPattern, object uniformValue)
{
List<UniformStateMember> structuredTypeMembers;
if (_TypeUniformState.TryGetValue(uniformValue.GetType(), out structuredTypeMembers)) {
// Recurse over structure fields
ApplyState(ctx, uniformContainer, uniformPattern, structuredTypeMembers, uniformValue);
} else
uniformContainer.SetUniform(ctx, uniformPattern, uniformValue);
}
#endregion
#region Uniform Block Support
/// <summary>
/// The tag the identifies the uniform block.
/// </summary>
protected virtual string UniformBlockTag { get { return (null); } }
/// <summary>
/// The buffer holding the uniform state. If the state is shared among multiple programs, the block layout must be
/// "shared", in order to grant the same uniform layout across all programs sharing the state.
/// </summary>
protected UniformBuffer UniformBuffer { get { return (_UniformBuffer); } }
/// <summary>
/// The buffer holding the uniform state. If the state is shared among multiple programs, the block layout must be
/// "shared", in order to grant the same uniform layout across all programs sharing the state.
/// </summary>
private UniformBuffer _UniformBuffer;
#endregion
#region GraphicsState Overrides
/// <summary>
/// Flag indicating whether the state is context-bound.
/// </summary>
/// <remarks>
/// It returns always false.
/// </remarks>
public override bool IsContextBound { get { return (false); } }
/// <summary>
/// Flag indicating whether the state can be applied on a <see cref="ShaderProgram"/>.
/// </summary>
public override bool IsProgramBound { get { return (true); } }
/// <summary>
/// Create or update resources defined by this IGraphicsState, based on the associated <see cref="ShaderProgram"/>.
/// </summary>
/// <param name="ctx">
/// A <see cref="GraphicsContext"/> used for allocating resources.
/// </param>
/// <param name="shaderProgram">
/// A <see cref="ShaderProgram"/> that will be used in conjunction with this IGraphicsState.
/// </param>
public override void Create(GraphicsContext ctx, ShaderProgram shaderProgram)
{
// Create IGraphicsResource uniforms (i.e. textures)
Dictionary<string, UniformStateMember> uniformState = UniformState;
foreach (KeyValuePair<string, UniformStateMember> pair in uniformState) {
if (pair.Value.GetUniformType().GetInterface("IGraphicsResource") == null)
continue;
IGraphicsResource graphicsResource = pair.Value.GetUniformValue(this) as IGraphicsResource;
if (graphicsResource == null)
continue;
// Create the IGraphicsResource associated with the uniform state variable
graphicsResource.Create(ctx);
}
// Create uniform buffer, if supported
if (UniformBlockTag != null && shaderProgram != null && shaderProgram.IsActiveUniformBlock(UniformBlockTag) && UniformBuffer == null) {
_UniformBuffer = shaderProgram.CreateUniformBlock(UniformBlockTag, MapBufferUsageMask.MapWriteBit);
_UniformBuffer.Create(ctx);
}
// Base implementation
base.Create(ctx, shaderProgram);
}
/// <summary>
/// Dispose resources allocated by <see cref="Create(GraphicsContext, ShaderProgram)"/>.
/// </summary>
public override void Delete()
{
if (_UniformBuffer != null) {
_UniformBuffer.Dispose();
_UniformBuffer = null;
}
Dictionary<string, UniformStateMember> uniformState = UniformState;
foreach (KeyValuePair<string, UniformStateMember> pair in uniformState) {
if (pair.Value.GetUniformType().GetInterface("IGraphicsResource") == null)
continue;
IGraphicsResource graphicsResource = pair.Value.GetUniformValue(this) as IGraphicsResource;
if (graphicsResource == null)
continue;
}
}
/// <summary>
/// Apply this depth test render state.
/// </summary>
/// <param name="ctx">
/// A <see cref="GraphicsContext"/> which has defined the shader program <paramref name="shaderProgram"/>.
/// </param>
/// <param name="shaderProgram">
/// The <see cref="ShaderProgram"/> which has the state set.
/// </param>
public override void Apply(GraphicsContext ctx, ShaderProgram shaderProgram)
{
if (UniformBlockTag != null && shaderProgram != null && shaderProgram.IsActiveUniformBlock(UniformBlockTag)) {
// Ensure uniform buffer existing
if (UniformBuffer == null) {
_UniformBuffer = shaderProgram.CreateUniformBlock(UniformBlockTag, MapBufferUsageMask.MapWriteBit);
_UniformBuffer.Create(ctx);
}
// Apply uniforms to uniform buffer
ApplyState(ctx, shaderProgram, String.Empty);
// Set uniform block
shaderProgram.SetUniformBlock(ctx, UniformBlockTag, _UniformBuffer);
} else {
// Apply uniforms to program
ApplyState(ctx, shaderProgram, String.Empty);
}
}
/// <summary>
/// Merge this state with another one.
/// </summary>
/// <param name="state">
/// A <see cref="IGraphicsState"/> having the same <see cref="StateIdentifier"/> of this state.
/// </param>
public override void Merge(IGraphicsState state)
{
if (state == null)
throw new ArgumentNullException("state");
ShaderUniformStateBase otherState = state as ShaderUniformStateBase;
if (otherState == null)
throw new ArgumentException("not a ShaderUniformState", "state");
throw new NotImplementedException();
}
/// <summary>
/// Indicates whether the current object is equal to another object of the same type.
/// </summary>
/// <param name="other">
/// A <see cref="GraphicsState"/> to compare to this GraphicsState.
/// </param>
/// <returns>
/// It returns true if the current object is equal to <paramref name="other"/>.
/// </returns>
/// <remarks>
/// <para>
/// This method test only whether <paramref name="other"/> type equals to this type.
/// </para>
/// </remarks>
/// <exception cref="ArgumentNullException">
/// This exception is thrown if the parameter <paramref name="other"/> is null.
/// </exception>
public override bool Equals(IGraphicsState other)
{
if (base.Equals(other) == false)
return (false);
throw new NotImplementedException();
}
#endregion
}
/// <summary>
/// Class describing a partial uniform state of a <see cref="ShaderProgram"/>
/// </summary>
/// <remarks>
/// This class is able to setup <see cref="ShaderProgram"/> uniform state by detecting fields and properties of derived
/// classes having the <see cref="ShaderUniformStateAttribute"/> attribute.
/// </remarks>
public class ShaderUniformState : ShaderUniformStateBase
{
#region Constructors
/// <summary>
/// Default constructor.
/// </summary>
/// <param name="stateId">
/// A <see cref="String"/> that specifies the state identifier.
/// </param>
public ShaderUniformState(string stateId)
{
if (stateId == null)
throw new ArgumentNullException("stateId");
_StateId = stateId;
}
#endregion
#region Ad-Hoc Uniform State
/// <summary>
/// Context used for compositing all information required for getting the uniform state.
/// </summary>
protected class UniformStateVariable : UniformStateMember
{
/// <summary>
/// Default constructor.
/// </summary>
/// <param name="uniformName">
/// A <see cref="String"/> that specifies the name of the uniform variable.
/// </param>
public UniformStateVariable(string uniformName, object value) : base(uniformName)
{
if (value == null)
throw new ArgumentNullException("value");
UniformValue = value;
}
/// <summary>
/// Get the <see cref="Type"/> of the uniform value.
/// </summary>
/// <returns>
/// It returns the <see cref="Type"/> corresponding to the uniform value.
/// </returns>
public override Type GetUniformType()
{
return (UniformValue.GetType());
}
/// <summary>
/// Get the uniform variable value.
/// </summary>
/// <param name="instance">
/// The <see cref="Object"/> that specify the instance defining <paramref name="memberInfo"/>.
/// </param>
/// <returns></returns>
public override object GetUniformValue(object instance) { return (UniformValue); }
/// <summary>
/// Get or set the uniform value.
/// </summary>
public object UniformValue;
}
/// <summary>
/// Set uniform variable state.
/// </summary>
/// <param name="uniformName">
///
/// </param>
/// <param name="value">
///
/// </param>
public void SetUniformState(string uniformName, object value)
{
if (uniformName == null)
throw new ArgumentNullException("uniformName");
UniformStateMember uniformStateMember;
if (_UniformProperties.TryGetValue(uniformName, out uniformStateMember)) {
UniformStateVariable uniformStateVariable = (UniformStateVariable)uniformStateMember;
IGraphicsResource prevResource = uniformStateVariable.UniformValue as IGraphicsResource;
if (prevResource != null)
prevResource.DecRef();
IGraphicsResource currResource = value as IGraphicsResource;
if (currResource != null)
currResource.IncRef();
uniformStateVariable.UniformValue = value;
} else {
IGraphicsResource currResource = value as IGraphicsResource;
if (currResource != null)
currResource.IncRef();
_UniformProperties.Add(uniformName, new UniformStateVariable(uniformName, value));
}
}
#endregion
#region ShaderUniformStateBase Overrides
/// <summary>
/// Get the identifier of this ShaderUniformState.
/// </summary>
public override string StateIdentifier { get { return (_StateId); } }
/// <summary>
/// The identifier of this ShaderUniformState.
/// </summary>
private readonly string _StateId;
/// <summary>
/// Unique index assigned to this GraphicsState.
/// </summary>
public static int StateSetIndex { get { return (_StateIndex); } }
/// <summary>
/// Unique index assigned to this GraphicsState.
/// </summary>
public override int StateIndex { get { return (_StateIndex); } }
/// <summary>
/// The index for this GraphicsState.
/// </summary>
private static int _StateIndex = NextStateIndex();
/// <summary>
/// Get the uniform state associated with this instance.
/// </summary>
protected override Dictionary<string, UniformStateMember> UniformState { get { return (_UniformProperties); } }
/// <summary>
/// The uniform state of this TransformState.
/// </summary>
private readonly Dictionary<string, UniformStateMember> _UniformProperties = new Dictionary<string, UniformStateMember>();
#endregion
}
}
| |
using System;
using Microsoft.SPOT;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
namespace ntools.Networking.FTP
{
public class FtpSession : Session
{
private string username, password;
private bool authorized;
private string path = "/";
private string type;
private IPEndPoint dataEndpoint;
private string renameFrom;
internal FtpSession(Socket socket)
: base(socket)
{
this.CommandReceived += OnCommandReceived;
Send(WELCOME);
}
private void OnCommandReceived(object sender, CommandReceivedEventArgs e)
{
switch (e.Command)
{
case COMMAND_USERNAME:
GotUsername(e.Parameter);
break;
case COMMAND_PASSWORD:
GotPassword(e.Parameter);
break;
case COMMAND_CURRENTDIRECTORY:
PWD();
break;
case COMMAND_SYSTEMTYPE:
SYST();
break;
case COMMAND_TYPE:
Type(e.Parameter);
break;
case COMMAND_DATAPORT:
Port(e.Parameter);
break;
case COMMAND_LIST:
List();
break;
case COMMAND_CHANGEDIRECTORY:
CWD(e.Parameter);
break;
case COMMAND_CHANGEDIRECTORYUP:
CWD("..");
break;
case COMMAND_RETRIEVE:
Retrieve(e.Parameter);
break;
case COMMAND_DELETEFILE:
Delete(e.Parameter);
break;
case COMMAND_MAKEDIR:
MKD(e.Parameter);
break;
case COMMAND_REMOVEDIR:
RemoveDirectory(e.Parameter);
break;
case COMMAND_STORE:
Store(e.Parameter);
break;
case COMMAND_RENAMEFROM:
RenameFrom(e.Parameter);
break;
case COMMAND_RENAMETO:
RenameTo(e.Parameter);
break;
default:
NotImplemented();
break;
}
}
private void GotUsername(string u)
{
if (this.authorized || this.username != null)
ForceClose();
else
{
this.username = u;
Send(STATUS_USERNAME);
}
}
private void GotPassword(string p)
{
if (this.authorized)
ForceClose();
else
{
this.password = p;
this.authorized = true;
Send(STATUS_PASSWORD);
}
}
private void PWD()
{
if (this.authorized)
Send(STATUS_PWD + "\"" + path + "\" is current directory");
else
ForceClose();
}
private void SYST()
{
if (this.authorized)
Send("AnySense Type: A");
else
ForceClose();
}
private void Type(string type)
{
this.type = type;
Send(STATUS_OK);
}
private void Port(string p)
{
string[] arr = p.Split(',');
byte[] ip = new byte[4];
for (int i = 0; i < 4; i++)
ip[i] = (byte)Int16.Parse(arr[i]);
int port = Int16.Parse(arr[4]) * 256 + Int16.Parse(arr[5]);
this.dataEndpoint = new IPEndPoint(new IPAddress(ip), port);
Send(STATUS_OK);
}
private void List()
{
if (this.authorized)
{
Send(STATUS_OPENCONNECTION);
var enumerator = Directory.EnumerateDirectories(ConvertPath(this.path)).GetEnumerator();
using (Socket datasocket = OpenDataConnection())
{
using (NetworkStream ns = new NetworkStream(datasocket))
{
using (StreamWriter sw = new StreamWriter(ns))
{
while (enumerator.MoveNext())
{
DirectoryInfo d = new DirectoryInfo((string)enumerator.Current);
string date = d.LastWriteTime.ToString("MMM dd HH:mm");
string line = "drwxr-xr-x 2 2003 2003 4096 " + date + " " + d.Name;
sw.WriteLine(line);
sw.Flush();
}
enumerator = Directory.EnumerateFiles(ConvertPath(this.path)).GetEnumerator();
while (enumerator.MoveNext())
{
FileInfo f = new FileInfo((string)enumerator.Current);
string date = f.LastWriteTime.ToString("MMM dd HH:mm");
string line = "-rw-r--r-- 2 2003 2003 " + f.Length + " " + date + " " + f.Name;
sw.WriteLine(line);
sw.Flush();
}
}
}
}
Send(STATUS_TRANSFERCOMPLETE);
}
else
{
ForceClose();
}
}
private void CWD(string path)
{
if (this.authorized)
{
if (path == "..")
this.path = this.path.Substring(0, this.path.LastIndexOf('/'));
else if (path.ToCharArray()[0] == '/')
this.path = path;
else
this.path += '/' + path;
//if (path == "..")
//{
// if (this.path.IndexOf('/') == -1)
// this.path = "/";
// else
// this.path = this.path.Substring(0, this.path.LastIndexOf('/') + 1);
//}
//else
// this.path = path;
//{
// if (this.path.ToCharArray()[this.path.Length - 1] == '/')
// this.path += path;
// else
// this.path += '/' + path;
//}
Send(STATUS_OK);
}
else
ForceClose();
}
private void Retrieve(string file)
{
file = ConvertPath(this.path) + "\\" + file;
if (this.authorized && File.Exists(file))
{
Send(STATUS_OPENCONNECTION);
using (Socket dataSocket = OpenDataConnection())
{
using (FileStream fs = new FileStream(file, FileMode.Open))
{
using (NetworkStream ns = new NetworkStream(dataSocket))
{
byte[] buffer = new byte[64];
int len;
do
{
len = fs.Read(buffer, 0, buffer.Length);
ns.Write(buffer, 0, len);
}
while (len == buffer.Length);
}
}
}
Send(STATUS_TRANSFERCOMPLETE);
}
else
{
ForceClose();
}
}
private void Delete(string file)
{
file = ConvertPath(this.path) + "\\" + file;
if (this.authorized && File.Exists(file))
{
File.Delete(file);
Send(STATUS_OK);
}
else
{
ForceClose();
}
}
private void RemoveDirectory(string path)
{
path = ConvertPath(this.path) + "\\" + path;
if (this.authorized && Directory.Exists(path))
{
Directory.Delete(path);
Send(STATUS_OK);
}
else
{
ForceClose();
}
}
private void MKD(string folder)
{
if (this.authorized)
{
folder = ConvertPath(this.path) + "\\" + folder;
Directory.CreateDirectory(folder);
Send(STATUS_OK);
}
else
{
ForceClose();
}
}
private void RenameFrom(string from)
{
if (this.authorized)
{
this.renameFrom = from;
Send(STATUS_OK);
}
else
ForceClose();
}
private void RenameTo(string to)
{
if (this.authorized)
{
if (this.renameFrom != null)
{
string from = ConvertPath(this.path) + "\\" + this.renameFrom;
to = ConvertPath(this.path) + "\\" + to;
if (File.GetAttributes(from) == FileAttributes.Directory)
Directory.Move(from, to);
else
File.Move(from, to);
Send(STATUS_OK);
}
else
{
Send(STATUS_FILEUNAVAILABLE);
}
}
else
{
ForceClose();
}
}
private void ForceClose()
{
}
private Socket OpenDataConnection()
{
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect(this.dataEndpoint);
socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel.Tcp, System.Net.Sockets.SocketOptionName.NoDelay, true);
socket.SendTimeout = 5000;
return socket;
}
private void Store(string file)
{
if (this.authorized)
{
file = ConvertPath(this.path) + "\\" + file;
Send(STATUS_OPENCONNECTION);
using (FileStream fs = new FileStream(file, FileMode.OpenOrCreate))
{
using (Socket socket = OpenDataConnection())
{
using (NetworkStream ns = new NetworkStream(socket))
{
byte[] buffer = new byte[1024];
int len=0;
do
{
len = ns.Read(buffer, 0, buffer.Length);
fs.Write(buffer, 0, len);
} while (len>0);
ns.Close();
ns.Dispose();
}
}
fs.Flush();
fs.Close();
fs.Dispose();
}
Send(STATUS_TRANSFERCOMPLETE);
}
else
{
ForceClose();
}
}
private void NotImplemented()
{
Send(STATUS_NOTIMPLEMENTED);
}
private string ConvertPath(string path)
{
if (path == "/")
return "\\SD\\";
else
return "\\SD\\" + path.Replace("/", "\\");
}
private const string WELCOME = "220 Welcome to Netduino FTP server.";
private const string STATUS_USERNAME = "331 User name ok. Enter password.";
private const string STATUS_PASSWORD = "230 User logged in.";
private const string STATUS_PWD = "257 ";
private const string STATUS_NOTIMPLEMENTED = "502 Command not implemented.";
private const string STATUS_OK = "200 OK";
private const string STATUS_OPENCONNECTION = "150 Status okay, opening data connection.";
private const string STATUS_TRANSFERCOMPLETE = "223 Transfer complete.";
private const string STATUS_FILEUNAVAILABLE = "550 File unavailable";
private const string COMMAND_USERNAME = "USER";
private const string COMMAND_PASSWORD = "PASS";
private const string COMMAND_CURRENTDIRECTORY = "PWD";
private const string COMMAND_SYSTEMTYPE = "SYST";
private const string COMMAND_TYPE = "TYPE";
private const string COMMAND_DATAPORT = "PORT";
private const string COMMAND_LIST = "LIST";
private const string COMMAND_CHANGEDIRECTORY = "CWD";
private const string COMMAND_CHANGEDIRECTORYUP = "CDUP";
private const string COMMAND_RETRIEVE = "RETR";
private const string COMMAND_STORE = "STOR";
private const string COMMAND_DELETEFILE = "DELE";
private const string COMMAND_MAKEDIR = "MKD";
private const string COMMAND_REMOVEDIR = "RMD";
private const string COMMAND_RENAMEFROM = "RNFR";
private const string COMMAND_RENAMETO = "RNTO";
}
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Linq;
using Avalonia.Logging;
using Avalonia.Platform;
using Avalonia.VisualTree;
namespace Avalonia.Layout
{
/// <summary>
/// Defines how a control aligns itself horizontally in its parent control.
/// </summary>
public enum HorizontalAlignment
{
/// <summary>
/// The control stretches to fill the width of the parent control.
/// </summary>
Stretch,
/// <summary>
/// The control aligns itself to the left of the parent control.
/// </summary>
Left,
/// <summary>
/// The control centers itself in the parent control.
/// </summary>
Center,
/// <summary>
/// The control aligns itself to the right of the parent control.
/// </summary>
Right,
}
/// <summary>
/// Defines how a control aligns itself vertically in its parent control.
/// </summary>
public enum VerticalAlignment
{
/// <summary>
/// The control stretches to fill the height of the parent control.
/// </summary>
Stretch,
/// <summary>
/// The control aligns itself to the top of the parent control.
/// </summary>
Top,
/// <summary>
/// The control centers itself within the parent control.
/// </summary>
Center,
/// <summary>
/// The control aligns itself to the bottom of the parent control.
/// </summary>
Bottom,
}
/// <summary>
/// Implements layout-related functionality for a control.
/// </summary>
public class Layoutable : Visual, ILayoutable
{
/// <summary>
/// Defines the <see cref="DesiredSize"/> property.
/// </summary>
public static readonly DirectProperty<Layoutable, Size> DesiredSizeProperty =
AvaloniaProperty.RegisterDirect<Layoutable, Size>(nameof(DesiredSize), o => o.DesiredSize);
/// <summary>
/// Defines the <see cref="Width"/> property.
/// </summary>
public static readonly StyledProperty<double> WidthProperty =
AvaloniaProperty.Register<Layoutable, double>(nameof(Width), double.NaN);
/// <summary>
/// Defines the <see cref="Height"/> property.
/// </summary>
public static readonly StyledProperty<double> HeightProperty =
AvaloniaProperty.Register<Layoutable, double>(nameof(Height), double.NaN);
/// <summary>
/// Defines the <see cref="MinWidth"/> property.
/// </summary>
public static readonly StyledProperty<double> MinWidthProperty =
AvaloniaProperty.Register<Layoutable, double>(nameof(MinWidth));
/// <summary>
/// Defines the <see cref="MaxWidth"/> property.
/// </summary>
public static readonly StyledProperty<double> MaxWidthProperty =
AvaloniaProperty.Register<Layoutable, double>(nameof(MaxWidth), double.PositiveInfinity);
/// <summary>
/// Defines the <see cref="MinHeight"/> property.
/// </summary>
public static readonly StyledProperty<double> MinHeightProperty =
AvaloniaProperty.Register<Layoutable, double>(nameof(MinHeight));
/// <summary>
/// Defines the <see cref="MaxHeight"/> property.
/// </summary>
public static readonly StyledProperty<double> MaxHeightProperty =
AvaloniaProperty.Register<Layoutable, double>(nameof(MaxHeight), double.PositiveInfinity);
/// <summary>
/// Defines the <see cref="Margin"/> property.
/// </summary>
public static readonly StyledProperty<Thickness> MarginProperty =
AvaloniaProperty.Register<Layoutable, Thickness>(nameof(Margin));
/// <summary>
/// Defines the <see cref="HorizontalAlignment"/> property.
/// </summary>
public static readonly StyledProperty<HorizontalAlignment> HorizontalAlignmentProperty =
AvaloniaProperty.Register<Layoutable, HorizontalAlignment>(nameof(HorizontalAlignment));
/// <summary>
/// Defines the <see cref="VerticalAlignment"/> property.
/// </summary>
public static readonly StyledProperty<VerticalAlignment> VerticalAlignmentProperty =
AvaloniaProperty.Register<Layoutable, VerticalAlignment>(nameof(VerticalAlignment));
/// <summary>
/// Defines the <see cref="UseLayoutRoundingProperty"/> property.
/// </summary>
public static readonly StyledProperty<bool> UseLayoutRoundingProperty =
AvaloniaProperty.Register<Layoutable, bool>(nameof(UseLayoutRounding), defaultValue: true, inherits: true);
private bool _measuring;
private Size? _previousMeasure;
private Rect? _previousArrange;
/// <summary>
/// Initializes static members of the <see cref="Layoutable"/> class.
/// </summary>
static Layoutable()
{
AffectsMeasure(
IsVisibleProperty,
WidthProperty,
HeightProperty,
MinWidthProperty,
MaxWidthProperty,
MinHeightProperty,
MaxHeightProperty,
MarginProperty,
HorizontalAlignmentProperty,
VerticalAlignmentProperty);
}
/// <summary>
/// Gets or sets the width of the element.
/// </summary>
public double Width
{
get { return GetValue(WidthProperty); }
set { SetValue(WidthProperty, value); }
}
/// <summary>
/// Gets or sets the height of the element.
/// </summary>
public double Height
{
get { return GetValue(HeightProperty); }
set { SetValue(HeightProperty, value); }
}
/// <summary>
/// Gets or sets the minimum width of the element.
/// </summary>
public double MinWidth
{
get { return GetValue(MinWidthProperty); }
set { SetValue(MinWidthProperty, value); }
}
/// <summary>
/// Gets or sets the maximum width of the element.
/// </summary>
public double MaxWidth
{
get { return GetValue(MaxWidthProperty); }
set { SetValue(MaxWidthProperty, value); }
}
/// <summary>
/// Gets or sets the minimum height of the element.
/// </summary>
public double MinHeight
{
get { return GetValue(MinHeightProperty); }
set { SetValue(MinHeightProperty, value); }
}
/// <summary>
/// Gets or sets the maximum height of the element.
/// </summary>
public double MaxHeight
{
get { return GetValue(MaxHeightProperty); }
set { SetValue(MaxHeightProperty, value); }
}
/// <summary>
/// Gets or sets the margin around the element.
/// </summary>
public Thickness Margin
{
get { return GetValue(MarginProperty); }
set { SetValue(MarginProperty, value); }
}
/// <summary>
/// Gets or sets the element's preferred horizontal alignment in its parent.
/// </summary>
public HorizontalAlignment HorizontalAlignment
{
get { return GetValue(HorizontalAlignmentProperty); }
set { SetValue(HorizontalAlignmentProperty, value); }
}
/// <summary>
/// Gets or sets the element's preferred vertical alignment in its parent.
/// </summary>
public VerticalAlignment VerticalAlignment
{
get { return GetValue(VerticalAlignmentProperty); }
set { SetValue(VerticalAlignmentProperty, value); }
}
/// <summary>
/// Gets the size that this element computed during the measure pass of the layout process.
/// </summary>
public Size DesiredSize
{
get;
private set;
}
/// <summary>
/// Gets a value indicating whether the control's layout measure is valid.
/// </summary>
public bool IsMeasureValid
{
get;
private set;
}
/// <summary>
/// Gets a value indicating whether the control's layouts arrange is valid.
/// </summary>
public bool IsArrangeValid
{
get;
private set;
}
/// <summary>
/// Gets or sets a value that determines whether the element should be snapped to pixel
/// boundaries at layout time.
/// </summary>
public bool UseLayoutRounding
{
get { return GetValue(UseLayoutRoundingProperty); }
set { SetValue(UseLayoutRoundingProperty, value); }
}
/// <summary>
/// Gets the available size passed in the previous layout pass, if any.
/// </summary>
Size? ILayoutable.PreviousMeasure => _previousMeasure;
/// <summary>
/// Gets the layout rect passed in the previous layout pass, if any.
/// </summary>
Rect? ILayoutable.PreviousArrange => _previousArrange;
/// <summary>
/// Creates the visual children of the control, if necessary
/// </summary>
public virtual void ApplyTemplate()
{
}
/// <summary>
/// Carries out a measure of the control.
/// </summary>
/// <param name="availableSize">The available size for the control.</param>
public void Measure(Size availableSize)
{
if (double.IsNaN(availableSize.Width) || double.IsNaN(availableSize.Height))
{
throw new InvalidOperationException("Cannot call Measure using a size with NaN values.");
}
if (!IsMeasureValid || _previousMeasure != availableSize)
{
var previousDesiredSize = DesiredSize;
var desiredSize = default(Size);
IsMeasureValid = true;
try
{
_measuring = true;
desiredSize = MeasureCore(availableSize).Constrain(availableSize);
}
finally
{
_measuring = false;
}
if (IsInvalidSize(desiredSize))
{
throw new InvalidOperationException("Invalid size returned for Measure.");
}
DesiredSize = desiredSize;
_previousMeasure = availableSize;
Logger.Verbose(LogArea.Layout, this, "Measure requested {DesiredSize}", DesiredSize);
if (DesiredSize != previousDesiredSize)
{
this.GetVisualParent<ILayoutable>()?.ChildDesiredSizeChanged(this);
}
}
}
/// <summary>
/// Arranges the control and its children.
/// </summary>
/// <param name="rect">The control's new bounds.</param>
public void Arrange(Rect rect)
{
if (IsInvalidRect(rect))
{
throw new InvalidOperationException("Invalid Arrange rectangle.");
}
if (!IsMeasureValid)
{
Measure(_previousMeasure ?? rect.Size);
}
if (!IsArrangeValid || _previousArrange != rect)
{
Logger.Verbose(LogArea.Layout, this, "Arrange to {Rect} ", rect);
IsArrangeValid = true;
ArrangeCore(rect);
_previousArrange = rect;
}
}
/// <summary>
/// Invalidates the measurement of the control and queues a new layout pass.
/// </summary>
public void InvalidateMeasure()
{
if (IsMeasureValid)
{
Logger.Verbose(LogArea.Layout, this, "Invalidated measure");
IsMeasureValid = false;
IsArrangeValid = false;
LayoutManager.Instance?.InvalidateMeasure(this);
InvalidateVisual();
}
}
/// <summary>
/// Invalidates the arrangement of the control and queues a new layout pass.
/// </summary>
public void InvalidateArrange()
{
if (IsArrangeValid)
{
Logger.Verbose(LogArea.Layout, this, "Invalidated arrange");
IsArrangeValid = false;
LayoutManager.Instance?.InvalidateArrange(this);
InvalidateVisual();
}
}
/// <inheritdoc/>
void ILayoutable.ChildDesiredSizeChanged(ILayoutable control)
{
if (!_measuring)
{
InvalidateMeasure();
}
}
/// <summary>
/// Marks a property as affecting the control's measurement.
/// </summary>
/// <param name="properties">The properties.</param>
/// <remarks>
/// After a call to this method in a control's static constructor, any change to the
/// property will cause <see cref="InvalidateMeasure"/> to be called on the element.
/// </remarks>
protected static void AffectsMeasure(params AvaloniaProperty[] properties)
{
foreach (var property in properties)
{
property.Changed.Subscribe(AffectsMeasureInvalidate);
}
}
/// <summary>
/// Marks a property as affecting the control's arrangement.
/// </summary>
/// <param name="properties">The properties.</param>
/// <remarks>
/// After a call to this method in a control's static constructor, any change to the
/// property will cause <see cref="InvalidateArrange"/> to be called on the element.
/// </remarks>
protected static void AffectsArrange(params AvaloniaProperty[] properties)
{
foreach (var property in properties)
{
property.Changed.Subscribe(AffectsArrangeInvalidate);
}
}
/// <summary>
/// The default implementation of the control's measure pass.
/// </summary>
/// <param name="availableSize">The size available to the control.</param>
/// <returns>The desired size for the control.</returns>
/// <remarks>
/// This method calls <see cref="MeasureOverride(Size)"/> which is probably the method you
/// want to override in order to modify a control's arrangement.
/// </remarks>
protected virtual Size MeasureCore(Size availableSize)
{
if (IsVisible)
{
var margin = Margin;
ApplyTemplate();
var constrained = LayoutHelper
.ApplyLayoutConstraints(this, availableSize)
.Deflate(margin);
var measured = MeasureOverride(constrained);
var width = measured.Width;
var height = measured.Height;
if (!double.IsNaN(Width))
{
width = Width;
}
width = Math.Min(width, MaxWidth);
width = Math.Max(width, MinWidth);
if (!double.IsNaN(Height))
{
height = Height;
}
height = Math.Min(height, MaxHeight);
height = Math.Max(height, MinHeight);
if (UseLayoutRounding)
{
var scale = GetLayoutScale();
width = Math.Ceiling(width * scale) / scale;
height = Math.Ceiling(height * scale) / scale;
}
return NonNegative(new Size(width, height).Inflate(margin));
}
else
{
return new Size();
}
}
/// <summary>
/// Measures the control and its child elements as part of a layout pass.
/// </summary>
/// <param name="availableSize">The size available to the control.</param>
/// <returns>The desired size for the control.</returns>
protected virtual Size MeasureOverride(Size availableSize)
{
double width = 0;
double height = 0;
foreach (ILayoutable child in this.GetVisualChildren())
{
child.Measure(availableSize);
width = Math.Max(width, child.DesiredSize.Width);
height = Math.Max(height, child.DesiredSize.Height);
}
return new Size(width, height);
}
/// <summary>
/// The default implementation of the control's arrange pass.
/// </summary>
/// <param name="finalRect">The control's new bounds.</param>
/// <remarks>
/// This method calls <see cref="ArrangeOverride(Size)"/> which is probably the method you
/// want to override in order to modify a control's arrangement.
/// </remarks>
protected virtual void ArrangeCore(Rect finalRect)
{
if (IsVisible)
{
var margin = Margin;
var originX = finalRect.X + margin.Left;
var originY = finalRect.Y + margin.Top;
var availableSizeMinusMargins = new Size(
Math.Max(0, finalRect.Width - margin.Left - margin.Right),
Math.Max(0, finalRect.Height - margin.Top - margin.Bottom));
var horizontalAlignment = HorizontalAlignment;
var verticalAlignment = VerticalAlignment;
var size = availableSizeMinusMargins;
var scale = GetLayoutScale();
if (horizontalAlignment != HorizontalAlignment.Stretch)
{
size = size.WithWidth(Math.Min(size.Width, DesiredSize.Width - margin.Left - margin.Right));
}
if (verticalAlignment != VerticalAlignment.Stretch)
{
size = size.WithHeight(Math.Min(size.Height, DesiredSize.Height - margin.Top - margin.Bottom));
}
size = LayoutHelper.ApplyLayoutConstraints(this, size);
if (UseLayoutRounding)
{
size = new Size(
Math.Ceiling(size.Width * scale) / scale,
Math.Ceiling(size.Height * scale) / scale);
availableSizeMinusMargins = new Size(
Math.Ceiling(availableSizeMinusMargins.Width * scale) / scale,
Math.Ceiling(availableSizeMinusMargins.Height * scale) / scale);
}
size = ArrangeOverride(size).Constrain(size);
switch (horizontalAlignment)
{
case HorizontalAlignment.Center:
case HorizontalAlignment.Stretch:
originX += (availableSizeMinusMargins.Width - size.Width) / 2;
break;
case HorizontalAlignment.Right:
originX += availableSizeMinusMargins.Width - size.Width;
break;
}
switch (verticalAlignment)
{
case VerticalAlignment.Center:
case VerticalAlignment.Stretch:
originY += (availableSizeMinusMargins.Height - size.Height) / 2;
break;
case VerticalAlignment.Bottom:
originY += availableSizeMinusMargins.Height - size.Height;
break;
}
if (UseLayoutRounding)
{
originX = Math.Floor(originX * scale) / scale;
originY = Math.Floor(originY * scale) / scale;
}
Bounds = new Rect(originX, originY, size.Width, size.Height);
}
}
/// <summary>
/// Positions child elements as part of a layout pass.
/// </summary>
/// <param name="finalSize">The size available to the control.</param>
/// <returns>The actual size used.</returns>
protected virtual Size ArrangeOverride(Size finalSize)
{
foreach (ILayoutable child in this.GetVisualChildren().OfType<ILayoutable>())
{
child.Arrange(new Rect(finalSize));
}
return finalSize;
}
/// <summary>
/// Calls <see cref="InvalidateMeasure"/> on the control on which a property changed.
/// </summary>
/// <param name="e">The event args.</param>
private static void AffectsMeasureInvalidate(AvaloniaPropertyChangedEventArgs e)
{
ILayoutable control = e.Sender as ILayoutable;
control?.InvalidateMeasure();
}
/// <summary>
/// Calls <see cref="InvalidateArrange"/> on the control on which a property changed.
/// </summary>
/// <param name="e">The event args.</param>
private static void AffectsArrangeInvalidate(AvaloniaPropertyChangedEventArgs e)
{
ILayoutable control = e.Sender as ILayoutable;
control?.InvalidateArrange();
}
/// <summary>
/// Tests whether any of a <see cref="Rect"/>'s properties incude nagative values,
/// a NaN or Infinity.
/// </summary>
/// <param name="rect">The rect.</param>
/// <returns>True if the rect is invalid; otherwise false.</returns>
private static bool IsInvalidRect(Rect rect)
{
return rect.Width < 0 || rect.Height < 0 ||
double.IsInfinity(rect.X) || double.IsInfinity(rect.Y) ||
double.IsInfinity(rect.Width) || double.IsInfinity(rect.Height) ||
double.IsNaN(rect.X) || double.IsNaN(rect.Y) ||
double.IsNaN(rect.Width) || double.IsNaN(rect.Height);
}
/// <summary>
/// Tests whether any of a <see cref="Size"/>'s properties incude nagative values,
/// a NaN or Infinity.
/// </summary>
/// <param name="size">The size.</param>
/// <returns>True if the size is invalid; otherwise false.</returns>
private static bool IsInvalidSize(Size size)
{
return size.Width < 0 || size.Height < 0 ||
double.IsInfinity(size.Width) || double.IsInfinity(size.Height) ||
double.IsNaN(size.Width) || double.IsNaN(size.Height);
}
/// <summary>
/// Ensures neither component of a <see cref="Size"/> is negative.
/// </summary>
/// <param name="size">The size.</param>
/// <returns>The non-negative size.</returns>
private static Size NonNegative(Size size)
{
return new Size(Math.Max(size.Width, 0), Math.Max(size.Height, 0));
}
private double GetLayoutScale()
{
var result = (VisualRoot as ILayoutRoot)?.LayoutScaling ?? 1.0;
if (result == 0 || double.IsNaN(result) || double.IsInfinity(result))
{
throw new Exception($"Invalid LayoutScaling returned from {VisualRoot.GetType()}");
}
return result;
}
}
}
| |
//---------------------------------------------------------------------
// <copyright file="EntitySqlException.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
namespace System.Data
{
using System;
using System.Data.Common.EntitySql;
using System.Data.Entity;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.Serialization;
using System.Security;
using System.Security.Permissions;
using System.Text;
/// <summary>
/// Represents an eSQL Query compilation exception;
/// The class of exceptional conditions that may cause this exception to be raised are mainly:
/// 1) Syntax Errors: raised during query text parsing and when a given query does not conform to eSQL formal grammar;
/// 2) Semantic Errors: raised when semantic rules of eSQL language are not met such as metadata or schema information
/// not accurate or not present, type validation errors, scoping rule violations, user of undefined variables, etc.
/// For more information, see eSQL Language Spec.
/// </summary>
[Serializable]
public sealed class EntitySqlException : EntityException
{
#region Private Fields
/// <summary>
/// error message description.
/// </summary>
private string _errorDescription;
/// <summary>
/// information about the context where the error occurred
/// </summary>
private string _errorContext;
/// <summary>
/// error line number
/// </summary>
private int _line;
/// <summary>
/// error column number
/// </summary>
private int _column;
#endregion
#region Public Constructors
/// <summary>
/// Initializes a new instance of <see cref="EntitySqlException"/> with the generic error message.
/// </summary>
public EntitySqlException()
: this(System.Data.Entity.Strings.GeneralQueryError)
{
HResult = HResults.InvalidQuery;
}
/// <summary>
/// Initializes a new instance of <see cref="EntitySqlException"/> with the given message.
/// </summary>
public EntitySqlException(string message)
: base(message)
{
HResult = HResults.InvalidQuery;
}
/// <summary>
/// Initializes a new instance of <see cref="EntitySqlException"/> with the given message and innerException instance.
/// </summary>
public EntitySqlException(string message, Exception innerException)
: base(message, innerException)
{
HResult = HResults.InvalidQuery;
}
/// <summary>
/// Initializes a new instance <see cref="EntitySqlException"/> with the given serializationInfo and streamingContext.
/// </summary>
/// <param name="serializationInfo"></param>
/// <param name="streamingContext"></param>
private EntitySqlException(SerializationInfo serializationInfo, StreamingContext streamingContext)
: base(serializationInfo, streamingContext)
{
HResult = HResults.InvalidQuery;
_errorDescription = serializationInfo.GetString("ErrorDescription");
_errorContext = serializationInfo.GetString("ErrorContext");
_line = serializationInfo.GetInt32("Line");
_column = serializationInfo.GetInt32("Column");
}
#endregion
#region Internal Constructors
/// <summary>
/// Initializes a new instance EntityException with an ErrorContext instance and a given error message.
/// </summary>
internal static EntitySqlException Create(ErrorContext errCtx, string errorMessage, Exception innerException)
{
return EntitySqlException.Create(errCtx.CommandText, errorMessage, errCtx.InputPosition, errCtx.ErrorContextInfo, errCtx.UseContextInfoAsResourceIdentifier, innerException);
}
/// <summary>
/// Initializes a new instance EntityException with contextual information to allow detailed error feedback.
/// </summary>
internal static EntitySqlException Create(string commandText,
string errorDescription,
int errorPosition,
string errorContextInfo,
bool loadErrorContextInfoFromResource,
Exception innerException)
{
int line;
int column;
string errorContext = FormatErrorContext(commandText, errorPosition, errorContextInfo, loadErrorContextInfoFromResource, out line, out column);
string errorMessage = FormatQueryError(errorDescription, errorContext);
return new EntitySqlException(errorMessage, errorDescription, errorContext, line, column, innerException);
}
/// <summary>
/// core constructor
/// </summary>
private EntitySqlException(string message, string errorDescription, string errorContext, int line, int column, Exception innerException)
: base(message, innerException)
{
_errorDescription = errorDescription;
_errorContext = errorContext;
_line = line;
_column = column;
HResult = HResults.InvalidQuery;
}
#endregion
#region Public Properties
/// <summary>
/// Gets the error description explaining the reason why the query was not accepted or an empty String.Empty
/// </summary>
public string ErrorDescription
{
get
{
return _errorDescription ?? String.Empty;
}
}
/// <summary>
/// Gets the aproximate context where the error occurred if available.
/// </summary>
public string ErrorContext
{
get
{
return _errorContext ?? String.Empty;
}
}
/// <summary>
/// Returns the the aproximate line number where the error occurred
/// </summary>
public int Line
{
get { return _line; }
}
/// <summary>
/// Returns the the aproximate column number where the error occurred
/// </summary>
public int Column
{
get { return _column; }
}
#endregion
#region Helpers
internal static string GetGenericErrorMessage(string commandText, int position)
{
int lineNumber = 0;
int colNumber = 0;
return FormatErrorContext(commandText, position, EntityRes.GenericSyntaxError, true, out lineNumber, out colNumber);
}
/// <summary>
/// Returns error context in the format [[errorContextInfo, ]line ddd, column ddd].
/// Returns empty string if errorPosition is less than 0 and errorContextInfo is not specified.
/// </summary>
internal static string FormatErrorContext(
string commandText,
int errorPosition,
string errorContextInfo,
bool loadErrorContextInfoFromResource,
out int lineNumber,
out int columnNumber)
{
Debug.Assert(errorPosition > -1, "position in input stream cannot be < 0");
Debug.Assert(errorPosition <= commandText.Length, "position in input stream cannot be greater than query text size");
if (loadErrorContextInfoFromResource)
{
errorContextInfo = !String.IsNullOrEmpty(errorContextInfo) ? EntityRes.GetString(errorContextInfo) : String.Empty;
}
//
// Replace control chars and newLines for single representation characters
//
StringBuilder sb = new StringBuilder(commandText.Length);
for (int i = 0; i < commandText.Length; i++)
{
Char c = commandText[i];
if (CqlLexer.IsNewLine(c))
{
c = '\n';
}
else if ((Char.IsControl(c) || Char.IsWhiteSpace(c)) && ('\r' != c))
{
c = ' ';
}
sb.Append(c);
}
commandText = sb.ToString().TrimEnd(new char[] { '\n' });
//
// Compute line and column
//
string[] queryLines = commandText.Split(new char[] { '\n' }, StringSplitOptions.None);
for (lineNumber = 0, columnNumber = errorPosition;
lineNumber < queryLines.Length && columnNumber > queryLines[lineNumber].Length;
columnNumber -= (queryLines[lineNumber].Length + 1), ++lineNumber) ;
++lineNumber; // switch lineNum and colNum to 1-based indexes
++columnNumber;
//
// Error context format: "[errorContextInfo,] line ddd, column ddd"
//
sb = new Text.StringBuilder();
if (!String.IsNullOrEmpty(errorContextInfo))
{
sb.AppendFormat(CultureInfo.CurrentCulture, "{0}, ", errorContextInfo);
}
if (errorPosition >= 0)
{
sb.AppendFormat(CultureInfo.CurrentCulture,
"{0} {1}, {2} {3}",
System.Data.Entity.Strings.LocalizedLine,
lineNumber,
System.Data.Entity.Strings.LocalizedColumn,
columnNumber);
}
return sb.ToString();
}
/// <summary>
/// Returns error message in the format: "error such and such[, near errorContext]."
/// </summary>
private static string FormatQueryError(string errorMessage, string errorContext)
{
//
// Message format: error such and such[, near errorContextInfo].
//
StringBuilder sb = new StringBuilder();
sb.Append(errorMessage);
if (!String.IsNullOrEmpty(errorContext))
{
sb.AppendFormat(CultureInfo.CurrentCulture, " {0} {1}", System.Data.Entity.Strings.LocalizedNear, errorContext);
}
return sb.Append(".").ToString();
}
#endregion
#region ISerializable implementation
/// <summary>
/// sets the System.Runtime.Serialization.SerializationInfo
/// with information about the exception.
/// </summary>
/// <param name="info">The System.Runtime.Serialization.SerializationInfo that holds the serialized
/// object data about the exception being thrown.
/// </param>
/// <param name="context"></param>
[SecurityCritical]
[PermissionSet(SecurityAction.LinkDemand, Unrestricted = true)]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue("ErrorDescription", _errorDescription);
info.AddValue("ErrorContext", _errorContext);
info.AddValue("Line", _line);
info.AddValue("Column", _column);
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Buffers;
using System.Diagnostics;
namespace System.Text.Formatting
{
// This whole API is very speculative, i.e. I am not sure I am happy with the design
// This API is trying to do composite formatting without boxing (or any other allocations).
// And because not all types in the platfrom implement IBufferFormattable (in particular built-in primitives don't),
// it needs to play some tricks with generic type parameters. But as you can see at the end of AppendUntyped, I am not sure how to tick the type system
// not never box.
public static class CompositeFormattingExtensions
{
public static void Format<TFormatter, T0>(this TFormatter formatter, string compositeFormat, T0 arg0) where TFormatter : ITextOutput
{
var reader = new CompositeFormatReader(compositeFormat);
while (true)
{
var segment = reader.Next();
if (segment == null) return;
if (segment.Value.Count == 0) // insertion point
{
if (segment.Value.Index == 0) formatter.AppendUntyped(arg0, segment.Value.Format);
else throw new Exception("invalid insertion point");
}
else // literal
{
formatter.Append(compositeFormat, segment.Value.Index, segment.Value.Count);
}
}
}
public static void Format<TFormatter, T0, T1>(this TFormatter formatter, string compositeFormat, T0 arg0, T1 arg1) where TFormatter : ITextOutput
{
var reader = new CompositeFormatReader(compositeFormat);
while (true)
{
var segment = reader.Next();
if (segment == null) return;
if (segment.Value.Count == 0) // insertion point
{
if (segment.Value.Index == 0) formatter.AppendUntyped(arg0, segment.Value.Format);
else if (segment.Value.Index == 1) formatter.AppendUntyped(arg1, segment.Value.Format);
else throw new Exception("invalid insertion point");
}
else // literal
{
formatter.Append(compositeFormat, segment.Value.Index, segment.Value.Count);
}
}
}
public static void Format<TFormatter, T0, T1, T2>(this TFormatter formatter, string compositeFormat, T0 arg0, T1 arg1, T2 arg2) where TFormatter : ITextOutput
{
var reader = new CompositeFormatReader(compositeFormat);
while (true)
{
var segment = reader.Next();
if (segment == null) return;
if (segment.Value.Count == 0) // insertion point
{
if (segment.Value.Index == 0) formatter.AppendUntyped(arg0, segment.Value.Format);
else if (segment.Value.Index == 1) formatter.AppendUntyped(arg1, segment.Value.Format);
else if (segment.Value.Index == 2) formatter.AppendUntyped(arg2, segment.Value.Format);
else throw new Exception("invalid insertion point");
}
else // literal
{
formatter.Append(compositeFormat, segment.Value.Index, segment.Value.Count);
}
}
}
public static void Format<TFormatter, T0, T1, T2, T3>(this TFormatter formatter, string compositeFormat, T0 arg0, T1 arg1, T2 arg2, T3 arg3) where TFormatter : ITextOutput
{
var reader = new CompositeFormatReader(compositeFormat);
while (true)
{
var segment = reader.Next();
if (segment == null) return;
if (segment.Value.Count == 0) // insertion point
{
if (segment.Value.Index == 0) formatter.AppendUntyped(arg0, segment.Value.Format);
else if (segment.Value.Index == 1) formatter.AppendUntyped(arg1, segment.Value.Format);
else if (segment.Value.Index == 2) formatter.AppendUntyped(arg2, segment.Value.Format);
else if (segment.Value.Index == 3) formatter.AppendUntyped(arg3, segment.Value.Format);
else throw new Exception("invalid insertion point");
}
else // literal
{
formatter.Append(compositeFormat, segment.Value.Index, segment.Value.Count);
}
}
}
public static void Format<TFormatter, T0, T1, T2, T3, T4>(this TFormatter formatter, string compositeFormat, T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4) where TFormatter : ITextOutput
{
var reader = new CompositeFormatReader(compositeFormat);
while (true)
{
var segment = reader.Next();
if (segment == null) return;
if (segment.Value.Count == 0) // insertion point
{
if (segment.Value.Index == 0) formatter.AppendUntyped(arg0, segment.Value.Format);
else if (segment.Value.Index == 1) formatter.AppendUntyped(arg1, segment.Value.Format);
else if (segment.Value.Index == 2) formatter.AppendUntyped(arg2, segment.Value.Format);
else if (segment.Value.Index == 3) formatter.AppendUntyped(arg3, segment.Value.Format);
else if (segment.Value.Index == 4) formatter.AppendUntyped(arg4, segment.Value.Format);
else throw new Exception("invalid insertion point");
}
else // literal
{
formatter.Append(compositeFormat, segment.Value.Index, segment.Value.Count);
}
}
}
// TODO: this should be removed and an ability to append substrings should be added
static void Append<TFormatter>(this TFormatter formatter, string whole, int index, int count) where TFormatter : ITextOutput
{
var buffer = formatter.Buffer;
var maxBytes = count << 4; // this is the worst case, i.e. 4 bytes per char
while(buffer.Length < maxBytes)
{
formatter.Enlarge(maxBytes);
buffer = formatter.Buffer;
}
// this should be optimized using fixed pointer to substring, but I will wait with this till we design proper substring
var characters = whole.Slice(index, count);
int bytesWritten;
int charactersConsumed;
if (!formatter.Encoder.TryEncode(characters, buffer, out charactersConsumed, out bytesWritten))
{
Debug.Assert(false, "this should never happen"); // because I pre-resized the buffer to 4 bytes per char at the top of this method.
}
formatter.Advance(bytesWritten);
}
static void AppendUntyped<TFormatter, T>(this TFormatter formatter, T value, TextFormat format) where TFormatter : ITextOutput
{
#region Built in types
var i32 = value as int?;
if (i32 != null)
{
formatter.Append(i32.Value, format);
return;
}
var i64 = value as long?;
if (i64 != null)
{
formatter.Append(i64.Value, format);
return;
}
var i16 = value as short?;
if (i16 != null)
{
formatter.Append(i16.Value, format);
return;
}
var b = value as byte?;
if (b != null)
{
formatter.Append(b.Value, format);
return;
}
var c = value as char?;
if (c != null)
{
formatter.Append(c.Value);
return;
}
var u32 = value as uint?;
if (u32 != null)
{
formatter.Append(u32.Value, format);
return;
}
var u64 = value as ulong?;
if (u64 != null)
{
formatter.Append(u64.Value, format);
return;
}
var u16 = value as ushort?;
if (u16 != null)
{
formatter.Append(u16.Value, format);
return;
}
var sb = value as sbyte?;
if (sb != null)
{
formatter.Append(sb.Value, format);
return;
}
var str = value as string;
if (str != null)
{
formatter.Append(str);
return;
}
var dt = value as DateTime?;
if (dt != null)
{
formatter.Append(dt.Value, format);
return;
}
var dto = value as DateTimeOffset?;
if (dto != null) {
formatter.Append(dto.Value, format);
return;
}
var ts = value as TimeSpan?;
if (ts != null)
{
formatter.Append(ts.Value, format);
return;
}
var guid = value as Guid?;
if (guid != null) {
formatter.Append(guid.Value, format);
return;
}
#endregion
if (value is IBufferFormattable)
{
formatter.Append((IBufferFormattable)value, format); // this is boxing. not sure how to avoid it.
return;
}
throw new NotSupportedException("value is not formattable.");
}
// this is just a state machine walking the composite format and instructing CompositeFormattingExtensions.Format overloads on what to do.
// this whole type is not just a hacky prototype.
// I will clean it up later if I decide that I like this whole composite format model.
struct CompositeFormatReader
{
string _compositeFormatString;
int _currentIndex;
int _spanStart;
State _state;
public CompositeFormatReader(string format)
{
_compositeFormatString = format;
_currentIndex = 0;
_spanStart = 0;
_state = State.New;
}
public CompositeSegment? Next()
{
while (_currentIndex < _compositeFormatString.Length)
{
char c = _compositeFormatString[_currentIndex];
if (c == '{')
{
if (_state == State.Literal)
{
_state = State.New;
return CompositeSegment.Literal(_spanStart, _currentIndex);
}
if ((_currentIndex + 1 < _compositeFormatString.Length) && (_compositeFormatString[_currentIndex + 1] == c))
{
_state = State.Literal;
_currentIndex++;
_spanStart = _currentIndex;
}
else
{
_currentIndex++;
return ParseInsertionPoint();
}
}
else if (c == '}')
{
if ((_currentIndex + 1 < _compositeFormatString.Length) && (_compositeFormatString[_currentIndex + 1] == c))
{
if (_state == State.Literal)
{
_state = State.New;
return CompositeSegment.Literal(_spanStart, _currentIndex);
}
_state = State.Literal;
_currentIndex++;
_spanStart = _currentIndex;
}
else
{
throw new Exception("missing start bracket");
}
}
else
{
if (_state != State.Literal)
{
_state = State.Literal;
_spanStart = _currentIndex;
}
}
_currentIndex++;
}
if (_state == State.Literal)
{
_state = State.New;
return CompositeSegment.Literal(_spanStart, _currentIndex);
}
return null;
}
// this should be replaced with InvariantFormatter.Parse
static bool TryParse(string compositeFormat, int start, int count, out uint value, out int consumed)
{
consumed = 0;
value = 0;
for (int i = start; i < start + count; i++)
{
var digit = (byte)(compositeFormat[i] - '0');
if (digit >= 0 && digit <= 9)
{
value *= 10;
value += digit;
consumed++;
}
else
{
if (i == start) return false;
else return true;
}
}
return true;
}
CompositeSegment ParseInsertionPoint()
{
uint arg;
int consumed;
char? formatSpecifier = null;
if (!TryParse(_compositeFormatString, _currentIndex, 5, out arg, out consumed))
{
throw new Exception("invalid insertion point");
}
_currentIndex += consumed;
if (_currentIndex >= _compositeFormatString.Length)
{
throw new Exception("missing end bracket");
}
if(_compositeFormatString[_currentIndex] == ':')
{
_currentIndex++;
formatSpecifier = _compositeFormatString[_currentIndex];
_currentIndex++;
}
if (_compositeFormatString[_currentIndex] != '}')
{
throw new Exception("missing end bracket");
}
_currentIndex++;
var parsedFormat = formatSpecifier.HasValue ? TextFormat.Parse(formatSpecifier.Value): default(TextFormat);
return CompositeSegment.InsertionPoint(arg, parsedFormat);
}
public enum State : byte
{
New,
Literal,
InsertionPoint
}
public struct CompositeSegment
{
public TextFormat Format { get; private set; }
public int Index { get; private set; }
public int Count { get; private set; }
public static CompositeSegment InsertionPoint(uint argIndex, TextFormat format)
{
return new CompositeSegment() { Index = (int)argIndex, Format = format };
}
public static CompositeSegment Literal(int startIndex, int endIndex)
{
return new CompositeSegment() { Index = startIndex, Count = endIndex - startIndex };
}
}
}
}
}
| |
// 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.ComponentModel;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Runtime.CompilerServices;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
namespace System.Data.SqlClient.SNI
{
/// <summary>
/// TCP connection handle
/// </summary>
internal class SNITCPHandle : SNIHandle
{
private readonly string _targetServer;
private readonly object _callbackObject;
private readonly Socket _socket;
private NetworkStream _tcpStream;
private Stream _stream;
private SslStream _sslStream;
private SslOverTdsStream _sslOverTdsStream;
private SNIAsyncCallback _receiveCallback;
private SNIAsyncCallback _sendCallback;
private bool _validateCert = true;
private int _bufferSize = TdsEnums.DEFAULT_LOGIN_PACKET_SIZE;
private uint _status = TdsEnums.SNI_UNINITIALIZED;
private Guid _connectionId = Guid.NewGuid();
private const int MaxParallelIpAddresses = 64;
/// <summary>
/// Dispose object
/// </summary>
public override void Dispose()
{
lock (this)
{
if (_sslOverTdsStream != null)
{
_sslOverTdsStream.Dispose();
_sslOverTdsStream = null;
}
if (_sslStream != null)
{
_sslStream.Dispose();
_sslStream = null;
}
if (_tcpStream != null)
{
_tcpStream.Dispose();
_tcpStream = null;
}
//Release any references held by _stream.
_stream = null;
}
}
/// <summary>
/// Connection ID
/// </summary>
public override Guid ConnectionId
{
get
{
return _connectionId;
}
}
/// <summary>
/// Connection status
/// </summary>
public override uint Status
{
get
{
return _status;
}
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="serverName">Server name</param>
/// <param name="port">TCP port number</param>
/// <param name="timerExpire">Connection timer expiration</param>
/// <param name="callbackObject">Callback object</param>
public SNITCPHandle(string serverName, int port, long timerExpire, object callbackObject, bool parallel)
{
_callbackObject = callbackObject;
_targetServer = serverName;
try
{
TimeSpan ts = default(TimeSpan);
// In case the Timeout is Infinite, we will receive the max value of Int64 as the tick count
// The infinite Timeout is a function of ConnectionString Timeout=0
bool isInfiniteTimeOut = long.MaxValue == timerExpire;
if (!isInfiniteTimeOut)
{
ts = DateTime.FromFileTime(timerExpire) - DateTime.Now;
ts = ts.Ticks < 0 ? TimeSpan.FromTicks(0) : ts;
}
Task<Socket> connectTask;
if (parallel)
{
Task<IPAddress[]> serverAddrTask = Dns.GetHostAddressesAsync(serverName);
serverAddrTask.Wait(ts);
IPAddress[] serverAddresses = serverAddrTask.Result;
if (serverAddresses.Length > MaxParallelIpAddresses)
{
// Fail if above 64 to match legacy behavior
ReportTcpSNIError(0, SNICommon.MultiSubnetFailoverWithMoreThan64IPs, string.Empty);
return;
}
connectTask = ParallelConnectAsync(serverAddresses, port);
if (!(isInfiniteTimeOut ? connectTask.Wait(-1) : connectTask.Wait(ts)))
{
ReportTcpSNIError(0, SNICommon.ConnOpenFailedError, string.Empty);
return;
}
_socket = connectTask.Result;
}
else
{
_socket = Connect(serverName, port, ts);
}
if (_socket == null || !_socket.Connected)
{
if (_socket != null)
{
_socket.Dispose();
_socket = null;
}
ReportTcpSNIError(0, SNICommon.ConnOpenFailedError, string.Empty);
return;
}
_socket.NoDelay = true;
_tcpStream = new NetworkStream(_socket, true);
_sslOverTdsStream = new SslOverTdsStream(_tcpStream);
_sslStream = new SslStream(_sslOverTdsStream, true, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
}
catch (SocketException se)
{
ReportTcpSNIError(se);
return;
}
catch (Exception e)
{
ReportTcpSNIError(e);
return;
}
_stream = _tcpStream;
_status = TdsEnums.SNI_SUCCESS;
}
private static Socket Connect(string serverName, int port, TimeSpan timeout)
{
IPAddress[] ipAddresses = Dns.GetHostAddresses(serverName);
IPAddress serverIPv4 = null;
IPAddress serverIPv6 = null;
foreach (IPAddress ipAdress in ipAddresses)
{
if (ipAdress.AddressFamily == AddressFamily.InterNetwork)
{
serverIPv4 = ipAdress;
}
else if (ipAdress.AddressFamily == AddressFamily.InterNetworkV6)
{
serverIPv6 = ipAdress;
}
}
ipAddresses = new IPAddress[] { serverIPv4, serverIPv6 };
Socket[] sockets = new Socket[2];
CancellationTokenSource cts = new CancellationTokenSource();
cts.CancelAfter(timeout);
void Cancel()
{
for (int i = 0; i < sockets.Length; ++i)
{
try
{
if (sockets[i] != null && !sockets[i].Connected)
{
sockets[i].Dispose();
sockets[i] = null;
}
}
catch { }
}
}
cts.Token.Register(Cancel);
Socket availableSocket = null;
for (int i = 0; i < sockets.Length; ++i)
{
try
{
if (ipAddresses[i] != null)
{
sockets[i] = new Socket(ipAddresses[i].AddressFamily, SocketType.Stream, ProtocolType.Tcp);
sockets[i].Connect(ipAddresses[i], port);
if (sockets[i] != null) // sockets[i] can be null if cancel callback is executed during connect()
{
if (sockets[i].Connected)
{
availableSocket = sockets[i];
break;
}
else
{
sockets[i].Dispose();
sockets[i] = null;
}
}
}
}
catch { }
}
return availableSocket;
}
private static Task<Socket> ParallelConnectAsync(IPAddress[] serverAddresses, int port)
{
if (serverAddresses == null)
{
throw new ArgumentNullException(nameof(serverAddresses));
}
if (serverAddresses.Length == 0)
{
throw new ArgumentOutOfRangeException(nameof(serverAddresses));
}
var sockets = new List<Socket>(serverAddresses.Length);
var connectTasks = new List<Task>(serverAddresses.Length);
var tcs = new TaskCompletionSource<Socket>();
var lastError = new StrongBox<Exception>();
var pendingCompleteCount = new StrongBox<int>(serverAddresses.Length);
foreach (IPAddress address in serverAddresses)
{
var socket = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
sockets.Add(socket);
// Start all connection tasks now, to prevent possible race conditions with
// calling ConnectAsync on disposed sockets.
try
{
connectTasks.Add(socket.ConnectAsync(address, port));
}
catch (Exception e)
{
connectTasks.Add(Task.FromException(e));
}
}
for (int i = 0; i < sockets.Count; i++)
{
ParallelConnectHelper(sockets[i], connectTasks[i], tcs, pendingCompleteCount, lastError, sockets);
}
return tcs.Task;
}
private static async void ParallelConnectHelper(
Socket socket,
Task connectTask,
TaskCompletionSource<Socket> tcs,
StrongBox<int> pendingCompleteCount,
StrongBox<Exception> lastError,
List<Socket> sockets)
{
bool success = false;
try
{
// Try to connect. If we're successful, store this task into the result task.
await connectTask.ConfigureAwait(false);
success = tcs.TrySetResult(socket);
if (success)
{
// Whichever connection completes the return task is responsible for disposing
// all of the sockets (except for whichever one is stored into the result task).
// This ensures that only one thread will attempt to dispose of a socket.
// This is also the closest thing we have to canceling connect attempts.
foreach (Socket otherSocket in sockets)
{
if (otherSocket != socket)
{
otherSocket.Dispose();
}
}
}
}
catch (Exception e)
{
// Store an exception to be published if no connection succeeds
Interlocked.Exchange(ref lastError.Value, e);
}
finally
{
// If we didn't successfully transition the result task to completed,
// then someone else did and they would have cleaned up, so there's nothing
// more to do. Otherwise, no one completed it yet or we failed; either way,
// see if we're the last outstanding connection, and if we are, try to complete
// the task, and if we're successful, it's our responsibility to dispose all of the sockets.
if (!success && Interlocked.Decrement(ref pendingCompleteCount.Value) == 0)
{
if (lastError.Value != null)
{
tcs.TrySetException(lastError.Value);
}
else
{
tcs.TrySetCanceled();
}
foreach (Socket s in sockets)
{
s.Dispose();
}
}
}
}
/// <summary>
/// Enable SSL
/// </summary>
public override uint EnableSsl(uint options)
{
_validateCert = (options & TdsEnums.SNI_SSL_VALIDATE_CERTIFICATE) != 0;
try
{
_sslStream.AuthenticateAsClient(_targetServer);
_sslOverTdsStream.FinishHandshake();
}
catch (AuthenticationException aue)
{
return ReportTcpSNIError(aue);
}
catch (InvalidOperationException ioe)
{
return ReportTcpSNIError(ioe);
}
_stream = _sslStream;
return TdsEnums.SNI_SUCCESS;
}
/// <summary>
/// Disable SSL
/// </summary>
public override void DisableSsl()
{
_sslStream.Dispose();
_sslStream = null;
_sslOverTdsStream.Dispose();
_sslOverTdsStream = null;
_stream = _tcpStream;
}
/// <summary>
/// Validate server certificate callback
/// </summary>
/// <param name="sender">Sender object</param>
/// <param name="cert">X.509 certificate</param>
/// <param name="chain">X.509 chain</param>
/// <param name="policyErrors">Policy errors</param>
/// <returns>True if certificate is valid</returns>
private bool ValidateServerCertificate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors policyErrors)
{
if (!_validateCert)
{
return true;
}
return SNICommon.ValidateSslServerCertificate(_targetServer, sender, cert, chain, policyErrors);
}
/// <summary>
/// Set buffer size
/// </summary>
/// <param name="bufferSize">Buffer size</param>
public override void SetBufferSize(int bufferSize)
{
_bufferSize = bufferSize;
}
/// <summary>
/// Send a packet synchronously
/// </summary>
/// <param name="packet">SNI packet</param>
/// <returns>SNI error code</returns>
public override uint Send(SNIPacket packet)
{
lock (this)
{
try
{
packet.WriteToStream(_stream);
return TdsEnums.SNI_SUCCESS;
}
catch (ObjectDisposedException ode)
{
return ReportTcpSNIError(ode);
}
catch (SocketException se)
{
return ReportTcpSNIError(se);
}
catch (IOException ioe)
{
return ReportTcpSNIError(ioe);
}
}
}
/// <summary>
/// Receive a packet synchronously
/// </summary>
/// <param name="packet">SNI packet</param>
/// <param name="timeoutInMilliseconds">Timeout in Milliseconds</param>
/// <returns>SNI error code</returns>
public override uint Receive(out SNIPacket packet, int timeoutInMilliseconds)
{
lock (this)
{
packet = null;
try
{
if (timeoutInMilliseconds > 0)
{
_socket.ReceiveTimeout = timeoutInMilliseconds;
}
else if (timeoutInMilliseconds == -1)
{ // SqlCient internally represents infinite timeout by -1, and for TcpClient this is translated to a timeout of 0
_socket.ReceiveTimeout = 0;
}
else
{
// otherwise it is timeout for 0 or less than -1
ReportTcpSNIError(0, SNICommon.ConnTimeoutError, string.Empty);
return TdsEnums.SNI_WAIT_TIMEOUT;
}
packet = new SNIPacket(_bufferSize);
packet.ReadFromStream(_stream);
if (packet.Length == 0)
{
var e = new Win32Exception();
return ReportErrorAndReleasePacket(packet, (uint)e.NativeErrorCode, 0, e.Message);
}
return TdsEnums.SNI_SUCCESS;
}
catch (ObjectDisposedException ode)
{
return ReportErrorAndReleasePacket(packet, ode);
}
catch (SocketException se)
{
return ReportErrorAndReleasePacket(packet, se);
}
catch (IOException ioe)
{
uint errorCode = ReportErrorAndReleasePacket(packet, ioe);
if (ioe.InnerException is SocketException && ((SocketException)(ioe.InnerException)).SocketErrorCode == SocketError.TimedOut)
{
errorCode = TdsEnums.SNI_WAIT_TIMEOUT;
}
return errorCode;
}
finally
{
_socket.ReceiveTimeout = 0;
}
}
}
/// <summary>
/// Set async callbacks
/// </summary>
/// <param name="receiveCallback">Receive callback</param>
/// <param name="sendCallback">Send callback</param>
/// <summary>
public override void SetAsyncCallbacks(SNIAsyncCallback receiveCallback, SNIAsyncCallback sendCallback)
{
_receiveCallback = receiveCallback;
_sendCallback = sendCallback;
}
/// <summary>
/// Send a packet asynchronously
/// </summary>
/// <param name="packet">SNI packet</param>
/// <param name="callback">Completion callback</param>
/// <returns>SNI error code</returns>
public override uint SendAsync(SNIPacket packet, bool disposePacketAfterSendAsync, SNIAsyncCallback callback = null)
{
SNIAsyncCallback cb = callback ?? _sendCallback;
lock (this)
{
packet.WriteToStreamAsync(_stream, cb, SNIProviders.TCP_PROV, disposePacketAfterSendAsync);
}
return TdsEnums.SNI_SUCCESS_IO_PENDING;
}
/// <summary>
/// Receive a packet asynchronously
/// </summary>
/// <param name="packet">SNI packet</param>
/// <returns>SNI error code</returns>
public override uint ReceiveAsync(ref SNIPacket packet)
{
packet = new SNIPacket(_bufferSize);
try
{
packet.ReadFromStreamAsync(_stream, _receiveCallback);
return TdsEnums.SNI_SUCCESS_IO_PENDING;
}
catch (Exception e) when (e is ObjectDisposedException || e is SocketException || e is IOException)
{
return ReportErrorAndReleasePacket(packet, e);
}
}
/// <summary>
/// Check SNI handle connection
/// </summary>
/// <param name="handle"></param>
/// <returns>SNI error status</returns>
public override uint CheckConnection()
{
try
{
// _socket.Poll method with argument SelectMode.SelectRead returns
// True : if Listen has been called and a connection is pending, or
// True : if data is available for reading, or
// True : if the connection has been closed, reset, or terminated, i.e no active connection.
// False : otherwise.
// _socket.Available property returns the number of bytes of data available to read.
//
// Since _socket.Connected alone doesn't guarantee if the connection is still active, we use it in
// combination with _socket.Poll method and _socket.Available == 0 check. When both of them
// return true we can safely determine that the connection is no longer active.
if (!_socket.Connected || (_socket.Poll(100, SelectMode.SelectRead) && _socket.Available == 0))
{
return TdsEnums.SNI_ERROR;
}
}
catch (SocketException se)
{
return ReportTcpSNIError(se);
}
catch (ObjectDisposedException ode)
{
return ReportTcpSNIError(ode);
}
return TdsEnums.SNI_SUCCESS;
}
private uint ReportTcpSNIError(Exception sniException)
{
_status = TdsEnums.SNI_ERROR;
return SNICommon.ReportSNIError(SNIProviders.TCP_PROV, SNICommon.InternalExceptionError, sniException);
}
private uint ReportTcpSNIError(uint nativeError, uint sniError, string errorMessage)
{
_status = TdsEnums.SNI_ERROR;
return SNICommon.ReportSNIError(SNIProviders.TCP_PROV, nativeError, sniError, errorMessage);
}
private uint ReportErrorAndReleasePacket(SNIPacket packet, Exception sniException)
{
if (packet != null)
{
packet.Release();
}
return ReportTcpSNIError(sniException);
}
private uint ReportErrorAndReleasePacket(SNIPacket packet, uint nativeError, uint sniError, string errorMessage)
{
if (packet != null)
{
packet.Release();
}
return ReportTcpSNIError(nativeError, sniError, errorMessage);
}
#if DEBUG
/// <summary>
/// Test handle for killing underlying connection
/// </summary>
public override void KillConnection()
{
_socket.Shutdown(SocketShutdown.Both);
}
#endif
}
}
| |
/*
* CP1257.cs - Baltic (Windows) code page.
*
* Copyright (c) 2002 Southern Storm Software, Pty Ltd
*
* 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
*/
// Generated from "ibm-5353.ucm".
namespace I18N.Other
{
using System;
using I18N.Common;
public class CP1257 : ByteEncoding
{
public CP1257()
: base(1257, ToChars, "Baltic (Windows)",
"iso-8859-4", "windows-1257", "windows-1257",
true, true, true, true, 1257)
{}
private static readonly char[] ToChars = {
'\u0000', '\u0001', '\u0002', '\u0003', '\u0004', '\u0005',
'\u0006', '\u0007', '\u0008', '\u0009', '\u000A', '\u000B',
'\u000C', '\u000D', '\u000E', '\u000F', '\u0010', '\u0011',
'\u0012', '\u0013', '\u0014', '\u0015', '\u0016', '\u0017',
'\u0018', '\u0019', '\u001A', '\u001B', '\u001C', '\u001D',
'\u001E', '\u001F', '\u0020', '\u0021', '\u0022', '\u0023',
'\u0024', '\u0025', '\u0026', '\u0027', '\u0028', '\u0029',
'\u002A', '\u002B', '\u002C', '\u002D', '\u002E', '\u002F',
'\u0030', '\u0031', '\u0032', '\u0033', '\u0034', '\u0035',
'\u0036', '\u0037', '\u0038', '\u0039', '\u003A', '\u003B',
'\u003C', '\u003D', '\u003E', '\u003F', '\u0040', '\u0041',
'\u0042', '\u0043', '\u0044', '\u0045', '\u0046', '\u0047',
'\u0048', '\u0049', '\u004A', '\u004B', '\u004C', '\u004D',
'\u004E', '\u004F', '\u0050', '\u0051', '\u0052', '\u0053',
'\u0054', '\u0055', '\u0056', '\u0057', '\u0058', '\u0059',
'\u005A', '\u005B', '\u005C', '\u005D', '\u005E', '\u005F',
'\u0060', '\u0061', '\u0062', '\u0063', '\u0064', '\u0065',
'\u0066', '\u0067', '\u0068', '\u0069', '\u006A', '\u006B',
'\u006C', '\u006D', '\u006E', '\u006F', '\u0070', '\u0071',
'\u0072', '\u0073', '\u0074', '\u0075', '\u0076', '\u0077',
'\u0078', '\u0079', '\u007A', '\u007B', '\u007C', '\u007D',
'\u007E', '\u007F', '\u20AC', '\u0081', '\u201A', '\u0083',
'\u201E', '\u2026', '\u2020', '\u2021', '\u0088', '\u2030',
'\u008A', '\u2039', '\u008C', '\u00A8', '\u02C7', '\u00B8',
'\u0090', '\u2018', '\u2019', '\u201C', '\u201D', '\u2022',
'\u2013', '\u2014', '\u0098', '\u2122', '\u009A', '\u203A',
'\u009C', '\u00AF', '\u02DB', '\u009F', '\u00A0', '\u003F',
'\u00A2', '\u00A3', '\u00A4', '\u003F', '\u00A6', '\u00A7',
'\u00D8', '\u00A9', '\u0156', '\u00AB', '\u00AC', '\u00AD',
'\u00AE', '\u00C6', '\u00B0', '\u00B1', '\u00B2', '\u00B3',
'\u00B4', '\u00B5', '\u00B6', '\u00B7', '\u00F8', '\u00B9',
'\u0157', '\u00BB', '\u00BC', '\u00BD', '\u00BE', '\u00E6',
'\u0104', '\u012E', '\u0100', '\u0106', '\u00C4', '\u00C5',
'\u0118', '\u0112', '\u010C', '\u00C9', '\u0179', '\u0116',
'\u0122', '\u0136', '\u012A', '\u013B', '\u0160', '\u0143',
'\u0145', '\u00D3', '\u014C', '\u00D5', '\u00D6', '\u00D7',
'\u0172', '\u0141', '\u015A', '\u016A', '\u00DC', '\u017B',
'\u017D', '\u00DF', '\u0105', '\u012F', '\u0101', '\u0107',
'\u00E4', '\u00E5', '\u0119', '\u0113', '\u010D', '\u00E9',
'\u017A', '\u0117', '\u0123', '\u0137', '\u012B', '\u013C',
'\u0161', '\u0144', '\u0146', '\u00F3', '\u014D', '\u00F5',
'\u00F6', '\u00F7', '\u0173', '\u0142', '\u015B', '\u016B',
'\u00FC', '\u017C', '\u017E', '\u02D9',
};
protected override void ToBytes(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
int ch;
while(charCount > 0)
{
ch = (int)(chars[charIndex++]);
if(ch >= 128) switch(ch)
{
case 0x0081:
case 0x0083:
case 0x0088:
case 0x008A:
case 0x008C:
case 0x0090:
case 0x0098:
case 0x009A:
case 0x009C:
case 0x009F:
case 0x00A0:
case 0x00A2:
case 0x00A3:
case 0x00A4:
case 0x00A6:
case 0x00A7:
case 0x00A9:
case 0x00AB:
case 0x00AC:
case 0x00AD:
case 0x00AE:
case 0x00B0:
case 0x00B1:
case 0x00B2:
case 0x00B3:
case 0x00B4:
case 0x00B5:
case 0x00B6:
case 0x00B7:
case 0x00B9:
case 0x00BB:
case 0x00BC:
case 0x00BD:
case 0x00BE:
case 0x00C4:
case 0x00C5:
case 0x00C9:
case 0x00D3:
case 0x00D5:
case 0x00D6:
case 0x00D7:
case 0x00DC:
case 0x00DF:
case 0x00E4:
case 0x00E5:
case 0x00E9:
case 0x00F3:
case 0x00F5:
case 0x00F6:
case 0x00F7:
case 0x00FC:
break;
case 0x00A8: ch = 0x8D; break;
case 0x00AF: ch = 0x9D; break;
case 0x00B8: ch = 0x8F; break;
case 0x00C6: ch = 0xAF; break;
case 0x00D8: ch = 0xA8; break;
case 0x00E6: ch = 0xBF; break;
case 0x00F8: ch = 0xB8; break;
case 0x0100: ch = 0xC2; break;
case 0x0101: ch = 0xE2; break;
case 0x0104: ch = 0xC0; break;
case 0x0105: ch = 0xE0; break;
case 0x0106: ch = 0xC3; break;
case 0x0107: ch = 0xE3; break;
case 0x010C: ch = 0xC8; break;
case 0x010D: ch = 0xE8; break;
case 0x0112: ch = 0xC7; break;
case 0x0113: ch = 0xE7; break;
case 0x0116: ch = 0xCB; break;
case 0x0117: ch = 0xEB; break;
case 0x0118: ch = 0xC6; break;
case 0x0119: ch = 0xE6; break;
case 0x0122: ch = 0xCC; break;
case 0x0123: ch = 0xEC; break;
case 0x012A: ch = 0xCE; break;
case 0x012B: ch = 0xEE; break;
case 0x012E: ch = 0xC1; break;
case 0x012F: ch = 0xE1; break;
case 0x0136: ch = 0xCD; break;
case 0x0137: ch = 0xED; break;
case 0x013B: ch = 0xCF; break;
case 0x013C: ch = 0xEF; break;
case 0x0141: ch = 0xD9; break;
case 0x0142: ch = 0xF9; break;
case 0x0143: ch = 0xD1; break;
case 0x0144: ch = 0xF1; break;
case 0x0145: ch = 0xD2; break;
case 0x0146: ch = 0xF2; break;
case 0x014C: ch = 0xD4; break;
case 0x014D: ch = 0xF4; break;
case 0x0156: ch = 0xAA; break;
case 0x0157: ch = 0xBA; break;
case 0x015A: ch = 0xDA; break;
case 0x015B: ch = 0xFA; break;
case 0x0160: ch = 0xD0; break;
case 0x0161: ch = 0xF0; break;
case 0x016A: ch = 0xDB; break;
case 0x016B: ch = 0xFB; break;
case 0x0172: ch = 0xD8; break;
case 0x0173: ch = 0xF8; break;
case 0x0179: ch = 0xCA; break;
case 0x017A: ch = 0xEA; break;
case 0x017B: ch = 0xDD; break;
case 0x017C: ch = 0xFD; break;
case 0x017D: ch = 0xDE; break;
case 0x017E: ch = 0xFE; break;
case 0x02C7: ch = 0x8E; break;
case 0x02D9: ch = 0xFF; break;
case 0x02DB: ch = 0x9E; break;
case 0x2013: ch = 0x96; break;
case 0x2014: ch = 0x97; break;
case 0x2018: ch = 0x91; break;
case 0x2019: ch = 0x92; break;
case 0x201A: ch = 0x82; break;
case 0x201C: ch = 0x93; break;
case 0x201D: ch = 0x94; break;
case 0x201E: ch = 0x84; break;
case 0x2020: ch = 0x86; break;
case 0x2021: ch = 0x87; break;
case 0x2022: ch = 0x95; break;
case 0x2026: ch = 0x85; break;
case 0x2030: ch = 0x89; break;
case 0x2039: ch = 0x8B; break;
case 0x203A: ch = 0x9B; break;
case 0x20AC: ch = 0x80; break;
case 0x2122: ch = 0x99; break;
default:
{
if(ch >= 0xFF01 && ch <= 0xFF5E)
ch -= 0xFEE0;
else
ch = 0x3F;
}
break;
}
bytes[byteIndex++] = (byte)ch;
--charCount;
}
}
protected override void ToBytes(String s, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
int ch;
while(charCount > 0)
{
ch = (int)(s[charIndex++]);
if(ch >= 128) switch(ch)
{
case 0x0081:
case 0x0083:
case 0x0088:
case 0x008A:
case 0x008C:
case 0x0090:
case 0x0098:
case 0x009A:
case 0x009C:
case 0x009F:
case 0x00A0:
case 0x00A2:
case 0x00A3:
case 0x00A4:
case 0x00A6:
case 0x00A7:
case 0x00A9:
case 0x00AB:
case 0x00AC:
case 0x00AD:
case 0x00AE:
case 0x00B0:
case 0x00B1:
case 0x00B2:
case 0x00B3:
case 0x00B4:
case 0x00B5:
case 0x00B6:
case 0x00B7:
case 0x00B9:
case 0x00BB:
case 0x00BC:
case 0x00BD:
case 0x00BE:
case 0x00C4:
case 0x00C5:
case 0x00C9:
case 0x00D3:
case 0x00D5:
case 0x00D6:
case 0x00D7:
case 0x00DC:
case 0x00DF:
case 0x00E4:
case 0x00E5:
case 0x00E9:
case 0x00F3:
case 0x00F5:
case 0x00F6:
case 0x00F7:
case 0x00FC:
break;
case 0x00A8: ch = 0x8D; break;
case 0x00AF: ch = 0x9D; break;
case 0x00B8: ch = 0x8F; break;
case 0x00C6: ch = 0xAF; break;
case 0x00D8: ch = 0xA8; break;
case 0x00E6: ch = 0xBF; break;
case 0x00F8: ch = 0xB8; break;
case 0x0100: ch = 0xC2; break;
case 0x0101: ch = 0xE2; break;
case 0x0104: ch = 0xC0; break;
case 0x0105: ch = 0xE0; break;
case 0x0106: ch = 0xC3; break;
case 0x0107: ch = 0xE3; break;
case 0x010C: ch = 0xC8; break;
case 0x010D: ch = 0xE8; break;
case 0x0112: ch = 0xC7; break;
case 0x0113: ch = 0xE7; break;
case 0x0116: ch = 0xCB; break;
case 0x0117: ch = 0xEB; break;
case 0x0118: ch = 0xC6; break;
case 0x0119: ch = 0xE6; break;
case 0x0122: ch = 0xCC; break;
case 0x0123: ch = 0xEC; break;
case 0x012A: ch = 0xCE; break;
case 0x012B: ch = 0xEE; break;
case 0x012E: ch = 0xC1; break;
case 0x012F: ch = 0xE1; break;
case 0x0136: ch = 0xCD; break;
case 0x0137: ch = 0xED; break;
case 0x013B: ch = 0xCF; break;
case 0x013C: ch = 0xEF; break;
case 0x0141: ch = 0xD9; break;
case 0x0142: ch = 0xF9; break;
case 0x0143: ch = 0xD1; break;
case 0x0144: ch = 0xF1; break;
case 0x0145: ch = 0xD2; break;
case 0x0146: ch = 0xF2; break;
case 0x014C: ch = 0xD4; break;
case 0x014D: ch = 0xF4; break;
case 0x0156: ch = 0xAA; break;
case 0x0157: ch = 0xBA; break;
case 0x015A: ch = 0xDA; break;
case 0x015B: ch = 0xFA; break;
case 0x0160: ch = 0xD0; break;
case 0x0161: ch = 0xF0; break;
case 0x016A: ch = 0xDB; break;
case 0x016B: ch = 0xFB; break;
case 0x0172: ch = 0xD8; break;
case 0x0173: ch = 0xF8; break;
case 0x0179: ch = 0xCA; break;
case 0x017A: ch = 0xEA; break;
case 0x017B: ch = 0xDD; break;
case 0x017C: ch = 0xFD; break;
case 0x017D: ch = 0xDE; break;
case 0x017E: ch = 0xFE; break;
case 0x02C7: ch = 0x8E; break;
case 0x02D9: ch = 0xFF; break;
case 0x02DB: ch = 0x9E; break;
case 0x2013: ch = 0x96; break;
case 0x2014: ch = 0x97; break;
case 0x2018: ch = 0x91; break;
case 0x2019: ch = 0x92; break;
case 0x201A: ch = 0x82; break;
case 0x201C: ch = 0x93; break;
case 0x201D: ch = 0x94; break;
case 0x201E: ch = 0x84; break;
case 0x2020: ch = 0x86; break;
case 0x2021: ch = 0x87; break;
case 0x2022: ch = 0x95; break;
case 0x2026: ch = 0x85; break;
case 0x2030: ch = 0x89; break;
case 0x2039: ch = 0x8B; break;
case 0x203A: ch = 0x9B; break;
case 0x20AC: ch = 0x80; break;
case 0x2122: ch = 0x99; break;
default:
{
if(ch >= 0xFF01 && ch <= 0xFF5E)
ch -= 0xFEE0;
else
ch = 0x3F;
}
break;
}
bytes[byteIndex++] = (byte)ch;
--charCount;
}
}
}; // class CP1257
public class ENCwindows_1257 : CP1257
{
public ENCwindows_1257() : base() {}
}; // class ENCwindows_1257
}; // namespace I18N.Other
| |
//==========================================================================================
//
// OpenNETCF.Windows.Forms.Key
// Copyright (c) 2003, OpenNETCF.org
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the OpenNETCF.org Shared Source License.
//
// 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 OpenNETCF.org Shared Source License
// for more details.
//
// You should have received a copy of the OpenNETCF.org Shared Source License
// along with this library; if not, email licensing@opennetcf.org to request a copy.
//
// If you wish to contact the OpenNETCF Advisory Board to discuss licensing, please
// email licensing@opennetcf.org.
//
// For general enquiries, email enquiries@opennetcf.org or visit our website at:
// http://www.opennetcf.org
//
// !!! A HUGE thank-you goes out to Casey Chesnut for supplying this class library !!!
// !!! You can contact Casey at http://www.brains-n-brawn.com !!!
//
//==========================================================================================
using System;
namespace FlickrNet.Security.Cryptography.NativeMethods
{
internal class Key
{
public static IntPtr ImportSessionKey(IntPtr prov, Calg algId, byte [] rawKey, bool reverse)
{
if(reverse == true)
Array.Reverse(rawKey, 0, rawKey.Length);
IntPtr nullKey = Key.ImportKey(prov, NullKey.PrivateKeyWithExponentOfOne, IntPtr.Zero, GenKeyParam.EXPORTABLE);
IntPtr key = Key.GenKey(prov, algId, GenKeyParam.EXPORTABLE);
byte [] baSessKey = Key.ExportKey(key, nullKey, KeyBlob.SIMPLEBLOB);
Key.DestroyKey(key);
Buffer.BlockCopy(rawKey, 0, baSessKey, 12, rawKey.Length);
key = Key.ImportKey(prov, baSessKey, IntPtr.Zero, GenKeyParam.EXPORTABLE);
Key.DestroyKey(nullKey);
return key;
}
public static byte [] ExportSessionKey(IntPtr prov, IntPtr key, int length, bool reverse)
{
IntPtr nullKey = Key.ImportKey(prov, NullKey.PrivateKeyWithExponentOfOne, IntPtr.Zero, GenKeyParam.EXPORTABLE);
byte [] baSessKey = Key.ExportKey(key, nullKey, KeyBlob.SIMPLEBLOB);
//uint bitLen = BitConverter.ToUInt16(baSessKey, 9);
//uint byteLen = bitLen / 8;
byte [] baExcKey = new byte[length]; //byteLen
Buffer.BlockCopy(baSessKey, 12, baExcKey, 0, baExcKey.Length);
if(reverse == true)
Array.Reverse(baExcKey, 0, baExcKey.Length);
Key.DestroyKey(nullKey);
return baExcKey;
}
public static void SetIv(IntPtr key, byte [] Iv)
{
SetKeyParam(key, KeyParam.IV, Iv);
}
/// <summary>
/// BAD_DATA
/// </summary>
public static void SetPaddingMode(IntPtr key, PaddingMode pm)
{
uint iPm = (uint) pm;
byte [] ba = BitConverter.GetBytes(iPm);
SetKeyParam(key, KeyParam.PADDING, ba);
}
public static PaddingMode GetPaddingMode(IntPtr key)
{
byte [] ba = GetKeyParam(key, KeyParam.PADDING);
uint iPm = BitConverter.ToUInt32(ba, 0);
PaddingMode pm = (PaddingMode) iPm;
return pm;
}
public static CipherMode GetCipherMode(IntPtr key)
{
byte [] ba = GetKeyParam(key, KeyParam.MODE);
uint iCm = BitConverter.ToUInt32(ba, 0);
CipherMode cm = (CipherMode) iCm;
return cm;
}
public static int GetBlockSize(IntPtr key)
{
byte [] ba = GetKeyParam(key, KeyParam.BLOCKLEN);
return BitConverter.ToInt32(ba, 0);
}
public static byte [] GetSalt(IntPtr key)
{
byte [] ba = GetKeyParam(key, KeyParam.SALT);
return ba;
}
public static byte [] GetIv(IntPtr key)
{
byte [] ba = GetKeyParam(key, KeyParam.IV);
return ba;
}
public static int GetKeyLength(IntPtr key)
{
byte [] ba = GetKeyParam(key, KeyParam.KEYLEN);
return BitConverter.ToInt32(ba, 0);
}
//algId can also be AT_KEYEXCHANGE = 1, AT_SIGNATURE = 2,
public static IntPtr GenKey(IntPtr prov, Calg algId, GenKeyParam flags)
{
IntPtr key;
bool retVal = Crypto.CryptGenKey(prov, (uint) algId, (uint) flags, out key);
ErrCode ec = Error.HandleRetVal(retVal);
return key;
}
public static IntPtr GetUserKey(IntPtr prov, KeySpec keySpec)
{
IntPtr key;
bool retVal = Crypto.CryptGetUserKey(prov, (uint) keySpec, out key);
ErrCode ec = Error.HandleRetVal(retVal, ErrCode.NTE_NO_KEY);
if(ec == ErrCode.NTE_NO_KEY) //2148073485
{
retVal = Crypto.CryptGenKey(prov, (uint)keySpec, (uint)GenKeyParam.EXPORTABLE, out key);
ec = Error.HandleRetVal(retVal);
//is this necessary? why not just use key from GenKey?
//retVal = Crypto.CryptGetUserKey(prov, (uint) keySpec, out key);
}
if(key == IntPtr.Zero)
throw new Exception(ec.ToString());
return key;
}
public static IntPtr DeriveKey(IntPtr prov, Calg algId, IntPtr hash, GenKeyParam flags)
{
IntPtr key;
bool retVal = Crypto.CryptDeriveKey(prov, (uint)algId, hash, (uint)flags, out key);
ErrCode ec = Error.HandleRetVal(retVal);
return key;
}
public static byte[] GetKeyParam(IntPtr key, KeyParam param)
{
byte[] data = new byte[0];
uint dataLen = 0;
uint flags = 0;
//length
bool retVal = Crypto.CryptGetKeyParam(key, (uint)param, data, ref dataLen, flags);
ErrCode ec = Error.HandleRetVal(retVal, ErrCode.MORE_DATA);
if(ec == ErrCode.MORE_DATA)
{
//data
data = new byte[dataLen];
retVal = Crypto.CryptGetKeyParam(key, (uint)param, data, ref dataLen, flags);
ec = Error.HandleRetVal(retVal);
}
return data;
}
public static void SetKeyParam(IntPtr key, KeyParam param, byte[] data)
{
uint flags = 0;
bool retVal = Crypto.CryptSetKeyParam(key, (uint) param, data, flags);
ErrCode ec = Error.HandleRetVal(retVal);
}
/// <summary>
/// INVALID_PARAMETER
/// </summary>
public static IntPtr DuplicateKey(IntPtr key)
{
uint reserved = 0;
uint flags = 0;
IntPtr outKey;
bool retVal = Crypto.CryptDuplicateKey(key, ref reserved, flags, out outKey);
ErrCode ec = Error.HandleRetVal(retVal);
return outKey;
}
public static void DestroyKey(IntPtr key)
{
if(key != IntPtr.Zero)
{
bool retVal = Crypto.CryptDestroyKey(key);
ErrCode ec = Error.HandleRetVal(retVal); //dont exception
}
}
public static byte [] ExportKey(IntPtr key, IntPtr pubKey, KeyBlob blobType)
{
uint flags = 0;
//byte[] data = new byte[0]; //did not work for PROV_DSS_DH
byte[] data = null;
uint dataLen = 0;
//length
bool retVal = Crypto.CryptExportKey(key, pubKey, (uint) blobType, flags, data, ref dataLen);
//ErrCode ec = Error.HandleRetVal(retVal, ErrCode.MORE_DATA);
//if(ec == ErrCode.MORE_DATA)
ErrCode ec = Error.HandleRetVal(retVal);
if(dataLen != 0)
{
//data
data = new byte[dataLen];
retVal = Crypto.CryptExportKey(key, pubKey, (uint) blobType, flags, data, ref dataLen);
ec = Error.HandleRetVal(retVal);
}
return data;
}
public static IntPtr ImportKey(IntPtr prov, byte[] keyBlob, IntPtr pubKey, GenKeyParam param)
{
uint keyLen = (uint) keyBlob.Length;
IntPtr key;
bool retVal = Crypto.CryptImportKey(prov, keyBlob, keyLen, pubKey, (uint) param, out key);
ErrCode ec = Error.HandleRetVal(retVal);
return key;
}
}
}
| |
/*
Copyright (c) 2017 Ahmed Kh. Zamil
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.Threading;
using System.Collections.Generic;
using Esiur.Data;
using Esiur.Misc;
using Esiur.Core;
using Esiur.Net.Sockets;
using Esiur.Resource;
using System.Threading.Tasks;
using System.Diagnostics;
namespace Esiur.Net;
public abstract class NetworkServer<TConnection> : IDestructible where TConnection : NetworkConnection, new()
{
//private bool isRunning;
private Sockets.ISocket listener;
public AutoList<TConnection, NetworkServer<TConnection>> Connections { get; internal set; }
private Thread thread;
//protected abstract void DataReceived(TConnection sender, NetworkBuffer data);
//protected abstract void ClientConnected(TConnection sender);
//protected abstract void ClientDisconnected(TConnection sender);
private Timer timer;
//public KeyList<string, TSession> Sessions = new KeyList<string, TSession>();
public event DestroyedEvent OnDestroy;
//public AutoList<TConnection, NetworkServer<TConnection>> Connections => connections;
private void MinuteThread(object state)
{
List<TConnection> ToBeClosed = null;
lock (Connections.SyncRoot)
{
foreach (TConnection c in Connections)
{
if (DateTime.Now.Subtract(c.LastAction).TotalSeconds >= Timeout)
{
if (ToBeClosed == null)
ToBeClosed = new List<TConnection>();
ToBeClosed.Add(c);
}
}
}
if (ToBeClosed != null)
{
//Console.WriteLine("Term: " + ToBeClosed.Count + " " + this.listener.LocalEndPoint.ToString());
foreach (TConnection c in ToBeClosed)
c.Close();// CloseAndWait();
ToBeClosed.Clear();
ToBeClosed = null;
}
}
public void Start(Sockets.ISocket socket)//, uint timeout, uint clock)
{
if (listener != null)
return;
Connections = new AutoList<TConnection, NetworkServer<TConnection>>(this);
if (Timeout > 0 & Clock > 0)
{
timer = new Timer(MinuteThread, null, TimeSpan.FromMinutes(0), TimeSpan.FromSeconds(Clock));
}
listener = socket;
// Start accepting
//var r = listener.Accept();
//r.Then(NewConnection);
//r.timeout?.Dispose();
//var rt = listener.Accept().Then()
thread = new Thread(new ThreadStart(() =>
{
while (true)
{
try
{
var s = listener.Accept();
if (s == null)
{
Console.Write("sock == null");
return;
}
Console.WriteLine("New Socket ... " + DateTime.Now);
var c = new TConnection();
//c.OnClose += ClientDisconnectedEventReceiver;
c.Assign(s);
Add(c);
//Connections.Add(c);
try
{
//ClientConnected(c);
ClientConnected(c);
//NetworkConnect(c);
}
catch
{
// something wrong with the child.
}
s.Begin();
// Accept more
//listener.Accept().Then(NewConnection);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}));
thread.Start();
}
[Attribute]
public uint Timeout
{
get;
set;
}
[Attribute]
public uint Clock
{
get;
set;
}
public void Stop()
{
var port = 0;
try
{
if (listener != null)
{
port = listener.LocalEndPoint.Port;
listener.Close();
}
// wait until the listener stops
//while (isRunning)
//{
// Thread.Sleep(100);
//}
//Console.WriteLine("Listener stopped");
var cons = Connections.ToArray();
//lock (connections.SyncRoot)
//{
foreach (TConnection con in cons)
con.Close();
//}
//Console.WriteLine("Sockets Closed");
//while (connections.Count > 0)
//{
// Console.WriteLine("Waiting... " + connections.Count);
// Thread.Sleep(1000);
//}
}
finally
{
Console.WriteLine("Server@{0} is down", port);
}
}
public virtual void Remove(TConnection connection)
{
//connection.OnDataReceived -= OnDataReceived;
//connection.OnConnect -= OnClientConnect;
connection.OnClose -= ClientDisconnectedEventReceiver;
Connections.Remove(connection);
}
public virtual void Add(TConnection connection)
{
//connection.OnDataReceived += OnDataReceived;
//connection.OnConnect += OnClientConnect;
connection.OnClose += ClientDisconnectedEventReceiver;// OnClientClose;
Connections.Add(connection);
}
public bool IsRunning
{
get
{
return listener.State == SocketState.Listening;
//isRunning;
}
}
//public void OnDataReceived(ISocket sender, NetworkBuffer data)
//{
// DataReceived((TConnection)sender, data);
//}
//public void OnClientConnect(ISocket sender)
//{
// if (sender == null)
// return;
// if (sender.RemoteEndPoint == null || sender.LocalEndPoint == null)
// { }
// //Console.WriteLine("NULL");
// else
// Global.Log("Connections", LogType.Debug, sender.RemoteEndPoint.Address.ToString()
// + "->" + sender.LocalEndPoint.Port + " at " + DateTime.UtcNow.ToString("d")
// + " " + DateTime.UtcNow.ToString("d"), false);
// // Console.WriteLine("Connected " + sender.RemoteEndPoint.ToString());
// ClientConnected((TConnection)sender);
//}
//public void OnClientClose(ISocket sender)
//{
//}
public void Destroy()
{
Stop();
OnDestroy?.Invoke(this);
}
private void ClientDisconnectedEventReceiver(NetworkConnection connection)
{
try
{
var con = connection as TConnection;
con.Destroy();
// con.OnClose -= ClientDisconnectedEventReceiver;
Remove(con);
//Connections.Remove(con);
ClientDisconnected(con);
//RemoveConnection((TConnection)sender);
//connections.Remove(sender)
//ClientDisconnected((TConnection)sender);
}
catch (Exception ex)
{
Global.Log("NetworkServer:OnClientDisconnect", LogType.Error, ex.ToString());
}
}
protected abstract void ClientDisconnected(TConnection connection);
protected abstract void ClientConnected(TConnection connection);
~NetworkServer()
{
Stop();
listener = null;
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="SoapProtocolReflector.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.Services.Description {
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml;
using System.Xml.Serialization;
using System.Xml.Schema;
using System.Collections;
using System;
using System.Reflection;
using System.Web.Services.Configuration;
internal class SoapProtocolReflector : ProtocolReflector {
// SoapProtocolInfo protocolInfo;
ArrayList mappings = new ArrayList();
SoapExtensionReflector[] extensions;
SoapReflectedMethod soapMethod;
internal override WsiProfiles ConformsTo {
get { return WsiProfiles.BasicProfile1_1; }
}
public override string ProtocolName {
get { return "Soap"; }
}
internal SoapReflectedMethod SoapMethod {
get { return soapMethod; }
}
internal SoapReflectionImporter SoapImporter {
get {
SoapReflectionImporter soapImporter = ReflectionContext[typeof(SoapReflectionImporter)] as SoapReflectionImporter;
if (soapImporter == null) {
soapImporter = SoapReflector.CreateSoapImporter(DefaultNamespace, SoapReflector.ServiceDefaultIsEncoded(ServiceType));
ReflectionContext[typeof(SoapReflectionImporter)] = soapImporter;
}
return soapImporter;
}
}
internal SoapSchemaExporter SoapExporter {
get {
SoapSchemaExporter soapExporter = ReflectionContext[typeof(SoapSchemaExporter)] as SoapSchemaExporter;
if (soapExporter == null) {
soapExporter = new SoapSchemaExporter(ServiceDescription.Types.Schemas);
ReflectionContext[typeof(SoapSchemaExporter)] = soapExporter;
}
return soapExporter;
}
}
protected override bool ReflectMethod() {
soapMethod = ReflectionContext[Method] as SoapReflectedMethod;
if (soapMethod == null) {
soapMethod = SoapReflector.ReflectMethod(Method, false, ReflectionImporter, SoapImporter, DefaultNamespace);
ReflectionContext[Method] = soapMethod;
soapMethod.portType = Binding != null ? Binding.Type : null;
}
WebMethodAttribute methodAttr = Method.MethodAttribute;
OperationBinding.Extensions.Add(CreateSoapOperationBinding(soapMethod.rpc ? SoapBindingStyle.Rpc : SoapBindingStyle.Document, soapMethod.action));
CreateMessage(soapMethod.rpc, soapMethod.use, soapMethod.paramStyle, InputMessage, OperationBinding.Input, soapMethod.requestMappings);
if (!soapMethod.oneWay)
CreateMessage(soapMethod.rpc, soapMethod.use, soapMethod.paramStyle, OutputMessage, OperationBinding.Output, soapMethod.responseMappings);
CreateHeaderMessages(soapMethod.name, soapMethod.use, soapMethod.inHeaderMappings, soapMethod.outHeaderMappings, soapMethod.headers, soapMethod.rpc);
if (soapMethod.rpc && soapMethod.use == SoapBindingUse.Encoded && soapMethod.methodInfo.OutParameters.Length > 0)
Operation.ParameterOrder = GetParameterOrder(soapMethod.methodInfo);
AllowExtensionsToReflectMethod();
return true;
}
protected override void ReflectDescription() {
AllowExtensionsToReflectDescription();
}
void CreateHeaderMessages(string methodName, SoapBindingUse use, XmlMembersMapping inHeaderMappings, XmlMembersMapping outHeaderMappings, SoapReflectedHeader[] headers, bool rpc) {
//
if (use == SoapBindingUse.Encoded) {
SoapExporter.ExportMembersMapping(inHeaderMappings, false);
if (outHeaderMappings != null)
SoapExporter.ExportMembersMapping(outHeaderMappings, false);
}
else {
SchemaExporter.ExportMembersMapping(inHeaderMappings);
if (outHeaderMappings != null)
SchemaExporter.ExportMembersMapping(outHeaderMappings);
}
CodeIdentifiers identifiers = new CodeIdentifiers();
int inCount = 0, outCount = 0;
for (int i = 0; i < headers.Length; i++) {
SoapReflectedHeader soapHeader = headers[i];
if (!soapHeader.custom) continue;
XmlMemberMapping member;
if ((soapHeader.direction & SoapHeaderDirection.In) != 0) {
member = inHeaderMappings[inCount++];
if (soapHeader.direction != SoapHeaderDirection.In)
outCount++;
}
else {
member = outHeaderMappings[outCount++];
}
MessagePart part = new MessagePart();
part.Name = member.XsdElementName;
if (use == SoapBindingUse.Encoded)
part.Type = new XmlQualifiedName(member.TypeName, member.TypeNamespace);
else
part.Element = new XmlQualifiedName(member.XsdElementName, member.Namespace);
Message message = new Message();
message.Name = identifiers.AddUnique(methodName + part.Name, message);
message.Parts.Add(part);
HeaderMessages.Add(message);
ServiceDescriptionFormatExtension soapHeaderBinding = CreateSoapHeaderBinding(new XmlQualifiedName(message.Name, Binding.ServiceDescription.TargetNamespace), part.Name, rpc ? member.Namespace : null, use);
if ((soapHeader.direction & SoapHeaderDirection.In) != 0)
OperationBinding.Input.Extensions.Add(soapHeaderBinding);
if ((soapHeader.direction & SoapHeaderDirection.Out) != 0)
OperationBinding.Output.Extensions.Add(soapHeaderBinding);
if ((soapHeader.direction & SoapHeaderDirection.Fault) != 0) {
if (soapMethod.IsClaimsConformance) {
throw new InvalidOperationException(Res.GetString(Res.BPConformanceHeaderFault, soapMethod.methodInfo.ToString(), soapMethod.methodInfo.DeclaringType.FullName, "Direction", typeof(SoapHeaderDirection).Name, SoapHeaderDirection.Fault.ToString()));
}
OperationBinding.Output.Extensions.Add(soapHeaderBinding);
}
}
}
void CreateMessage(bool rpc, SoapBindingUse use, SoapParameterStyle paramStyle, Message message, MessageBinding messageBinding, XmlMembersMapping members) {
bool wrapped = paramStyle != SoapParameterStyle.Bare;
if (use == SoapBindingUse.Encoded)
CreateEncodedMessage(message, messageBinding, members, wrapped && !rpc);
else
CreateLiteralMessage(message, messageBinding, members, wrapped && !rpc, rpc);
}
void CreateEncodedMessage(Message message, MessageBinding messageBinding, XmlMembersMapping members, bool wrapped) {
SoapExporter.ExportMembersMapping(members, wrapped);
if (wrapped) {
MessagePart part = new MessagePart();
part.Name = "parameters";
part.Type = new XmlQualifiedName(members.TypeName, members.TypeNamespace);
message.Parts.Add(part);
}
else {
for (int i = 0; i < members.Count; i++) {
XmlMemberMapping member = members[i];
MessagePart part = new MessagePart();
part.Name = member.XsdElementName;
part.Type = new XmlQualifiedName(member.TypeName, member.TypeNamespace);
message.Parts.Add(part);
}
}
messageBinding.Extensions.Add(CreateSoapBodyBinding(SoapBindingUse.Encoded, members.Namespace));
}
void CreateLiteralMessage(Message message, MessageBinding messageBinding, XmlMembersMapping members, bool wrapped, bool rpc) {
if (members.Count == 1 && members[0].Any && members[0].ElementName.Length == 0 && !wrapped) {
string typeName = SchemaExporter.ExportAnyType(members[0].Namespace);
MessagePart part = new MessagePart();
part.Name = members[0].MemberName;
part.Type = new XmlQualifiedName(typeName, members[0].Namespace);
message.Parts.Add(part);
}
else {
SchemaExporter.ExportMembersMapping(members, !rpc);
if (wrapped) {
MessagePart part = new MessagePart();
part.Name = "parameters";
part.Element = new XmlQualifiedName(members.XsdElementName, members.Namespace);
message.Parts.Add(part);
}
else {
for (int i = 0; i < members.Count; i++) {
XmlMemberMapping member = members[i];
MessagePart part = new MessagePart();
if (rpc) {
// Generate massage part with the type attribute
if (member.TypeName == null || member.TypeName.Length == 0) {
throw new InvalidOperationException(Res.GetString(Res.WsdlGenRpcLitAnonimousType, Method.DeclaringType.Name, Method.Name, member.MemberName));
}
part.Name = member.XsdElementName;
part.Type = new XmlQualifiedName(member.TypeName, member.TypeNamespace);
}
else {
part.Name = XmlConvert.EncodeLocalName(member.MemberName);
part.Element = new XmlQualifiedName(member.XsdElementName, member.Namespace);
}
message.Parts.Add(part);
}
}
}
messageBinding.Extensions.Add(CreateSoapBodyBinding(SoapBindingUse.Literal, rpc ? members.Namespace : null));
}
static string[] GetParameterOrder(LogicalMethodInfo methodInfo) {
ParameterInfo[] parameters = methodInfo.Parameters;
string[] parameterOrder = new string[parameters.Length];
for (int i = 0; i < parameters.Length; i++) {
parameterOrder[i] = parameters[i].Name;
}
return parameterOrder;
}
protected override string ReflectMethodBinding() {
return SoapReflector.GetSoapMethodBinding(Method);
}
protected override void BeginClass() {
if (Binding != null) {
SoapBindingStyle style;
if (SoapReflector.GetSoapServiceAttribute(ServiceType) is SoapRpcServiceAttribute)
style = SoapBindingStyle.Rpc;
else
style = SoapBindingStyle.Document;
Binding.Extensions.Add(CreateSoapBinding(style));
SoapReflector.IncludeTypes(Methods, SoapImporter);
}
Port.Extensions.Add(CreateSoapAddressBinding(ServiceUrl));
}
void AllowExtensionsToReflectMethod() {
if (extensions == null) {
TypeElementCollection extensionTypes = WebServicesSection.Current.SoapExtensionReflectorTypes;
extensions = new SoapExtensionReflector[extensionTypes.Count];
for (int i = 0; i < extensions.Length; i++) {
SoapExtensionReflector extension = (SoapExtensionReflector)Activator.CreateInstance(extensionTypes[i].Type);
extension.ReflectionContext = this;
extensions[i] = extension;
}
}
foreach (SoapExtensionReflector extension in extensions) {
extension.ReflectMethod();
}
}
void AllowExtensionsToReflectDescription() {
if (extensions == null) {
TypeElementCollection extensionTypes = WebServicesSection.Current.SoapExtensionReflectorTypes;
extensions = new SoapExtensionReflector[extensionTypes.Count];
for (int i = 0; i < extensions.Length; i++) {
SoapExtensionReflector extension = (SoapExtensionReflector)Activator.CreateInstance(extensionTypes[i].Type);
extension.ReflectionContext = this;
extensions[i] = extension;
}
}
foreach (SoapExtensionReflector extension in extensions) {
extension.ReflectDescription();
}
}
protected virtual SoapBinding CreateSoapBinding(SoapBindingStyle style) {
SoapBinding soapBinding = new SoapBinding();
soapBinding.Transport = SoapBinding.HttpTransport;
soapBinding.Style = style;
return soapBinding;
}
protected virtual SoapAddressBinding CreateSoapAddressBinding(string serviceUrl) {
SoapAddressBinding soapAddress = new SoapAddressBinding();
soapAddress.Location = serviceUrl;
if (this.UriFixups != null)
{
this.UriFixups.Add(delegate(Uri current)
{
soapAddress.Location = DiscoveryServerType.CombineUris(current, soapAddress.Location);
});
}
return soapAddress;
}
protected virtual SoapOperationBinding CreateSoapOperationBinding(SoapBindingStyle style, string action) {
SoapOperationBinding soapOperation = new SoapOperationBinding();
soapOperation.SoapAction = action;
soapOperation.Style = style;
return soapOperation;
}
protected virtual SoapBodyBinding CreateSoapBodyBinding(SoapBindingUse use, string ns) {
SoapBodyBinding soapBodyBinding = new SoapBodyBinding();
soapBodyBinding.Use = use;
if (use == SoapBindingUse.Encoded)
soapBodyBinding.Encoding = Soap.Encoding;
soapBodyBinding.Namespace = ns;
return soapBodyBinding;
}
protected virtual SoapHeaderBinding CreateSoapHeaderBinding(XmlQualifiedName message, string partName, SoapBindingUse use) {
return CreateSoapHeaderBinding(message, partName, null, use);
}
protected virtual SoapHeaderBinding CreateSoapHeaderBinding(XmlQualifiedName message, string partName, string ns, SoapBindingUse use) {
SoapHeaderBinding soapHeaderBinding = new SoapHeaderBinding();
soapHeaderBinding.Message = message;
soapHeaderBinding.Part = partName;
soapHeaderBinding.Use = use;
if (use == SoapBindingUse.Encoded) {
soapHeaderBinding.Encoding = Soap.Encoding;
soapHeaderBinding.Namespace = ns;
}
return soapHeaderBinding;
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// 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 OneGet.Sdk {
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Security;
using Resources;
public abstract class Request {
private Dictionary<string, string[]> _options;
private string[] _packageSources = null;
#region OneGet Interfaces
public interface IProviderServices {
bool IsElevated { get; }
string GetCanonicalPackageId(string providerName, string packageName, string version);
string ParseProviderName(string canonicalPackageId);
string ParsePackageName(string canonicalPackageId);
string ParsePackageVersion(string canonicalPackageId);
void DownloadFile(Uri remoteLocation, string localFilename, Request requestObject);
bool IsSupportedArchive(string localFilename, Request requestObject);
IEnumerable<string> UnpackArchive(string localFilename, string destinationFolder, Request requestObject);
void AddPinnedItemToTaskbar(string item, Request requestObject);
void RemovePinnedItemFromTaskbar(string item, Request requestObject);
void CreateShortcutLink(string linkPath, string targetPath, string description, string workingDirectory, string arguments, Request requestObject);
void SetEnvironmentVariable(string variable, string value, string context, Request requestObject);
void RemoveEnvironmentVariable(string variable, string context, Request requestObject);
void CopyFile(string sourcePath, string destinationPath, Request requestObject);
void Delete(string path, Request requestObject);
void DeleteFolder(string folder, Request requestObject);
void CreateFolder(string folder, Request requestObject);
void DeleteFile(string filename, Request requestObject);
string GetKnownFolder(string knownFolder, Request requestObject);
string CanonicalizePath(string text, string currentDirectory);
bool FileExists(string path);
bool DirectoryExists(string path);
bool Install(string fileName, string additionalArgs, Request requestObject);
bool IsSignedAndTrusted(string filename, Request requestObject);
bool ExecuteElevatedAction(string provider, string payload, Request requestObject);
}
public interface IPackageProvider {
}
public interface IPackageManagementService {
int Version { get; }
IEnumerable<string> ProviderNames { get; }
IEnumerable<string> AllProviderNames { get; }
IEnumerable<IPackageProvider> PackageProviders { get; }
IEnumerable<IPackageProvider> SelectProvidersWithFeature(string featureName);
IEnumerable<IPackageProvider> SelectProvidersWithFeature(string featureName, string value);
IEnumerable<IPackageProvider> SelectProviders(string providerName, Request requestObject);
bool RequirePackageProvider(string requestor, string packageProviderName, string minimumVersion, Request requestObject);
}
#endregion
#region core-apis
public abstract dynamic PackageManagementService {get;}
public abstract IProviderServices ProviderServices {get;}
#endregion
#region copy host-apis
/* Synced/Generated code =================================================== */
public abstract bool IsCanceled {get;}
public abstract string GetMessageString(string messageText, string defaultText);
public abstract bool Warning(string messageText);
public abstract bool Error(string id, string category, string targetObjectValue, string messageText);
public abstract bool Message(string messageText);
public abstract bool Verbose(string messageText);
public abstract bool Debug(string messageText);
public abstract int StartProgress(int parentActivityId, string messageText);
public abstract bool Progress(int activityId, int progressPercentage, string messageText);
public abstract bool CompleteProgress(int activityId, bool isSuccessful);
/// <summary>
/// Used by a provider to request what metadata keys were passed from the user
/// </summary>
/// <returns></returns>
public abstract IEnumerable<string> OptionKeys {get;}
/// <summary>
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public abstract IEnumerable<string> GetOptionValues(string key);
public abstract IEnumerable<string> Sources {get;}
public abstract string CredentialUsername {get;}
public abstract SecureString CredentialPassword {get;}
public abstract bool ShouldBootstrapProvider(string requestor, string providerName, string providerVersion, string providerType, string location, string destination);
public abstract bool ShouldContinueWithUntrustedPackageSource(string package, string packageSource);
public abstract bool AskPermission(string permission);
public abstract bool IsInteractive {get;}
public abstract int CallCount {get;}
#endregion
#region copy response-apis
/* Synced/Generated code =================================================== */
/// <summary>
/// Used by a provider to return fields for a SoftwareIdentity.
/// </summary>
/// <param name="fastPath"></param>
/// <param name="name"></param>
/// <param name="version"></param>
/// <param name="versionScheme"></param>
/// <param name="summary"></param>
/// <param name="source"></param>
/// <param name="searchKey"></param>
/// <param name="fullPath"></param>
/// <param name="packageFileName"></param>
/// <returns></returns>
public abstract bool YieldSoftwareIdentity(string fastPath, string name, string version, string versionScheme, string summary, string source, string searchKey, string fullPath, string packageFileName);
public abstract bool YieldSoftwareMetadata(string parentFastPath, string name, string value);
public abstract bool YieldEntity(string parentFastPath, string name, string regid, string role, string thumbprint);
public abstract bool YieldLink(string parentFastPath, string referenceUri, string relationship, string mediaType, string ownership, string use, string appliesToMedia, string artifact);
#if M2
public abstract bool YieldSwidtag(string fastPath, string xmlOrJsonDoc);
public abstract bool YieldMetadata(string fieldId, string @namespace, string name, string value);
#endif
/// <summary>
/// Used by a provider to return fields for a package source (repository)
/// </summary>
/// <param name="name"></param>
/// <param name="location"></param>
/// <param name="isTrusted"></param>
/// <param name="isRegistered"></param>
/// <param name="isValidated"></param>
/// <returns></returns>
public abstract bool YieldPackageSource(string name, string location, bool isTrusted, bool isRegistered, bool isValidated);
/// <summary>
/// Used by a provider to return the fields for a Metadata Definition
/// The cmdlets can use this to supply tab-completion for metadata to the user.
/// </summary>
/// <param name="name">the provider-defined name of the option</param>
/// <param name="expectedType"> one of ['string','int','path','switch']</param>
/// <param name="isRequired">if the parameter is mandatory</param>
/// <returns></returns>
public abstract bool YieldDynamicOption(string name, string expectedType, bool isRequired);
public abstract bool YieldKeyValuePair(string key, string value);
public abstract bool YieldValue(string value);
#endregion
/// <summary>
/// Yield values in a dictionary as key/value pairs. (one pair for each value in each key)
/// </summary>
/// <param name="dictionary"></param>
/// <returns></returns>
public bool Yield(Dictionary<string, string[]> dictionary) {
return dictionary.All(Yield);
}
public bool Yield(KeyValuePair<string, string[]> pair) {
if (pair.Value.Length == 0) {
return YieldKeyValuePair(pair.Key, null);
}
return pair.Value.All(each => YieldKeyValuePair(pair.Key, each));
}
public bool Error(ErrorCategory category, string targetObjectValue, string messageText, params object[] args) {
return Error(messageText, category.ToString(), targetObjectValue, FormatMessageString(messageText, args));
}
public bool Warning(string messageText, params object[] args) {
return Warning(FormatMessageString(messageText, args));
}
public bool Message(string messageText, params object[] args) {
return Message(FormatMessageString(messageText, args));
}
public bool Verbose(string messageText, params object[] args) {
return Verbose(FormatMessageString(messageText, args));
}
public bool Debug(string messageText, params object[] args) {
return Debug(FormatMessageString(messageText, args));
}
public int StartProgress(int parentActivityId, string messageText, params object[] args) {
return StartProgress(parentActivityId, FormatMessageString(messageText, args));
}
public bool Progress(int activityId, int progressPercentage, string messageText, params object[] args) {
return Progress(activityId, progressPercentage, FormatMessageString(messageText, args));
}
public string GetOptionValue(string name) {
// get the value from the request
return (GetOptionValues(name) ?? Enumerable.Empty<string>()).LastOrDefault();
}
private static string FixMeFormat(string formatString, object[] args) {
if (args == null || args.Length == 0) {
// not really any args, and not really expectng any
return formatString.Replace('{', '\u00ab').Replace('}', '\u00bb');
}
return args.Aggregate(formatString.Replace('{', '\u00ab').Replace('}', '\u00bb'), (current, arg) => current + string.Format(CultureInfo.CurrentCulture, " \u00ab{0}\u00bb", arg));
}
internal string GetMessageStringInternal(string messageText) {
return Messages.ResourceManager.GetString(messageText);
}
internal string FormatMessageString(string messageText, params object[] args) {
if (string.IsNullOrEmpty(messageText)) {
return string.Empty;
}
if (args == null) {
return messageText;
}
if (messageText.StartsWith(Constants.MSGPrefix, true, CultureInfo.CurrentCulture)) {
// check with the caller first, then with the local resources, and fallback to using the messageText itself.
messageText = GetMessageString(messageText.Substring(Constants.MSGPrefix.Length), GetMessageStringInternal(messageText) ?? messageText) ?? GetMessageStringInternal(messageText) ?? messageText;
}
// if it doesn't look like we have the correct number of parameters
// let's return a fix-me-format string.
var c = messageText.ToCharArray().Where(each => each == '{').Count();
if (c < args.Length) {
return FixMeFormat(messageText, args);
}
return string.Format(CultureInfo.CurrentCulture, messageText, args);
}
public bool YieldDynamicOption(string name, string expectedType, bool isRequired, IEnumerable<string> permittedValues) {
return YieldDynamicOption(name, expectedType, isRequired) && (permittedValues ?? Enumerable.Empty<string>()).All(each => YieldKeyValuePair(name, each));
}
public Dictionary<string, string[]> Options {
get {
return _options ?? (_options = OptionKeys.Where(each => !string.IsNullOrWhiteSpace(each)).ToDictionary(k => k, (k) => (GetOptionValues(k) ?? new string[0]).ToArray()));
}
}
public IEnumerable<string> PackageSources {
get {
return _packageSources ?? (_packageSources = (Sources ?? new string[0]).ToArray());
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
**
**
** Purpose: Wraps a stream and provides convenient read functionality
** for strings and primitive types.
**
**
============================================================*/
namespace System.IO {
using System;
using System.Runtime;
using System.Text;
using System.Globalization;
using System.Diagnostics.Contracts;
using System.Security;
[System.Runtime.InteropServices.ComVisible(true)]
public class BinaryReader : IDisposable
{
private const int MaxCharBytesSize = 128;
private Stream m_stream;
private byte[] m_buffer;
private Decoder m_decoder;
private byte[] m_charBytes;
private char[] m_singleChar;
private char[] m_charBuffer;
private int m_maxCharsSize; // From MaxCharBytesSize & Encoding
// Performance optimization for Read() w/ Unicode. Speeds us up by ~40%
private bool m_2BytesPerChar;
private bool m_isMemoryStream; // "do we sit on MemoryStream?" for Read/ReadInt32 perf
private bool m_leaveOpen;
public BinaryReader(Stream input) : this(input, new UTF8Encoding(), false) {
}
public BinaryReader(Stream input, Encoding encoding) : this(input, encoding, false) {
}
public BinaryReader(Stream input, Encoding encoding, bool leaveOpen) {
if (input==null) {
throw new ArgumentNullException("input");
}
if (encoding==null) {
throw new ArgumentNullException("encoding");
}
if (!input.CanRead)
throw new ArgumentException(Environment.GetResourceString("Argument_StreamNotReadable"));
Contract.EndContractBlock();
m_stream = input;
m_decoder = encoding.GetDecoder();
m_maxCharsSize = encoding.GetMaxCharCount(MaxCharBytesSize);
int minBufferSize = encoding.GetMaxByteCount(1); // max bytes per one char
if (minBufferSize < 16)
minBufferSize = 16;
m_buffer = new byte[minBufferSize];
// m_charBuffer and m_charBytes will be left null.
// For Encodings that always use 2 bytes per char (or more),
// special case them here to make Read() & Peek() faster.
m_2BytesPerChar = encoding is UnicodeEncoding;
// check if BinaryReader is based on MemoryStream, and keep this for it's life
// we cannot use "as" operator, since derived classes are not allowed
m_isMemoryStream = (m_stream.GetType() == typeof(MemoryStream));
m_leaveOpen = leaveOpen;
Contract.Assert(m_decoder!=null, "[BinaryReader.ctor]m_decoder!=null");
}
public virtual Stream BaseStream {
get {
return m_stream;
}
}
public virtual void Close() {
Dispose(true);
}
protected virtual void Dispose(bool disposing) {
if (disposing) {
Stream copyOfStream = m_stream;
m_stream = null;
if (copyOfStream != null && !m_leaveOpen)
copyOfStream.Close();
}
m_stream = null;
m_buffer = null;
m_decoder = null;
m_charBytes = null;
m_singleChar = null;
m_charBuffer = null;
}
public void Dispose()
{
Dispose(true);
}
public virtual int PeekChar() {
Contract.Ensures(Contract.Result<int>() >= -1);
if (m_stream==null) __Error.FileNotOpen();
if (!m_stream.CanSeek)
return -1;
long origPos = m_stream.Position;
int ch = Read();
m_stream.Position = origPos;
return ch;
}
public virtual int Read() {
Contract.Ensures(Contract.Result<int>() >= -1);
if (m_stream==null) {
__Error.FileNotOpen();
}
return InternalReadOneChar();
}
public virtual bool ReadBoolean(){
FillBuffer(1);
return (m_buffer[0]!=0);
}
public virtual byte ReadByte() {
// Inlined to avoid some method call overhead with FillBuffer.
if (m_stream==null) __Error.FileNotOpen();
int b = m_stream.ReadByte();
if (b == -1)
__Error.EndOfFile();
return (byte) b;
}
[CLSCompliant(false)]
public virtual sbyte ReadSByte() {
FillBuffer(1);
return (sbyte)(m_buffer[0]);
}
public virtual char ReadChar() {
int value = Read();
if (value==-1) {
__Error.EndOfFile();
}
return (char)value;
}
public virtual short ReadInt16() {
FillBuffer(2);
return (short)(m_buffer[0] | m_buffer[1] << 8);
}
[CLSCompliant(false)]
public virtual ushort ReadUInt16(){
FillBuffer(2);
return (ushort)(m_buffer[0] | m_buffer[1] << 8);
}
public virtual int ReadInt32() {
if (m_isMemoryStream) {
if (m_stream==null) __Error.FileNotOpen();
// read directly from MemoryStream buffer
MemoryStream mStream = m_stream as MemoryStream;
Contract.Assert(mStream != null, "m_stream as MemoryStream != null");
return mStream.InternalReadInt32();
}
else
{
FillBuffer(4);
return (int)(m_buffer[0] | m_buffer[1] << 8 | m_buffer[2] << 16 | m_buffer[3] << 24);
}
}
[CLSCompliant(false)]
public virtual uint ReadUInt32() {
FillBuffer(4);
return (uint)(m_buffer[0] | m_buffer[1] << 8 | m_buffer[2] << 16 | m_buffer[3] << 24);
}
public virtual long ReadInt64() {
FillBuffer(8);
uint lo = (uint)(m_buffer[0] | m_buffer[1] << 8 |
m_buffer[2] << 16 | m_buffer[3] << 24);
uint hi = (uint)(m_buffer[4] | m_buffer[5] << 8 |
m_buffer[6] << 16 | m_buffer[7] << 24);
return (long) ((ulong)hi) << 32 | lo;
}
[CLSCompliant(false)]
public virtual ulong ReadUInt64() {
FillBuffer(8);
uint lo = (uint)(m_buffer[0] | m_buffer[1] << 8 |
m_buffer[2] << 16 | m_buffer[3] << 24);
uint hi = (uint)(m_buffer[4] | m_buffer[5] << 8 |
m_buffer[6] << 16 | m_buffer[7] << 24);
return ((ulong)hi) << 32 | lo;
}
[System.Security.SecuritySafeCritical] // auto-generated
public virtual unsafe float ReadSingle() {
FillBuffer(4);
uint tmpBuffer = (uint)(m_buffer[0] | m_buffer[1] << 8 | m_buffer[2] << 16 | m_buffer[3] << 24);
return *((float*)&tmpBuffer);
}
[System.Security.SecuritySafeCritical] // auto-generated
public virtual unsafe double ReadDouble() {
FillBuffer(8);
uint lo = (uint)(m_buffer[0] | m_buffer[1] << 8 |
m_buffer[2] << 16 | m_buffer[3] << 24);
uint hi = (uint)(m_buffer[4] | m_buffer[5] << 8 |
m_buffer[6] << 16 | m_buffer[7] << 24);
ulong tmpBuffer = ((ulong)hi) << 32 | lo;
return *((double*)&tmpBuffer);
}
public virtual decimal ReadDecimal() {
FillBuffer(16);
try {
return Decimal.ToDecimal(m_buffer);
}
catch (ArgumentException e) {
// ReadDecimal cannot leak out ArgumentException
throw new IOException(Environment.GetResourceString("Arg_DecBitCtor"), e);
}
}
public virtual String ReadString() {
Contract.Ensures(Contract.Result<String>() != null);
if (m_stream == null)
__Error.FileNotOpen();
int currPos = 0;
int n;
int stringLength;
int readLength;
int charsRead;
// Length of the string in bytes, not chars
stringLength = Read7BitEncodedInt();
if (stringLength<0) {
throw new IOException(Environment.GetResourceString("IO.IO_InvalidStringLen_Len", stringLength));
}
if (stringLength==0) {
return String.Empty;
}
if (m_charBytes==null) {
m_charBytes = new byte[MaxCharBytesSize];
}
if (m_charBuffer == null) {
m_charBuffer = new char[m_maxCharsSize];
}
StringBuilder sb = null;
do
{
readLength = ((stringLength - currPos)>MaxCharBytesSize)?MaxCharBytesSize:(stringLength - currPos);
n = m_stream.Read(m_charBytes, 0, readLength);
if (n==0) {
__Error.EndOfFile();
}
charsRead = m_decoder.GetChars(m_charBytes, 0, n, m_charBuffer, 0);
if (currPos == 0 && n == stringLength)
return new String(m_charBuffer, 0, charsRead);
if (sb == null)
sb = StringBuilderCache.Acquire(stringLength); // Actual string length in chars may be smaller.
sb.Append(m_charBuffer, 0, charsRead);
currPos +=n;
} while (currPos<stringLength);
return StringBuilderCache.GetStringAndRelease(sb);
}
[SecuritySafeCritical]
public virtual int Read(char[] buffer, int index, int count) {
if (buffer==null) {
throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
}
if (index < 0) {
throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
if (count < 0) {
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
if (buffer.Length - index < count) {
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
}
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.Ensures(Contract.Result<int>() <= count);
Contract.EndContractBlock();
if (m_stream==null)
__Error.FileNotOpen();
// SafeCritical: index and count have already been verified to be a valid range for the buffer
return InternalReadChars(buffer, index, count);
}
[SecurityCritical]
private int InternalReadChars(char[] buffer, int index, int count) {
Contract.Requires(buffer != null);
Contract.Requires(index >= 0 && count >= 0);
Contract.Assert(m_stream != null);
int numBytes = 0;
int charsRemaining = count;
if (m_charBytes==null) {
m_charBytes = new byte[MaxCharBytesSize];
}
while (charsRemaining > 0) {
int charsRead = 0;
// We really want to know what the minimum number of bytes per char
// is for our encoding. Otherwise for UnicodeEncoding we'd have to
// do ~1+log(n) reads to read n characters.
numBytes = charsRemaining;
// special case for DecoderNLS subclasses when there is a hanging byte from the previous loop
DecoderNLS decoder = m_decoder as DecoderNLS;
if (decoder != null && decoder.HasState && numBytes > 1) {
numBytes -= 1;
}
if (m_2BytesPerChar)
numBytes <<= 1;
if (numBytes > MaxCharBytesSize)
numBytes = MaxCharBytesSize;
int position = 0;
byte[] byteBuffer = null;
if (m_isMemoryStream)
{
MemoryStream mStream = m_stream as MemoryStream;
Contract.Assert(mStream != null, "m_stream as MemoryStream != null");
position = mStream.InternalGetPosition();
numBytes = mStream.InternalEmulateRead(numBytes);
byteBuffer = mStream.InternalGetBuffer();
}
else
{
numBytes = m_stream.Read(m_charBytes, 0, numBytes);
byteBuffer = m_charBytes;
}
if (numBytes == 0) {
return (count - charsRemaining);
}
Contract.Assert(byteBuffer != null, "expected byteBuffer to be non-null");
unsafe {
fixed (byte* pBytes = byteBuffer)
fixed (char* pChars = buffer) {
charsRead = m_decoder.GetChars(pBytes + position, numBytes, pChars + index, charsRemaining, false);
}
}
charsRemaining -= charsRead;
index+=charsRead;
}
// this should never fail
Contract.Assert(charsRemaining >= 0, "We read too many characters.");
// we may have read fewer than the number of characters requested if end of stream reached
// or if the encoding makes the char count too big for the buffer (e.g. fallback sequence)
return (count - charsRemaining);
}
private int InternalReadOneChar() {
// I know having a separate InternalReadOneChar method seems a little
// redundant, but this makes a scenario like the security parser code
// 20% faster, in addition to the optimizations for UnicodeEncoding I
// put in InternalReadChars.
int charsRead = 0;
int numBytes = 0;
long posSav = posSav = 0;
if (m_stream.CanSeek)
posSav = m_stream.Position;
if (m_charBytes==null) {
m_charBytes = new byte[MaxCharBytesSize];
}
if (m_singleChar==null) {
m_singleChar = new char[1];
}
while (charsRead == 0) {
// We really want to know what the minimum number of bytes per char
// is for our encoding. Otherwise for UnicodeEncoding we'd have to
// do ~1+log(n) reads to read n characters.
// Assume 1 byte can be 1 char unless m_2BytesPerChar is true.
numBytes = m_2BytesPerChar ? 2 : 1;
int r = m_stream.ReadByte();
m_charBytes[0] = (byte) r;
if (r == -1)
numBytes = 0;
if (numBytes == 2) {
r = m_stream.ReadByte();
m_charBytes[1] = (byte) r;
if (r == -1)
numBytes = 1;
}
if (numBytes==0) {
// Console.WriteLine("Found no bytes. We're outta here.");
return -1;
}
Contract.Assert(numBytes == 1 || numBytes == 2, "BinaryReader::InternalReadOneChar assumes it's reading one or 2 bytes only.");
try {
charsRead = m_decoder.GetChars(m_charBytes, 0, numBytes, m_singleChar, 0);
}
catch
{
// Handle surrogate char
if (m_stream.CanSeek)
m_stream.Seek((posSav - m_stream.Position), SeekOrigin.Current);
// else - we can't do much here
throw;
}
Contract.Assert(charsRead < 2, "InternalReadOneChar - assuming we only got 0 or 1 char, not 2!");
// Console.WriteLine("That became: " + charsRead + " characters.");
}
if (charsRead == 0)
return -1;
return m_singleChar[0];
}
[SecuritySafeCritical]
public virtual char[] ReadChars(int count) {
if (count<0) {
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
Contract.Ensures(Contract.Result<char[]>() != null);
Contract.Ensures(Contract.Result<char[]>().Length <= count);
Contract.EndContractBlock();
if (m_stream == null) {
__Error.FileNotOpen();
}
if (count == 0) {
return EmptyArray<Char>.Value;
}
// SafeCritical: we own the chars buffer, and therefore can guarantee that the index and count are valid
char[] chars = new char[count];
int n = InternalReadChars(chars, 0, count);
if (n!=count) {
char[] copy = new char[n];
Buffer.InternalBlockCopy(chars, 0, copy, 0, 2*n); // sizeof(char)
chars = copy;
}
return chars;
}
public virtual int Read(byte[] buffer, int index, int count) {
if (buffer==null)
throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0)
throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.Ensures(Contract.Result<int>() <= count);
Contract.EndContractBlock();
if (m_stream==null) __Error.FileNotOpen();
return m_stream.Read(buffer, index, count);
}
public virtual byte[] ReadBytes(int count) {
if (count < 0) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.Ensures(Contract.Result<byte[]>().Length <= Contract.OldValue(count));
Contract.EndContractBlock();
if (m_stream==null) __Error.FileNotOpen();
if (count == 0) {
return EmptyArray<Byte>.Value;
}
byte[] result = new byte[count];
int numRead = 0;
do {
int n = m_stream.Read(result, numRead, count);
if (n == 0)
break;
numRead += n;
count -= n;
} while (count > 0);
if (numRead != result.Length) {
// Trim array. This should happen on EOF & possibly net streams.
byte[] copy = new byte[numRead];
Buffer.InternalBlockCopy(result, 0, copy, 0, numRead);
result = copy;
}
return result;
}
protected virtual void FillBuffer(int numBytes) {
if (m_buffer != null && (numBytes < 0 || numBytes > m_buffer.Length)) {
throw new ArgumentOutOfRangeException("numBytes", Environment.GetResourceString("ArgumentOutOfRange_BinaryReaderFillBuffer"));
}
int bytesRead=0;
int n = 0;
if (m_stream==null) __Error.FileNotOpen();
// Need to find a good threshold for calling ReadByte() repeatedly
// vs. calling Read(byte[], int, int) for both buffered & unbuffered
// streams.
if (numBytes==1) {
n = m_stream.ReadByte();
if (n==-1)
__Error.EndOfFile();
m_buffer[0] = (byte)n;
return;
}
do {
n = m_stream.Read(m_buffer, bytesRead, numBytes-bytesRead);
if (n==0) {
__Error.EndOfFile();
}
bytesRead+=n;
} while (bytesRead<numBytes);
}
internal protected int Read7BitEncodedInt() {
// Read out an Int32 7 bits at a time. The high bit
// of the byte when on means to continue reading more bytes.
int count = 0;
int shift = 0;
byte b;
do {
// Check for a corrupted stream. Read a max of 5 bytes.
// In a future version, add a DataFormatException.
if (shift == 5 * 7) // 5 bytes max per Int32, shift += 7
throw new FormatException(Environment.GetResourceString("Format_Bad7BitInt32"));
// ReadByte handles end of stream cases for us.
b = ReadByte();
count |= (b & 0x7F) << shift;
shift += 7;
} while ((b & 0x80) != 0);
return count;
}
}
}
| |
//
// GlobalActions.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2007 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using Mono.Unix;
using Gtk;
using Hyena;
using Banshee.Base;
using Banshee.ServiceStack;
using Banshee.Streaming;
using Banshee.Gui.Dialogs;
using Banshee.Widgets;
using Banshee.Playlist;
namespace Banshee.Gui
{
public class GlobalActions : BansheeActionGroup
{
public GlobalActions () : base ("Global")
{
Add (new ActionEntry [] {
// Media Menu
new ActionEntry ("MediaMenuAction", null,
Catalog.GetString ("_Media"), null, null, null),
new ActionEntry ("ImportAction", Stock.Open,
Catalog.GetString ("Import _Media..."), "<control>I",
Catalog.GetString ("Import media from a variety of sources"), OnImport),
new ActionEntry ("ImportPlaylistAction", null,
Catalog.GetString ("Import _Playlist..."), null,
Catalog.GetString ("Import a playlist"), OnImportPlaylist),
new ActionEntry ("RescanAction", null,
Catalog.GetString ("Rescan Music Library"), null,
Catalog.GetString ("Rescan the Music Library folder"), delegate {
new Banshee.Collection.RescanPipeline (ServiceManager.SourceManager.MusicLibrary);
}),
new ActionEntry ("OpenLocationAction", null,
Catalog.GetString ("Open _Location..."), "<control>L",
Catalog.GetString ("Open a remote location for playback"), OnOpenLocation),
new ActionEntry ("QuitAction", Stock.Quit,
Catalog.GetString ("_Quit"), "<control>Q",
Catalog.GetString ("Quit Banshee"), OnQuit),
// Edit Menu
new ActionEntry ("EditMenuAction", null,
Catalog.GetString("_Edit"), null, null, null),
new ActionEntry ("PreferencesAction", Stock.Preferences,
Catalog.GetString ("_Preferences"), null,
Catalog.GetString ("Modify your personal preferences"), OnPreferences),
new ActionEntry ("ExtensionsAction", null,
Catalog.GetString ("Manage _Extensions"), null,
Catalog.GetString ("Manage extensions to add new features to Banshee"), OnExtensions),
// Tools menu
new ActionEntry ("ToolsMenuAction", null,
Catalog.GetString ("_Tools"), null, null, null),
// Help Menu
new ActionEntry ("HelpMenuAction", null,
Catalog.GetString ("_Help"), null, null, null),
new ActionEntry ("WebMenuAction", null,
Catalog.GetString ("_Web Resources"), null, null, null),
new ActionEntry ("WikiGuideAction", Stock.Help,
Catalog.GetString ("Banshee _User Guide (Wiki)"), null,
Catalog.GetString ("Learn about how to use Banshee"), delegate {
Banshee.Web.Browser.Open ("http://banshee-project.org/support/guide/");
}),
new ActionEntry ("WikiSearchHelpAction", null,
Catalog.GetString ("Advanced Collection Searching"), null,
Catalog.GetString ("Learn advanced ways to search your media collection"), delegate {
Banshee.Web.Browser.Open ("http://banshee-project.org/support/guide/searching/");
}),
new ActionEntry ("WikiAction", null,
Catalog.GetString ("Banshee _Home Page"), null,
Catalog.GetString ("Visit the Banshee Home Page"), delegate {
Banshee.Web.Browser.Open ("http://banshee-project.org/");
}),
new ActionEntry ("WikiDeveloperAction", null,
Catalog.GetString ("_Get Involved"), null,
Catalog.GetString ("Become a contributor to Banshee"), delegate {
Banshee.Web.Browser.Open ("http://banshee-project.org/contribute/");
}),
new ActionEntry ("VersionInformationAction", null,
Catalog.GetString ("_Version Information"), null,
Catalog.GetString ("View detailed version and configuration information"), OnVersionInformation),
new ActionEntry("AboutAction", "gtk-about", OnAbout)
});
this["ExtensionsAction"].Visible = false;
}
#region Media Menu Actions
private void OnImport (object o, EventArgs args)
{
var dialog = new Banshee.Library.Gui.ImportDialog ();
var res = dialog.Run ();
var src = dialog.ActiveSource;
dialog.Destroy ();
if (res == Gtk.ResponseType.Ok) {
src.Import ();
}
}
private void OnOpenLocation (object o, EventArgs args)
{
OpenLocationDialog dialog = new OpenLocationDialog ();
ResponseType response = dialog.Run ();
string address = dialog.Address;
dialog.Destroy ();
if (response == ResponseType.Ok) {
RadioTrackInfo.OpenPlay (address);
}
}
private void OnImportPlaylist (object o, EventArgs args)
{
// Prompt user for location of the playlist.
var chooser = Banshee.Gui.Dialogs.FileChooserDialog.CreateForImport (Catalog.GetString("Import Playlist"), true);
chooser.AddFilter (Hyena.Gui.GtkUtilities.GetFileFilter (Catalog.GetString ("Playlists"), PlaylistFileUtil.PlaylistExtensions));
int response = chooser.Run();
string [] uris = null;
if (response == (int) ResponseType.Ok) {
uris = chooser.Uris;
chooser.Destroy();
} else {
chooser.Destroy();
return;
}
if (uris == null || uris.Length == 0) {
return;
}
Banshee.Kernel.Scheduler.Schedule (new Banshee.Kernel.DelegateJob (delegate {
foreach (string uri in uris) {
PlaylistFileUtil.ImportPlaylistToLibrary (uri);
}
}));
}
private void OnQuit (object o, EventArgs args)
{
Banshee.ServiceStack.Application.Shutdown ();
}
#endregion
#region Edit Menu Actions
private void OnPreferences (object o, EventArgs args)
{
try {
Banshee.Preferences.Gui.PreferenceDialog dialog = new Banshee.Preferences.Gui.PreferenceDialog ();
dialog.Run ();
dialog.Destroy ();
} catch (ApplicationException) {
}
}
private void OnExtensions (object o, EventArgs args)
{
Mono.Addins.Gui.AddinManagerWindow.Run (PrimaryWindow);
}
#endregion
#region Help Menu Actions
private void OnVersionInformation (object o, EventArgs args)
{
Hyena.Gui.Dialogs.VersionInformationDialog dialog = new Hyena.Gui.Dialogs.VersionInformationDialog ();
dialog.Run ();
dialog.Destroy ();
}
private void OnAbout (object o, EventArgs args)
{
Banshee.Gui.Dialogs.AboutDialog dialog = new Banshee.Gui.Dialogs.AboutDialog ();
dialog.Show ();
}
#endregion
}
}
| |
/*
* 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.Globalization;
using QuantConnect.Logging;
using QuantConnect.Util;
namespace QuantConnect.Data.Market
{
/// <summary>
/// QuoteBar class for second and minute resolution data:
/// An OHLC implementation of the QuantConnect BaseData class with parameters for candles.
/// </summary>
public class QuoteBar : BaseData, IBaseDataBar
{
// scale factor used in QC equity/forex data files
private const decimal _scaleFactor = 1 / 10000m;
/// <summary>
/// Average bid size
/// </summary>
public decimal LastBidSize { get; set; }
/// <summary>
/// Average ask size
/// </summary>
public decimal LastAskSize { get; set; }
/// <summary>
/// Bid OHLC
/// </summary>
public Bar Bid { get; set; }
/// <summary>
/// Ask OHLC
/// </summary>
public Bar Ask { get; set; }
/// <summary>
/// Opening price of the bar: Defined as the price at the start of the time period.
/// </summary>
public decimal Open
{
get
{
if (Bid != null && Ask != null)
{
if (Bid.Open != 0m && Ask.Open != 0m)
return (Bid.Open + Ask.Open) / 2m;
if (Bid.Open != 0)
return Bid.Open;
if (Ask.Open != 0)
return Ask.Open;
return 0m;
}
if (Bid != null)
{
return Bid.Open;
}
if (Ask != null)
{
return Ask.Open;
}
return 0m;
}
}
/// <summary>
/// High price of the QuoteBar during the time period.
/// </summary>
public decimal High
{
get
{
if (Bid != null && Ask != null)
{
if (Bid.High != 0m && Ask.High != 0m)
return (Bid.High + Ask.High) / 2m;
if (Bid.High != 0)
return Bid.High;
if (Ask.High != 0)
return Ask.High;
return 0m;
}
if (Bid != null)
{
return Bid.High;
}
if (Ask != null)
{
return Ask.High;
}
return 0m;
}
}
/// <summary>
/// Low price of the QuoteBar during the time period.
/// </summary>
public decimal Low
{
get
{
if (Bid != null && Ask != null)
{
if (Bid.Low != 0m && Ask.Low != 0m)
return (Bid.Low + Ask.Low) / 2m;
if (Bid.Low != 0)
return Bid.Low;
if (Ask.Low != 0)
return Ask.Low;
return 0m;
}
if (Bid != null)
{
return Bid.Low;
}
if (Ask != null)
{
return Ask.Low;
}
return 0m;
}
}
/// <summary>
/// Closing price of the QuoteBar. Defined as the price at Start Time + TimeSpan.
/// </summary>
public decimal Close
{
get
{
if (Bid != null && Ask != null)
{
if (Bid.Close != 0m && Ask.Close != 0m)
return (Bid.Close + Ask.Close) / 2m;
if (Bid.Close != 0)
return Bid.Close;
if (Ask.Close != 0)
return Ask.Close;
return 0m;
}
if (Bid != null)
{
return Bid.Close;
}
if (Ask != null)
{
return Ask.Close;
}
return Value;
}
}
/// <summary>
/// The closing time of this bar, computed via the Time and Period
/// </summary>
public override DateTime EndTime
{
get { return Time + Period; }
set { Period = value - Time; }
}
/// <summary>
/// The period of this quote bar, (second, minute, daily, ect...)
/// </summary>
public TimeSpan Period { get; set; }
/// <summary>
/// Default initializer to setup an empty quotebar.
/// </summary>
public QuoteBar()
{
Symbol = Symbol.Empty;
Time = new DateTime();
Bid = new Bar();
Ask = new Bar();
Value = 0;
Period = TimeSpan.FromMinutes(1);
DataType = MarketDataType.QuoteBar;
}
/// <summary>
/// Initialize Quote Bar with Bid(OHLC) and Ask(OHLC) Values:
/// </summary>
/// <param name="time">DateTime Timestamp of the bar</param>
/// <param name="symbol">Market MarketType Symbol</param>
/// <param name="bid">Bid OLHC bar</param>
/// <param name="lastBidSize">Average bid size over period</param>
/// <param name="ask">Ask OLHC bar</param>
/// <param name="lastAskSize">Average ask size over period</param>
/// <param name="period">The period of this bar, specify null for default of 1 minute</param>
public QuoteBar(DateTime time, Symbol symbol, IBar bid, decimal lastBidSize, IBar ask, decimal lastAskSize, TimeSpan? period = null)
{
Symbol = symbol;
Time = time;
Bid = bid == null ? null : new Bar(bid.Open, bid.High, bid.Low, bid.Close);
Ask = ask == null ? null : new Bar(ask.Open, ask.High, ask.Low, ask.Close);
if (Bid != null) LastBidSize = lastBidSize;
if (Ask != null) LastAskSize = lastAskSize;
Value = Close;
Period = period ?? TimeSpan.FromMinutes(1);
DataType = MarketDataType.QuoteBar;
}
/// <summary>
/// Update the quotebar - build the bar from this pricing information:
/// </summary>
/// <param name="lastTrade">The last trade price</param>
/// <param name="bidPrice">Current bid price</param>
/// <param name="askPrice">Current asking price</param>
/// <param name="volume">Volume of this trade</param>
/// <param name="bidSize">The size of the current bid, if available, if not, pass 0</param>
/// <param name="askSize">The size of the current ask, if available, if not, pass 0</param>
public override void Update(decimal lastTrade, decimal bidPrice, decimal askPrice, decimal volume, decimal bidSize, decimal askSize)
{
// update our bid and ask bars - handle null values, this is to give good values for midpoint OHLC
if (Bid == null && bidPrice != 0) Bid = new Bar();
if (Bid != null) Bid.Update(bidPrice);
if (Ask == null && askPrice != 0) Ask = new Bar();
if (Ask != null) Ask.Update(askPrice);
if (bidSize > 0)
{
LastBidSize = bidSize;
}
if (askSize > 0)
{
LastAskSize = askSize;
}
// be prepared for updates without trades
if (lastTrade != 0) Value = lastTrade;
else if (askPrice != 0) Value = askPrice;
else if (bidPrice != 0) Value = bidPrice;
}
/// <summary>
/// QuoteBar Reader: Fetch the data from the QC storage and feed it line by line into the engine.
/// </summary>
/// <param name="config">Symbols, Resolution, DataType, </param>
/// <param name="line">Line from the data file requested</param>
/// <param name="date">Date of this reader request</param>
/// <param name="isLiveMode">true if we're in live mode, false for backtesting mode</param>
/// <returns>Enumerable iterator for returning each line of the required data.</returns>
public override BaseData Reader(SubscriptionDataConfig config, string line, DateTime date, bool isLiveMode)
{
var csvLength = line.Split(',').Length;
try
{
// "Scaffold" code - simple check to see how the data is formatted and decide how to parse appropriately
// TODO: Once all FX is reprocessed to QuoteBars, remove this check
if (csvLength > 5)
{
switch (config.SecurityType)
{
case SecurityType.Equity:
return ParseEquity(config, line, date);
case SecurityType.Forex:
case SecurityType.Crypto:
return ParseForex(config, line, date);
case SecurityType.Cfd:
return ParseCfd(config, line, date);
case SecurityType.Option:
return ParseOption(config, line, date);
case SecurityType.Future:
return ParseFuture(config, line, date);
}
}
// Parse as trade
return ParseTradeAsQuoteBar(config, date, line);
}
catch (Exception err)
{
Log.Error("QuoteBar.Reader(): Error parsing line: '{0}', Symbol: {1}, SecurityType: {2}, Resolution: {3}, Date: {4}, Message: {5}",
line, config.Symbol.Value, config.SecurityType, config.Resolution, date.ToString("yyyy-MM-dd"), err);
}
// if we couldn't parse it above return a default instance
return new QuoteBar { Symbol = config.Symbol, Period = config.Increment };
}
private static bool HasShownWarning;
/// <summary>
/// "Scaffold" code - If the data being read is formatted as a TradeBar, use this method to deserialize it
/// TODO: Once all Forex data refactored to use QuoteBar formatted data, remove this method
/// </summary>
/// <param name="config">Symbols, Resolution, DataType, </param>
/// <param name="line">Line from the data file requested</param>
/// <param name="date">Date of this reader request</param>
/// <returns><see cref="QuoteBar"/> with the bid/ask prices set to same values</returns>
[Obsolete("All Forex data should use Quotes instead of Trades.")]
private QuoteBar ParseTradeAsQuoteBar(SubscriptionDataConfig config, DateTime date, string line)
{
if (!HasShownWarning)
{
Logging.Log.Error("QuoteBar.ParseTradeAsQuoteBar(): Data formatted as Trade when Quote format was expected. Support for this will disappear June 2017.");
HasShownWarning = true;
}
var quoteBar = new QuoteBar
{
Period = config.Increment,
Symbol = config.Symbol
};
var csv = line.ToCsv(5);
if (config.Resolution == Resolution.Daily || config.Resolution == Resolution.Hour)
{
// hourly and daily have different time format, and can use slow, robust c# parser.
quoteBar.Time = DateTime.ParseExact(csv[0], DateFormat.TwelveCharacter, CultureInfo.InvariantCulture).ConvertTo(config.DataTimeZone, config.ExchangeTimeZone);
}
else
{
//Fast decimal conversion
quoteBar.Time = date.Date.AddMilliseconds(csv[0].ToInt32()).ConvertTo(config.DataTimeZone, config.ExchangeTimeZone);
}
var bid = new Bar
{
Open = csv[1].ToDecimal(),
High = csv[2].ToDecimal(),
Low = csv[3].ToDecimal(),
Close = csv[4].ToDecimal()
};
var ask = new Bar
{
Open = csv[1].ToDecimal(),
High = csv[2].ToDecimal(),
Low = csv[3].ToDecimal(),
Close = csv[4].ToDecimal()
};
quoteBar.Ask = ask;
quoteBar.Bid = bid;
quoteBar.Value = quoteBar.Close;
return quoteBar;
}
/// <summary>
/// Parse a quotebar representing a future with a scaling factor
/// </summary>
/// <param name="config">Symbols, Resolution, DataType</param>
/// <param name="line">Line from the data file requested</param>
/// <param name="date">Date of this reader request</param>
/// <returns><see cref="QuoteBar"/> with the bid/ask set to same values</returns>
public QuoteBar ParseFuture(SubscriptionDataConfig config, string line, DateTime date)
{
return ParseQuote(config, date, line, false);
}
/// <summary>
/// Parse a quotebar representing an option with a scaling factor
/// </summary>
/// <param name="config">Symbols, Resolution, DataType</param>
/// <param name="line">Line from the data file requested</param>
/// <param name="date">Date of this reader request</param>
/// <returns><see cref="QuoteBar"/> with the bid/ask set to same values</returns>
public QuoteBar ParseOption(SubscriptionDataConfig config, string line, DateTime date)
{
return ParseQuote(config, date, line, true);
}
/// <summary>
/// Parse a quotebar representing a cfd without a scaling factor
/// </summary>
/// <param name="config">Symbols, Resolution, DataType</param>
/// <param name="line">Line from the data file requested</param>
/// <param name="date">Date of this reader request</param>
/// <returns><see cref="QuoteBar"/> with the bid/ask set to same values</returns>
public QuoteBar ParseCfd(SubscriptionDataConfig config, string line, DateTime date)
{
return ParseQuote(config, date, line, false);
}
/// <summary>
/// Parse a quotebar representing a forex without a scaling factor
/// </summary>
/// <param name="config">Symbols, Resolution, DataType</param>
/// <param name="line">Line from the data file requested</param>
/// <param name="date">Date of this reader request</param>
/// <returns><see cref="QuoteBar"/> with the bid/ask set to same values</returns>
public QuoteBar ParseForex(SubscriptionDataConfig config, string line, DateTime date)
{
return ParseQuote(config, date, line, false);
}
/// <summary>
/// Parse a quotebar representing an equity with a scaling factor
/// </summary>
/// <param name="config">Symbols, Resolution, DataType</param>
/// <param name="line">Line from the data file requested</param>
/// <param name="date">Date of this reader request</param>
/// <returns><see cref="QuoteBar"/> with the bid/ask set to same values</returns>
public QuoteBar ParseEquity(SubscriptionDataConfig config, string line, DateTime date)
{
return ParseQuote(config, date, line, true);
}
/// <summary>
/// "Scaffold" code - If the data being read is formatted as a QuoteBar, use this method to deserialize it
/// TODO: Once all Forex data refactored to use QuoteBar formatted data, use only this method
/// </summary>
/// <param name="config">Symbols, Resolution, DataType, </param>
/// <param name="line">Line from the data file requested</param>
/// <param name="date">Date of this reader request</param>
/// <param name="useScaleFactor">Whether the data has a scaling factor applied</param>
/// <returns><see cref="QuoteBar"/> with the bid/ask prices set appropriately</returns>
private QuoteBar ParseQuote(SubscriptionDataConfig config, DateTime date, string line, bool useScaleFactor)
{
var scaleFactor = useScaleFactor
? _scaleFactor
: 1;
var quoteBar = new QuoteBar
{
Period = config.Increment,
Symbol = config.Symbol
};
var csv = line.ToCsv(10);
if (config.Resolution == Resolution.Daily || config.Resolution == Resolution.Hour)
{
// hourly and daily have different time format, and can use slow, robust c# parser.
quoteBar.Time = DateTime.ParseExact(csv[0], DateFormat.TwelveCharacter, CultureInfo.InvariantCulture).ConvertTo(config.DataTimeZone, config.ExchangeTimeZone);
}
else
{
// Using custom "ToDecimal" conversion for speed on high resolution data.
quoteBar.Time = date.Date.AddMilliseconds(csv[0].ToInt32()).ConvertTo(config.DataTimeZone, config.ExchangeTimeZone);
}
// only create the bid if it exists in the file
if (csv[1].Length != 0 || csv[2].Length != 0 || csv[3].Length != 0 || csv[4].Length != 0)
{
quoteBar.Bid = new Bar
{
Open = config.GetNormalizedPrice(csv[1].ToDecimal() * scaleFactor),
High = config.GetNormalizedPrice(csv[2].ToDecimal() * scaleFactor),
Low = config.GetNormalizedPrice(csv[3].ToDecimal() * scaleFactor),
Close = config.GetNormalizedPrice(csv[4].ToDecimal() * scaleFactor)
};
quoteBar.LastBidSize = csv[5].ToDecimal();
}
else
{
quoteBar.Bid = null;
}
// only create the ask if it exists in the file
if (csv[6].Length != 0 || csv[7].Length != 0 || csv[8].Length != 0 || csv[9].Length != 0)
{
quoteBar.Ask = new Bar
{
Open = config.GetNormalizedPrice(csv[6].ToDecimal() * scaleFactor),
High = config.GetNormalizedPrice(csv[7].ToDecimal() * scaleFactor),
Low = config.GetNormalizedPrice(csv[8].ToDecimal() * scaleFactor),
Close = config.GetNormalizedPrice(csv[9].ToDecimal() * scaleFactor)
};
quoteBar.LastAskSize = csv[10].ToDecimal();
}
else
{
quoteBar.Ask = null;
}
quoteBar.Value = quoteBar.Close;
return quoteBar;
}
/// <summary>
/// Get Source for Custom Data File
/// >> What source file location would you prefer for each type of usage:
/// </summary>
/// <param name="config">Configuration object</param>
/// <param name="date">Date of this source request if source spread across multiple files</param>
/// <param name="isLiveMode">true if we're in live mode, false for backtesting mode</param>
/// <returns>String source location of the file</returns>
public override SubscriptionDataSource GetSource(SubscriptionDataConfig config, DateTime date, bool isLiveMode)
{
if (isLiveMode)
{
return new SubscriptionDataSource(string.Empty, SubscriptionTransportMedium.LocalFile);
}
var source = LeanData.GenerateZipFilePath(Globals.DataFolder, config.Symbol, date, config.Resolution, config.TickType);
if (config.SecurityType == SecurityType.Option ||
config.SecurityType == SecurityType.Future)
{
source += "#" + LeanData.GenerateZipEntryName(config.Symbol, date, config.Resolution, config.TickType);
}
return new SubscriptionDataSource(source, SubscriptionTransportMedium.LocalFile, FileFormat.Csv);
}
/// <summary>
/// Return a new instance clone of this quote bar, used in fill forward
/// </summary>
/// <returns>A clone of the current quote bar</returns>
public override BaseData Clone()
{
return new QuoteBar
{
Ask = Ask == null ? null : Ask.Clone(),
Bid = Bid == null ? null : Bid.Clone(),
LastAskSize = LastAskSize,
LastBidSize = LastBidSize,
Symbol = Symbol,
Time = Time,
Period = Period,
Value = Value,
DataType = DataType
};
}
/// <summary>
/// Collapses QuoteBars into TradeBars object when
/// algorithm requires FX data, but calls OnData(<see cref="TradeBars"/>)
/// TODO: (2017) Remove this method in favor of using OnData(<see cref="Slice"/>)
/// </summary>
/// <returns><see cref="TradeBars"/></returns>
[Obsolete("For backwards compatibility only. When FX data is traded, all algorithms should use OnData(Slice)")]
public TradeBar Collapse()
{
return new TradeBar(EndTime, Symbol, Open, High, Low, Close, 0);
}
}
}
| |
using System;
using Microsoft.Xna.Framework;
using Terraria;
namespace Terraria.ModLoader
{
/// <summary>
/// This serves as a place for you to program behaviors of equipment textures. This is useful for equipment slots that do not have any item associated with them (for example, the Werewolf buff). Note that this class is purely for visual effects.
/// </summary>
public class EquipTexture
{
/// <summary>
/// The name and folders of the texture file used by this equipment texture.
/// </summary>
public string Texture
{
get;
internal set;
}
/// <summary>
/// The mod that added this equipment texture.
/// </summary>
public Mod mod
{
get;
internal set;
}
/// <summary>
/// The internal name of this equipment texture.
/// </summary>
public string Name
{
get;
internal set;
}
/// <summary>
/// The type of equipment that this equipment texture is used as.
/// </summary>
public EquipType Type
{
get;
internal set;
}
/// <summary>
/// The slot (internal ID) of this equipment texture.
/// </summary>
public int Slot
{
get;
internal set;
}
/// <summary>
/// The item that is associated with this equipment texture. Null if no item is associated with this.
/// </summary>
public ModItem item
{
get;
internal set;
}
/// <summary>
/// Allows you to create special effects (such as dust) when this equipment texture is displayed on the player under the given equipment type. By default this will call the associated ModItem's UpdateVanity if there is an associated ModItem.
/// </summary>
/// <param name="player"></param>
/// <param name="type"></param>
public virtual void UpdateVanity(Player player, EquipType type)
{
if (item != null)
{
item.UpdateVanity(player, type);
}
}
/// <summary>
/// Returns whether or not the head armor, body armor, and leg armor textures make up a set. This hook is used for the PreUpdateVanitySet, UpdateVanitySet, and ArmorSetShadow hooks. By default this will return the same thing as the associated ModItem's IsVanitySet, or false if no ModItem is associated.
/// </summary>
/// <param name="head"></param>
/// <param name="body"></param>
/// <param name="legs"></param>
/// <returns></returns>
public virtual bool IsVanitySet(int head, int body, int legs)
{
if (item == null)
{
return false;
}
return item.IsVanitySet(head, body, legs);
}
/// <summary>
/// Allows you to create special effects (such as the necro armor's hurt noise) when the player wears this equipment texture's vanity set. This hook is called regardless of whether the player is frozen in any way. By default this will call the associated ModItem's PreUpdateVanitySet if there is an associated ModItem.
/// </summary>
/// <param name="player"></param>
public virtual void PreUpdateVanitySet(Player player)
{
if (item != null)
{
item.PreUpdateVanitySet(player);
}
}
/// <summary>
/// Allows you to create special effects (such as dust) when the player wears this equipment texture's vanity set. This hook will only be called if the player is not frozen in any way. By default this will call the associated ModItem's UpdateVanitySet if there is an associated ModItem.
/// </summary>
/// <param name="player"></param>
public virtual void UpdateVanitySet(Player player)
{
if (item != null)
{
item.UpdateVanitySet(player);
}
}
/// <summary>
/// Allows you to determine special visual effects this vanity set has on the player without having to code them yourself. By default this will call the associated ModItem's ArmorSetShadows if there is an associated ModItem.
/// </summary>
/// <param name="player"></param>
public virtual void ArmorSetShadows(Player player)
{
if (item != null)
{
item.ArmorSetShadows(player);
}
}
/// <summary>
/// Allows you to modify the equipment that the player appears to be wearing. This hook will only be called for body textures and leg textures. Note that equipSlot is not the same as the item type of the armor the player will appear to be wearing. Worn equipment has a separate set of IDs. You can find the vanilla equipment IDs by looking at the headSlot, bodySlot, and legSlot fields for items, and modded equipment IDs by looking at EquipLoader.
///If this hook is called on body armor, equipSlot allows you to modify the leg armor the player appears to be wearing. If you modify it, make sure to set robes to true. If this hook is called on leg armor, equipSlot allows you to modify the leg armor the player appears to be wearing, and the robes parameter is useless.
///By default, if there is an associated ModItem, this will call that ModItem's SetMatch.
/// </summary>
/// <param name="male"></param>
/// <param name="equipSlot"></param>
/// <param name="robes"></param>
public virtual void SetMatch(bool male, ref int equipSlot, ref bool robes)
{
if (item != null)
{
item.SetMatch(male, ref equipSlot, ref robes);
}
}
/// <summary>
/// Allows you to determine whether the skin/shirt on the player's arms and hands are drawn when this body equipment texture is worn. By default both flags will be false. Note that if drawHands is false, the arms will not be drawn either. If there is an associated ModItem, by default this will call that ModItem's DrawHands.
/// </summary>
/// <param name="drawHands"></param>
/// <param name="drawArms"></param>
public virtual void DrawHands(ref bool drawHands, ref bool drawArms)
{
if (item != null)
{
item.DrawHands(ref drawHands, ref drawArms);
}
}
/// <summary>
/// Allows you to determine whether the player's hair or alt (hat) hair draws when this head equipment texture is worn. By default both flags will be false. If there is an associated ModItem, by default this will call that ModItem's DrawHair.
/// </summary>
/// <param name="drawHair"></param>
/// <param name="drawAltHair"></param>
public virtual void DrawHair(ref bool drawHair, ref bool drawAltHair)
{
if (item != null)
{
item.DrawHair(ref drawHair, ref drawAltHair);
}
}
/// <summary>
/// Return false to hide the player's head when this head equipment texture is worn. By default this will return the associated ModItem's DrawHead, or true if there is no associated ModItem.
/// </summary>
/// <returns></returns>
public virtual bool DrawHead()
{
return item == null || item.DrawHead();
}
/// <summary>
/// Return false to hide the player's body when this body equipment texture is worn. By default this will return the associated ModItem's DrawBody, or true if there is no associated ModItem.
/// </summary>
/// <returns></returns>
public virtual bool DrawBody()
{
return item == null || item.DrawBody();
}
/// <summary>
/// Return false to hide the player's legs when this leg or shoe equipment texture is worn. By default this will return the associated ModItem's DrawLegs, or true if there is no associated ModItem.
/// </summary>
/// <returns></returns>
public virtual bool DrawLegs()
{
return item == null || item.DrawLegs();
}
/// <summary>
/// Allows you to modify the colors in which this armor texture and surrounding accessories are drawn, in addition to which glow mask and in what color is drawn. By default this will call the associated ModItem's DrawArmorColor if there is an associated ModItem.
/// </summary>
/// <param name="drawPlayer"></param>
/// <param name="shadow"></param>
/// <param name="color"></param>
/// <param name="glowMask"></param>
/// <param name="glowMaskColor"></param>
public virtual void DrawArmorColor(Player drawPlayer, float shadow, ref Color color, ref int glowMask, ref Color glowMaskColor)
{
if (item != null)
{
item.DrawArmorColor(drawPlayer, shadow, ref color, ref glowMask, ref glowMaskColor);
}
}
/// <summary>
/// Allows you to modify which glow mask and in what color is drawn on the player's arms. Note that this is only called for body equipment textures. By default this will call the associated ModItem's ArmorArmGlowMask if there is an associated ModItem.
/// </summary>
/// <param name="drawPlayer"></param>
/// <param name="shadow"></param>
/// <param name="glowMask"></param>
/// <param name="color"></param>
public virtual void ArmorArmGlowMask(Player drawPlayer, float shadow, ref int glowMask, ref Color color)
{
if (item != null)
{
item.ArmorArmGlowMask(drawPlayer, shadow, ref glowMask, ref color);
}
}
/// <summary>
/// Allows you to modify vertical wing speeds.
/// </summary>
/// <param name="player"></param>
/// <param name="ascentWhenFalling"></param>
/// <param name="ascentWhenRising"></param>
/// <param name="maxCanAscendMultiplier"></param>
/// <param name="maxAscentMultiplier"></param>
/// <param name="constantAscend"></param>
public virtual void VerticalWingSpeeds(Player player, ref float ascentWhenFalling, ref float ascentWhenRising,
ref float maxCanAscendMultiplier, ref float maxAscentMultiplier, ref float constantAscend)
{
if (item != null)
{
item.VerticalWingSpeeds(player, ref ascentWhenFalling, ref ascentWhenRising, ref maxCanAscendMultiplier,
ref maxAscentMultiplier, ref constantAscend);
}
}
/// <summary>
/// Allows you to modify horizontal wing speeds.
/// </summary>
/// <param name="player"></param>
/// <param name="speed"></param>
/// <param name="acceleration"></param>
public virtual void HorizontalWingSpeeds(Player player, ref float speed, ref float acceleration)
{
if (item != null)
{
item.HorizontalWingSpeeds(player, ref speed, ref acceleration);
}
}
/// <summary>
/// Allows for wing textures to do various things while in use. "inUse" is whether or not the jump button is currently pressed. Called when this wing texture visually appears on the player. Use to animate wings, create dusts, invoke sounds, and create lights. By default this will call the associated ModItem's WingUpdate if there is an associated ModItem.
/// </summary>
/// <param name="player"></param>
/// <param name="inUse"></param>
[method: Obsolete("WingUpdate will return a bool value later. (Use NewWingUpdate in the meantime.) False will keep everything the same. True, you need to handle all animations in your own code.")]
public virtual void WingUpdate(Player player, bool inUse)
{
item?.WingUpdate(player, inUse);
}
/// <summary>
/// Allows for wing textures to do various things while in use. "inUse" is whether or not the jump button is currently pressed. Called when this wing texture visually appears on the player. Use to animate wings, create dusts, invoke sounds, and create lights. By default this will call the associated ModItem's WingUpdate if there is an associated ModItem.
/// </summary>
/// <param name="player"></param>
/// <param name="inUse"></param>
/// <returns></returns>
public virtual bool NewWingUpdate(Player player, bool inUse)
{
WingUpdate(player, inUse);
return item?.NewWingUpdate(player, inUse) ?? false;
}
}
}
| |
// Copyright (c) 2014 hugula
// direct https://github.com/Hugulor/Hugula
//
using System.Collections;
using System.IO;
using System;
using System.Text;
[SLua.CustomLuaClass]
public class Msg {
public Msg()
{
buff=new MemoryStream();
br=new BinaryReader(buff);
}
public Msg(byte[] bytes)
{
buff=new MemoryStream(bytes);
br=new BinaryReader(buff);
this.Type=ReadShort();
}
public long Length
{
get{
return buff.Length;
}
}
public long Position
{
get{
return buff.Position;
}
set{
buff.Position=value;
}
}
public byte[] ToArray()
{
return buff.ToArray();
}
public string Debug()
{
byte[] bts = ToArray();
string bstr="";
foreach(byte i in bts)
{
bstr+=" "+i+" ";
}
return bstr;
}
public static string Debug(byte[] bts)
{
string bstr = "";
foreach (byte i in bts)
{
bstr += " " + i + " ";
}
return bstr;
}
/// <summary>
/// our message pro
/// </summary>
/// <returns>
/// The C array.
/// </returns>
public byte[] ToCArray()
{
byte[] date=ToArray();
short len=(short)(date.Length+2);//date[].length+type(short)
short type=(short)this.Type;
byte[] lenBytes = BitConverter.GetBytes(len);// date.length
System.Array.Reverse(lenBytes);
byte[] typeBytes=BitConverter.GetBytes(type);//tyep bytes
System.Array.Reverse(typeBytes);
int allLen=lenBytes.Length+typeBytes.Length+date.Length;
byte[] send=new byte[allLen];
lenBytes.CopyTo(send,0);//len
typeBytes.CopyTo(send,lenBytes.Length);//type
date.CopyTo(send,lenBytes.Length+typeBytes.Length);
return send;
}
public int Type
{
get{
return _type;
}
set
{
_type=value;
}
}
#region write
public void Write(byte[] value)
{
buff.Write(value,0,value.Length);
}
public void WriteBoolean(bool value)
{
buff.WriteByte (value ? ((byte)1) : ((byte)0));
}
public void WriteByte(byte value)
{
buff.WriteByte(value);
}
public void WriteChar(char value)
{
byte b= Convert.ToByte(value);
buff.WriteByte(b);
}
public void WriteUShort(ushort value)
{
byte[] bytes =BitConverter.GetBytes(value);
WriteBigEndian(bytes);
}
public void WriteUInt(uint value)
{
byte[] bytes =BitConverter.GetBytes(value);
WriteBigEndian(bytes);
}
public void WriteULong(ulong value)
{
byte[] bytes =BitConverter.GetBytes(value);
WriteBigEndian(bytes);
}
public void WriteShort(int value)
{
byte[] bytes = BitConverter.GetBytes((short)value);
WriteBigEndian(bytes);
}
public void WriteFloat(float value)
{
byte[] bytes = BitConverter.GetBytes(value);
WriteBigEndian(bytes);
}
public void WriteInt(int value)
{
// Debug.Log("writeInt ::::::::::::"+value);
byte[] bytes = BitConverter.GetBytes(value);
WriteBigEndian(bytes);
}
public void WriteString(string value)
{
UTF8Encoding utf8Encoding = new UTF8Encoding();
int byteCount = utf8Encoding.GetByteCount(value);
byte[] buffer = utf8Encoding.GetBytes(value);
this.WriteShort(byteCount);
if (buffer.Length > 0)
Write(buffer);
}
public void WriteUTFBytes(string value)
{
UTF8Encoding utf8Encoding = new UTF8Encoding();
byte[] buffer = utf8Encoding.GetBytes(value);
if (buffer.Length > 0)
Write(buffer);
}
#endregion
#region read
public bool ReadBoolean()
{
return br.ReadBoolean();
}
public byte ReadByte()
{
return br.ReadByte();
}
public char ReadChar()
{
byte byt = br.ReadByte();
return Convert.ToChar(byt);
}
public ushort ReadUShort()
{
byte[] bytes = br.ReadBytes(2);
Array.Reverse(bytes);
return BitConverter.ToUInt16( bytes, 0 );
}
public uint ReadUInt()
{
byte[] bytes = br.ReadBytes(4);
Array.Reverse(bytes);
return BitConverter.ToUInt32( bytes, 0 );
}
public ulong ReadULong()
{
byte[] bytes = br.ReadBytes(8);
Array.Reverse(bytes);
return BitConverter.ToUInt64( bytes, 0 );
}
public short ReadShort()
{
byte[] bytes = br.ReadBytes(2);
Array.Reverse(bytes);
return BitConverter.ToInt16(bytes,0);
}
public int ReadInt()
{
byte[] bytes = br.ReadBytes(4);
Array.Reverse(bytes);
return BitConverter.ToInt32(bytes,0);
}
public float ReadFloat()
{
byte[] bytes = br.ReadBytes(4);
Array.Reverse(bytes);
float value = BitConverter.ToSingle(bytes, 0);
return value;
}
public string ReadString()
{
int length = ReadShort();
return ReadUTF(length);
}
public string ReadUTF(int length)
{
if( length == 0 )
return string.Empty;
byte[] encodedBytes = br.ReadBytes(length);
string decodedString = Encoding.UTF8.GetString(encodedBytes, 0, encodedBytes.Length);
return decodedString;
}
#endregion
#region member
protected void WriteBigEndian(byte[] bytes)
{
if( bytes == null )
return;
for(int i = bytes.Length-1; i >= 0; i--) // for(int i = 0; i < bytes.Length; i++)
{
buff.WriteByte( bytes[i] );
}
}
protected MemoryStream buff;
protected BinaryReader br;
protected int _type;
#endregion
}
| |
S/W Version Information
Model: Ref.Device-PQ
Tizen-Version: 2.2.1
Build-Number: Tizen_Ref.Device-PQ_20131107.2323
Build-Date: 2013.11.07 23:23:19
Crash Information
Process Name: QRDemo
PID: 22957
Date: 2013-11-30 10:32:26(GMT+0400)
Executable File Path: /opt/apps/vd84JCg9vN/bin/QRDemo
This process is multi-thread process
pid=22957 tid=22957
Signal: 11
(SIGSEGV)
si_code: -6
signal sent by tkill (sent by pid 22957, uid 5000)
Register Information
r0 = 0x00000038, r1 = 0x00144490
r2 = 0x00144490, r3 = 0x0016f76e
r4 = 0x00000038, r5 = 0x00144490
r6 = 0x000e4358, r7 = 0xfff21d0c
r8 = 0xbebc9028, r9 = 0xffff73d0
r10 = 0xfff2289c, fp = 0xbebc8c58
ip = 0xb430d1c5, sp = 0xbebc8c20
lr = 0xb26ab868, pc = 0xb430d1cc
cpsr = 0x60000030
Memory Information
MemTotal: 797320 KB
MemFree: 53604 KB
Buffers: 40448 KB
Cached: 289860 KB
VmPeak: 122272 KB
VmSize: 122268 KB
VmLck: 0 KB
VmHWM: 22512 KB
VmRSS: 22512 KB
VmData: 8640 KB
VmStk: 136 KB
VmExe: 32 KB
VmLib: 79000 KB
VmPTE: 102 KB
VmSwap: 0 KB
Maps Information
00008000 00010000 r-xp /usr/bin/launchpad_preloading_preinitializing_daemon
00018000 000dc000 rw-p [heap]
000dc000 0016a000 rw-p [heap]
afd76000 afd82000 r-xp /usr/lib/libtzsvc.so.0.0.1
afd8f000 afd91000 r-xp /usr/lib/libemail-network.so.1.1.0
afd99000 afe43000 r-xp /usr/lib/libuw-imap-toolkit.so.0.0.0
afe51000 afe55000 r-xp /usr/lib/libss-client.so.1.0.0
afe5d000 afe62000 r-xp /usr/lib/libmmutil_jpeg.so.0.0.0
afe6b000 afe85000 r-xp /usr/lib/libnfc.so.1.0.0
afe8d000 afe9e000 r-xp /usr/lib/libnfc-common-lib.so.1.0.0
afea7000 afecd000 r-xp /usr/lib/libbluetooth-api.so.1.0.0
afed6000 afefc000 r-xp /usr/lib/libzmq.so.3.0.0
aff06000 aff0f000 r-xp /usr/lib/libpims-ipc.so.0.0.30
aff17000 aff1c000 r-xp /usr/lib/libmemenv.so.1.1.0
aff24000 aff62000 r-xp /usr/lib/libleveldb.so.1.1.0
aff6b000 aff73000 r-xp /usr/lib/libgstfft-0.10.so.0.25.0
aff7b000 affa5000 r-xp /usr/lib/libgstaudio-0.10.so.0.25.0
affae000 affbd000 r-xp /usr/lib/libgstvideo-0.10.so.0.25.0
affc5000 affdd000 r-xp /usr/lib/libgstpbutils-0.10.so.0.25.0
affdf000 b0004000 r-xp /usr/lib/libxslt.so.1.1.16
b000d000 b0011000 r-xp /usr/lib/libeukit.so.1.7.99
b0019000 b0021000 r-xp /usr/lib/libui-gadget-1.so.0.1.0
b0029000 b0032000 r-xp /usr/lib/libmsg_vobject.so
b003b000 b0045000 r-xp /usr/lib/libdrm-client.so.0.0.1
b004d000 b0066000 r-xp /usr/lib/libmsg_plugin_manager.so
b006f000 b00a8000 r-xp /usr/lib/libmsg_framework_handler.so
b00b1000 b00e5000 r-xp /usr/lib/libmsg_transaction_proxy.so
b00ee000 b012e000 r-xp /usr/lib/libmsg_utils.so
b012f000 b013e000 r-xp /usr/lib/libemail-common-use.so.1.1.0
b0147000 b01c2000 r-xp /usr/lib/libemail-core.so.1.1.0
b01d2000 b021b000 r-xp /usr/lib/libemail-storage.so.1.1.0
b0224000 b0231000 r-xp /usr/lib/libemail-ipc.so.1.1.0
b0239000 b0263000 r-xp /usr/lib/libSLP-location.so.0.0.0
b026c000 b0275000 r-xp /usr/lib/libdownload-provider-interface.so.1.1.6
b027d000 b0284000 r-xp /usr/lib/libmedia-utils.so.0.0.0
b028c000 b028e000 r-xp /usr/lib/libmedia-hash.so.1.0.0
b0296000 b02af000 r-xp /usr/lib/libmedia-thumbnail.so.1.0.0
b02b7000 b02b9000 r-xp /usr/lib/libmedia-svc-hash.so.1.0.0
b02c1000 b02d9000 r-xp /usr/lib/libmedia-service.so.1.0.0
b02e1000 b02f5000 r-xp /usr/lib/libnetwork.so.0.0.0
b02fe000 b0309000 r-xp /usr/lib/libstt.so
b0311000 b0317000 r-xp /usr/lib/libbadge.so.0.0.1
b031f000 b0325000 r-xp /usr/lib/libcapi-appfw-app-manager.so.0.1.0
b032d000 b0333000 r-xp /usr/lib/libshortcut.so.0.0.1
b033c000 b033f000 r-xp /usr/lib/libminicontrol-provider.so.0.0.1
b0347000 b0352000 r-xp /usr/lib/liblivebox-service.so.0.0.1
b035a000 b036f000 r-xp /usr/lib/liblivebox-viewer.so.0.0.1
b0377000 b037b000 r-xp /usr/lib/libcapi-appfw-package-manager.so.0.0.30
b0383000 b05a0000 r-xp /usr/lib/libface-engine-plugin.so
b05fe000 b0604000 r-xp /usr/lib/libcapi-network-nfc.so.0.0.11
b060d000 b0624000 r-xp /usr/lib/libcapi-network-bluetooth.so.0.1.40
b062c000 b0634000 r-xp /usr/lib/libcapi-network-wifi.so.0.1.2_24
b063c000 b0655000 r-xp /usr/lib/libaccounts-svc.so.0.2.66
b065d000 b06cf000 r-xp /usr/lib/libcontacts-service2.so.0.9.114.7
b06ee000 b0731000 r-xp /usr/lib/libcalendar-service2.so.0.1.44
b073b000 b0743000 r-xp /usr/lib/libcapi-web-favorites.so
b0744000 b1946000 r-xp /usr/lib/libewebkit2.so.0.11.113
b1a2b000 b1a33000 r-xp /usr/lib/libpush.so.0.2.12
b1a3b000 b1a56000 r-xp /usr/lib/libmsg_mapi.so.0.1.0
b1a5f000 b1a77000 r-xp /usr/lib/libemail-api.so.1.1.0
b1a7f000 b1a88000 r-xp /usr/lib/libcapi-system-sensor.so.0.1.17
b1a91000 b1a94000 r-xp /usr/lib/libcapi-telephony-sim.so.0.1.7
b1a9c000 b1a9f000 r-xp /usr/lib/libcapi-telephony-network-info.so.0.1.0
b1aa8000 b1ab3000 r-xp /usr/lib/libcapi-location-manager.so.0.1.11
b1abb000 b1abf000 r-xp /usr/lib/libcapi-web-url-download.so.0.1.0
b1ac7000 b1ae8000 r-xp /usr/lib/libcapi-content-media-content.so.0.2.59
b1af0000 b1af2000 r-xp /usr/lib/libcamsrcjpegenc.so.0.0.0
b1afa000 b1b0e000 r-xp /usr/lib/libwifi-direct.so.0.0
b1b16000 b1b1e000 r-xp /usr/lib/libcapi-network-tethering.so.0.1.0
b1b1f000 b1b28000 r-xp /usr/lib/libcapi-network-connection.so.0.1.3_18
b1b30000 b1b64000 r-xp /usr/lib/libopenal.so.1.13.0
b1b6d000 b1b70000 r-xp /usr/lib/libalut.so.0.1.0
b1b7a000 b1b7f000 r-xp /usr/lib/osp/libosp-speech-stt.so.1.2.2.0
b1b87000 b1ba5000 r-xp /usr/lib/osp/libosp-shell-core.so.1.2.2.1
b1bae000 b1c1f000 r-xp /usr/lib/osp/libosp-shell.so.1.2.2.1
b1c31000 b1c37000 r-xp /usr/lib/osp/libosp-speech-tts.so.1.2.2.0
b1c3f000 b1c62000 r-xp /usr/lib/osp/libosp-face.so.1.2.2.0
b1c6c000 b1cca000 r-xp /usr/lib/osp/libosp-nfc.so.1.2.2.0
b1cd6000 b1d31000 r-xp /usr/lib/osp/libosp-bluetooth.so.1.2.2.0
b1d3d000 b1db0000 r-xp /usr/lib/osp/libosp-wifi.so.1.2.2.0
b1dbc000 b1e7d000 r-xp /usr/lib/osp/libosp-social.so.1.2.2.0
b1e87000 b1efc000 r-xp /usr/lib/osp/libosp-web.so.1.2.2.0
b1f0a000 b1f57000 r-xp /usr/lib/osp/libosp-messaging.so.1.2.2.0
b1f61000 b1f7e000 r-xp /usr/lib/osp/libosp-uix.so.1.2.2.0
b1f88000 b1fa7000 r-xp /usr/lib/osp/libosp-telephony.so.1.2.2.0
b1fb0000 b1fc9000 r-xp /usr/lib/osp/libosp-locations.so.1.2.2.3
b1fd2000 b202f000 r-xp /usr/lib/osp/libosp-content.so.1.2.2.0
b2038000 b204a000 r-xp /usr/lib/osp/libosp-ime.so.1.2.2.0
b2053000 b206d000 r-xp /usr/lib/osp/libosp-json.so.1.2.2.0
b2077000 b2089000 r-xp /usr/lib/libmmfile_utils.so.0.0.0
b2091000 b2096000 r-xp /usr/lib/libmmffile.so.0.0.0
b209e000 b2102000 r-xp /usr/lib/libmmfcamcorder.so.0.0.0
b210f000 b21d4000 r-xp /usr/lib/osp/libosp-net.so.1.2.2.0
b21e2000 b2405000 r-xp /usr/lib/osp/libarengine.so
b2481000 b2486000 r-xp /usr/lib/libcapi-media-metadata-extractor.so
b248e000 b2493000 r-xp /usr/lib/libcapi-media-recorder.so.0.1.3
b249b000 b24a6000 r-xp /usr/lib/libcapi-media-camera.so.0.1.4
b24ae000 b24b1000 r-xp /usr/lib/libcapi-media-sound-manager.so.0.1.1
b24b9000 b24c7000 r-xp /usr/lib/libcapi-media-player.so.0.1.1
b24cf000 b24f0000 r-xp /usr/lib/libopencore-amrnb.so.0.0.2
b24f9000 b24fd000 r-xp /usr/lib/libogg.so.0.7.1
b2505000 b2527000 r-xp /usr/lib/libvorbis.so.0.4.3
b252f000 b2533000 r-xp /usr/lib/libcapi-media-audio-io.so.0.2.0
b253b000 b2559000 r-xp /usr/lib/osp/libosp-image.so.1.2.2.0
b2562000 b2580000 r-xp /usr/lib/osp/libosp-vision.so.1.2.2.0
b2589000 b2680000 r-xp /usr/lib/osp/libosp-media.so.1.2.2.0
b26a4000 b26b4000 r-xp /opt/usr/apps/vd84JCg9vN/bin/QRDemo.exe
b26bd000 b272f000 r-xp /usr/lib/libosp-env-config.so.1.2.2.1
b2737000 b2771000 r-xp /usr/lib/libpulsecommon-0.9.23.so
b277a000 b277e000 r-xp /usr/lib/libmmfsoundcommon.so.0.0.0
b2786000 b27b7000 r-xp /usr/lib/libpulse.so.0.12.4
b27bf000 b2822000 r-xp /usr/lib/libasound.so.2.0.0
b282c000 b282f000 r-xp /usr/lib/libpulse-simple.so.0.0.3
b2837000 b283b000 r-xp /usr/lib/libascenario-0.2.so.0.0.0
b2844000 b2861000 r-xp /usr/lib/libavsysaudio.so.0.0.1
b2869000 b2877000 r-xp /usr/lib/libmmfsound.so.0.1.0
b287f000 b291b000 r-xp /usr/lib/libgstreamer-0.10.so.0.30.0
b2927000 b2968000 r-xp /usr/lib/libgstbase-0.10.so.0.30.0
b2971000 b297a000 r-xp /usr/lib/libgstapp-0.10.so.0.25.0
b2982000 b298f000 r-xp /usr/lib/libgstinterfaces-0.10.so.0.25.0
b2998000 b299e000 r-xp /usr/lib/libUMP.so
b29a6000 b29a9000 r-xp /usr/lib/libmm_ta.so.0.0.0
b29b1000 b29c0000 r-xp /usr/lib/libICE.so.6.3.0
b29ca000 b29cf000 r-xp /usr/lib/libSM.so.6.0.1
b29d7000 b29d8000 r-xp /usr/lib/libmmfkeysound.so.0.0.0
b29e0000 b29e8000 r-xp /usr/lib/libmmfcommon.so.0.0.0
b29f0000 b29f8000 r-xp /usr/lib/libaudio-session-mgr.so.0.0.0
b2a03000 b2a06000 r-xp /usr/lib/libmmfsession.so.0.0.0
b2a0e000 b2a52000 r-xp /usr/lib/libmmfplayer.so.0.0.0
b2a5b000 b2a6e000 r-xp /usr/lib/libEGL_platform.so
b2a77000 b2b4e000 r-xp /usr/lib/libMali.so
b2b59000 b2b5f000 r-xp /usr/lib/libxcb-render.so.0.0.0
b2b67000 b2b68000 r-xp /usr/lib/libxcb-shm.so.0.0.0
b2b71000 b2baf000 r-xp /usr/lib/libGLESv2.so.2.0
b2bb7000 b2c02000 r-xp /usr/lib/libtiff.so.5.1.0
b2c0d000 b2c36000 r-xp /usr/lib/libturbojpeg.so
b2c4f000 b2c55000 r-xp /usr/lib/libmmutil_imgp.so.0.0.0
b2c5d000 b2c63000 r-xp /usr/lib/libgif.so.4.1.6
b2c6b000 b2c8d000 r-xp /usr/lib/libavutil.so.51.73.101
b2c9c000 b2cca000 r-xp /usr/lib/libswscale.so.2.1.101
b2cd3000 b2fca000 r-xp /usr/lib/libavcodec.so.54.59.100
b32f1000 b330a000 r-xp /usr/lib/libpng12.so.0.50.0
b3313000 b3319000 r-xp /usr/lib/libfeedback.so.0.1.4
b3321000 b332d000 r-xp /usr/lib/libtts.so
b3335000 b334c000 r-xp /usr/lib/libEGL.so.1.4
b3355000 b340c000 r-xp /usr/lib/libcairo.so.2.11200.12
b3416000 b3430000 r-xp /usr/lib/osp/libosp-image-core.so.1.2.2.0
b3439000 b3d37000 r-xp /usr/lib/osp/libosp-uifw.so.1.2.2.1
b3daa000 b3daf000 r-xp /usr/lib/libslp_devman_plugin.so
b3db8000 b3dbb000 r-xp /usr/lib/libsyspopup_caller.so.0.1.0
b3dc3000 b3dc7000 r-xp /usr/lib/libsysman.so.0.2.0
b3dcf000 b3de0000 r-xp /usr/lib/libsecurity-server-commons.so.1.0.0
b3de9000 b3deb000 r-xp /usr/lib/libsystemd-daemon.so.0.0.1
b3df3000 b3df5000 r-xp /usr/lib/libdeviced.so.0.1.0
b3dfd000 b3e13000 r-xp /usr/lib/libpkgmgr_parser.so.0.1.0
b3e1b000 b3e1d000 r-xp /usr/lib/libpkgmgr_installer_status_broadcast_server.so.0.1.0
b3e25000 b3e28000 r-xp /usr/lib/libpkgmgr_installer_client.so.0.1.0
b3e30000 b3e33000 r-xp /usr/lib/libdevice-node.so.0.1
b3e3b000 b3e3f000 r-xp /usr/lib/libheynoti.so.0.0.2
b3e47000 b3e8c000 r-xp /usr/lib/libsoup-2.4.so.1.5.0
b3e95000 b3eaa000 r-xp /usr/lib/libsecurity-server-client.so.1.0.1
b3eb3000 b3eb7000 r-xp /usr/lib/libcapi-system-info.so.0.2.0
b3ebf000 b3ec4000 r-xp /usr/lib/libcapi-system-system-settings.so.0.0.2
b3ecc000 b3ecd000 r-xp /usr/lib/libcapi-system-power.so.0.1.1
b3ed6000 b3ed9000 r-xp /usr/lib/libcapi-system-device.so.0.1.0
b3ee1000 b3ee4000 r-xp /usr/lib/libcapi-system-runtime-info.so.0.0.3
b3eed000 b3ef0000 r-xp /usr/lib/libcapi-network-serial.so.0.0.8
b3ef8000 b3ef9000 r-xp /usr/lib/libcapi-content-mime-type.so.0.0.2
b3f01000 b3f0f000 r-xp /usr/lib/libcapi-appfw-application.so.0.1.0
b3f18000 b3f3a000 r-xp /usr/lib/libSLP-tapi.so.0.0.0
b3f42000 b3f45000 r-xp /usr/lib/libuuid.so.1.3.0
b3f4e000 b3f6c000 r-xp /usr/lib/libpkgmgr-info.so.0.0.17
b3f74000 b3f8b000 r-xp /usr/lib/libpkgmgr-client.so.0.1.68
b3f94000 b3f95000 r-xp /usr/lib/libpmapi.so.1.2
b3f9d000 b3fa5000 r-xp /usr/lib/libminizip.so.1.0.0
b3fad000 b3fb8000 r-xp /usr/lib/libmessage-port.so.1.2.2.1
b3fc0000 b4098000 r-xp /usr/lib/libxml2.so.2.7.8
b40a5000 b40c3000 r-xp /usr/lib/libpcre.so.0.0.1
b40cb000 b40ce000 r-xp /usr/lib/libiniparser.so.0
b40d7000 b40db000 r-xp /usr/lib/libhaptic.so.0.1
b40e3000 b40ee000 r-xp /usr/lib/libcryptsvc.so.0.0.1
b40fb000 b4100000 r-xp /usr/lib/libdevman.so.0.1
b4109000 b410d000 r-xp /usr/lib/libchromium.so.1.0
b4115000 b411b000 r-xp /usr/lib/libappsvc.so.0.1.0
b4123000 b4124000 r-xp /usr/lib/osp/libappinfo.so.1.2.2.1
b4134000 b4136000 r-xp /opt/usr/apps/vd84JCg9vN/bin/QRDemo
b413e000 b4144000 r-xp /usr/lib/libalarm.so.0.0.0
b414d000 b415f000 r-xp /usr/lib/libprivacy-manager-client.so.0.0.5
b4167000 b4467000 r-xp /usr/lib/osp/libosp-appfw.so.1.2.2.1
b4486000 b4490000 r-xp /lib/libnss_files-2.13.so
b4499000 b44a2000 r-xp /lib/libnss_nis-2.13.so
b44ab000 b44bc000 r-xp /lib/libnsl-2.13.so
b44c7000 b44cd000 r-xp /lib/libnss_compat-2.13.so
b44d6000 b44df000 r-xp /usr/lib/libcapi-security-privilege-manager.so.0.0.3
b4807000 b4818000 r-xp /usr/lib/libcom-core.so.0.0.1
b4820000 b4822000 r-xp /usr/lib/libdri2.so.0.0.0
b482a000 b4832000 r-xp /usr/lib/libdrm.so.2.4.0
b483a000 b483e000 r-xp /usr/lib/libtbm.so.1.0.0
b4846000 b4849000 r-xp /usr/lib/libXv.so.1.0.0
b4851000 b491c000 r-xp /usr/lib/libscim-1.0.so.8.2.3
b4932000 b4942000 r-xp /usr/lib/libnotification.so.0.1.0
b494a000 b496e000 r-xp /usr/lib/ecore/immodules/libisf-imf-module.so
b4977000 b4987000 r-xp /lib/libresolv-2.13.so
b498b000 b498d000 r-xp /usr/lib/libgmodule-2.0.so.0.3200.3
b4995000 b4ae8000 r-xp /usr/lib/libcrypto.so.1.0.0
b4b06000 b4b52000 r-xp /usr/lib/libssl.so.1.0.0
b4b5e000 b4b8a000 r-xp /usr/lib/libidn.so.11.5.44
b4b93000 b4b9d000 r-xp /usr/lib/libcares.so.2.0.0
b4ba5000 b4bbc000 r-xp /lib/libexpat.so.1.5.2
b4bc6000 b4bea000 r-xp /usr/lib/libicule.so.48.1
b4bf3000 b4bfb000 r-xp /usr/lib/libsf_common.so
b4c03000 b4c9e000 r-xp /usr/lib/libstdc++.so.6.0.14
b4cb1000 b4d8e000 r-xp /usr/lib/libgio-2.0.so.0.3200.3
b4d99000 b4dbe000 r-xp /usr/lib/libexif.so.12.3.3
b4dd2000 b4ddc000 r-xp /usr/lib/libethumb.so.1.7.99
b4de4000 b4e28000 r-xp /usr/lib/libsndfile.so.1.0.25
b4e36000 b4e38000 r-xp /usr/lib/libctxdata.so.0.0.0
b4e40000 b4e4e000 r-xp /usr/lib/libremix.so.0.0.0
b4e56000 b4e57000 r-xp /usr/lib/libecore_imf_evas.so.1.7.99
b4e5f000 b4e78000 r-xp /usr/lib/liblua-5.1.so
b4e81000 b4e88000 r-xp /usr/lib/libembryo.so.1.7.99
b4e91000 b4e94000 r-xp /usr/lib/libecore_input_evas.so.1.7.99
b4e9c000 b4ed9000 r-xp /usr/lib/libcurl.so.4.3.0
b4ee3000 b4ee7000 r-xp /usr/lib/libecore_ipc.so.1.7.99
b4ef0000 b4f5a000 r-xp /usr/lib/libpixman-1.so.0.28.2
b4f67000 b4f8b000 r-xp /usr/lib/libfontconfig.so.1.5.0
b4f94000 b4ff0000 r-xp /usr/lib/libharfbuzz.so.0.907.0
b5002000 b5016000 r-xp /usr/lib/libfribidi.so.0.3.1
b501e000 b5073000 r-xp /usr/lib/libfreetype.so.6.8.1
b507e000 b50a2000 r-xp /usr/lib/libjpeg.so.8.0.2
b50ba000 b50d1000 r-xp /lib/libz.so.1.2.5
b50d9000 b50e6000 r-xp /usr/lib/libsensor.so.1.1.0
b50f1000 b50f3000 r-xp /usr/lib/libapp-checker.so.0.1.0
b50fb000 b5101000 r-xp /usr/lib/libxdgmime.so.1.1.0
b6218000 b6300000 r-xp /usr/lib/libicuuc.so.48.1
b630d000 b642d000 r-xp /usr/lib/libicui18n.so.48.1
b643b000 b643e000 r-xp /usr/lib/libSLP-db-util.so.0.1.0
b6446000 b644f000 r-xp /usr/lib/libvconf.so.0.2.45
b6457000 b6465000 r-xp /usr/lib/libail.so.0.1.0
b646d000 b6485000 r-xp /usr/lib/libdbus-glib-1.so.2.2.2
b6486000 b648b000 r-xp /usr/lib/libffi.so.5.0.10
b6493000 b6494000 r-xp /usr/lib/libgthread-2.0.so.0.3200.3
b649c000 b64a6000 r-xp /usr/lib/libXext.so.6.4.0
b64af000 b64b2000 r-xp /usr/lib/libXtst.so.6.1.0
b64ba000 b64c0000 r-xp /usr/lib/libXrender.so.1.3.0
b64c8000 b64ce000 r-xp /usr/lib/libXrandr.so.2.2.0
b64d6000 b64d7000 r-xp /usr/lib/libXinerama.so.1.0.0
b64e0000 b64e9000 r-xp /usr/lib/libXi.so.6.1.0
b64f1000 b64f4000 r-xp /usr/lib/libXfixes.so.3.1.0
b64fc000 b64fe000 r-xp /usr/lib/libXgesture.so.7.0.0
b6506000 b6508000 r-xp /usr/lib/libXcomposite.so.1.0.0
b6510000 b6511000 r-xp /usr/lib/libXdamage.so.1.1.0
b651a000 b6521000 r-xp /usr/lib/libXcursor.so.1.0.2
b6529000 b6531000 r-xp /usr/lib/libemotion.so.1.7.99
b6539000 b6554000 r-xp /usr/lib/libecore_con.so.1.7.99
b655d000 b6562000 r-xp /usr/lib/libecore_imf.so.1.7.99
b656b000 b6573000 r-xp /usr/lib/libethumb_client.so.1.7.99
b657b000 b657d000 r-xp /usr/lib/libefreet_trash.so.1.7.99
b6585000 b6589000 r-xp /usr/lib/libefreet_mime.so.1.7.99
b6592000 b65a8000 r-xp /usr/lib/libefreet.so.1.7.99
b65b2000 b65bb000 r-xp /usr/lib/libedbus.so.1.7.99
b65c3000 b65c8000 r-xp /usr/lib/libecore_fb.so.1.7.99
b65d1000 b662d000 r-xp /usr/lib/libedje.so.1.7.99
b6637000 b664e000 r-xp /usr/lib/libecore_input.so.1.7.99
b6669000 b666e000 r-xp /usr/lib/libecore_file.so.1.7.99
b6676000 b6693000 r-xp /usr/lib/libecore_evas.so.1.7.99
b669c000 b66db000 r-xp /usr/lib/libeina.so.1.7.99
b66e4000 b6793000 r-xp /usr/lib/libevas.so.1.7.99
b67b5000 b67c8000 r-xp /usr/lib/libeet.so.1.7.99
b67d1000 b683b000 r-xp /lib/libm-2.13.so
b6847000 b684e000 r-xp /usr/lib/libutilX.so.1.1.0
b6856000 b685b000 r-xp /usr/lib/libappcore-common.so.1.1
b6863000 b686e000 r-xp /usr/lib/libaul.so.0.1.0
b6877000 b68ab000 r-xp /usr/lib/libgobject-2.0.so.0.3200.3
b68b4000 b68e4000 r-xp /usr/lib/libecore_x.so.1.7.99
b68ed000 b6902000 r-xp /usr/lib/libecore.so.1.7.99
b6919000 b6a39000 r-xp /usr/lib/libelementary.so.1.7.99
b6a4c000 b6a4f000 r-xp /lib/libattr.so.1.1.0
b6a57000 b6a59000 r-xp /usr/lib/libXau.so.6.0.0
b6a61000 b6a67000 r-xp /lib/librt-2.13.so
b6a70000 b6a78000 r-xp /lib/libcrypt-2.13.so
b6aa8000 b6aab000 r-xp /lib/libcap.so.2.21
b6ab3000 b6ab5000 r-xp /usr/lib/libiri.so
b6abd000 b6ad2000 r-xp /usr/lib/libxcb.so.1.1.0
b6ada000 b6ae5000 r-xp /lib/libunwind.so.8.0.1
b6b13000 b6c30000 r-xp /lib/libc-2.13.so
b6c3e000 b6c47000 r-xp /lib/libgcc_s-4.5.3.so.1
b6c4f000 b6c52000 r-xp /usr/lib/libsmack.so.1.0.0
b6c5a000 b6c86000 r-xp /usr/lib/libdbus-1.so.3.7.2
b6c8f000 b6c93000 r-xp /usr/lib/libbundle.so.0.1.22
b6c9b000 b6c9d000 r-xp /lib/libdl-2.13.so
b6ca6000 b6d80000 r-xp /usr/lib/libglib-2.0.so.0.3200.3
b6d89000 b6df3000 r-xp /usr/lib/libsqlite3.so.0.8.6
b6dfd000 b6e0a000 r-xp /usr/lib/libprivilege-control.so.0.0.2
b6e13000 b6ef9000 r-xp /usr/lib/libX11.so.6.3.0
b6f04000 b6f18000 r-xp /lib/libpthread-2.13.so
b6f28000 b6f2c000 r-xp /usr/lib/libappcore-efl.so.1.1
b6f35000 b6f36000 r-xp /usr/lib/libdlog.so.0.0.0
b6f3e000 b6f42000 r-xp /usr/lib/libsys-assert.so
b6f4a000 b6f67000 r-xp /lib/ld-2.13.so
bebaa000 bebcb000 rwxp [stack]
End of Maps Information
Callstack Information (PID:22957)
Call Stack Count: 27
0: Tizen::Io::RemoteMessagePort::SendMessage(Tizen::Base::Collection::IMap const*) + 0x7 (0xb430d1cc) [/usr/lib/osp/libosp-appfw.so] + 0x1a61cc
1: QRMessagePort::SendMessage(Tizen::Base::Collection::IMap const*) + 0x8c (0xb26ab868) [/opt/apps/vd84JCg9vN/bin/QRDemo.exe] + 0x7868
2: QrCodeRecognizer::OnAppInitialized() + 0x36c (0xb26ac9b4) [/opt/apps/vd84JCg9vN/bin/QRDemo.exe] + 0x89b4
3: Tizen::App::_UiAppImpl::OnAppInitialized() + 0x18 (0xb3ae5d1d) [/usr/lib/osp/libosp-uifw.so] + 0x6acd1d
4: Tizen::App::_AppImpl::OnService(service_s*, void*) + 0x208 (0xb425460d) [/usr/lib/osp/libosp-appfw.so] + 0xed60d
5: app_appcore_reset + 0x20 (0xb3f09b75) [/usr/lib/libcapi-appfw-application.so.0] + 0x8b75
6: __do_app + 0x2b4 (0xb6f2a0fd) [/usr/lib/libappcore-efl.so.1] + 0x20fd
7: __aul_handler + 0x60 (0xb685798d) [/usr/lib/libappcore-common.so.1] + 0x198d
8: app_start + 0x1c (0xb68661fd) [/usr/lib/libaul.so.0] + 0x31fd
9: __app_start_internal + 0x8 (0xb6866b25) [/usr/lib/libaul.so.0] + 0x3b25
10: g_idle_dispatch + 0xe (0xb6cdcc53) [/usr/lib/libglib-2.0.so.0] + 0x36c53
11: g_main_context_dispatch + 0xce (0xb6cdea37) [/usr/lib/libglib-2.0.so.0] + 0x38a37
12: _ecore_glib_select + 0x3ae (0xb68fc337) [/usr/lib/libecore.so.1] + 0xf337
13: _ecore_main_select + 0x294 (0xb68f78b9) [/usr/lib/libecore.so.1] + 0xa8b9
14: _ecore_main_loop_iterate_internal + 0x2de (0xb68f82f3) [/usr/lib/libecore.so.1] + 0xb2f3
15: ecore_main_loop_begin + 0x30 (0xb68f85cd) [/usr/lib/libecore.so.1] + 0xb5cd
16: elm_run + 0x6 (0xb69c119f) [/usr/lib/libelementary.so.1] + 0xa819f
17: appcore_efl_main + 0x2d4 (0xb6f2a7d5) [/usr/lib/libappcore-efl.so.1] + 0x27d5
18: app_efl_main + 0xc6 (0xb3f09e6b) [/usr/lib/libcapi-appfw-application.so.0] + 0x8e6b
19: Tizen::App::_AppImpl::Execute(Tizen::App::_IAppImpl*) + 0xe6 (0xb42548b3) [/usr/lib/osp/libosp-appfw.so] + 0xed8b3
20: Tizen::App::UiApp::Execute(Tizen::App::UiApp* (*)(), Tizen::Base::Collection::IList const*) + 0x64 (0xb3ae5a89) [/usr/lib/osp/libosp-uifw.so] + 0x6aca89
21: OspMain + 0x13c (0xb26abc60) [/opt/apps/vd84JCg9vN/bin/QRDemo.exe] + 0x7c60
22: main + 0x194 (0xb4134f21) [/opt/apps/vd84JCg9vN/bin/QRDemo] + 0xf21
23: __launchpad_main_loop + 0xe54 (0xb259) [/usr/bin/launchpad_preloading_preinitializing_daemon] + 0xb259
24: main + 0x486 (0xbcb3) [/usr/bin/launchpad_preloading_preinitializing_daemon] + 0xbcb3
25: __libc_start_main + 0x114 (0xb6b286e8) [/lib/libc.so.6] + 0x156e8
26: (0xa110) [/usr/bin/launchpad_preloading_preinitializing_daemon] + 0xa110
End of Call Stack
Package Information
Package Name: vd84JCg9vN.QRDemo
Package ID : vd84JCg9vN
Version: 1.0.0
Package Type: tpk
App Name: QRDemo
App ID: vd84JCg9vN.QRDemo
Type: Application
Categories: (NULL)
| |
using Lucene.Net.Documents;
namespace Lucene.Net.Index
{
using NUnit.Framework;
using BytesRef = Lucene.Net.Util.BytesRef;
using Directory = Lucene.Net.Store.Directory;
using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator;
using Document = Documents.Document;
using Field = Field;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer;
using TestUtil = Lucene.Net.Util.TestUtil;
[TestFixture]
public class TestSegmentTermDocs : LuceneTestCase
{
private Document TestDoc;
private Directory Dir;
private SegmentCommitInfo Info;
[SetUp]
public override void SetUp()
{
base.SetUp();
TestDoc = new Document();
Dir = NewDirectory();
DocHelper.SetupDoc(TestDoc);
Info = DocHelper.WriteDoc(Random(), Dir, TestDoc);
}
[TearDown]
public override void TearDown()
{
Dir.Dispose();
base.TearDown();
}
[Test]
public virtual void Test()
{
Assert.IsTrue(Dir != null);
}
[Test]
public virtual void TestTermDocs()
{
TestTermDocs(1);
}
public virtual void TestTermDocs(int indexDivisor)
{
//After adding the document, we should be able to read it back in
SegmentReader reader = new SegmentReader(Info, indexDivisor, NewIOContext(Random()));
Assert.IsTrue(reader != null);
Assert.AreEqual(indexDivisor, reader.TermInfosIndexDivisor);
TermsEnum terms = reader.Fields.Terms(DocHelper.TEXT_FIELD_2_KEY).Iterator(null);
terms.SeekCeil(new BytesRef("field"));
DocsEnum termDocs = TestUtil.Docs(Random(), terms, reader.LiveDocs, null, DocsEnum.FLAG_FREQS);
if (termDocs.NextDoc() != DocIdSetIterator.NO_MORE_DOCS)
{
int docId = termDocs.DocID();
Assert.IsTrue(docId == 0);
int freq = termDocs.Freq();
Assert.IsTrue(freq == 3);
}
reader.Dispose();
}
[Test]
public virtual void TestBadSeek()
{
TestBadSeek(1);
}
public virtual void TestBadSeek(int indexDivisor)
{
{
//After adding the document, we should be able to read it back in
SegmentReader reader = new SegmentReader(Info, indexDivisor, NewIOContext(Random()));
Assert.IsTrue(reader != null);
DocsEnum termDocs = TestUtil.Docs(Random(), reader, "textField2", new BytesRef("bad"), reader.LiveDocs, null, 0);
Assert.IsNull(termDocs);
reader.Dispose();
}
{
//After adding the document, we should be able to read it back in
SegmentReader reader = new SegmentReader(Info, indexDivisor, NewIOContext(Random()));
Assert.IsTrue(reader != null);
DocsEnum termDocs = TestUtil.Docs(Random(), reader, "junk", new BytesRef("bad"), reader.LiveDocs, null, 0);
Assert.IsNull(termDocs);
reader.Dispose();
}
}
[Test]
public virtual void TestSkipTo()
{
TestSkipTo(1);
}
public virtual void TestSkipTo(int indexDivisor)
{
Directory dir = NewDirectory();
IndexWriter writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMergePolicy(NewLogMergePolicy()));
Term ta = new Term("content", "aaa");
for (int i = 0; i < 10; i++)
{
AddDoc(writer, "aaa aaa aaa aaa");
}
Term tb = new Term("content", "bbb");
for (int i = 0; i < 16; i++)
{
AddDoc(writer, "bbb bbb bbb bbb");
}
Term tc = new Term("content", "ccc");
for (int i = 0; i < 50; i++)
{
AddDoc(writer, "ccc ccc ccc ccc");
}
// assure that we deal with a single segment
writer.ForceMerge(1);
writer.Dispose();
IndexReader reader = DirectoryReader.Open(dir, indexDivisor);
DocsEnum tdocs = TestUtil.Docs(Random(), reader, ta.Field, new BytesRef(ta.Text()), MultiFields.GetLiveDocs(reader), null, DocsEnum.FLAG_FREQS);
// without optimization (assumption skipInterval == 16)
// with next
Assert.IsTrue(tdocs.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
Assert.AreEqual(0, tdocs.DocID());
Assert.AreEqual(4, tdocs.Freq());
Assert.IsTrue(tdocs.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
Assert.AreEqual(1, tdocs.DocID());
Assert.AreEqual(4, tdocs.Freq());
Assert.IsTrue(tdocs.Advance(2) != DocIdSetIterator.NO_MORE_DOCS);
Assert.AreEqual(2, tdocs.DocID());
Assert.IsTrue(tdocs.Advance(4) != DocIdSetIterator.NO_MORE_DOCS);
Assert.AreEqual(4, tdocs.DocID());
Assert.IsTrue(tdocs.Advance(9) != DocIdSetIterator.NO_MORE_DOCS);
Assert.AreEqual(9, tdocs.DocID());
Assert.IsFalse(tdocs.Advance(10) != DocIdSetIterator.NO_MORE_DOCS);
// without next
tdocs = TestUtil.Docs(Random(), reader, ta.Field, new BytesRef(ta.Text()), MultiFields.GetLiveDocs(reader), null, 0);
Assert.IsTrue(tdocs.Advance(0) != DocIdSetIterator.NO_MORE_DOCS);
Assert.AreEqual(0, tdocs.DocID());
Assert.IsTrue(tdocs.Advance(4) != DocIdSetIterator.NO_MORE_DOCS);
Assert.AreEqual(4, tdocs.DocID());
Assert.IsTrue(tdocs.Advance(9) != DocIdSetIterator.NO_MORE_DOCS);
Assert.AreEqual(9, tdocs.DocID());
Assert.IsFalse(tdocs.Advance(10) != DocIdSetIterator.NO_MORE_DOCS);
// exactly skipInterval documents and therefore with optimization
// with next
tdocs = TestUtil.Docs(Random(), reader, tb.Field, new BytesRef(tb.Text()), MultiFields.GetLiveDocs(reader), null, DocsEnum.FLAG_FREQS);
Assert.IsTrue(tdocs.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
Assert.AreEqual(10, tdocs.DocID());
Assert.AreEqual(4, tdocs.Freq());
Assert.IsTrue(tdocs.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
Assert.AreEqual(11, tdocs.DocID());
Assert.AreEqual(4, tdocs.Freq());
Assert.IsTrue(tdocs.Advance(12) != DocIdSetIterator.NO_MORE_DOCS);
Assert.AreEqual(12, tdocs.DocID());
Assert.IsTrue(tdocs.Advance(15) != DocIdSetIterator.NO_MORE_DOCS);
Assert.AreEqual(15, tdocs.DocID());
Assert.IsTrue(tdocs.Advance(24) != DocIdSetIterator.NO_MORE_DOCS);
Assert.AreEqual(24, tdocs.DocID());
Assert.IsTrue(tdocs.Advance(25) != DocIdSetIterator.NO_MORE_DOCS);
Assert.AreEqual(25, tdocs.DocID());
Assert.IsFalse(tdocs.Advance(26) != DocIdSetIterator.NO_MORE_DOCS);
// without next
tdocs = TestUtil.Docs(Random(), reader, tb.Field, new BytesRef(tb.Text()), MultiFields.GetLiveDocs(reader), null, DocsEnum.FLAG_FREQS);
Assert.IsTrue(tdocs.Advance(5) != DocIdSetIterator.NO_MORE_DOCS);
Assert.AreEqual(10, tdocs.DocID());
Assert.IsTrue(tdocs.Advance(15) != DocIdSetIterator.NO_MORE_DOCS);
Assert.AreEqual(15, tdocs.DocID());
Assert.IsTrue(tdocs.Advance(24) != DocIdSetIterator.NO_MORE_DOCS);
Assert.AreEqual(24, tdocs.DocID());
Assert.IsTrue(tdocs.Advance(25) != DocIdSetIterator.NO_MORE_DOCS);
Assert.AreEqual(25, tdocs.DocID());
Assert.IsFalse(tdocs.Advance(26) != DocIdSetIterator.NO_MORE_DOCS);
// much more than skipInterval documents and therefore with optimization
// with next
tdocs = TestUtil.Docs(Random(), reader, tc.Field, new BytesRef(tc.Text()), MultiFields.GetLiveDocs(reader), null, DocsEnum.FLAG_FREQS);
Assert.IsTrue(tdocs.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
Assert.AreEqual(26, tdocs.DocID());
Assert.AreEqual(4, tdocs.Freq());
Assert.IsTrue(tdocs.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
Assert.AreEqual(27, tdocs.DocID());
Assert.AreEqual(4, tdocs.Freq());
Assert.IsTrue(tdocs.Advance(28) != DocIdSetIterator.NO_MORE_DOCS);
Assert.AreEqual(28, tdocs.DocID());
Assert.IsTrue(tdocs.Advance(40) != DocIdSetIterator.NO_MORE_DOCS);
Assert.AreEqual(40, tdocs.DocID());
Assert.IsTrue(tdocs.Advance(57) != DocIdSetIterator.NO_MORE_DOCS);
Assert.AreEqual(57, tdocs.DocID());
Assert.IsTrue(tdocs.Advance(74) != DocIdSetIterator.NO_MORE_DOCS);
Assert.AreEqual(74, tdocs.DocID());
Assert.IsTrue(tdocs.Advance(75) != DocIdSetIterator.NO_MORE_DOCS);
Assert.AreEqual(75, tdocs.DocID());
Assert.IsFalse(tdocs.Advance(76) != DocIdSetIterator.NO_MORE_DOCS);
//without next
tdocs = TestUtil.Docs(Random(), reader, tc.Field, new BytesRef(tc.Text()), MultiFields.GetLiveDocs(reader), null, 0);
Assert.IsTrue(tdocs.Advance(5) != DocIdSetIterator.NO_MORE_DOCS);
Assert.AreEqual(26, tdocs.DocID());
Assert.IsTrue(tdocs.Advance(40) != DocIdSetIterator.NO_MORE_DOCS);
Assert.AreEqual(40, tdocs.DocID());
Assert.IsTrue(tdocs.Advance(57) != DocIdSetIterator.NO_MORE_DOCS);
Assert.AreEqual(57, tdocs.DocID());
Assert.IsTrue(tdocs.Advance(74) != DocIdSetIterator.NO_MORE_DOCS);
Assert.AreEqual(74, tdocs.DocID());
Assert.IsTrue(tdocs.Advance(75) != DocIdSetIterator.NO_MORE_DOCS);
Assert.AreEqual(75, tdocs.DocID());
Assert.IsFalse(tdocs.Advance(76) != DocIdSetIterator.NO_MORE_DOCS);
reader.Dispose();
dir.Dispose();
}
[Test]
public virtual void TestIndexDivisor()
{
TestDoc = new Document();
DocHelper.SetupDoc(TestDoc);
DocHelper.WriteDoc(Random(), Dir, TestDoc);
TestTermDocs(2);
TestBadSeek(2);
TestSkipTo(2);
}
private void AddDoc(IndexWriter writer, string value)
{
Document doc = new Document();
doc.Add(NewTextField("content", value, Field.Store.NO));
writer.AddDocument(doc);
}
}
}
| |
//
// Copyright 2012-2013, Xamarin Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using Android.App;
using Android.Webkit;
using Android.OS;
using System.Threading.Tasks;
using Xamarin.Utilities.Android;
using System.Timers;
using System.Collections.Generic;
using Java.Interop;
namespace Xamarin.Auth
{
[Activity (Label = "Web Authenticator")]
#if XAMARIN_AUTH_INTERNAL
internal class WebAuthenticatorActivity : Activity
#else
public class WebAuthenticatorActivity : Activity
#endif
{
WebView webView;
internal class State : Java.Lang.Object
{
public WebAuthenticator Authenticator;
}
internal static readonly ActivityStateRepository<State> StateRepo = new ActivityStateRepository<State> ();
State state;
public class JavascriptInterceptor : Java.Lang.Object
{
private WebAuthenticatorActivity _activity;
public JavascriptInterceptor (WebAuthenticatorActivity activity)
{
_activity = activity;
}
[Export]
public void OnReceivedSamlResponse (string base64SamlResponse)
{
Console.WriteLine ("SAMLResponse={0}", base64SamlResponse);
_activity.OnSamlResponseReceived2 (base64SamlResponse);
}
}
protected override void OnCreate (Bundle savedInstanceState)
{
base.OnCreate (savedInstanceState);
//
// Load the state either from a configuration change or from the intent.
//
state = LastNonConfigurationInstance as State;
if (state == null && Intent.HasExtra ("StateKey")) {
var stateKey = Intent.GetStringExtra ("StateKey");
state = StateRepo.Remove (stateKey);
}
if (state == null) {
Finish ();
return;
}
Title = state.Authenticator.Title;
//
// Watch for completion
//
state.Authenticator.Completed += (s, e) => {
SetResult (e.IsAuthenticated ? Result.Ok : Result.Canceled);
Finish ();
};
state.Authenticator.Error += (s, e) => {
if (e.Exception != null) {
this.ShowError ("Authentication Error", e.Exception);
}
else {
this.ShowError ("Authentication Error", e.Message);
}
BeginLoadingInitialUrl ();
};
//
// Build the UI
//
webView = new WebView (this) {
Id = 42,
};
JavascriptInterceptor jsInterceptor = new JavascriptInterceptor (this);
webView.AddJavascriptInterface (jsInterceptor, "jsInterceptor");
webView.Settings.JavaScriptEnabled = true;
webView.SetWebViewClient (new Client (this));
webView.SetWebChromeClient (new ChromeClient ());
SetContentView (webView);
//
// Restore the UI state or start over
//
if (savedInstanceState != null) {
webView.RestoreState (savedInstanceState);
}
else {
if (Intent.GetBooleanExtra ("ClearCookies", true))
WebAuthenticator.ClearCookies();
BeginLoadingInitialUrl ();
}
}
void BeginLoadingInitialUrl ()
{
state.Authenticator.GetInitialUrlAsync ().ContinueWith (t => {
if (t.IsFaulted) {
this.ShowError ("Authentication Error", t.Exception);
}
else {
webView.LoadUrl (t.Result.AbsoluteUri);
}
}, TaskScheduler.FromCurrentSynchronizationContext ());
}
public override void OnBackPressed ()
{
state.Authenticator.OnCancelled ();
}
public override Java.Lang.Object OnRetainNonConfigurationInstance ()
{
return state;
}
protected override void OnSaveInstanceState (Bundle outState)
{
base.OnSaveInstanceState (outState);
webView.SaveState (outState);
}
public void OnSamlResponseReceived2 (string samlResponse)
{
this.RunOnUiThread (delegate {
Dictionary<string,string> formParams = new Dictionary<string,string> ();
formParams.Add ("SAMLResponse", samlResponse);
this.state.Authenticator.OnPageLoading (new Uri (webView.Url), formParams);
this.EndProgress ();
this.webView.StopLoading ();
});
}
void BeginProgress (string message)
{
webView.Enabled = false;
}
void EndProgress ()
{
webView.Enabled = true;
}
class ChromeClient : WebChromeClient
{
public override bool OnJsAlert (WebView view, string url, string message, JsResult result)
{
return base.OnJsAlert (view, url, message, result);
}
public override bool OnConsoleMessage (ConsoleMessage consoleMessage)
{
Console.WriteLine (consoleMessage.Message ());
return base.OnConsoleMessage (consoleMessage);
}
}
class Client : WebViewClient
{
WebAuthenticatorActivity activity;
public Client (WebAuthenticatorActivity activity)
{
this.activity = activity;
}
public override bool ShouldOverrideUrlLoading (WebView view, string url)
{
return false;
}
public override void OnPageStarted (WebView view, string url, Android.Graphics.Bitmap favicon)
{
var uri = new Uri (url);
view.LoadUrl ("javascript:var resp=document.getElementsByName('SAMLResponse'); if(resp[0] && resp[0].value) { window.jsInterceptor.OnReceivedSamlResponse(resp[0].value); }");
// view.LoadUrl ("javascript:var resp=document.getElementsByTagName('input'); if(resp[0]){alert(resp[0].value);} if(resp[0] && resp[0].value) { window.jsInterceptor.OnReceivedSamlResponse(resp[0].value); }");
// view.LoadUrl ("javascript:alert(document.forms[0].value);");
// activity.state.Authenticator.OnPageLoading (uri, formParams);
activity.BeginProgress (uri.Authority);
}
public override void OnPageFinished (WebView view, string url)
{
var uri = new Uri (url);
// activity.state.Authenticator.OnPageLoaded (uri);
activity.EndProgress ();
}
}
}
}
| |
namespace System
{
using FluentAssertions;
using Xunit;
using static System.DateTime;
using static System.DayOfWeek;
using static System.Globalization.CultureInfo;
using static System.TimeSpan;
public class DateTimeExtensionsTest
{
[Fact]
public void first_day_of_week_in_month_should_return_expected_result()
{
// arrange
var date = new DateTime( 2013, 3, 1 );
var expected = new DateTime( 2013, 3, 4 );
// act
var actual = date.FirstDayOfWeekInMonth( Monday );
// assert
actual.Date.Should().Be( expected.Date );
}
[Fact]
public void last_day_of_week_in_month_should_return_expected_result()
{
// arrange
var date = new DateTime( 2013, 3, 1 );
var expected = new DateTime( 2013, 3, 29 );
// act
var actual = date.LastDayOfWeekInMonth( Friday );
// assert
actual.Date.Should().Be( expected.Date );
}
[Fact]
public void day_of_week_in_month_should_return_expected_result()
{
// arrange
var date = new DateTime( 2013, 3, 1 );
var expected = new DateTime( 2013, 3, 11 );
// act
var actual = date.DayOfWeekInMonth( 2, Monday );
// assert
actual.Date.Should().Be( expected.Date );
}
[Fact]
public void start_of_day_should_return_expected_result()
{
// arrange
var now = Now;
var expected = now.Date;
// act
var startOfDay = now.StartOfDay();
// assert
startOfDay.Should().Be( expected );
}
[Fact]
public void start_of_week_should_return_expected_result()
{
// arrange
var date = new DateTime( 2013, 3, 1 );
var expected = new DateTime( 2013, 2, 24 );
// act
var startOfWeek = date.StartOfWeek();
// assert
startOfWeek.Date.Should().Be( expected.Date );
}
[Theory]
[InlineData( Sunday, "02-24-2013" )]
[InlineData( Monday, "02-25-2013" )]
public void start_of_week_with_custom_day_should_return_expected_result( DayOfWeek dayOfWeek, string expectedDate )
{
// arrange
var date = new DateTime( 2013, 3, 1 );
var expected = DateTime.Parse( expectedDate );
// act
var startOfWeek = date.StartOfWeek( dayOfWeek );
// assert
startOfWeek.Date.Should().Be( expected.Date );
}
[Fact]
public void start_of_month_should_return_expected_result()
{
// arrange
var date = new DateTime( 2013, 3, 26 );
var expected = new DateTime( 2013, 3, 1 );
// act
var startOfMonth = date.StartOfMonth();
// assert
startOfMonth.Date.Should().Be( expected.Date );
}
[Fact]
public void start_of_quarter_should_return_expected_result()
{
// arrange
var date = new DateTime( 2013, 3, 1 );
var expected = new DateTime( 2013, 1, 1 );
// act
var startOfQuarter = date.StartOfQuarter();
// assert
startOfQuarter.Date.Should().Be( expected.Date );
}
[Fact]
public void start_of_semester_should_return_expected_result()
{
// arrange
var date = new DateTime( 2013, 3, 1 );
var expected = new DateTime( 2013, 1, 1 );
// act
var startOfSemester = date.StartOfSemester();
// assert
startOfSemester.Date.Should().Be( expected.Date );
}
[Fact]
public void start_of_year_should_return_expected_result()
{
// arrange
var date = new DateTime( 2013, 3, 1 );
var expected = new DateTime( 2013, 1, 1 );
// act
var startOfYear = date.StartOfYear();
// assert
startOfYear.Date.Should().Be( expected.Date );
}
[Fact]
public void end_of_day_should_return_expected_result()
{
// arrange
var date = Now;
var expected = Today.AddDays( 1d ).Subtract( FromTicks( 1L ) );
// act
var endOfDay = date.EndOfDay();
// assert
endOfDay.Should().Be( expected );
}
[Fact]
public void end_of_week_should_return_expected_result()
{
// arrange
var date = new DateTime( 2013, 3, 1 );
var expected = new DateTime( 2013, 3, 2 );
// act
var endOfWeek = date.EndOfWeek();
// assert
endOfWeek.Date.Should().Be( expected.Date );
}
[Fact]
public void end_of_month_should_return_expected_result()
{
// arrange
var date = new DateTime( 2013, 3, 1 );
var expected = new DateTime( 2013, 3, 31 );
// act
var endOfMonth = date.EndOfMonth();
// assert
endOfMonth.Date.Should().Be( expected.Date );
}
[Fact]
public void end_of_quarter_should_return_expected_result()
{
// arrange
var date = new DateTime( 2013, 3, 1 );
var expected = new DateTime( 2013, 3, 31 );
// act
var endOfQuarter = date.EndOfQuarter();
// assert
endOfQuarter.Date.Should().Be( expected.Date );
}
[Fact]
public void end_of_semester_should_return_expected_result()
{
// arrange
var date = new DateTime( 2013, 3, 1 );
var expected = new DateTime( 2013, 6, 30 );
// act
var endOfSemester = date.EndOfSemester();
// assert
endOfSemester.Date.Should().Be( expected.Date );
}
[Fact]
public void end_of_year_should_return_expected_result()
{
// arrange
var date = new DateTime( 2013, 3, 1 );
var expected = new DateTime( 2013, 12, 31 );
// act
var endOfYear = date.EndOfYear();
// assert
endOfYear.Date.Should().Be( expected.Date );
}
[Fact]
public void week__should_return_expected_result()
{
// arrange
var date = new DateTime( 2013, 3, 1 );
// act
var week = date.Week();
// assert
week.Should().Be( 9 );
}
[Fact]
public void quarter_should_return_expected_result()
{
// arrange
var date = new DateTime( 2013, 4, 1 );
// act
var quarter = date.Quarter();
// assert
quarter.Should().Be( 2 );
}
[Fact]
public void semester_should_return_expected_result()
{
// arrange
var date = new DateTime( 2013, 4, 1 );
// act
var semester = date.Semester();
// assert
semester.Should().Be( 1 );
}
[Fact]
public void year_should_return_expected_result()
{
// arrange
var date = new DateTime( 2013, 3, 1 );
// act
var year = date.Year();
// assert
year.Should().Be( 2013 );
}
[Theory]
[InlineData( 2013, true )]
[InlineData( 10000, false )]
public void is_representable_should_return_expected_result_for_date( int year, bool expected )
{
// arrange
var date = Today;
var calendar = CurrentCulture.Calendar;
// act
var result = date.IsRepresentable( calendar, year, 1, 1 );
// assert
result.Should().Be( expected );
}
}
}
| |
using Shouldly;
using System;
using Xunit;
namespace Valit.Tests.Double
{
public class Double_IsEqualTo_Tests
{
[Fact]
public void Double_IsEqualTo_For_Not_Nullable_Values_Throws_When_Null_Rule_Is_Given()
{
var exception = Record.Exception(() => {
((IValitRule<Model, double>)null)
.IsEqualTo(1);
});
exception.ShouldBeOfType(typeof(ValitException));
}
[Fact]
public void Double_IsEqualTo_For_Not_Nullable_Value_And_Nullable_Value_Throws_When_Null_Rule_Is_Given()
{
var exception = Record.Exception(() => {
((IValitRule<Model, double>)null)
.IsEqualTo((double?)1);
});
exception.ShouldBeOfType(typeof(ValitException));
}
[Fact]
public void Double_IsEqualTo_For_Nullable_Value_And_Not_Nullable_Value_Throws_When_Null_Rule_Is_Given()
{
var exception = Record.Exception(() => {
((IValitRule<Model, double?>)null)
.IsEqualTo(1);
});
exception.ShouldBeOfType(typeof(ValitException));
}
[Fact]
public void Double_IsEqualTo_For_Nullable_Values_Throws_When_Null_Rule_Is_Given()
{
var exception = Record.Exception(() => {
((IValitRule<Model, double?>)null)
.IsEqualTo((double?)1);
});
exception.ShouldBeOfType(typeof(ValitException));
}
[Theory]
[InlineData(10, false)]
[InlineData(double.NaN, false)]
public void Double_IsEqualTo_Returns_Proper_Results_For_NaN_And_Value(double value, bool expected)
{
IValitResult result = ValitRules<Model>
.Create()
.Ensure(m => m.NaN, _ => _
.IsEqualTo(value))
.For(_model)
.Validate();
result.Succeeded.ShouldBe(expected);
}
[Theory]
[InlineData(10, false)]
[InlineData(double.NaN, false)]
public void Double_IsEqualTo_Returns_Proper_Results_For_NaN_And_NullableValue(double? value, bool expected)
{
IValitResult result = ValitRules<Model>
.Create()
.Ensure(m => m.NaN, _ => _
.IsEqualTo(value))
.For(_model)
.Validate();
result.Succeeded.ShouldBe(expected);
}
[Theory]
[InlineData(10, false)]
[InlineData(double.NaN, false)]
public void Double_IsEqualTo_Returns_Proper_Results_For_NullableNaN_And_Value(double value, bool expected)
{
IValitResult result = ValitRules<Model>
.Create()
.Ensure(m => m.NullableNaN, _ => _
.IsEqualTo(value))
.For(_model)
.Validate();
result.Succeeded.ShouldBe(expected);
}
[Theory]
[InlineData(10, false)]
[InlineData(double.NaN, false)]
public void Double_IsEqualTo_Returns_Proper_Results_For_NullableNaN_And_NullableValue(double? value, bool expected)
{
IValitResult result = ValitRules<Model>
.Create()
.Ensure(m => m.NullableNaN, _ => _
.IsEqualTo(value))
.For(_model)
.Validate();
result.Succeeded.ShouldBe(expected);
}
[Theory]
[InlineData(10, true)]
[InlineData(11, false)]
[InlineData(9, false)]
[InlineData(double.NaN, false)]
public void Double_IsEqualTo_Returns_Proper_Results_For_Not_Nullable_Values(double value, bool expected)
{
IValitResult result = ValitRules<Model>
.Create()
.Ensure(m => m.Value, _ => _
.IsEqualTo(value))
.For(_model)
.Validate();
result.Succeeded.ShouldBe(expected);
}
[Theory]
[InlineData((double)10, true)]
[InlineData((double)11, false)]
[InlineData((double)9, false)]
[InlineData(double.NaN, false)]
[InlineData(null, false)]
public void Double_IsEqualTo_Returns_Proper_Results_For_Not_Nullable_Value_And_Nullable_Value(double? value, bool expected)
{
IValitResult result = ValitRules<Model>
.Create()
.Ensure(m => m.Value, _ => _
.IsEqualTo(value))
.For(_model)
.Validate();
result.Succeeded.ShouldBe(expected);
}
[Theory]
[InlineData(false, 10, true)]
[InlineData(false, 11, false)]
[InlineData(false, 9, false)]
[InlineData(true, 10, false)]
[InlineData(false, double.NaN, false)]
[InlineData(true, double.NaN, false)]
public void Double_IsEqualTo_Returns_Proper_Results_For_Nullable_Value_And_Not_Nullable_Value(bool useNullValue, double value, bool expected)
{
IValitResult result = ValitRules<Model>
.Create()
.Ensure(m => useNullValue ? m.NullValue : m.NullableValue, _ => _
.IsEqualTo(value))
.For(_model)
.Validate();
result.Succeeded.ShouldBe(expected);
}
[Theory]
[InlineData(false, (double)10, true)]
[InlineData(false, (double)11, false)]
[InlineData(false, (double)9, false)]
[InlineData(false, double.NaN, false)]
[InlineData(false, null, false)]
[InlineData(true, (double)10, false)]
[InlineData(true, double.NaN, false)]
[InlineData(true, null, false)]
public void Double_IsEqualTo_Returns_Proper_Results_For_Nullable_Values(bool useNullValue, double? value, bool expected)
{
IValitResult result = ValitRules<Model>
.Create()
.Ensure(m => useNullValue ? m.NullValue : m.NullableValue, _ => _
.IsEqualTo(value))
.For(_model)
.Validate();
result.Succeeded.ShouldBe(expected);
}
#region ARRANGE
public Double_IsEqualTo_Tests()
{
_model = new Model();
}
private readonly Model _model;
class Model
{
public double Value => 10;
public double NaN => double.NaN;
public double? NullableValue => 10;
public double? NullValue => null;
public double? NullableNaN => double.NaN;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Nop.Core;
using Nop.Core.Caching;
using Nop.Core.Data;
using Nop.Core.Domain.Catalog;
using Nop.Core.Domain.Security;
using Nop.Core.Domain.Stores;
using Nop.Services.Customers;
using Nop.Services.Events;
namespace Nop.Services.Catalog
{
/// <summary>
/// Manufacturer service
/// </summary>
public partial class ManufacturerService : IManufacturerService
{
#region Constants
/// <summary>
/// Key for caching
/// </summary>
/// <remarks>
/// {0} : manufacturer ID
/// </remarks>
private const string MANUFACTURERS_BY_ID_KEY = "Nop.manufacturer.id-{0}";
/// <summary>
/// Key for caching
/// </summary>
/// <remarks>
/// {0} : show hidden records?
/// {1} : manufacturer ID
/// {2} : page index
/// {3} : page size
/// {4} : current customer ID
/// {5} : store ID
/// </remarks>
private const string PRODUCTMANUFACTURERS_ALLBYMANUFACTURERID_KEY = "Nop.productmanufacturer.allbymanufacturerid-{0}-{1}-{2}-{3}-{4}-{5}";
/// <summary>
/// Key for caching
/// </summary>
/// <remarks>
/// {0} : show hidden records?
/// {1} : product ID
/// {2} : current customer ID
/// {3} : store ID
/// </remarks>
private const string PRODUCTMANUFACTURERS_ALLBYPRODUCTID_KEY = "Nop.productmanufacturer.allbyproductid-{0}-{1}-{2}-{3}";
/// <summary>
/// Key pattern to clear cache
/// </summary>
private const string MANUFACTURERS_PATTERN_KEY = "Nop.manufacturer.";
/// <summary>
/// Key pattern to clear cache
/// </summary>
private const string PRODUCTMANUFACTURERS_PATTERN_KEY = "Nop.productmanufacturer.";
#endregion
#region Fields
private readonly IRepository<Manufacturer> _manufacturerRepository;
private readonly IRepository<ProductManufacturer> _productManufacturerRepository;
private readonly IRepository<Product> _productRepository;
private readonly IRepository<AclRecord> _aclRepository;
private readonly IRepository<StoreMapping> _storeMappingRepository;
private readonly IWorkContext _workContext;
private readonly IStoreContext _storeContext;
private readonly IEventPublisher _eventPublisher;
private readonly ICacheManager _cacheManager;
private readonly CatalogSettings _catalogSettings;
#endregion
#region Ctor
/// <summary>
/// Ctor
/// </summary>
/// <param name="cacheManager">Cache manager</param>
/// <param name="manufacturerRepository">Category repository</param>
/// <param name="productManufacturerRepository">ProductCategory repository</param>
/// <param name="productRepository">Product repository</param>
/// <param name="aclRepository">ACL record repository</param>
/// <param name="storeMappingRepository">Store mapping repository</param>
/// <param name="workContext">Work context</param>
/// <param name="storeContext">Store context</param>
/// <param name="catalogSettings">Catalog settings</param>
/// <param name="eventPublisher">Event published</param>
public ManufacturerService(ICacheManager cacheManager,
IRepository<Manufacturer> manufacturerRepository,
IRepository<ProductManufacturer> productManufacturerRepository,
IRepository<Product> productRepository,
IRepository<AclRecord> aclRepository,
IRepository<StoreMapping> storeMappingRepository,
IWorkContext workContext,
IStoreContext storeContext,
CatalogSettings catalogSettings,
IEventPublisher eventPublisher)
{
this._cacheManager = cacheManager;
this._manufacturerRepository = manufacturerRepository;
this._productManufacturerRepository = productManufacturerRepository;
this._productRepository = productRepository;
this._aclRepository = aclRepository;
this._storeMappingRepository = storeMappingRepository;
this._workContext = workContext;
this._storeContext = storeContext;
this._catalogSettings = catalogSettings;
this._eventPublisher = eventPublisher;
}
#endregion
#region Methods
/// <summary>
/// Deletes a manufacturer
/// </summary>
/// <param name="manufacturer">Manufacturer</param>
public virtual void DeleteManufacturer(Manufacturer manufacturer)
{
if (manufacturer == null)
throw new ArgumentNullException("manufacturer");
manufacturer.Deleted = true;
UpdateManufacturer(manufacturer);
}
/// <summary>
/// Gets all manufacturers
/// </summary>
/// <param name="manufacturerName">Manufacturer name</param>
/// <param name="pageIndex">Page index</param>
/// <param name="pageSize">Page size</param>
/// <param name="showHidden">A value indicating whether to show hidden records</param>
/// <returns>Manufacturers</returns>
public virtual IPagedList<Manufacturer> GetAllManufacturers(string manufacturerName = "",
int pageIndex = 0,
int pageSize = int.MaxValue,
bool showHidden = false)
{
var query = _manufacturerRepository.Table;
if (!showHidden)
query = query.Where(m => m.Published);
if (!String.IsNullOrWhiteSpace(manufacturerName))
query = query.Where(m => m.Name.Contains(manufacturerName));
query = query.Where(m => !m.Deleted);
query = query.OrderBy(m => m.DisplayOrder);
if (!showHidden && (!_catalogSettings.IgnoreAcl || !_catalogSettings.IgnoreStoreLimitations))
{
if (!_catalogSettings.IgnoreAcl)
{
//ACL (access control list)
var allowedCustomerRolesIds = _workContext.CurrentCustomer.GetCustomerRoleIds();
query = from m in query
join acl in _aclRepository.Table
on new { c1 = m.Id, c2 = "Manufacturer" } equals new { c1 = acl.EntityId, c2 = acl.EntityName } into m_acl
from acl in m_acl.DefaultIfEmpty()
where !m.SubjectToAcl || allowedCustomerRolesIds.Contains(acl.CustomerRoleId)
select m;
}
if (!_catalogSettings.IgnoreStoreLimitations)
{
//Store mapping
var currentStoreId = _storeContext.CurrentStore.Id;
query = from m in query
join sm in _storeMappingRepository.Table
on new { c1 = m.Id, c2 = "Manufacturer" } equals new { c1 = sm.EntityId, c2 = sm.EntityName } into m_sm
from sm in m_sm.DefaultIfEmpty()
where !m.LimitedToStores || currentStoreId == sm.StoreId
select m;
}
//only distinct manufacturers (group by ID)
query = from m in query
group m by m.Id
into mGroup
orderby mGroup.Key
select mGroup.FirstOrDefault();
query = query.OrderBy(m => m.DisplayOrder);
}
return new PagedList<Manufacturer>(query, pageIndex, pageSize);
}
/// <summary>
/// Gets a manufacturer
/// </summary>
/// <param name="manufacturerId">Manufacturer identifier</param>
/// <returns>Manufacturer</returns>
public virtual Manufacturer GetManufacturerById(int manufacturerId)
{
if (manufacturerId == 0)
return null;
string key = string.Format(MANUFACTURERS_BY_ID_KEY, manufacturerId);
return _cacheManager.Get(key, () => _manufacturerRepository.GetById(manufacturerId));
}
/// <summary>
/// Inserts a manufacturer
/// </summary>
/// <param name="manufacturer">Manufacturer</param>
public virtual void InsertManufacturer(Manufacturer manufacturer)
{
if (manufacturer == null)
throw new ArgumentNullException("manufacturer");
_manufacturerRepository.Insert(manufacturer);
//cache
_cacheManager.RemoveByPattern(MANUFACTURERS_PATTERN_KEY);
_cacheManager.RemoveByPattern(PRODUCTMANUFACTURERS_PATTERN_KEY);
//event notification
_eventPublisher.EntityInserted(manufacturer);
}
/// <summary>
/// Updates the manufacturer
/// </summary>
/// <param name="manufacturer">Manufacturer</param>
public virtual void UpdateManufacturer(Manufacturer manufacturer)
{
if (manufacturer == null)
throw new ArgumentNullException("manufacturer");
_manufacturerRepository.Update(manufacturer);
//cache
_cacheManager.RemoveByPattern(MANUFACTURERS_PATTERN_KEY);
_cacheManager.RemoveByPattern(PRODUCTMANUFACTURERS_PATTERN_KEY);
//event notification
_eventPublisher.EntityUpdated(manufacturer);
}
/// <summary>
/// Deletes a product manufacturer mapping
/// </summary>
/// <param name="productManufacturer">Product manufacturer mapping</param>
public virtual void DeleteProductManufacturer(ProductManufacturer productManufacturer)
{
if (productManufacturer == null)
throw new ArgumentNullException("productManufacturer");
_productManufacturerRepository.Delete(productManufacturer);
//cache
_cacheManager.RemoveByPattern(MANUFACTURERS_PATTERN_KEY);
_cacheManager.RemoveByPattern(PRODUCTMANUFACTURERS_PATTERN_KEY);
//event notification
_eventPublisher.EntityDeleted(productManufacturer);
}
/// <summary>
/// Gets product manufacturer collection
/// </summary>
/// <param name="manufacturerId">Manufacturer identifier</param>
/// <param name="pageIndex">Page index</param>
/// <param name="pageSize">Page size</param>
/// <param name="showHidden">A value indicating whether to show hidden records</param>
/// <returns>Product manufacturer collection</returns>
public virtual IPagedList<ProductManufacturer> GetProductManufacturersByManufacturerId(int manufacturerId,
int pageIndex = 0, int pageSize = int.MaxValue, bool showHidden = false)
{
if (manufacturerId == 0)
return new PagedList<ProductManufacturer>(new List<ProductManufacturer>(), pageIndex, pageSize);
string key = string.Format(PRODUCTMANUFACTURERS_ALLBYMANUFACTURERID_KEY, showHidden, manufacturerId, pageIndex, pageSize, _workContext.CurrentCustomer.Id, _storeContext.CurrentStore.Id);
return _cacheManager.Get(key, () =>
{
var query = from pm in _productManufacturerRepository.Table
join p in _productRepository.Table on pm.ProductId equals p.Id
where pm.ManufacturerId == manufacturerId &&
!p.Deleted &&
(showHidden || p.Published)
orderby pm.DisplayOrder
select pm;
if (!showHidden && (!_catalogSettings.IgnoreAcl || !_catalogSettings.IgnoreStoreLimitations))
{
if (!_catalogSettings.IgnoreAcl)
{
//ACL (access control list)
var allowedCustomerRolesIds = _workContext.CurrentCustomer.GetCustomerRoleIds();
query = from pm in query
join m in _manufacturerRepository.Table on pm.ManufacturerId equals m.Id
join acl in _aclRepository.Table
on new { c1 = m.Id, c2 = "Manufacturer" } equals new { c1 = acl.EntityId, c2 = acl.EntityName } into m_acl
from acl in m_acl.DefaultIfEmpty()
where !m.SubjectToAcl || allowedCustomerRolesIds.Contains(acl.CustomerRoleId)
select pm;
}
if (!_catalogSettings.IgnoreStoreLimitations)
{
//Store mapping
var currentStoreId = _storeContext.CurrentStore.Id;
query = from pm in query
join m in _manufacturerRepository.Table on pm.ManufacturerId equals m.Id
join sm in _storeMappingRepository.Table
on new { c1 = m.Id, c2 = "Manufacturer" } equals new { c1 = sm.EntityId, c2 = sm.EntityName } into m_sm
from sm in m_sm.DefaultIfEmpty()
where !m.LimitedToStores || currentStoreId == sm.StoreId
select pm;
}
//only distinct manufacturers (group by ID)
query = from pm in query
group pm by pm.Id
into pmGroup
orderby pmGroup.Key
select pmGroup.FirstOrDefault();
query = query.OrderBy(pm => pm.DisplayOrder);
}
var productManufacturers = new PagedList<ProductManufacturer>(query, pageIndex, pageSize);
return productManufacturers;
});
}
/// <summary>
/// Gets a product manufacturer mapping collection
/// </summary>
/// <param name="productId">Product identifier</param>
/// <param name="showHidden">A value indicating whether to show hidden records</param>
/// <returns>Product manufacturer mapping collection</returns>
public virtual IList<ProductManufacturer> GetProductManufacturersByProductId(int productId, bool showHidden = false)
{
if (productId == 0)
return new List<ProductManufacturer>();
string key = string.Format(PRODUCTMANUFACTURERS_ALLBYPRODUCTID_KEY, showHidden, productId, _workContext.CurrentCustomer.Id, _storeContext.CurrentStore.Id);
return _cacheManager.Get(key, () =>
{
var query = from pm in _productManufacturerRepository.Table
join m in _manufacturerRepository.Table on pm.ManufacturerId equals m.Id
where pm.ProductId == productId &&
!m.Deleted &&
(showHidden || m.Published)
orderby pm.DisplayOrder
select pm;
if (!showHidden && (!_catalogSettings.IgnoreAcl || !_catalogSettings.IgnoreStoreLimitations))
{
if (!_catalogSettings.IgnoreAcl)
{
//ACL (access control list)
var allowedCustomerRolesIds = _workContext.CurrentCustomer.GetCustomerRoleIds();
query = from pm in query
join m in _manufacturerRepository.Table on pm.ManufacturerId equals m.Id
join acl in _aclRepository.Table
on new { c1 = m.Id, c2 = "Manufacturer" } equals new { c1 = acl.EntityId, c2 = acl.EntityName } into m_acl
from acl in m_acl.DefaultIfEmpty()
where !m.SubjectToAcl || allowedCustomerRolesIds.Contains(acl.CustomerRoleId)
select pm;
}
if (!_catalogSettings.IgnoreStoreLimitations)
{
//Store mapping
var currentStoreId = _storeContext.CurrentStore.Id;
query = from pm in query
join m in _manufacturerRepository.Table on pm.ManufacturerId equals m.Id
join sm in _storeMappingRepository.Table
on new { c1 = m.Id, c2 = "Manufacturer" } equals new { c1 = sm.EntityId, c2 = sm.EntityName } into m_sm
from sm in m_sm.DefaultIfEmpty()
where !m.LimitedToStores || currentStoreId == sm.StoreId
select pm;
}
//only distinct manufacturers (group by ID)
query = from pm in query
group pm by pm.Id
into mGroup
orderby mGroup.Key
select mGroup.FirstOrDefault();
query = query.OrderBy(pm => pm.DisplayOrder);
}
var productManufacturers = query.ToList();
return productManufacturers;
});
}
/// <summary>
/// Gets a product manufacturer mapping
/// </summary>
/// <param name="productManufacturerId">Product manufacturer mapping identifier</param>
/// <returns>Product manufacturer mapping</returns>
public virtual ProductManufacturer GetProductManufacturerById(int productManufacturerId)
{
if (productManufacturerId == 0)
return null;
return _productManufacturerRepository.GetById(productManufacturerId);
}
/// <summary>
/// Inserts a product manufacturer mapping
/// </summary>
/// <param name="productManufacturer">Product manufacturer mapping</param>
public virtual void InsertProductManufacturer(ProductManufacturer productManufacturer)
{
if (productManufacturer == null)
throw new ArgumentNullException("productManufacturer");
_productManufacturerRepository.Insert(productManufacturer);
//cache
_cacheManager.RemoveByPattern(MANUFACTURERS_PATTERN_KEY);
_cacheManager.RemoveByPattern(PRODUCTMANUFACTURERS_PATTERN_KEY);
//event notification
_eventPublisher.EntityInserted(productManufacturer);
}
/// <summary>
/// Updates the product manufacturer mapping
/// </summary>
/// <param name="productManufacturer">Product manufacturer mapping</param>
public virtual void UpdateProductManufacturer(ProductManufacturer productManufacturer)
{
if (productManufacturer == null)
throw new ArgumentNullException("productManufacturer");
_productManufacturerRepository.Update(productManufacturer);
//cache
_cacheManager.RemoveByPattern(MANUFACTURERS_PATTERN_KEY);
_cacheManager.RemoveByPattern(PRODUCTMANUFACTURERS_PATTERN_KEY);
//event notification
_eventPublisher.EntityUpdated(productManufacturer);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
using MS.Core;
namespace System.Reflection
{
public static class __CustomAttributeExtensions
{
public static IObservable<System.Attribute> GetCustomAttribute(IObservable<System.Reflection.Assembly> element,
IObservable<System.Type> attributeType)
{
return Observable.Zip(element, attributeType,
(elementLambda, attributeTypeLambda) =>
System.Reflection.CustomAttributeExtensions.GetCustomAttribute(elementLambda, attributeTypeLambda));
}
public static IObservable<System.Attribute> GetCustomAttribute(IObservable<System.Reflection.Module> element,
IObservable<System.Type> attributeType)
{
return Observable.Zip(element, attributeType,
(elementLambda, attributeTypeLambda) =>
System.Reflection.CustomAttributeExtensions.GetCustomAttribute(elementLambda, attributeTypeLambda));
}
public static IObservable<System.Attribute> GetCustomAttribute(
IObservable<System.Reflection.MemberInfo> element, IObservable<System.Type> attributeType)
{
return Observable.Zip(element, attributeType,
(elementLambda, attributeTypeLambda) =>
System.Reflection.CustomAttributeExtensions.GetCustomAttribute(elementLambda, attributeTypeLambda));
}
public static IObservable<System.Attribute> GetCustomAttribute(
IObservable<System.Reflection.ParameterInfo> element, IObservable<System.Type> attributeType)
{
return Observable.Zip(element, attributeType,
(elementLambda, attributeTypeLambda) =>
System.Reflection.CustomAttributeExtensions.GetCustomAttribute(elementLambda, attributeTypeLambda));
}
public static IObservable<T> GetCustomAttribute<T>(IObservable<System.Reflection.Assembly> element)
where T : System.Attribute
{
return Observable.Select(element,
(elementLambda) => System.Reflection.CustomAttributeExtensions.GetCustomAttribute<T>(elementLambda));
}
public static IObservable<T> GetCustomAttribute<T>(IObservable<System.Reflection.Module> element)
where T : System.Attribute
{
return Observable.Select(element,
(elementLambda) => System.Reflection.CustomAttributeExtensions.GetCustomAttribute<T>(elementLambda));
}
public static IObservable<T> GetCustomAttribute<T>(IObservable<System.Reflection.MemberInfo> element)
where T : System.Attribute
{
return Observable.Select(element,
(elementLambda) => System.Reflection.CustomAttributeExtensions.GetCustomAttribute<T>(elementLambda));
}
public static IObservable<T> GetCustomAttribute<T>(IObservable<System.Reflection.ParameterInfo> element)
where T : System.Attribute
{
return Observable.Select(element,
(elementLambda) => System.Reflection.CustomAttributeExtensions.GetCustomAttribute<T>(elementLambda));
}
public static IObservable<System.Attribute> GetCustomAttribute(
IObservable<System.Reflection.MemberInfo> element, IObservable<System.Type> attributeType,
IObservable<System.Boolean> inherit)
{
return Observable.Zip(element, attributeType, inherit,
(elementLambda, attributeTypeLambda, inheritLambda) =>
System.Reflection.CustomAttributeExtensions.GetCustomAttribute(elementLambda, attributeTypeLambda,
inheritLambda));
}
public static IObservable<System.Attribute> GetCustomAttribute(
IObservable<System.Reflection.ParameterInfo> element, IObservable<System.Type> attributeType,
IObservable<System.Boolean> inherit)
{
return Observable.Zip(element, attributeType, inherit,
(elementLambda, attributeTypeLambda, inheritLambda) =>
System.Reflection.CustomAttributeExtensions.GetCustomAttribute(elementLambda, attributeTypeLambda,
inheritLambda));
}
public static IObservable<T> GetCustomAttribute<T>(IObservable<System.Reflection.MemberInfo> element,
IObservable<System.Boolean> inherit) where T : System.Attribute
{
return Observable.Zip(element, inherit,
(elementLambda, inheritLambda) =>
System.Reflection.CustomAttributeExtensions.GetCustomAttribute<T>(elementLambda, inheritLambda));
}
public static IObservable<T> GetCustomAttribute<T>(IObservable<System.Reflection.ParameterInfo> element,
IObservable<System.Boolean> inherit) where T : System.Attribute
{
return Observable.Zip(element, inherit,
(elementLambda, inheritLambda) =>
System.Reflection.CustomAttributeExtensions.GetCustomAttribute<T>(elementLambda, inheritLambda));
}
public static IObservable<System.Collections.Generic.IEnumerable<System.Attribute>> GetCustomAttributes(
IObservable<System.Reflection.Assembly> element)
{
return Observable.Select(element,
(elementLambda) => System.Reflection.CustomAttributeExtensions.GetCustomAttributes(elementLambda));
}
public static IObservable<System.Collections.Generic.IEnumerable<System.Attribute>> GetCustomAttributes(
IObservable<System.Reflection.Module> element)
{
return Observable.Select(element,
(elementLambda) => System.Reflection.CustomAttributeExtensions.GetCustomAttributes(elementLambda));
}
public static IObservable<System.Collections.Generic.IEnumerable<System.Attribute>> GetCustomAttributes(
IObservable<System.Reflection.MemberInfo> element)
{
return Observable.Select(element,
(elementLambda) => System.Reflection.CustomAttributeExtensions.GetCustomAttributes(elementLambda));
}
public static IObservable<System.Collections.Generic.IEnumerable<System.Attribute>> GetCustomAttributes(
IObservable<System.Reflection.ParameterInfo> element)
{
return Observable.Select(element,
(elementLambda) => System.Reflection.CustomAttributeExtensions.GetCustomAttributes(elementLambda));
}
public static IObservable<System.Collections.Generic.IEnumerable<System.Attribute>> GetCustomAttributes(
IObservable<System.Reflection.MemberInfo> element, IObservable<System.Boolean> inherit)
{
return Observable.Zip(element, inherit,
(elementLambda, inheritLambda) =>
System.Reflection.CustomAttributeExtensions.GetCustomAttributes(elementLambda, inheritLambda));
}
public static IObservable<System.Collections.Generic.IEnumerable<System.Attribute>> GetCustomAttributes(
IObservable<System.Reflection.ParameterInfo> element, IObservable<System.Boolean> inherit)
{
return Observable.Zip(element, inherit,
(elementLambda, inheritLambda) =>
System.Reflection.CustomAttributeExtensions.GetCustomAttributes(elementLambda, inheritLambda));
}
public static IObservable<System.Collections.Generic.IEnumerable<System.Attribute>> GetCustomAttributes(
IObservable<System.Reflection.Assembly> element, IObservable<System.Type> attributeType)
{
return Observable.Zip(element, attributeType,
(elementLambda, attributeTypeLambda) =>
System.Reflection.CustomAttributeExtensions.GetCustomAttributes(elementLambda, attributeTypeLambda));
}
public static IObservable<System.Collections.Generic.IEnumerable<System.Attribute>> GetCustomAttributes(
IObservable<System.Reflection.Module> element, IObservable<System.Type> attributeType)
{
return Observable.Zip(element, attributeType,
(elementLambda, attributeTypeLambda) =>
System.Reflection.CustomAttributeExtensions.GetCustomAttributes(elementLambda, attributeTypeLambda));
}
public static IObservable<System.Collections.Generic.IEnumerable<System.Attribute>> GetCustomAttributes(
IObservable<System.Reflection.MemberInfo> element, IObservable<System.Type> attributeType)
{
return Observable.Zip(element, attributeType,
(elementLambda, attributeTypeLambda) =>
System.Reflection.CustomAttributeExtensions.GetCustomAttributes(elementLambda, attributeTypeLambda));
}
public static IObservable<System.Collections.Generic.IEnumerable<System.Attribute>> GetCustomAttributes(
IObservable<System.Reflection.ParameterInfo> element, IObservable<System.Type> attributeType)
{
return Observable.Zip(element, attributeType,
(elementLambda, attributeTypeLambda) =>
System.Reflection.CustomAttributeExtensions.GetCustomAttributes(elementLambda, attributeTypeLambda));
}
public static IObservable<IEnumerable<T>> GetCustomAttributes<T>(IObservable<System.Reflection.Assembly> element)
where T : System.Attribute
{
return Observable.Select(element,
(elementLambda) => System.Reflection.CustomAttributeExtensions.GetCustomAttributes<T>(elementLambda));
}
public static IObservable<IEnumerable<T>> GetCustomAttributes<T>(IObservable<System.Reflection.Module> element)
where T : System.Attribute
{
return Observable.Select(element,
(elementLambda) => System.Reflection.CustomAttributeExtensions.GetCustomAttributes<T>(elementLambda));
}
public static IObservable<IEnumerable<T>> GetCustomAttributes<T>(
IObservable<System.Reflection.MemberInfo> element) where T : System.Attribute
{
return Observable.Select(element,
(elementLambda) => System.Reflection.CustomAttributeExtensions.GetCustomAttributes<T>(elementLambda));
}
public static IObservable<IEnumerable<T>> GetCustomAttributes<T>(
IObservable<System.Reflection.ParameterInfo> element) where T : System.Attribute
{
return Observable.Select(element,
(elementLambda) => System.Reflection.CustomAttributeExtensions.GetCustomAttributes<T>(elementLambda));
}
public static IObservable<System.Collections.Generic.IEnumerable<System.Attribute>> GetCustomAttributes(
IObservable<System.Reflection.MemberInfo> element, IObservable<System.Type> attributeType,
IObservable<System.Boolean> inherit)
{
return Observable.Zip(element, attributeType, inherit,
(elementLambda, attributeTypeLambda, inheritLambda) =>
System.Reflection.CustomAttributeExtensions.GetCustomAttributes(elementLambda, attributeTypeLambda,
inheritLambda));
}
public static IObservable<System.Collections.Generic.IEnumerable<System.Attribute>> GetCustomAttributes(
IObservable<System.Reflection.ParameterInfo> element, IObservable<System.Type> attributeType,
IObservable<System.Boolean> inherit)
{
return Observable.Zip(element, attributeType, inherit,
(elementLambda, attributeTypeLambda, inheritLambda) =>
System.Reflection.CustomAttributeExtensions.GetCustomAttributes(elementLambda, attributeTypeLambda,
inheritLambda));
}
public static IObservable<IEnumerable<T>> GetCustomAttributes<T>(
IObservable<System.Reflection.MemberInfo> element, IObservable<System.Boolean> inherit)
where T : System.Attribute
{
return Observable.Zip(element, inherit,
(elementLambda, inheritLambda) =>
System.Reflection.CustomAttributeExtensions.GetCustomAttributes<T>(elementLambda, inheritLambda));
}
public static IObservable<IEnumerable<T>> GetCustomAttributes<T>(
IObservable<System.Reflection.ParameterInfo> element, IObservable<System.Boolean> inherit)
where T : System.Attribute
{
return Observable.Zip(element, inherit,
(elementLambda, inheritLambda) =>
System.Reflection.CustomAttributeExtensions.GetCustomAttributes<T>(elementLambda, inheritLambda));
}
public static IObservable<System.Boolean> IsDefined(IObservable<System.Reflection.Assembly> element,
IObservable<System.Type> attributeType)
{
return Observable.Zip(element, attributeType,
(elementLambda, attributeTypeLambda) =>
System.Reflection.CustomAttributeExtensions.IsDefined(elementLambda, attributeTypeLambda));
}
public static IObservable<System.Boolean> IsDefined(IObservable<System.Reflection.Module> element,
IObservable<System.Type> attributeType)
{
return Observable.Zip(element, attributeType,
(elementLambda, attributeTypeLambda) =>
System.Reflection.CustomAttributeExtensions.IsDefined(elementLambda, attributeTypeLambda));
}
public static IObservable<System.Boolean> IsDefined(IObservable<System.Reflection.MemberInfo> element,
IObservable<System.Type> attributeType)
{
return Observable.Zip(element, attributeType,
(elementLambda, attributeTypeLambda) =>
System.Reflection.CustomAttributeExtensions.IsDefined(elementLambda, attributeTypeLambda));
}
public static IObservable<System.Boolean> IsDefined(IObservable<System.Reflection.ParameterInfo> element,
IObservable<System.Type> attributeType)
{
return Observable.Zip(element, attributeType,
(elementLambda, attributeTypeLambda) =>
System.Reflection.CustomAttributeExtensions.IsDefined(elementLambda, attributeTypeLambda));
}
public static IObservable<System.Boolean> IsDefined(IObservable<System.Reflection.MemberInfo> element,
IObservable<System.Type> attributeType, IObservable<System.Boolean> inherit)
{
return Observable.Zip(element, attributeType, inherit,
(elementLambda, attributeTypeLambda, inheritLambda) =>
System.Reflection.CustomAttributeExtensions.IsDefined(elementLambda, attributeTypeLambda,
inheritLambda));
}
public static IObservable<System.Boolean> IsDefined(IObservable<System.Reflection.ParameterInfo> element,
IObservable<System.Type> attributeType, IObservable<System.Boolean> inherit)
{
return Observable.Zip(element, attributeType, inherit,
(elementLambda, attributeTypeLambda, inheritLambda) =>
System.Reflection.CustomAttributeExtensions.IsDefined(elementLambda, attributeTypeLambda,
inheritLambda));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
namespace System.Data.SqlClient.SNI
{
/// <summary>
/// MARS handle
/// </summary>
internal sealed class SNIMarsHandle : SNIHandle
{
private const uint ACK_THRESHOLD = 2;
private readonly SNIMarsConnection _connection;
private readonly uint _status = TdsEnums.SNI_UNINITIALIZED;
private readonly Queue<SNIPacket> _receivedPacketQueue = new Queue<SNIPacket>();
private readonly Queue<SNIMarsQueuedPacket> _sendPacketQueue = new Queue<SNIMarsQueuedPacket>();
private readonly object _callbackObject;
private readonly Guid _connectionId = Guid.NewGuid();
private readonly ushort _sessionId;
private readonly ManualResetEventSlim _packetEvent = new ManualResetEventSlim(false);
private readonly ManualResetEventSlim _ackEvent = new ManualResetEventSlim(false);
private readonly SNISMUXHeader _currentHeader = new SNISMUXHeader();
private uint _sendHighwater = 4;
private int _asyncReceives = 0;
private uint _receiveHighwater = 4;
private uint _receiveHighwaterLastAck = 4;
private uint _sequenceNumber;
private SNIError _connectionError;
public override Guid ConnectionId => _connectionId;
public override uint Status => _status;
public override int ReserveHeaderSize => SNISMUXHeader.HEADER_LENGTH;
/// <summary>
/// Dispose object
/// </summary>
public override void Dispose()
{
try
{
SendControlPacket(SNISMUXFlags.SMUX_FIN);
}
catch (Exception e)
{
SNICommon.ReportSNIError(SNIProviders.SMUX_PROV, SNICommon.InternalExceptionError, e);
throw;
}
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="connection">MARS connection</param>
/// <param name="sessionId">MARS session ID</param>
/// <param name="callbackObject">Callback object</param>
/// <param name="async">true if connection is asynchronous</param>
public SNIMarsHandle(SNIMarsConnection connection, ushort sessionId, object callbackObject, bool async)
{
_sessionId = sessionId;
_connection = connection;
_callbackObject = callbackObject;
SendControlPacket(SNISMUXFlags.SMUX_SYN);
_status = TdsEnums.SNI_SUCCESS;
}
/// <summary>
/// Send control packet
/// </summary>
/// <param name="flags">SMUX header flags</param>
private void SendControlPacket(SNISMUXFlags flags)
{
SNIPacket packet = new SNIPacket(headerSize: SNISMUXHeader.HEADER_LENGTH, dataSize: 0);
lock (this)
{
SetupSMUXHeader(0, flags);
_currentHeader.Write(packet.GetHeaderBuffer(SNISMUXHeader.HEADER_LENGTH));
packet.SetHeaderActive();
}
_connection.Send(packet);
}
private void SetupSMUXHeader(int length, SNISMUXFlags flags)
{
Debug.Assert(Monitor.IsEntered(this), "must take lock on self before updating mux header");
_currentHeader.SMID = 83;
_currentHeader.flags = (byte)flags;
_currentHeader.sessionId = _sessionId;
_currentHeader.length = (uint)SNISMUXHeader.HEADER_LENGTH + (uint)length;
_currentHeader.sequenceNumber = ((flags == SNISMUXFlags.SMUX_FIN) || (flags == SNISMUXFlags.SMUX_ACK)) ? _sequenceNumber - 1 : _sequenceNumber++;
_currentHeader.highwater = _receiveHighwater;
_receiveHighwaterLastAck = _currentHeader.highwater;
}
/// <summary>
/// Generate a packet with SMUX header
/// </summary>
/// <param name="packet">SNI packet</param>
/// <returns>The packet with the SMUx header set.</returns>
private SNIPacket SetPacketSMUXHeader(SNIPacket packet)
{
Debug.Assert(packet.ReservedHeaderSize == SNISMUXHeader.HEADER_LENGTH, "mars handle attempting to mux packet without mux reservation");
SetupSMUXHeader(packet.Length, SNISMUXFlags.SMUX_DATA);
_currentHeader.Write(packet.GetHeaderBuffer(SNISMUXHeader.HEADER_LENGTH));
packet.SetHeaderActive();
return packet;
}
/// <summary>
/// Send a packet synchronously
/// </summary>
/// <param name="packet">SNI packet</param>
/// <returns>SNI error code</returns>
public override uint Send(SNIPacket packet)
{
Debug.Assert(packet.ReservedHeaderSize == SNISMUXHeader.HEADER_LENGTH, "mars handle attempting to send muxed packet without mux reservation in Send");
while (true)
{
lock (this)
{
if (_sequenceNumber < _sendHighwater)
{
break;
}
}
_ackEvent.Wait();
lock (this)
{
_ackEvent.Reset();
}
}
SNIPacket muxedPacket = null;
lock (this)
{
muxedPacket = SetPacketSMUXHeader(packet);
}
return _connection.Send(muxedPacket);
}
/// <summary>
/// Send packet asynchronously
/// </summary>
/// <param name="packet">SNI packet</param>
/// <param name="callback">Completion callback</param>
/// <returns>SNI error code</returns>
private uint InternalSendAsync(SNIPacket packet, SNIAsyncCallback callback)
{
Debug.Assert(packet.ReservedHeaderSize == SNISMUXHeader.HEADER_LENGTH, "mars handle attempting to send muxed packet without mux reservation in InternalSendAsync");
lock (this)
{
if (_sequenceNumber >= _sendHighwater)
{
return TdsEnums.SNI_QUEUE_FULL;
}
SNIPacket muxedPacket = SetPacketSMUXHeader(packet);
muxedPacket.SetCompletionCallback(callback ?? HandleSendComplete);
return _connection.SendAsync(muxedPacket, callback);
}
}
/// <summary>
/// Send pending packets
/// </summary>
/// <returns>SNI error code</returns>
private uint SendPendingPackets()
{
SNIMarsQueuedPacket packet = null;
while (true)
{
lock (this)
{
if (_sequenceNumber < _sendHighwater)
{
if (_sendPacketQueue.Count != 0)
{
packet = _sendPacketQueue.Peek();
uint result = InternalSendAsync(packet.Packet, packet.Callback);
if (result != TdsEnums.SNI_SUCCESS && result != TdsEnums.SNI_SUCCESS_IO_PENDING)
{
return result;
}
_sendPacketQueue.Dequeue();
continue;
}
else
{
_ackEvent.Set();
}
}
break;
}
}
return TdsEnums.SNI_SUCCESS;
}
/// <summary>
/// Send a packet asynchronously
/// </summary>
/// <param name="packet">SNI packet</param>
/// <param name="callback">Completion callback</param>
/// <returns>SNI error code</returns>
public override uint SendAsync(SNIPacket packet, bool disposePacketAfterSendAsync, SNIAsyncCallback callback = null)
{
lock (this)
{
_sendPacketQueue.Enqueue(new SNIMarsQueuedPacket(packet, callback != null ? callback : HandleSendComplete));
}
SendPendingPackets();
return TdsEnums.SNI_SUCCESS_IO_PENDING;
}
/// <summary>
/// Receive a packet asynchronously
/// </summary>
/// <param name="packet">SNI packet</param>
/// <returns>SNI error code</returns>
public override uint ReceiveAsync(ref SNIPacket packet)
{
lock (_receivedPacketQueue)
{
int queueCount = _receivedPacketQueue.Count;
if (_connectionError != null)
{
return SNICommon.ReportSNIError(_connectionError);
}
if (queueCount == 0)
{
_asyncReceives++;
return TdsEnums.SNI_SUCCESS_IO_PENDING;
}
packet = _receivedPacketQueue.Dequeue();
if (queueCount == 1)
{
_packetEvent.Reset();
}
}
lock (this)
{
_receiveHighwater++;
}
SendAckIfNecessary();
return TdsEnums.SNI_SUCCESS;
}
/// <summary>
/// Handle receive error
/// </summary>
public void HandleReceiveError(SNIPacket packet)
{
lock (_receivedPacketQueue)
{
_connectionError = SNILoadHandle.SingletonInstance.LastError;
_packetEvent.Set();
}
((TdsParserStateObject)_callbackObject).ReadAsyncCallback(PacketHandle.FromManagedPacket(packet), 1);
}
/// <summary>
/// Handle send completion
/// </summary>
/// <param name="packet">SNI packet</param>
/// <param name="sniErrorCode">SNI error code</param>
public void HandleSendComplete(SNIPacket packet, uint sniErrorCode)
{
lock (this)
{
Debug.Assert(_callbackObject != null);
((TdsParserStateObject)_callbackObject).WriteAsyncCallback(PacketHandle.FromManagedPacket(packet), sniErrorCode);
}
}
/// <summary>
/// Handle SMUX acknowledgement
/// </summary>
/// <param name="highwater">Send highwater mark</param>
public void HandleAck(uint highwater)
{
lock (this)
{
if (_sendHighwater != highwater)
{
_sendHighwater = highwater;
SendPendingPackets();
}
}
}
/// <summary>
/// Handle receive completion
/// </summary>
/// <param name="packet">SNI packet</param>
/// <param name="header">SMUX header</param>
public void HandleReceiveComplete(SNIPacket packet, SNISMUXHeader header)
{
lock (this)
{
if (_sendHighwater != header.highwater)
{
HandleAck(header.highwater);
}
lock (_receivedPacketQueue)
{
if (_asyncReceives == 0)
{
_receivedPacketQueue.Enqueue(packet);
_packetEvent.Set();
return;
}
_asyncReceives--;
Debug.Assert(_callbackObject != null);
((TdsParserStateObject)_callbackObject).ReadAsyncCallback(PacketHandle.FromManagedPacket(packet), 0);
}
}
lock (this)
{
_receiveHighwater++;
}
SendAckIfNecessary();
}
/// <summary>
/// Send ACK if we've hit highwater threshold
/// </summary>
private void SendAckIfNecessary()
{
uint receiveHighwater;
uint receiveHighwaterLastAck;
lock (this)
{
receiveHighwater = _receiveHighwater;
receiveHighwaterLastAck = _receiveHighwaterLastAck;
}
if (receiveHighwater - receiveHighwaterLastAck > ACK_THRESHOLD)
{
SendControlPacket(SNISMUXFlags.SMUX_ACK);
}
}
/// <summary>
/// Receive a packet synchronously
/// </summary>
/// <param name="packet">SNI packet</param>
/// <param name="timeoutInMilliseconds">Timeout in Milliseconds</param>
/// <returns>SNI error code</returns>
public override uint Receive(out SNIPacket packet, int timeoutInMilliseconds)
{
packet = null;
int queueCount;
uint result = TdsEnums.SNI_SUCCESS_IO_PENDING;
while (true)
{
lock (_receivedPacketQueue)
{
if (_connectionError != null)
{
return SNICommon.ReportSNIError(_connectionError);
}
queueCount = _receivedPacketQueue.Count;
if (queueCount > 0)
{
packet = _receivedPacketQueue.Dequeue();
if (queueCount == 1)
{
_packetEvent.Reset();
}
result = TdsEnums.SNI_SUCCESS;
}
}
if (result == TdsEnums.SNI_SUCCESS)
{
lock (this)
{
_receiveHighwater++;
}
SendAckIfNecessary();
return result;
}
if (!_packetEvent.Wait(timeoutInMilliseconds))
{
SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.SMUX_PROV, 0, SNICommon.ConnTimeoutError, string.Empty);
return TdsEnums.SNI_WAIT_TIMEOUT;
}
}
}
/// <summary>
/// Check SNI handle connection
/// </summary>
/// <returns>SNI error status</returns>
public override uint CheckConnection()
{
return _connection.CheckConnection();
}
/// <summary>
/// Set async callbacks
/// </summary>
/// <param name="receiveCallback">Receive callback</param>
/// <param name="sendCallback">Send callback</param>
public override void SetAsyncCallbacks(SNIAsyncCallback receiveCallback, SNIAsyncCallback sendCallback)
{
}
/// <summary>
/// Set buffer size
/// </summary>
/// <param name="bufferSize">Buffer size</param>
public override void SetBufferSize(int bufferSize)
{
}
/// <summary>
/// Enable SSL
/// </summary>
public override uint EnableSsl(uint options)
{
return _connection.EnableSsl(options);
}
/// <summary>
/// Disable SSL
/// </summary>
public override void DisableSsl()
{
_connection.DisableSsl();
}
#if DEBUG
/// <summary>
/// Test handle for killing underlying connection
/// </summary>
public override void KillConnection()
{
_connection.KillConnection();
}
#endif
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UMA;
namespace UMA.Examples
{
public class UMACrowd : MonoBehaviour
{
public UMACrowdRandomSet[] randomPool;
public UMAGeneratorBase generator;
public UMAData umaData;
public UMAContextBase UMAContextBase;
public RuntimeAnimatorController animationController;
public float atlasResolutionScale = 1;
public bool generateUMA;
public bool generateLotsUMA;
public bool hideWhileGeneratingLots;
public bool stressTest;
public Vector2 umaCrowdSize;
public bool randomDna;
public bool allAtOnce;
public UMARecipeBase[] additionalRecipes;
public float space = 1;
public Transform zeroPoint;
private int spawnX;
private int spawnY;
public SharedColorTable SkinColors;
public SharedColorTable HairColors;
// public SharedColorTable EyeColors; TODO: Add support for eye colors
// public SharedColorTable ClothesColors; TODO: Add support for clothes colors
public string[] keywords;
public UMADataEvent CharacterCreated;
public UMADataEvent CharacterDestroyed;
public UMADataEvent CharacterUpdated;
void Awake()
{
if (space <= 0) space = 1;
if (UMAContextBase == null)
{
UMAContextBase = UMAContext.Instance;
}
if (generator == null)
{
GameObject go = GameObject.Find("UMAGenerator");
if (go != null)
{
generator = go.GetComponent<UMAGenerator>();
}
else
{
generator = UMAContextBase.GetComponent<UMAGenerator>();
}
}
}
void Update()
{
if (generateUMA)
{
umaCrowdSize = Vector2.one;
int randomResult = Random.Range(0, 2);
GenerateOneUMA(randomResult);
generateUMA = false;
generateLotsUMA = false;
}
if (generateLotsUMA)
{
if (generator.IsIdle())
{
if (allAtOnce)
{
for (int i = 0; i < umaCrowdSize.x * umaCrowdSize.y; i++)
{
int randomResult = Random.Range(0, 2);
GenerateOneUMA(randomResult);
generateUMA = false;
generateLotsUMA = false;
}
}
else
{
int randomResult = Random.Range(0, 2);
GenerateOneUMA(randomResult);
}
}
}
if (stressTest && generator.IsIdle() && !generateLotsUMA && !generateUMA)
{
RandomizeAll();
}
}
private void DefineSlots(UMACrowdRandomSet.CrowdRaceData race)
{
Color skinColor;
Color HairColor;
Color Shine = Color.black;
if (SkinColors != null)
{
OverlayColorData ocd = SkinColors.colors[Random.Range(0, SkinColors.colors.Length)];
skinColor = ocd.color;
Shine = ocd.channelAdditiveMask[2];
}
else
{
float skinTone = Random.Range(0.1f, 0.6f);
skinColor = new Color(skinTone + Random.Range(0.35f, 0.4f), skinTone + Random.Range(0.25f, 0.4f), skinTone + Random.Range(0.35f, 0.4f), 1);
}
if (HairColors != null)
{
HairColor = HairColors.colors[Random.Range(0, HairColors.colors.Length)].color;
}
else
{
HairColor = new Color(Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), 1.0f);
}
var keywordsLookup = new HashSet<string>(keywords);
UMACrowdRandomSet.Apply(umaData, race, skinColor, HairColor, Shine, keywordsLookup, UMAContextBase);
}
void DefineSlots()
{
Color skinColor = new Color(1, 1, 1, 1);
float skinTone;
skinTone = Random.Range(0.1f, 0.6f);
skinColor = new Color(skinTone + Random.Range(0.35f, 0.4f), skinTone + Random.Range(0.25f, 0.4f), skinTone + Random.Range(0.35f, 0.4f), 1);
Color HairColor = new Color(Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), 1);
if (umaData.umaRecipe.raceData.raceName == "HumanMale" || umaData.umaRecipe.raceData.raceName == "HumanMaleDCS")
{
int randomResult = 0;
//Male Avatar
umaData.umaRecipe.slotDataList = new SlotData[15];
umaData.umaRecipe.slotDataList[0] = UMAContextBase.InstantiateSlot("MaleEyes");
umaData.umaRecipe.slotDataList[0].AddOverlay(UMAContextBase.InstantiateOverlay("EyeOverlay"));
umaData.umaRecipe.slotDataList[0].AddOverlay(UMAContextBase.InstantiateOverlay("EyeOverlayAdjust", new Color(Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), 1)));
randomResult = Random.Range(0, 2);
if (randomResult == 0)
{
umaData.umaRecipe.slotDataList[1] = UMAContextBase.InstantiateSlot("MaleFace");
randomResult = Random.Range(0, 2);
if (randomResult == 0)
{
umaData.umaRecipe.slotDataList[1].AddOverlay(UMAContextBase.InstantiateOverlay("MaleHead01", skinColor));
}
else if (randomResult == 1)
{
umaData.umaRecipe.slotDataList[1].AddOverlay(UMAContextBase.InstantiateOverlay("MaleHead02", skinColor));
}
}
else if (randomResult == 1)
{
umaData.umaRecipe.slotDataList[1] = UMAContextBase.InstantiateSlot("MaleHead_Head");
randomResult = Random.Range(0, 2);
if (randomResult == 0)
{
umaData.umaRecipe.slotDataList[1].AddOverlay(UMAContextBase.InstantiateOverlay("MaleHead01", skinColor));
}
else if (randomResult == 1)
{
umaData.umaRecipe.slotDataList[1].AddOverlay(UMAContextBase.InstantiateOverlay("MaleHead02", skinColor));
}
umaData.umaRecipe.slotDataList[7] = UMAContextBase.InstantiateSlot("MaleHead_Eyes", umaData.umaRecipe.slotDataList[1].GetOverlayList());
umaData.umaRecipe.slotDataList[9] = UMAContextBase.InstantiateSlot("MaleHead_Mouth", umaData.umaRecipe.slotDataList[1].GetOverlayList());
randomResult = Random.Range(0, 2);
if (randomResult == 0)
{
umaData.umaRecipe.slotDataList[10] = UMAContextBase.InstantiateSlot("MaleHead_PigNose", umaData.umaRecipe.slotDataList[1].GetOverlayList());
umaData.umaRecipe.slotDataList[1].AddOverlay(UMAContextBase.InstantiateOverlay("MaleHead_PigNose", skinColor));
}
else if (randomResult == 1)
{
umaData.umaRecipe.slotDataList[10] = UMAContextBase.InstantiateSlot("MaleHead_Nose", umaData.umaRecipe.slotDataList[1].GetOverlayList());
}
randomResult = Random.Range(0, 2);
if (randomResult == 0)
{
umaData.umaRecipe.slotDataList[8] = UMAContextBase.InstantiateSlot("MaleHead_ElvenEars");
umaData.umaRecipe.slotDataList[8].AddOverlay(UMAContextBase.InstantiateOverlay("ElvenEars", skinColor));
}
else if (randomResult == 1)
{
umaData.umaRecipe.slotDataList[8] = UMAContextBase.InstantiateSlot("MaleHead_Ears", umaData.umaRecipe.slotDataList[1].GetOverlayList());
}
}
randomResult = Random.Range(0, 3);
if (randomResult == 0)
{
umaData.umaRecipe.slotDataList[1].AddOverlay(UMAContextBase.InstantiateOverlay("MaleHair01", HairColor * 0.25f));
}
else if (randomResult == 1)
{
umaData.umaRecipe.slotDataList[1].AddOverlay(UMAContextBase.InstantiateOverlay("MaleHair02", HairColor * 0.25f));
}
else
{
}
randomResult = Random.Range(0, 4);
if (randomResult == 0)
{
umaData.umaRecipe.slotDataList[1].AddOverlay(UMAContextBase.InstantiateOverlay("MaleBeard01", HairColor * 0.15f));
}
else if (randomResult == 1)
{
umaData.umaRecipe.slotDataList[1].AddOverlay(UMAContextBase.InstantiateOverlay("MaleBeard02", HairColor * 0.15f));
}
else if (randomResult == 2)
{
umaData.umaRecipe.slotDataList[1].AddOverlay(UMAContextBase.InstantiateOverlay("MaleBeard03", HairColor * 0.15f));
}
else
{
}
//Extra beard composition
randomResult = Random.Range(0, 4);
if (randomResult == 0)
{
umaData.umaRecipe.slotDataList[1].AddOverlay(UMAContextBase.InstantiateOverlay("MaleBeard01", HairColor * 0.15f));
}
else if (randomResult == 1)
{
umaData.umaRecipe.slotDataList[1].AddOverlay(UMAContextBase.InstantiateOverlay("MaleBeard02", HairColor * 0.15f));
}
else if (randomResult == 2)
{
umaData.umaRecipe.slotDataList[1].AddOverlay(UMAContextBase.InstantiateOverlay("MaleBeard03", HairColor * 0.15f));
}
else
{
}
randomResult = Random.Range(0, 2);
if (randomResult == 0)
{
umaData.umaRecipe.slotDataList[1].AddOverlay(UMAContextBase.InstantiateOverlay("MaleEyebrow01", HairColor * 0.05f));
}
else
{
umaData.umaRecipe.slotDataList[1].AddOverlay(UMAContextBase.InstantiateOverlay("MaleEyebrow02", HairColor * 0.05f));
}
umaData.umaRecipe.slotDataList[2] = UMAContextBase.InstantiateSlot("MaleTorso");
randomResult = Random.Range(0, 2);
if (randomResult == 0)
{
umaData.umaRecipe.slotDataList[2].AddOverlay(UMAContextBase.InstantiateOverlay("MaleBody01", skinColor));
}
else
{
umaData.umaRecipe.slotDataList[2].AddOverlay(UMAContextBase.InstantiateOverlay("MaleBody02", skinColor));
}
randomResult = Random.Range(0, 2);
if (randomResult == 0)
{
umaData.umaRecipe.slotDataList[2].AddOverlay(UMAContextBase.InstantiateOverlay("MaleShirt01", new Color(Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), 1)));
}
umaData.umaRecipe.slotDataList[3] = UMAContextBase.InstantiateSlot("MaleHands", umaData.umaRecipe.slotDataList[2].GetOverlayList());
umaData.umaRecipe.slotDataList[4] = UMAContextBase.InstantiateSlot("MaleInnerMouth");
umaData.umaRecipe.slotDataList[4].AddOverlay(UMAContextBase.InstantiateOverlay("InnerMouth"));
randomResult = Random.Range(0, 2);
if (randomResult == 0)
{
umaData.umaRecipe.slotDataList[5] = UMAContextBase.InstantiateSlot("MaleLegs", umaData.umaRecipe.slotDataList[2].GetOverlayList());
umaData.umaRecipe.slotDataList[2].AddOverlay(UMAContextBase.InstantiateOverlay("MaleUnderwear01", new Color(Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), 1)));
}
else
{
umaData.umaRecipe.slotDataList[5] = UMAContextBase.InstantiateSlot("MaleJeans01");
umaData.umaRecipe.slotDataList[5].AddOverlay(UMAContextBase.InstantiateOverlay("MaleJeans01", new Color(Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), 1)));
}
umaData.umaRecipe.slotDataList[6] = UMAContextBase.InstantiateSlot("MaleFeet", umaData.umaRecipe.slotDataList[2].GetOverlayList());
}
else if (umaData.umaRecipe.raceData.raceName == "HumanFemale" || umaData.umaRecipe.raceData.raceName == "HumanFemaleDCS")
{
int randomResult = 0;
//Female Avatar
//Example of dynamic list
List<SlotData> tempSlotList = new List<SlotData>();
tempSlotList.Add(UMAContextBase.InstantiateSlot("FemaleEyes"));
tempSlotList[tempSlotList.Count - 1].AddOverlay(UMAContextBase.InstantiateOverlay("EyeOverlay"));
tempSlotList[tempSlotList.Count - 1].AddOverlay(UMAContextBase.InstantiateOverlay("EyeOverlayAdjust", new Color(Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), 1)));
int headIndex = 0;
randomResult = Random.Range(0, 2);
if (randomResult == 0)
{
tempSlotList.Add(UMAContextBase.InstantiateSlot("FemaleFace"));
headIndex = tempSlotList.Count - 1;
tempSlotList[headIndex].AddOverlay(UMAContextBase.InstantiateOverlay("FemaleHead01", skinColor));
tempSlotList[headIndex].AddOverlay(UMAContextBase.InstantiateOverlay("FemaleEyebrow01", new Color(0.125f, 0.065f, 0.065f, 1.0f)));
randomResult = Random.Range(0, 2);
if (randomResult == 0)
{
tempSlotList[headIndex].AddOverlay(UMAContextBase.InstantiateOverlay("FemaleLipstick01", new Color(skinColor.r + Random.Range(0.0f, 0.3f), skinColor.g, skinColor.b + Random.Range(0.0f, 0.2f), 1)));
}
}
else if (randomResult == 1)
{
tempSlotList.Add(UMAContextBase.InstantiateSlot("FemaleHead_Head"));
headIndex = tempSlotList.Count - 1;
tempSlotList[headIndex].AddOverlay(UMAContextBase.InstantiateOverlay("FemaleHead01", skinColor));
tempSlotList[headIndex].AddOverlay(UMAContextBase.InstantiateOverlay("FemaleEyebrow01", new Color(0.125f, 0.065f, 0.065f, 1.0f)));
tempSlotList.Add(UMAContextBase.InstantiateSlot("FemaleHead_Eyes", tempSlotList[headIndex].GetOverlayList()));
tempSlotList.Add(UMAContextBase.InstantiateSlot("FemaleHead_Mouth", tempSlotList[headIndex].GetOverlayList()));
tempSlotList.Add(UMAContextBase.InstantiateSlot("FemaleHead_Nose", tempSlotList[headIndex].GetOverlayList()));
randomResult = Random.Range(0, 2);
if (randomResult == 0)
{
tempSlotList.Add(UMAContextBase.InstantiateSlot("FemaleHead_ElvenEars"));
tempSlotList[tempSlotList.Count - 1].AddOverlay(UMAContextBase.InstantiateOverlay("ElvenEars", skinColor));
}
else if (randomResult == 1)
{
tempSlotList.Add(UMAContextBase.InstantiateSlot("FemaleHead_Ears", tempSlotList[headIndex].GetOverlayList()));
}
randomResult = Random.Range(0, 2);
if (randomResult == 0)
{
tempSlotList[headIndex].AddOverlay(UMAContextBase.InstantiateOverlay("FemaleLipstick01", new Color(skinColor.r + Random.Range(0.0f, 0.3f), skinColor.g, skinColor.b + Random.Range(0.0f, 0.2f), 1)));
}
}
tempSlotList.Add(UMAContextBase.InstantiateSlot("FemaleEyelash"));
tempSlotList[tempSlotList.Count - 1].AddOverlay(UMAContextBase.InstantiateOverlay("FemaleEyelash", Color.black));
tempSlotList.Add(UMAContextBase.InstantiateSlot("FemaleTorso"));
int bodyIndex = tempSlotList.Count - 1;
randomResult = Random.Range(0, 2);
if (randomResult == 0)
{
tempSlotList[bodyIndex].AddOverlay(UMAContextBase.InstantiateOverlay("FemaleBody01", skinColor));
} if (randomResult == 1)
{
tempSlotList[bodyIndex].AddOverlay(UMAContextBase.InstantiateOverlay("FemaleBody02", skinColor));
}
tempSlotList[bodyIndex].AddOverlay(UMAContextBase.InstantiateOverlay("FemaleUnderwear01", new Color(Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), 1)));
randomResult = Random.Range(0, 4);
if (randomResult == 0)
{
tempSlotList[bodyIndex].AddOverlay(UMAContextBase.InstantiateOverlay("FemaleShirt01", new Color(Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), 1)));
}
else if (randomResult == 1)
{
tempSlotList[bodyIndex].AddOverlay(UMAContextBase.InstantiateOverlay("FemaleShirt02", new Color(Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), 1)));
}
else if (randomResult == 2)
{
tempSlotList.Add(UMAContextBase.InstantiateSlot("FemaleTshirt01"));
tempSlotList[tempSlotList.Count - 1].AddOverlay(UMAContextBase.InstantiateOverlay("FemaleTshirt01", new Color(Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), 1)));
}
else
{
}
tempSlotList.Add(UMAContextBase.InstantiateSlot("FemaleHands", tempSlotList[bodyIndex].GetOverlayList()));
tempSlotList.Add(UMAContextBase.InstantiateSlot("FemaleInnerMouth"));
tempSlotList[tempSlotList.Count - 1].AddOverlay(UMAContextBase.InstantiateOverlay("InnerMouth"));
tempSlotList.Add(UMAContextBase.InstantiateSlot("FemaleFeet", tempSlotList[bodyIndex].GetOverlayList()));
randomResult = Random.Range(0, 2);
if (randomResult == 0)
{
tempSlotList.Add(UMAContextBase.InstantiateSlot("FemaleLegs", tempSlotList[bodyIndex].GetOverlayList()));
}
else if (randomResult == 1)
{
tempSlotList.Add(UMAContextBase.InstantiateSlot("FemaleLegs", tempSlotList[bodyIndex].GetOverlayList()));
tempSlotList[bodyIndex].AddOverlay(UMAContextBase.InstantiateOverlay("FemaleJeans01", new Color(Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), 1)));
}
randomResult = Random.Range(0, 3);
if (randomResult == 0)
{
tempSlotList.Add(UMAContextBase.InstantiateSlot("FemaleShortHair01", tempSlotList[headIndex].GetOverlayList()));
tempSlotList[headIndex].AddOverlay(UMAContextBase.InstantiateOverlay("FemaleShortHair01", HairColor));
}
else if (randomResult == 1)
{
tempSlotList.Add(UMAContextBase.InstantiateSlot("FemaleLongHair01", tempSlotList[headIndex].GetOverlayList()));
tempSlotList[headIndex].AddOverlay(UMAContextBase.InstantiateOverlay("FemaleLongHair01", HairColor));
}
else
{
tempSlotList.Add(UMAContextBase.InstantiateSlot("FemaleLongHair01", tempSlotList[headIndex].GetOverlayList()));
tempSlotList[headIndex].AddOverlay(UMAContextBase.InstantiateOverlay("FemaleLongHair01", HairColor));
tempSlotList.Add(UMAContextBase.InstantiateSlot("FemaleLongHair01_Module"));
tempSlotList[tempSlotList.Count - 1].AddOverlay(UMAContextBase.InstantiateOverlay("FemaleLongHair01_Module", HairColor));
}
umaData.SetSlots(tempSlotList.ToArray());
}
}
protected virtual void SetUMAData()
{
umaData.atlasResolutionScale = atlasResolutionScale;
umaData.OnCharacterCreated += CharacterCreatedCallback;
}
void CharacterCreatedCallback(UMAData umaData)
{
if (generateLotsUMA && hideWhileGeneratingLots)
{
if (umaData.animator != null)
umaData.animator.enabled = false;
Renderer[] renderers = umaData.GetRenderers();
for (int i = 0; i < renderers.Length; i++)
{
renderers[i].enabled = false;
}
}
}
//Dont use LegacyDNA here
public static void RandomizeShape(UMAData umaData)
{
var allDNA = umaData.umaRecipe.GetAllDna();
UMADnaBase mainDNA = null;
//find the main dna to use
foreach(UMADnaBase dna in allDNA)
{
if(System.Array.IndexOf(dna.Names, "height") > -1)
{
mainDNA = dna;
break;
}
}
if (mainDNA != null && mainDNA.GetType() == typeof(DynamicUMADna))
{
DynamicUMADna umaDna = mainDNA as DynamicUMADna;
umaDna.SetValue("height", Random.Range(0.4f, 0.5f));
umaDna.SetValue("headSize", Random.Range(0.485f, 0.515f));
umaDna.SetValue("headWidth", Random.Range(0.4f, 0.6f));
umaDna.SetValue("neckThickness", Random.Range(0.495f, 0.51f));
if (umaData.umaRecipe.raceData.raceName.IndexOf("HumanMale") > -1)
{
umaDna.SetValue("handsSize", Random.Range(0.485f, 0.515f));
umaDna.SetValue("feetSize", Random.Range(0.485f, 0.515f));
umaDna.SetValue("legSeparation", Random.Range(0.4f, 0.6f));
umaDna.SetValue("waist", 0.5f);
}
else
{
umaDna.SetValue("handsSize", Random.Range(0.485f, 0.515f));
umaDna.SetValue("feetSize", Random.Range(0.485f, 0.515f));
umaDna.SetValue("legSeparation", Random.Range(0.485f, 0.515f));
umaDna.SetValue("waist", Random.Range(0.3f, 0.8f));
}
umaDna.SetValue("armLength", Random.Range(0.485f, 0.515f));
umaDna.SetValue("forearmLength", Random.Range(0.485f, 0.515f));
umaDna.SetValue("armWidth", Random.Range(0.3f, 0.8f));
umaDna.SetValue("forearmWidth", Random.Range(0.3f, 0.8f));
umaDna.SetValue("upperMuscle", Random.Range(0.0f, 1.0f));
umaDna.SetValue("upperWeight", Random.Range(-0.2f, 0.2f) + umaDna.GetValue("upperMuscle"));
if (umaDna.GetValue("upperWeight") > 1.0) { umaDna.SetValue("upperWeight", 1.0f); }
if (umaDna.GetValue("upperWeight") < 0.0) { umaDna.SetValue("upperWeight", 0.0f); }
umaDna.SetValue("lowerMuscle", Random.Range(-0.2f, 0.2f) + umaDna.GetValue("upperMuscle"));
if (umaDna.GetValue("lowerMuscle") > 1.0) { umaDna.SetValue("lowerMuscle", 1.0f); }
if (umaDna.GetValue("lowerMuscle") < 0.0) { umaDna.SetValue("lowerMuscle", 0.0f); }
umaDna.SetValue("lowerWeight", Random.Range(-0.1f, 0.1f) + umaDna.GetValue("upperWeight"));
if (umaDna.GetValue("lowerWeight") > 1.0) { umaDna.SetValue("lowerWeight", 1.0f); }
if (umaDna.GetValue("lowerWeight") < 0.0) { umaDna.SetValue("lowerWeight", 0.0f); }
umaDna.SetValue("belly", umaDna.GetValue("upperWeight") * Random.Range(0.0f, 1.0f));
umaDna.SetValue("legsSize", Random.Range(0.45f, 0.6f));
umaDna.SetValue("gluteusSize", Random.Range(0.4f, 0.6f));
umaDna.SetValue("earsSize", Random.Range(0.3f, 0.8f));
umaDna.SetValue("earsPosition", Random.Range(0.3f, 0.8f));
umaDna.SetValue("earsRotation", Random.Range(0.3f, 0.8f));
umaDna.SetValue("noseSize", Random.Range(0.3f, 0.8f));
umaDna.SetValue("noseCurve", Random.Range(0.3f, 0.8f));
umaDna.SetValue("noseWidth", Random.Range(0.3f, 0.8f));
umaDna.SetValue("noseInclination", Random.Range(0.3f, 0.8f));
umaDna.SetValue("nosePosition", Random.Range(0.3f, 0.8f));
umaDna.SetValue("nosePronounced", Random.Range(0.3f, 0.8f));
umaDna.SetValue("noseFlatten", Random.Range(0.3f, 0.8f));
umaDna.SetValue("chinSize", Random.Range(0.3f, 0.8f));
umaDna.SetValue("chinPronounced", Random.Range(0.3f, 0.8f));
umaDna.SetValue("chinPosition", Random.Range(0.3f, 0.8f));
umaDna.SetValue("mandibleSize", Random.Range(0.45f, 0.52f));
umaDna.SetValue("jawsSize", Random.Range(0.3f, 0.8f));
umaDna.SetValue("jawsPosition", Random.Range(0.3f, 0.8f));
umaDna.SetValue("cheekSize", Random.Range(0.3f, 0.8f));
umaDna.SetValue("cheekPosition", Random.Range(0.3f, 0.8f));
umaDna.SetValue("lowCheekPronounced", Random.Range(0.3f, 0.8f));
umaDna.SetValue("lowCheekPosition", Random.Range(0.3f, 0.8f));
umaDna.SetValue("foreheadSize", Random.Range(0.3f, 0.8f));
umaDna.SetValue("foreheadPosition", Random.Range(0.15f, 0.65f));
umaDna.SetValue("lipsSize", Random.Range(0.3f, 0.8f));
umaDna.SetValue("mouthSize", Random.Range(0.3f, 0.8f));
umaDna.SetValue("eyeRotation", Random.Range(0.3f, 0.8f));
umaDna.SetValue("eyeSize", Random.Range(0.3f, 0.8f));
umaDna.SetValue("breastSize", Random.Range(0.3f, 0.8f));
}
else if (mainDNA != null)
{
RandomizeShapeLegacy(umaData);
}
}
private static void RandomizeShapeLegacy(UMAData umaData)
{
UMADnaHumanoid umaDna = umaData.umaRecipe.GetDna<UMADnaHumanoid>();
umaDna.height = Random.Range(0.4f, 0.5f);
umaDna.headSize = Random.Range(0.485f, 0.515f);
umaDna.headWidth = Random.Range(0.4f, 0.6f);
umaDna.neckThickness = Random.Range(0.495f, 0.51f);
if (umaData.umaRecipe.raceData.raceName == "HumanMale")
{
umaDna.handsSize = Random.Range(0.485f, 0.515f);
umaDna.feetSize = Random.Range(0.485f, 0.515f);
umaDna.legSeparation = Random.Range(0.4f, 0.6f);
umaDna.waist = 0.5f;
}
else
{
umaDna.handsSize = Random.Range(0.485f, 0.515f);
umaDna.feetSize = Random.Range(0.485f, 0.515f);
umaDna.legSeparation = Random.Range(0.485f, 0.515f);
umaDna.waist = Random.Range(0.3f, 0.8f);
}
umaDna.armLength = Random.Range(0.485f, 0.515f);
umaDna.forearmLength = Random.Range(0.485f, 0.515f);
umaDna.armWidth = Random.Range(0.3f, 0.8f);
umaDna.forearmWidth = Random.Range(0.3f, 0.8f);
umaDna.upperMuscle = Random.Range(0.0f, 1.0f);
umaDna.upperWeight = Random.Range(-0.2f, 0.2f) + umaDna.upperMuscle;
if (umaDna.upperWeight > 1.0) { umaDna.upperWeight = 1.0f; }
if (umaDna.upperWeight < 0.0) { umaDna.upperWeight = 0.0f; }
umaDna.lowerMuscle = Random.Range(-0.2f, 0.2f) + umaDna.upperMuscle;
if (umaDna.lowerMuscle > 1.0) { umaDna.lowerMuscle = 1.0f; }
if (umaDna.lowerMuscle < 0.0) { umaDna.lowerMuscle = 0.0f; }
umaDna.lowerWeight = Random.Range(-0.1f, 0.1f) + umaDna.upperWeight;
if (umaDna.lowerWeight > 1.0) { umaDna.lowerWeight = 1.0f; }
if (umaDna.lowerWeight < 0.0) { umaDna.lowerWeight = 0.0f; }
umaDna.belly = umaDna.upperWeight * Random.Range(0.0f, 1.0f);
umaDna.legsSize = Random.Range(0.45f, 0.6f);
umaDna.gluteusSize = Random.Range(0.4f, 0.6f);
umaDna.earsSize = Random.Range(0.3f, 0.8f);
umaDna.earsPosition = Random.Range(0.3f, 0.8f);
umaDna.earsRotation = Random.Range(0.3f, 0.8f);
umaDna.noseSize = Random.Range(0.3f, 0.8f);
umaDna.noseCurve = Random.Range(0.3f, 0.8f);
umaDna.noseWidth = Random.Range(0.3f, 0.8f);
umaDna.noseInclination = Random.Range(0.3f, 0.8f);
umaDna.nosePosition = Random.Range(0.3f, 0.8f);
umaDna.nosePronounced = Random.Range(0.3f, 0.8f);
umaDna.noseFlatten = Random.Range(0.3f, 0.8f);
umaDna.chinSize = Random.Range(0.3f, 0.8f);
umaDna.chinPronounced = Random.Range(0.3f, 0.8f);
umaDna.chinPosition = Random.Range(0.3f, 0.8f);
umaDna.mandibleSize = Random.Range(0.45f, 0.52f);
umaDna.jawsSize = Random.Range(0.3f, 0.8f);
umaDna.jawsPosition = Random.Range(0.3f, 0.8f);
umaDna.cheekSize = Random.Range(0.3f, 0.8f);
umaDna.cheekPosition = Random.Range(0.3f, 0.8f);
umaDna.lowCheekPronounced = Random.Range(0.3f, 0.8f);
umaDna.lowCheekPosition = Random.Range(0.3f, 0.8f);
umaDna.foreheadSize = Random.Range(0.3f, 0.8f);
umaDna.foreheadPosition = Random.Range(0.15f, 0.65f);
umaDna.lipsSize = Random.Range(0.3f, 0.8f);
umaDna.mouthSize = Random.Range(0.3f, 0.8f);
umaDna.eyeRotation = Random.Range(0.3f, 0.8f);
umaDna.eyeSize = Random.Range(0.3f, 0.8f);
umaDna.breastSize = Random.Range(0.3f, 0.8f);
}
protected virtual void GenerateUMAShapes()
{
/*UMADnaHumanoid umaDna = umaData.umaRecipe.GetDna<UMADnaHumanoid>();
if (umaDna == null)
{
umaDna = new UMADnaHumanoid();
umaData.umaRecipe.AddDna(umaDna);
}*/
if (randomDna)
{
RandomizeShape(umaData);
}
}
public void ResetSpawnPos(){
spawnX = 0;
spawnY = 0;
}
public GameObject GenerateUMA(int sex, Vector3 position)
{
GameObject newGO = new GameObject("Generated Character");
newGO.transform.parent = transform;
newGO.transform.position = position;
newGO.transform.rotation = zeroPoint != null ? zeroPoint.rotation : transform.rotation;
UMADynamicAvatar umaDynamicAvatar = newGO.AddComponent<UMADynamicAvatar>();
umaDynamicAvatar.Initialize();
umaData = umaDynamicAvatar.umaData;
umaData.CharacterCreated = new UMADataEvent(CharacterCreated);
umaData.CharacterDestroyed = new UMADataEvent(CharacterDestroyed);
umaData.CharacterUpdated = new UMADataEvent(CharacterUpdated);
umaDynamicAvatar.umaGenerator = generator;
umaData.umaGenerator = generator;
var umaRecipe = umaDynamicAvatar.umaData.umaRecipe;
UMACrowdRandomSet.CrowdRaceData race = null;
if (randomPool != null && randomPool.Length > 0)
{
int randomResult = Random.Range(0, randomPool.Length);
race = randomPool[randomResult].data;
string theRaceId = race.raceID;
umaRecipe.SetRace(UMAContextBase.GetRace(race.raceID));
}
else
{
if (sex == 0)
{
umaRecipe.SetRace(UMAContextBase.GetRace("HumanMaleDCS"));
}
else
{
umaRecipe.SetRace(UMAContextBase.GetRace("HumanFemaleDCS"));
}
}
SetUMAData();
if (race != null && race.slotElements.Length > 0)
{
DefineSlots(race);
}
else
{
DefineSlots();
}
AddAdditionalSlots();
GenerateUMAShapes();
if (animationController != null)
{
umaDynamicAvatar.animationController = animationController;
}
umaDynamicAvatar.Show();
return newGO;
}
public GameObject GenerateOneUMA(int sex)
{
Vector3 zeroPos = Vector3.zero;
if (zeroPoint != null)
zeroPos = zeroPoint.position;
Vector3 newPos = zeroPos + new Vector3((spawnX - umaCrowdSize.x / 2f + 0.5f) * space, 0f, (spawnY - umaCrowdSize.y / 2f + 0.5f) * space);
if (spawnY < umaCrowdSize.y)
{
spawnX++;
if (spawnX >= umaCrowdSize.x)
{
spawnX = 0;
spawnY++;
}
}
else
{
if (hideWhileGeneratingLots)
{
UMAData[] generatedCrowd = GetComponentsInChildren<UMAData>();
foreach (UMAData generatedData in generatedCrowd)
{
if (generatedData.animator != null)
generatedData.animator.enabled = true;
Renderer[] renderers = generatedData.GetRenderers();
for (int i = 0; i < renderers.Length; i++)
{
renderers[i].enabled = true;
}
}
}
generateLotsUMA = false;
spawnX = 0;
spawnY = 0;
return null;
}
return GenerateUMA(sex, newPos);
}
private void AddAdditionalSlots()
{
umaData.AddAdditionalRecipes(additionalRecipes, UMAContextBase.Instance);
}
public void ReplaceAll()
{
if (generateUMA || generateLotsUMA)
{
Debug.LogWarning("Can't replace while spawning.");
return;
}
int childCount = gameObject.transform.childCount;
while(--childCount >= 0)
{
Transform child = gameObject.transform.GetChild(childCount);
UMAUtils.DestroySceneObject(child.gameObject);
}
if (umaCrowdSize.x <= 1 && umaCrowdSize.y <= 1)
generateUMA = true;
else
generateLotsUMA = true;
}
public void RandomizeAllDna()
{
for (int i = 0; i < transform.childCount; i++)
{
var umaData = transform.GetChild(i).GetComponent<UMAData>();
UMACrowd.RandomizeShape(umaData);
umaData.Dirty(true, false, false);
}
}
public void RandomizeAll()
{
if (generateUMA || generateLotsUMA)
{
Debug.LogWarning("Can't randomize while spawning.");
return;
}
int childCount = gameObject.transform.childCount;
for (int i = 0; i < childCount; i++)
{
Transform child = gameObject.transform.GetChild(i);
UMADynamicAvatar umaDynamicAvatar = child.gameObject.GetComponent<UMADynamicAvatar>();
if (umaDynamicAvatar == null)
{
Debug.Log("Couldn't find dynamic avatar on child: " + child.gameObject.name);
continue;
}
umaData = umaDynamicAvatar.umaData;
var umaRecipe = umaDynamicAvatar.umaData.umaRecipe;
UMACrowdRandomSet.CrowdRaceData race = null;
if (randomPool != null && randomPool.Length > 0)
{
int randomResult = Random.Range(0, randomPool.Length);
race = randomPool[randomResult].data;
umaRecipe.SetRace(UMAContextBase.GetRace(race.raceID));
}
else
{
if (Random.value < 0.5f)
{
umaRecipe.SetRace(UMAContextBase.GetRace("HumanMaleDCS"));
}
else
{
umaRecipe.SetRace(UMAContextBase.GetRace("HumanFemaleDCS"));
}
}
// SetUMAData();
if (race != null && race.slotElements.Length > 0)
{
DefineSlots(race);
}
else
{
DefineSlots();
}
AddAdditionalSlots();
GenerateUMAShapes();
if (animationController != null)
{
umaDynamicAvatar.animationController = animationController;
}
umaDynamicAvatar.Show();
}
}
}
}
| |
#region License
// Copyright (c) 2007-2009, Sean Chambers <schambers80@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Collections.Generic;
using System.Data;
using FluentMigrator.Expressions;
using FluentMigrator.Infrastructure;
using FluentMigrator.Model;
namespace FluentMigrator.Builders.Alter.Column
{
public class AlterColumnExpressionBuilder : ExpressionBuilderWithColumnTypesBase<AlterColumnExpression, IAlterColumnOptionSyntax>,
IAlterColumnOnTableSyntax,
IAlterColumnAsTypeOrInSchemaSyntax,
IAlterColumnOptionOrForeignKeyCascadeSyntax,
IColumnExpressionBuilder
{
private readonly IMigrationContext _context;
public AlterColumnExpressionBuilder(AlterColumnExpression expression, IMigrationContext context)
: base(expression)
{
_context = context;
ColumnHelper = new ColumnExpressionBuilderHelper(this, context);
}
public ForeignKeyDefinition CurrentForeignKey { get; set; }
public ColumnExpressionBuilderHelper ColumnHelper { get; set; }
public IAlterColumnAsTypeOrInSchemaSyntax OnTable(string name)
{
Expression.TableName = name;
return this;
}
public IAlterColumnAsTypeSyntax InSchema(string schemaName)
{
Expression.SchemaName = schemaName;
return this;
}
public IAlterColumnOptionSyntax WithDefault(SystemMethods method)
{
return WithDefaultValue(method);
}
public IAlterColumnOptionSyntax WithDefaultValue(object value)
{
// we need to do a drop constraint and then add constraint to change the default value
var dc = new AlterDefaultConstraintExpression
{
TableName = Expression.TableName,
SchemaName = Expression.SchemaName,
ColumnName = Expression.Column.Name,
DefaultValue = value
};
_context.Expressions.Add(dc);
Expression.Column.DefaultValue = value;
return this;
}
public IAlterColumnOptionSyntax WithColumnDescription(string description)
{
Expression.Column.ColumnDescription = description;
return this;
}
public IAlterColumnOptionSyntax Identity()
{
Expression.Column.IsIdentity = true;
return this;
}
public IAlterColumnOptionSyntax Indexed()
{
return Indexed(null);
}
public IAlterColumnOptionSyntax Indexed(string indexName)
{
ColumnHelper.Indexed(indexName);
return this;
}
public IAlterColumnOptionSyntax PrimaryKey()
{
Expression.Column.IsPrimaryKey = true;
return this;
}
public IAlterColumnOptionSyntax PrimaryKey(string primaryKeyName)
{
Expression.Column.IsPrimaryKey = true;
Expression.Column.PrimaryKeyName = primaryKeyName;
return this;
}
public IAlterColumnOptionSyntax Nullable()
{
ColumnHelper.SetNullable(true);
return this;
}
public IAlterColumnOptionSyntax NotNullable()
{
ColumnHelper.SetNullable(false);
return this;
}
public IAlterColumnOptionSyntax Unique()
{
ColumnHelper.Unique(null);
return this;
}
public IAlterColumnOptionSyntax Unique(string indexName)
{
ColumnHelper.Unique(indexName);
return this;
}
public IAlterColumnOptionOrForeignKeyCascadeSyntax ForeignKey(string primaryTableName, string primaryColumnName)
{
return ForeignKey(null, null, primaryTableName, primaryColumnName);
}
public IAlterColumnOptionOrForeignKeyCascadeSyntax ForeignKey(string foreignKeyName, string primaryTableName, string primaryColumnName)
{
return ForeignKey(foreignKeyName, null, primaryTableName, primaryColumnName);
}
public IAlterColumnOptionOrForeignKeyCascadeSyntax ForeignKey(string foreignKeyName, string primaryTableSchema, string primaryTableName,
string primaryColumnName)
{
Expression.Column.IsForeignKey = true;
var fk = new CreateForeignKeyExpression
{
ForeignKey = new ForeignKeyDefinition
{
Name = foreignKeyName,
PrimaryTable = primaryTableName,
PrimaryTableSchema = primaryTableSchema,
ForeignTable = Expression.TableName,
ForeignTableSchema = Expression.SchemaName
}
};
fk.ForeignKey.PrimaryColumns.Add(primaryColumnName);
fk.ForeignKey.ForeignColumns.Add(Expression.Column.Name);
_context.Expressions.Add(fk);
CurrentForeignKey = fk.ForeignKey;
return this;
}
public IAlterColumnOptionOrForeignKeyCascadeSyntax ReferencedBy(string foreignTableName, string foreignColumnName)
{
return ReferencedBy(null, null, foreignTableName, foreignColumnName);
}
public IAlterColumnOptionOrForeignKeyCascadeSyntax ReferencedBy(string foreignKeyName, string foreignTableName, string foreignColumnName)
{
return ReferencedBy(foreignKeyName, null, foreignTableName, foreignColumnName);
}
public IAlterColumnOptionOrForeignKeyCascadeSyntax ReferencedBy(string foreignKeyName, string foreignTableSchema, string foreignTableName,
string foreignColumnName)
{
var fk = new CreateForeignKeyExpression
{
ForeignKey = new ForeignKeyDefinition
{
Name = foreignKeyName,
PrimaryTable = Expression.TableName,
PrimaryTableSchema = Expression.SchemaName,
ForeignTable = foreignTableName,
ForeignTableSchema = foreignTableSchema
}
};
fk.ForeignKey.PrimaryColumns.Add(Expression.Column.Name);
fk.ForeignKey.ForeignColumns.Add(foreignColumnName);
_context.Expressions.Add(fk);
CurrentForeignKey = fk.ForeignKey;
return this;
}
public IAlterColumnOptionOrForeignKeyCascadeSyntax ForeignKey()
{
Expression.Column.IsForeignKey = true;
return this;
}
[Obsolete("Please use ReferencedBy syntax. This method will be removed in the next version")]
public IAlterColumnOptionSyntax References(string foreignKeyName, string foreignTableName, IEnumerable<string> foreignColumnNames)
{
return References(foreignKeyName, null, foreignTableName, foreignColumnNames);
}
[Obsolete("Please use ReferencedBy syntax. This method will be removed in the next version")]
public IAlterColumnOptionSyntax References(string foreignKeyName, string foreignTableSchema, string foreignTableName,
IEnumerable<string> foreignColumnNames)
{
var fk = new CreateForeignKeyExpression
{
ForeignKey = new ForeignKeyDefinition
{
Name = foreignKeyName,
PrimaryTable = Expression.TableName,
PrimaryTableSchema = Expression.SchemaName,
ForeignTable = foreignTableName,
ForeignTableSchema = foreignTableSchema
}
};
fk.ForeignKey.PrimaryColumns.Add(Expression.Column.Name);
foreach (var foreignColumnName in foreignColumnNames)
fk.ForeignKey.ForeignColumns.Add(foreignColumnName);
_context.Expressions.Add(fk);
return this;
}
public override ColumnDefinition GetColumnForType()
{
return Expression.Column;
}
public IAlterColumnOptionOrForeignKeyCascadeSyntax OnDelete(Rule rule)
{
CurrentForeignKey.OnDelete = rule;
return this;
}
public IAlterColumnOptionOrForeignKeyCascadeSyntax OnUpdate(Rule rule)
{
CurrentForeignKey.OnUpdate = rule;
return this;
}
public IAlterColumnOptionSyntax OnDeleteOrUpdate(Rule rule)
{
OnDelete(rule);
OnUpdate(rule);
return this;
}
string IColumnExpressionBuilder.SchemaName
{
get
{
return Expression.SchemaName;
}
}
string IColumnExpressionBuilder.TableName
{
get
{
return Expression.TableName;
}
}
ColumnDefinition IColumnExpressionBuilder.Column
{
get
{
return Expression.Column;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Web;
using System.Web.Hosting;
using Orchard.Specs.Util;
using Path = Bleroy.FluentPath.Path;
namespace Orchard.Specs.Hosting {
public class WebHost {
private readonly Path _orchardTemp;
private WebHostAgent _webHostAgent;
private Path _tempSite;
private Path _orchardWebPath;
private Path _codeGenDir;
private IEnumerable<string> _knownModules;
private IEnumerable<string> _knownThemes;
private IEnumerable<string> _knownBinAssemblies;
public WebHost(Path orchardTemp) {
_orchardTemp = orchardTemp;
}
public void Initialize(string templateName, string virtualDirectory, DynamicCompilationOption dynamicCompilationOption) {
var stopwatch = new Stopwatch();
stopwatch.Start();
var baseDir = Path.Get(AppDomain.CurrentDomain.BaseDirectory);
_tempSite = _orchardTemp.Combine(System.IO.Path.GetRandomFileName());
try { _tempSite.Delete(); }
catch { }
// Trying the two known relative paths to the Orchard.Web directory.
// The second one is for the target "spec" in orchard.proj.
_orchardWebPath = baseDir;
while (!_orchardWebPath.Combine("Orchard.proj").Exists && _orchardWebPath.Parent != null) {
_orchardWebPath = _orchardWebPath.Parent;
}
_orchardWebPath = _orchardWebPath.Combine("src").Combine("Orchard.Web");
Log("Initialization of ASP.NET host for template web site \"{0}\":", templateName);
Log(" Source location: \"{0}\"", _orchardWebPath);
Log(" Temporary location: \"{0}\"", _tempSite);
_knownModules = _orchardWebPath.Combine("Modules").Directories.Where(d => d.Combine("module.txt").Exists).Select(d => d.FileName).ToList();
//foreach (var filename in _knownModules)
// Log("Available Module: \"{0}\"", filename);
_knownThemes = _orchardWebPath.Combine("Themes").Directories.Where(d => d.Combine("theme.txt").Exists).Select(d => d.FileName).ToList();
//foreach (var filename in _knownThemes)
// Log("Available Theme: \"{0}\"", filename);
_knownBinAssemblies = _orchardWebPath.Combine("bin").GetFiles("*.dll").Select(f => f.FileNameWithoutExtension);
//foreach (var filename in _knownBinAssemblies)
// Log("Assembly in ~/bin: \"{0}\"", filename);
Log("Copy files from template \"{0}\"", templateName);
baseDir.Combine("Hosting").Combine(templateName)
.DeepCopy(_tempSite);
if (dynamicCompilationOption != DynamicCompilationOption.Enabled) {
var sourceConfig = baseDir.Combine("Hosting").Combine("TemplateConfigs");
var siteConfig = _tempSite.Combine("Config");
switch (dynamicCompilationOption) {
case DynamicCompilationOption.Disabled:
File.Copy(sourceConfig.Combine("DisableDynamicCompilation.HostComponents.config"), siteConfig.Combine("HostComponents.config"));
break;
case DynamicCompilationOption.Force:
File.Copy(sourceConfig.Combine("ForceDynamicCompilation.HostComponents.config"), siteConfig.Combine("HostComponents.config"));
break;
}
}
Log("Copy binaries of the \"Orchard.Web\" project");
_orchardWebPath.Combine("bin")
.ShallowCopy("*.dll", _tempSite.Combine("bin"))
.ShallowCopy("*.pdb", _tempSite.Combine("bin"));
Log("Copy SqlCe native binaries");
if (_orchardWebPath.Combine("bin").Combine("x86").IsDirectory) {
_orchardWebPath.Combine("bin").Combine("x86")
.DeepCopy("*.*", _tempSite.Combine("bin").Combine("x86"));
}
if (_orchardWebPath.Combine("bin").Combine("amd64").IsDirectory) {
_orchardWebPath.Combine("bin").Combine("amd64")
.DeepCopy("*.*", _tempSite.Combine("bin").Combine("amd64"));
}
//Log("Copy roslyn binaries");
//if (_orchardWebPath.Combine("bin").Combine("roslyn").IsDirectory) {
// _orchardWebPath.Combine("bin").Combine("roslyn")
// .DeepCopy("*.*", _tempSite.Combine("bin").Combine("roslyn"));
//}
// Copy binaries of this project, so that remote execution of lambda
// can be achieved through serialization to the ASP.NET appdomain
// (see Execute(Action) method)
Log("Copy Orchard.Specflow test project binaries");
baseDir.ShallowCopy(
path => IsSpecFlowTestAssembly(path) && !_tempSite.Combine("bin").Combine(path.FileName).Exists,
_tempSite.Combine("bin"));
Log("Copy Orchard recipes");
_orchardWebPath.Combine("Modules").Combine("Orchard.Setup").Combine("Recipes").DeepCopy("*.xml", _tempSite.Combine("Modules").Combine("Orchard.Setup").Combine("Recipes"));
StartAspNetHost(virtualDirectory);
Log("ASP.NET host initialization completed in {0} sec", stopwatch.Elapsed.TotalSeconds);
}
private void StartAspNetHost(string virtualDirectory) {
Log("Starting up ASP.NET host");
HostName = "localhost";
PhysicalDirectory = _tempSite;
VirtualDirectory = virtualDirectory;
_webHostAgent = (WebHostAgent)ApplicationHost.CreateApplicationHost(typeof(WebHostAgent), VirtualDirectory, PhysicalDirectory);
var shuttle = new Shuttle();
Execute(() => { shuttle.CodeGenDir = HttpRuntime.CodegenDir; });
// ASP.NET folder seems to be always nested into an empty directory
_codeGenDir = shuttle.CodeGenDir;
_codeGenDir = _codeGenDir.Parent;
Log("ASP.NET CodeGenDir: \"{0}\"", _codeGenDir);
}
[Serializable]
public class Shuttle {
public string CodeGenDir;
}
public void Dispose() {
if (_webHostAgent != null) {
_webHostAgent.Shutdown();
_webHostAgent = null;
}
Clean();
}
private void Log(string format, params object[] args) {
Trace.WriteLine(string.Format(format, args));
}
public void Clean() {
// Try to delete temporary files for up to ~1.2 seconds.
for (int i = 0; i < 4; i++) {
Log("Waiting 300msec before trying to delete temporary files");
Thread.Sleep(300);
if (TryDeleteTempFiles(i == 4)) {
Log("Successfully deleted all temporary files");
break;
}
}
}
private bool TryDeleteTempFiles(bool lastTry) {
var result = true;
if (_codeGenDir != null && _codeGenDir.Exists) {
Log("Trying to delete temporary files at \"{0}\"", _codeGenDir);
try {
_codeGenDir.Delete(true); // <- clean as much as possible
}
catch (Exception e) {
if (lastTry)
Log("Failure: \"{0}\"", e);
result = false;
}
}
if (_tempSite != null && _tempSite.Exists)
try {
Log("Trying to delete temporary files at \"{0}\"", _tempSite);
_tempSite.Delete(true); // <- progressively clean as much as possible
}
catch (Exception e) {
if (lastTry)
Log("failure: \"{0}\"", e);
result = false;
}
return result;
}
public void CopyExtension(string extensionFolder, string extensionName, ExtensionDeploymentOptions deploymentOptions) {
Log("Copy extension \"{0}\\{1}\" (options={2})", extensionFolder, extensionName, deploymentOptions);
var sourceModule = _orchardWebPath.Combine(extensionFolder).Combine(extensionName);
var targetModule = _tempSite.Combine(extensionFolder).Combine(extensionName);
sourceModule.ShallowCopy("*.txt", targetModule);
sourceModule.ShallowCopy("*.info", targetModule);
sourceModule.ShallowCopy("*.config", targetModule);
if ((deploymentOptions & ExtensionDeploymentOptions.SourceCode) == ExtensionDeploymentOptions.SourceCode) {
sourceModule.ShallowCopy("*.csproj", targetModule);
sourceModule.DeepCopy("*.cs", targetModule);
}
if (sourceModule.Combine("bin").IsDirectory) {
sourceModule.Combine("bin").ShallowCopy(path => IsExtensionBinaryFile(path, extensionName, deploymentOptions), targetModule.Combine("bin"));
}
if (sourceModule.Combine("Views").IsDirectory)
sourceModule.Combine("Views").DeepCopy(targetModule.Combine("Views"));
// don't copy content folders as they are useless in this headless scenario
}
public void CopyFile(string source, string destination) {
StackTrace st = new StackTrace(true);
Path origin = null;
foreach(var sf in st.GetFrames()) {
var sourceFile = sf.GetFileName();
if(String.IsNullOrEmpty(sourceFile)) {
continue;
}
var testOrigin = Path.Get(sourceFile).Parent.Combine(source);
if(testOrigin.Exists) {
origin = testOrigin;
break;
}
}
if(origin == null) {
throw new FileNotFoundException("File not found: " + source);
}
var target = _tempSite.Combine(destination);
Directory.CreateDirectory(target.DirectoryName);
File.Copy(origin, target);
}
private bool IsExtensionBinaryFile(Path path, string extensionName, ExtensionDeploymentOptions deploymentOptions) {
bool isValidExtension = IsAssemblyFile(path);
if (!isValidExtension)
return false;
bool isAssemblyInWebAppBin = _knownBinAssemblies.Contains(path.FileNameWithoutExtension, StringComparer.OrdinalIgnoreCase);
if (isAssemblyInWebAppBin)
return false;
bool isExtensionAssembly = IsOrchardExtensionFile(path);
bool copyExtensionAssembly = (deploymentOptions & ExtensionDeploymentOptions.CompiledAssembly) == ExtensionDeploymentOptions.CompiledAssembly;
if (isExtensionAssembly && !copyExtensionAssembly)
return false;
return true;
}
private bool IsSpecFlowTestAssembly(Path path) {
if (!IsAssemblyFile(path))
return false;
if (IsOrchardExtensionFile(path))
return false;
return true;
}
private bool IsAssemblyFile(Path path) {
return StringComparer.OrdinalIgnoreCase.Equals(path.Extension, ".exe") ||
StringComparer.OrdinalIgnoreCase.Equals(path.Extension, ".dll") ||
StringComparer.OrdinalIgnoreCase.Equals(path.Extension, ".pdb");
}
private bool IsOrchardExtensionFile(Path path) {
return _knownModules.Where(name => StringComparer.OrdinalIgnoreCase.Equals(name, path.FileNameWithoutExtension)).Any() ||
_knownThemes.Where(name => StringComparer.OrdinalIgnoreCase.Equals(name, path.FileNameWithoutExtension)).Any();
}
public string HostName { get; set; }
public string PhysicalDirectory { get; private set; }
public string VirtualDirectory { get; private set; }
public string Cookies { get; set; }
public void Execute(Action action) {
var shuttleSend = new SerializableDelegate<Action>(action);
var shuttleRecv = _webHostAgent.Execute(shuttleSend);
CopyFields(shuttleRecv.Delegate.Target, shuttleSend.Delegate.Target);
}
private static void CopyFields<T>(T from, T to) where T : class {
if (from == null || to == null)
return;
foreach (FieldInfo fieldInfo in from.GetType().GetFields()) {
var value = fieldInfo.GetValue(from);
fieldInfo.SetValue(to, value);
}
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Cloud.Talent.V4
{
/// <summary>Settings for <see cref="CompletionClient"/> instances.</summary>
public sealed partial class CompletionSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="CompletionSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="CompletionSettings"/>.</returns>
public static CompletionSettings GetDefault() => new CompletionSettings();
/// <summary>Constructs a new <see cref="CompletionSettings"/> object with default settings.</summary>
public CompletionSettings()
{
}
private CompletionSettings(CompletionSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
CompleteQuerySettings = existing.CompleteQuerySettings;
OnCopy(existing);
}
partial void OnCopy(CompletionSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>CompletionClient.CompleteQuery</c> and <c>CompletionClient.CompleteQueryAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: 5</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.DeadlineExceeded"/>,
/// <see cref="grpccore::StatusCode.Unavailable"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 30 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings CompleteQuerySettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(30000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 5, initialBackoff: sys::TimeSpan.FromMilliseconds(100), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.DeadlineExceeded, grpccore::StatusCode.Unavailable)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="CompletionSettings"/> object.</returns>
public CompletionSettings Clone() => new CompletionSettings(this);
}
/// <summary>
/// Builder class for <see cref="CompletionClient"/> to provide simple configuration of credentials, endpoint etc.
/// </summary>
public sealed partial class CompletionClientBuilder : gaxgrpc::ClientBuilderBase<CompletionClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public CompletionSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public CompletionClientBuilder()
{
UseJwtAccessWithScopes = CompletionClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref CompletionClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<CompletionClient> task);
/// <summary>Builds the resulting client.</summary>
public override CompletionClient Build()
{
CompletionClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<CompletionClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<CompletionClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private CompletionClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return CompletionClient.Create(callInvoker, Settings);
}
private async stt::Task<CompletionClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return CompletionClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => CompletionClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => CompletionClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => CompletionClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>Completion client wrapper, for convenient use.</summary>
/// <remarks>
/// A service handles auto completion.
/// </remarks>
public abstract partial class CompletionClient
{
/// <summary>
/// The default endpoint for the Completion service, which is a host of "jobs.googleapis.com" and a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "jobs.googleapis.com:443";
/// <summary>The default Completion scopes.</summary>
/// <remarks>
/// The default Completion scopes are:
/// <list type="bullet">
/// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item>
/// <item><description>https://www.googleapis.com/auth/jobs</description></item>
/// </list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/jobs",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="CompletionClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="CompletionClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="CompletionClient"/>.</returns>
public static stt::Task<CompletionClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new CompletionClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="CompletionClient"/> using the default credentials, endpoint and settings.
/// To specify custom credentials or other settings, use <see cref="CompletionClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="CompletionClient"/>.</returns>
public static CompletionClient Create() => new CompletionClientBuilder().Build();
/// <summary>
/// Creates a <see cref="CompletionClient"/> which uses the specified call invoker for remote operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="CompletionSettings"/>.</param>
/// <returns>The created <see cref="CompletionClient"/>.</returns>
internal static CompletionClient Create(grpccore::CallInvoker callInvoker, CompletionSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
Completion.CompletionClient grpcClient = new Completion.CompletionClient(callInvoker);
return new CompletionClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC Completion client</summary>
public virtual Completion.CompletionClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Completes the specified prefix with keyword suggestions.
/// Intended for use by a job search auto-complete search box.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual CompleteQueryResponse CompleteQuery(CompleteQueryRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Completes the specified prefix with keyword suggestions.
/// Intended for use by a job search auto-complete search box.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<CompleteQueryResponse> CompleteQueryAsync(CompleteQueryRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Completes the specified prefix with keyword suggestions.
/// Intended for use by a job search auto-complete search box.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<CompleteQueryResponse> CompleteQueryAsync(CompleteQueryRequest request, st::CancellationToken cancellationToken) =>
CompleteQueryAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>Completion client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// A service handles auto completion.
/// </remarks>
public sealed partial class CompletionClientImpl : CompletionClient
{
private readonly gaxgrpc::ApiCall<CompleteQueryRequest, CompleteQueryResponse> _callCompleteQuery;
/// <summary>
/// Constructs a client wrapper for the Completion service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="CompletionSettings"/> used within this client.</param>
public CompletionClientImpl(Completion.CompletionClient grpcClient, CompletionSettings settings)
{
GrpcClient = grpcClient;
CompletionSettings effectiveSettings = settings ?? CompletionSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callCompleteQuery = clientHelper.BuildApiCall<CompleteQueryRequest, CompleteQueryResponse>(grpcClient.CompleteQueryAsync, grpcClient.CompleteQuery, effectiveSettings.CompleteQuerySettings).WithGoogleRequestParam("tenant", request => request.Tenant);
Modify_ApiCall(ref _callCompleteQuery);
Modify_CompleteQueryApiCall(ref _callCompleteQuery);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_CompleteQueryApiCall(ref gaxgrpc::ApiCall<CompleteQueryRequest, CompleteQueryResponse> call);
partial void OnConstruction(Completion.CompletionClient grpcClient, CompletionSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC Completion client</summary>
public override Completion.CompletionClient GrpcClient { get; }
partial void Modify_CompleteQueryRequest(ref CompleteQueryRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Completes the specified prefix with keyword suggestions.
/// Intended for use by a job search auto-complete search box.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override CompleteQueryResponse CompleteQuery(CompleteQueryRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_CompleteQueryRequest(ref request, ref callSettings);
return _callCompleteQuery.Sync(request, callSettings);
}
/// <summary>
/// Completes the specified prefix with keyword suggestions.
/// Intended for use by a job search auto-complete search box.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<CompleteQueryResponse> CompleteQueryAsync(CompleteQueryRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_CompleteQueryRequest(ref request, ref callSettings);
return _callCompleteQuery.Async(request, callSettings);
}
}
}
| |
namespace javax.security.cert
{
[global::MonoJavaBridge.JavaClass(typeof(global::javax.security.cert.X509Certificate_))]
public abstract partial class X509Certificate : javax.security.cert.Certificate
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static X509Certificate()
{
InitJNI();
}
protected X509Certificate(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _getInstance16076;
public static global::javax.security.cert.X509Certificate getInstance(byte[] arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(javax.security.cert.X509Certificate.staticClass, global::javax.security.cert.X509Certificate._getInstance16076, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as javax.security.cert.X509Certificate;
}
internal static global::MonoJavaBridge.MethodId _getInstance16077;
public static global::javax.security.cert.X509Certificate getInstance(java.io.InputStream arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(javax.security.cert.X509Certificate.staticClass, global::javax.security.cert.X509Certificate._getInstance16077, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as javax.security.cert.X509Certificate;
}
internal static global::MonoJavaBridge.MethodId _getVersion16078;
public abstract int getVersion();
internal static global::MonoJavaBridge.MethodId _getSerialNumber16079;
public abstract global::java.math.BigInteger getSerialNumber();
internal static global::MonoJavaBridge.MethodId _getIssuerDN16080;
public abstract global::java.security.Principal getIssuerDN();
internal static global::MonoJavaBridge.MethodId _checkValidity16081;
public abstract void checkValidity();
internal static global::MonoJavaBridge.MethodId _checkValidity16082;
public abstract void checkValidity(java.util.Date arg0);
internal static global::MonoJavaBridge.MethodId _getSubjectDN16083;
public abstract global::java.security.Principal getSubjectDN();
internal static global::MonoJavaBridge.MethodId _getNotBefore16084;
public abstract global::java.util.Date getNotBefore();
internal static global::MonoJavaBridge.MethodId _getNotAfter16085;
public abstract global::java.util.Date getNotAfter();
internal static global::MonoJavaBridge.MethodId _getSigAlgName16086;
public abstract global::java.lang.String getSigAlgName();
internal static global::MonoJavaBridge.MethodId _getSigAlgOID16087;
public abstract global::java.lang.String getSigAlgOID();
internal static global::MonoJavaBridge.MethodId _getSigAlgParams16088;
public abstract byte[] getSigAlgParams();
internal static global::MonoJavaBridge.MethodId _X509Certificate16089;
public X509Certificate() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(javax.security.cert.X509Certificate.staticClass, global::javax.security.cert.X509Certificate._X509Certificate16089);
Init(@__env, handle);
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::javax.security.cert.X509Certificate.staticClass = @__env.NewGlobalRef(@__env.FindClass("javax/security/cert/X509Certificate"));
global::javax.security.cert.X509Certificate._getInstance16076 = @__env.GetStaticMethodIDNoThrow(global::javax.security.cert.X509Certificate.staticClass, "getInstance", "([B)Ljavax/security/cert/X509Certificate;");
global::javax.security.cert.X509Certificate._getInstance16077 = @__env.GetStaticMethodIDNoThrow(global::javax.security.cert.X509Certificate.staticClass, "getInstance", "(Ljava/io/InputStream;)Ljavax/security/cert/X509Certificate;");
global::javax.security.cert.X509Certificate._getVersion16078 = @__env.GetMethodIDNoThrow(global::javax.security.cert.X509Certificate.staticClass, "getVersion", "()I");
global::javax.security.cert.X509Certificate._getSerialNumber16079 = @__env.GetMethodIDNoThrow(global::javax.security.cert.X509Certificate.staticClass, "getSerialNumber", "()Ljava/math/BigInteger;");
global::javax.security.cert.X509Certificate._getIssuerDN16080 = @__env.GetMethodIDNoThrow(global::javax.security.cert.X509Certificate.staticClass, "getIssuerDN", "()Ljava/security/Principal;");
global::javax.security.cert.X509Certificate._checkValidity16081 = @__env.GetMethodIDNoThrow(global::javax.security.cert.X509Certificate.staticClass, "checkValidity", "()V");
global::javax.security.cert.X509Certificate._checkValidity16082 = @__env.GetMethodIDNoThrow(global::javax.security.cert.X509Certificate.staticClass, "checkValidity", "(Ljava/util/Date;)V");
global::javax.security.cert.X509Certificate._getSubjectDN16083 = @__env.GetMethodIDNoThrow(global::javax.security.cert.X509Certificate.staticClass, "getSubjectDN", "()Ljava/security/Principal;");
global::javax.security.cert.X509Certificate._getNotBefore16084 = @__env.GetMethodIDNoThrow(global::javax.security.cert.X509Certificate.staticClass, "getNotBefore", "()Ljava/util/Date;");
global::javax.security.cert.X509Certificate._getNotAfter16085 = @__env.GetMethodIDNoThrow(global::javax.security.cert.X509Certificate.staticClass, "getNotAfter", "()Ljava/util/Date;");
global::javax.security.cert.X509Certificate._getSigAlgName16086 = @__env.GetMethodIDNoThrow(global::javax.security.cert.X509Certificate.staticClass, "getSigAlgName", "()Ljava/lang/String;");
global::javax.security.cert.X509Certificate._getSigAlgOID16087 = @__env.GetMethodIDNoThrow(global::javax.security.cert.X509Certificate.staticClass, "getSigAlgOID", "()Ljava/lang/String;");
global::javax.security.cert.X509Certificate._getSigAlgParams16088 = @__env.GetMethodIDNoThrow(global::javax.security.cert.X509Certificate.staticClass, "getSigAlgParams", "()[B");
global::javax.security.cert.X509Certificate._X509Certificate16089 = @__env.GetMethodIDNoThrow(global::javax.security.cert.X509Certificate.staticClass, "<init>", "()V");
}
}
[global::MonoJavaBridge.JavaProxy(typeof(global::javax.security.cert.X509Certificate))]
public sealed partial class X509Certificate_ : javax.security.cert.X509Certificate
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static X509Certificate_()
{
InitJNI();
}
internal X509Certificate_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _getVersion16090;
public override int getVersion()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::javax.security.cert.X509Certificate_._getVersion16090);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::javax.security.cert.X509Certificate_.staticClass, global::javax.security.cert.X509Certificate_._getVersion16090);
}
internal static global::MonoJavaBridge.MethodId _getSerialNumber16091;
public override global::java.math.BigInteger getSerialNumber()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::javax.security.cert.X509Certificate_._getSerialNumber16091)) as java.math.BigInteger;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::javax.security.cert.X509Certificate_.staticClass, global::javax.security.cert.X509Certificate_._getSerialNumber16091)) as java.math.BigInteger;
}
internal static global::MonoJavaBridge.MethodId _getIssuerDN16092;
public override global::java.security.Principal getIssuerDN()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.security.Principal>(@__env.CallObjectMethod(this.JvmHandle, global::javax.security.cert.X509Certificate_._getIssuerDN16092)) as java.security.Principal;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.security.Principal>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::javax.security.cert.X509Certificate_.staticClass, global::javax.security.cert.X509Certificate_._getIssuerDN16092)) as java.security.Principal;
}
internal static global::MonoJavaBridge.MethodId _checkValidity16093;
public override void checkValidity()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::javax.security.cert.X509Certificate_._checkValidity16093);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::javax.security.cert.X509Certificate_.staticClass, global::javax.security.cert.X509Certificate_._checkValidity16093);
}
internal static global::MonoJavaBridge.MethodId _checkValidity16094;
public override void checkValidity(java.util.Date arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::javax.security.cert.X509Certificate_._checkValidity16094, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::javax.security.cert.X509Certificate_.staticClass, global::javax.security.cert.X509Certificate_._checkValidity16094, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getSubjectDN16095;
public override global::java.security.Principal getSubjectDN()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.security.Principal>(@__env.CallObjectMethod(this.JvmHandle, global::javax.security.cert.X509Certificate_._getSubjectDN16095)) as java.security.Principal;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.security.Principal>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::javax.security.cert.X509Certificate_.staticClass, global::javax.security.cert.X509Certificate_._getSubjectDN16095)) as java.security.Principal;
}
internal static global::MonoJavaBridge.MethodId _getNotBefore16096;
public override global::java.util.Date getNotBefore()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::javax.security.cert.X509Certificate_._getNotBefore16096)) as java.util.Date;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::javax.security.cert.X509Certificate_.staticClass, global::javax.security.cert.X509Certificate_._getNotBefore16096)) as java.util.Date;
}
internal static global::MonoJavaBridge.MethodId _getNotAfter16097;
public override global::java.util.Date getNotAfter()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::javax.security.cert.X509Certificate_._getNotAfter16097)) as java.util.Date;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::javax.security.cert.X509Certificate_.staticClass, global::javax.security.cert.X509Certificate_._getNotAfter16097)) as java.util.Date;
}
internal static global::MonoJavaBridge.MethodId _getSigAlgName16098;
public override global::java.lang.String getSigAlgName()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::javax.security.cert.X509Certificate_._getSigAlgName16098)) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::javax.security.cert.X509Certificate_.staticClass, global::javax.security.cert.X509Certificate_._getSigAlgName16098)) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _getSigAlgOID16099;
public override global::java.lang.String getSigAlgOID()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::javax.security.cert.X509Certificate_._getSigAlgOID16099)) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::javax.security.cert.X509Certificate_.staticClass, global::javax.security.cert.X509Certificate_._getSigAlgOID16099)) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _getSigAlgParams16100;
public override byte[] getSigAlgParams()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<byte>(@__env.CallObjectMethod(this.JvmHandle, global::javax.security.cert.X509Certificate_._getSigAlgParams16100)) as byte[];
else
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<byte>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::javax.security.cert.X509Certificate_.staticClass, global::javax.security.cert.X509Certificate_._getSigAlgParams16100)) as byte[];
}
internal static global::MonoJavaBridge.MethodId _toString16101;
public override global::java.lang.String toString()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::javax.security.cert.X509Certificate_._toString16101)) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::javax.security.cert.X509Certificate_.staticClass, global::javax.security.cert.X509Certificate_._toString16101)) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _getEncoded16102;
public override byte[] getEncoded()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<byte>(@__env.CallObjectMethod(this.JvmHandle, global::javax.security.cert.X509Certificate_._getEncoded16102)) as byte[];
else
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<byte>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::javax.security.cert.X509Certificate_.staticClass, global::javax.security.cert.X509Certificate_._getEncoded16102)) as byte[];
}
internal static global::MonoJavaBridge.MethodId _verify16103;
public override void verify(java.security.PublicKey arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::javax.security.cert.X509Certificate_._verify16103, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::javax.security.cert.X509Certificate_.staticClass, global::javax.security.cert.X509Certificate_._verify16103, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _verify16104;
public override void verify(java.security.PublicKey arg0, java.lang.String arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::javax.security.cert.X509Certificate_._verify16104, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::javax.security.cert.X509Certificate_.staticClass, global::javax.security.cert.X509Certificate_._verify16104, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _getPublicKey16105;
public override global::java.security.PublicKey getPublicKey()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.security.PublicKey>(@__env.CallObjectMethod(this.JvmHandle, global::javax.security.cert.X509Certificate_._getPublicKey16105)) as java.security.PublicKey;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.security.PublicKey>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::javax.security.cert.X509Certificate_.staticClass, global::javax.security.cert.X509Certificate_._getPublicKey16105)) as java.security.PublicKey;
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::javax.security.cert.X509Certificate_.staticClass = @__env.NewGlobalRef(@__env.FindClass("javax/security/cert/X509Certificate"));
global::javax.security.cert.X509Certificate_._getVersion16090 = @__env.GetMethodIDNoThrow(global::javax.security.cert.X509Certificate_.staticClass, "getVersion", "()I");
global::javax.security.cert.X509Certificate_._getSerialNumber16091 = @__env.GetMethodIDNoThrow(global::javax.security.cert.X509Certificate_.staticClass, "getSerialNumber", "()Ljava/math/BigInteger;");
global::javax.security.cert.X509Certificate_._getIssuerDN16092 = @__env.GetMethodIDNoThrow(global::javax.security.cert.X509Certificate_.staticClass, "getIssuerDN", "()Ljava/security/Principal;");
global::javax.security.cert.X509Certificate_._checkValidity16093 = @__env.GetMethodIDNoThrow(global::javax.security.cert.X509Certificate_.staticClass, "checkValidity", "()V");
global::javax.security.cert.X509Certificate_._checkValidity16094 = @__env.GetMethodIDNoThrow(global::javax.security.cert.X509Certificate_.staticClass, "checkValidity", "(Ljava/util/Date;)V");
global::javax.security.cert.X509Certificate_._getSubjectDN16095 = @__env.GetMethodIDNoThrow(global::javax.security.cert.X509Certificate_.staticClass, "getSubjectDN", "()Ljava/security/Principal;");
global::javax.security.cert.X509Certificate_._getNotBefore16096 = @__env.GetMethodIDNoThrow(global::javax.security.cert.X509Certificate_.staticClass, "getNotBefore", "()Ljava/util/Date;");
global::javax.security.cert.X509Certificate_._getNotAfter16097 = @__env.GetMethodIDNoThrow(global::javax.security.cert.X509Certificate_.staticClass, "getNotAfter", "()Ljava/util/Date;");
global::javax.security.cert.X509Certificate_._getSigAlgName16098 = @__env.GetMethodIDNoThrow(global::javax.security.cert.X509Certificate_.staticClass, "getSigAlgName", "()Ljava/lang/String;");
global::javax.security.cert.X509Certificate_._getSigAlgOID16099 = @__env.GetMethodIDNoThrow(global::javax.security.cert.X509Certificate_.staticClass, "getSigAlgOID", "()Ljava/lang/String;");
global::javax.security.cert.X509Certificate_._getSigAlgParams16100 = @__env.GetMethodIDNoThrow(global::javax.security.cert.X509Certificate_.staticClass, "getSigAlgParams", "()[B");
global::javax.security.cert.X509Certificate_._toString16101 = @__env.GetMethodIDNoThrow(global::javax.security.cert.X509Certificate_.staticClass, "toString", "()Ljava/lang/String;");
global::javax.security.cert.X509Certificate_._getEncoded16102 = @__env.GetMethodIDNoThrow(global::javax.security.cert.X509Certificate_.staticClass, "getEncoded", "()[B");
global::javax.security.cert.X509Certificate_._verify16103 = @__env.GetMethodIDNoThrow(global::javax.security.cert.X509Certificate_.staticClass, "verify", "(Ljava/security/PublicKey;)V");
global::javax.security.cert.X509Certificate_._verify16104 = @__env.GetMethodIDNoThrow(global::javax.security.cert.X509Certificate_.staticClass, "verify", "(Ljava/security/PublicKey;Ljava/lang/String;)V");
global::javax.security.cert.X509Certificate_._getPublicKey16105 = @__env.GetMethodIDNoThrow(global::javax.security.cert.X509Certificate_.staticClass, "getPublicKey", "()Ljava/security/PublicKey;");
}
}
}
| |
/**
* Directory Flood Version 1.1
* Author: Thomas Gassner
* Date: 06.11.2008
*
* This programm is a console application to flood the current directory
* with subfolders or empty files.
* This programm is for testing only.
* To rattan someone's Computer is illegal!!
*
* With this programm users can compare the times how long the Windows Explorer
* and other file explorer need for handling Directories with a lot of items.
*/
using System;
using System.Text;
using System.IO;
namespace DirFlood.NET {
/// <summary>
/// Implements the directory- and fileflood with static methods
/// </summary>
class DirFlood {
/// <summary>
/// sees a string as a number and increments this number
/// This number can be represented by some numbersystems.
/// The numbersystems can have a base between 2 and 35.
/// The ciphers are: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, f, g, h,
/// i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z
/// </summary>
/// <param name="basis">Is the base of the number system of the number
/// represented by the string. The Minimum is 2 and the Maximum is 35.</param>
/// <param name="value">Is the old number represented by a string that has to be incremented.</param>
/// <returns>The incremented number represented by a string.</returns>
private static string incrementString(int basis, string value) {
//Checks the base for correct values
if ((basis < 2) || (basis > 35)) {
throw new ArgumentOutOfRangeException();
} // if
//if the value is a emptx string return the first number -> 0
if (value.Equals("")) {
return "0";
} // if
//convert the string into an integer array for better calculating
int[] intarr = new int[value.Length];
for (int i = 0; i < value.Length; i++) {
char ch = value[value.Length-i-1];
if (ch >= '0' && ch <= '9') {
intarr[i] = ch - '0';
} else {
if (ch >= 'a' && ch <= 'z') {
intarr[i] = ch - 'a' + 10;
} // if
} // else
} // for
bool carryover = true;
int j = 0;
//increment beginning by the first digit. if there is a carryover increment the next and so on.
while (carryover && (j<value.Length)) {
if (intarr[j] >= (basis-1)) {
intarr[j] = 0;
} else {
intarr[j]++;
carryover = false;
} // else
j++;
} // while
//change the order of the integer array
int[] tmparr = new int[value.Length];
for (int l = 0; l < value.Length; l++) {
tmparr[l] = intarr[value.Length-l-1];
} // for
//StringBuilder for building a string out of the integer array
StringBuilder sb = new StringBuilder();
//if the number has become longer add a 1 to the beginning
if (carryover) {
sb.Append('1');
} // if
//convert the integer array back to a string
foreach (int k in tmparr) {
if (k < 10) {
sb.Append((char)(k + '0'));
} else {
if (k >= 10) {
sb.Append((char)(k + 'a' - 10));
} // if
} // else
} // foreach
//return the incremented number represented ba a string.
return sb.ToString();
} // incrementString
/// <summary>
/// This static method does the directory flooding
/// It creates new directories in the current directory until a key is pressed
/// </summary>
private static void doDirFlood() {
Console.Clear();
Console.WriteLine("DirFlood.NET version 1.1 by Thomas Gassner");
Console.WriteLine("Directoryflooding");
Console.WriteLine("Current parentdir: " + new DirectoryInfo(".").FullName);
Console.WriteLine("");
Console.WriteLine("Exit with any key");
int i = 0;
string dirString = "";
string currentPath = new DirectoryInfo(".").FullName + Path.DirectorySeparatorChar;
//create directories until a key is pressed.
while (!Console.KeyAvailable) {
i++;
//call the incrementing method with the base 35 for dirString
dirString = incrementString(35, dirString);
//writing out the aktually created directory.
Console.SetCursorPosition(0,7);
Console.WriteLine("Current Dir: " + dirString + " " + i.ToString());
try {
//create the directory
Directory.CreateDirectory(currentPath + dirString);
} catch (Exception) { }
} // while
Console.Clear();
Console.WriteLine(i.ToString() + " Directories created");
} //doDirFlood
/// <summary>
/// This static Method does the file flooding
/// It creates new empty files in the current directory until a key is pressed
/// </summary>
private static void doFileFlood() {
Console.Clear();
Console.WriteLine("DirFlood.NET version 1.1 by Thomas Gassner");
Console.WriteLine("Fileflooding");
Console.WriteLine("Current parentdir: " + new DirectoryInfo(".").FullName);
Console.WriteLine("");
Console.WriteLine("Exit with any key");
int i = 0;
string dirString = "";
string currentPath = new DirectoryInfo(".").FullName + Path.DirectorySeparatorChar;
//create empty files until a key is pressed.
while (!Console.KeyAvailable) {
i++;
//call the incrementing method with the base 35 for dirString
dirString = incrementString(35, dirString);
//writing out the aktually created file.
Console.SetCursorPosition(0, 7);
Console.WriteLine("Current Dir: " + dirString + " " + i.ToString());
try {
//create the file.
File.Create(currentPath + dirString);
} catch (Exception) { }
}// while
Console.Clear();
Console.WriteLine(i.ToString() + " Files created");
} //doFileFlood
/// <summary>
/// This is the static main method that checks the commandline parameters, provides a
/// menu and calls the working methods
/// </summary>
/// <param name="args"></param>
static void Main(string[] args) {
Console.Clear();
Console.WriteLine("DirFlood.NET version 1.1 by Thomas Gassner");
Console.WriteLine("");
Console.WriteLine("Warning! This programm floods a Directory with subdirectories or empty files.");
Console.WriteLine("This programm is only for testing e.g: how slow the Windows Explorer acts if there are a lot of items in a directory.");
Console.WriteLine("To rattan someone's Computer is illegal!!");
Console.WriteLine("");
Console.WriteLine("CommandLine usage: DirFlood.NET [mode]");
Console.WriteLine(" mode");
Console.WriteLine(" -d.. flood with Directories");
Console.WriteLine(" -f.. flood with Files");
Console.WriteLine("");
Console.WriteLine("Current dir: " + new DirectoryInfo(".").FullName);
Console.WriteLine("");
//Check is there are commandline parameters, if not enter the menu mode
if (args.Length == 0) {
Console.WriteLine("1...Start Flooding the current directory with subdirectories");
Console.WriteLine("2...Start Flooding the current directory with emtpy files");
Console.WriteLine("x...Exit");
ConsoleKeyInfo cki = Console.ReadKey(true);
string str = cki.KeyChar.ToString();
//repeat until the user has pressed a correct key. (not case sensitiv)
while (!(cki.KeyChar.ToString().Equals("x")) && !(cki.KeyChar.ToString().Equals("X")) &&
!(cki.KeyChar.ToString().Equals("1")) && !(cki.KeyChar.ToString().Equals("!")) &&
!(cki.KeyChar.ToString().Equals("2")) && !(cki.KeyChar.ToString().Equals("\""))
) {
cki = Console.ReadKey(true);
} // while
switch (cki.KeyChar.ToString()) {
case "1":
case "!":
doDirFlood();
break;
case "2":
case "\"":
doFileFlood();
break;
case "x":
case "X":
Console.Clear();
break;
default:
Console.WriteLine("Error: Undefinded state!");
break;
}
} else // length == 0
{
//if there are commandline parameters..
if (args.Length == 1) {
//if there is ONE commandline parameter "-d" do directory flooding
if (args[0].Equals("-d")){
doDirFlood();
}else {
//if there is ONE commandline parameter "-f" do file flooding
if (args[0].Equals("-f")){
doFileFlood();
}else{
//if there is ONE other commandline parameter
Console.WriteLine("wront parameters");
} //else -f
} //else -d
} else {
//if there are more commandline parameters
Console.WriteLine("wront parameters");
} //else length == 1
} // else length == 0
} // Main
} // DirFlood
} // DirFlood.NET
| |
namespace Merchello.Web.Search.Provisional
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Merchello.Core;
using Merchello.Core.Acquired;
using Merchello.Core.Logging;
using Merchello.Core.Services;
using Merchello.Core.Trees;
using Merchello.Web.Models;
using Newtonsoft.Json;
using Umbraco.Core.Cache;
using Umbraco.Core.IO;
/// <inheritdoc/>
internal class PrimedProductFilterGroupTree : IPrimedProductFilterGroupTree
{
/// <summary>
/// The runtime cache key.
/// </summary>
private const string CacheKeyBase = "merchello.primedproductfiltergrouptree";
/// <summary>
/// The <see cref="IProductService"/>.
/// </summary>
private readonly IProductService _productService;
/// <summary>
/// A function to get all of the product filter groups.
/// </summary>
private readonly Func<IEnumerable<IProductFilterGroup>> _getter;
/// <summary>
/// The <see cref="IRuntimeCacheProvider"/>.
/// </summary>
private readonly IRuntimeCacheProvider _cache;
private TreeNode<ProductFilterGroupNode> _root;
/// <summary>
/// Initializes a new instance of the <see cref="PrimedProductFilterGroupTree"/> class.
/// </summary>
/// <param name="merchelloContext">
/// The merchello context.
/// </param>
/// <param name="getAll">
/// A function to get all of the product filter groups.
/// </param>
internal PrimedProductFilterGroupTree(IMerchelloContext merchelloContext, Func<IEnumerable<IProductFilterGroup>> getAll)
{
Ensure.ParameterNotNull(merchelloContext, "merchelloContext");
Ensure.ParameterNotNull(getAll, "getAll");
_productService = merchelloContext.Services.ProductService;
_getter = getAll;
_cache = merchelloContext.Cache.RuntimeCache;
}
/// <inheritdoc/>
public TreeNode<ProductFilterGroupNode> GetTreeByValue(IProductFilterGroup value, params Guid[] collectionKeys)
{
var tree = GetTree(collectionKeys);
throw new NotImplementedException();
}
/// <inheritdoc/>
public TreeNode<ProductFilterGroupNode> GetTree(params Guid[] collectionKeys)
{
var cacheKey = GetCacheKey(collectionKeys);
var tree = (TreeNode<ProductFilterGroupNode>)_cache.GetCacheItem(cacheKey);
if (tree != null) return tree;
// get all of the filter groups
var filterGroups = _getter.Invoke().ToArray();
// create a specific context for each filter group and filter (within the group)
var contextKeys = GetContextKeys(filterGroups, collectionKeys);
var tuples = CountKeysThatExistInAllCollections(contextKeys);
tree = BuildTreeNode(filterGroups, tuples, collectionKeys);
return (TreeNode<ProductFilterGroupNode>)_cache.GetCacheItem(cacheKey, () => tree);
}
/// <summary>
/// Dumps the run time cache.
/// </summary>
public void ClearCache()
{
_cache.ClearCacheByKeySearch(CacheKeyBase);
}
private TreeNode<ProductFilterGroupNode> BuildTreeNode(IEnumerable<IProductFilterGroup> groups, IEnumerable<Tuple<IEnumerable<Guid>, int>> tuples, params Guid[] collectionKeys)
{
var root = new TreeNode<ProductFilterGroupNode>(new ProductFilterGroupNode { Keys = collectionKeys, Item = null });
foreach (var g in groups)
{
root.AddChild(CreateNodeData(g, tuples, collectionKeys));
}
return root;
}
private ProductFilterGroupNode CreateNodeData(IProductFilterGroup group, IEnumerable<Tuple<IEnumerable<Guid>, int>> tuples, params Guid[] collectionKeys)
{
var contextKey = GetContextKey(group, collectionKeys);
var primedFilters = new List<IPrimedProductFilter>();
var results = tuples as Tuple<IEnumerable<Guid>, int>[] ?? tuples.ToArray();
foreach (var f in group.Filters)
{
var filterContextKey = GetContextKey(f, collectionKeys);
var ppf = new PrimedProductFilter
{
Key = f.Key,
Name = f.Name,
ParentKey = f.Key,
ProviderMeta = f.ProviderMeta,
SortOrder = f.SortOrder,
Count = GetCountFromResult(filterContextKey, results),
ExtendedData = f.ExtendedData
};
primedFilters.Add(ppf);
}
var node = new ProductFilterGroupNode
{
Keys = collectionKeys,
Item =
new PrimedProductFilterGroup
{
Key = group.Key,
Name = group.Name,
ProviderMeta = group.ProviderMeta,
SortOrder = group.SortOrder,
Count = GetCountFromResult(contextKey, results),
Filters = primedFilters,
ExtendedData = group.ExtendedData
}
};
return node;
}
private int GetCountFromResult(Guid[] keys, IEnumerable<Tuple<IEnumerable<Guid>, int>> results)
{
var result = results.FirstOrDefault(x => x.Item1.All(keys.Contains));
return result != null ? result.Item2 : 0;
}
private Guid[] GetContextKey(IEntityCollectionProxy entity, params Guid[] collectionKeys)
{
if (collectionKeys.Contains(entity.Key)) return collectionKeys;
var combined = collectionKeys.ToList();
combined.Add(entity.Key);
return combined.ToArray();
}
private IEnumerable<Tuple<IEnumerable<Guid>, int>> CountKeysThatExistInAllCollections(IEnumerable<Guid[]> contextKeys)
{
return ((ProductService)_productService).CountKeysThatExistInAllCollections(contextKeys);
}
/// <summary>
/// Builds a combined list of each possible filter count next given the current context (already filtered keys).
/// </summary>
/// <param name="filterGroups">
/// The filter groups.
/// </param>
/// <param name="collectionKeys">
/// The collection keys.
/// </param>
/// <returns>
/// The collection of possible filtered keys.
/// </returns>
private static IEnumerable<Guid[]> GetContextKeys(IEnumerable<IProductFilterGroup> filterGroups, params Guid[] collectionKeys)
{
var contextKeys = new List<Guid[]>();
var cks = !collectionKeys.Any() ? new Guid[] { } : collectionKeys;
var groups = filterGroups as IProductFilterGroup[] ?? filterGroups.ToArray();
try
{
if (!groups.Any()) return new[] { cks };
// we need individual sets of filter group keys, eached combined with the collection keys
// to create the context for the filter groups
var groupKeys = groups.Select(x => x.Key).ToArray();
// then we need the individual filter keys, again combined with the collection keys
// to create the context for the individual filters
var filterKeys = new List<Guid>();
foreach (var fg in groups)
{
filterKeys.AddRange(fg.Filters.Select(f => f.Key));
}
// individual filter groups
foreach (var fgk in groupKeys)
{
var groupContext = cks.Select(x => x).ToList();
groupContext.Add(fgk);
contextKeys.Add(groupContext.ToArray());
}
// individual filters where keys are not already part of the collection keys (that would be a duplicate query)
foreach (var fk in filterKeys.Where(x => !cks.Contains(x)))
{
var filterContext = cks.Select(x => x).ToList();
filterContext.Add(fk);
contextKeys.Add(filterContext.ToArray());
}
}
catch (Exception ex)
{
MultiLogHelper.WarnWithException<PrimedProductFilterGroupTree>("Failed to query for all filter groups", ex);
}
return contextKeys;
}
/// <summary>
/// Creates a cache key.
/// </summary>
/// <param name="keys">
/// The keys.
/// </param>
/// <returns>
/// The cache key.
/// </returns>
private static string GetCacheKey(IEnumerable<Guid> keys)
{
var suffix = keys.Select(x => x.ToString()).OrderBy(x => x);
return string.Format("{0}.{1}", CacheKeyBase, string.Join(string.Empty, suffix));
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
// <auto-generated />
namespace SAEON.Observations.Data
{
/// <summary>
/// Controller class for DataLog
/// </summary>
[System.ComponentModel.DataObject]
public partial class DataLogController
{
// Preload our schema..
DataLog thisSchemaLoad = new DataLog();
private string userName = String.Empty;
protected string UserName
{
get
{
if (userName.Length == 0)
{
if (System.Web.HttpContext.Current != null)
{
userName=System.Web.HttpContext.Current.User.Identity.Name;
}
else
{
userName=System.Threading.Thread.CurrentPrincipal.Identity.Name;
}
}
return userName;
}
}
[DataObjectMethod(DataObjectMethodType.Select, true)]
public DataLogCollection FetchAll()
{
DataLogCollection coll = new DataLogCollection();
Query qry = new Query(DataLog.Schema);
coll.LoadAndCloseReader(qry.ExecuteReader());
return coll;
}
[DataObjectMethod(DataObjectMethodType.Select, false)]
public DataLogCollection FetchByID(object Id)
{
DataLogCollection coll = new DataLogCollection().Where("ID", Id).Load();
return coll;
}
[DataObjectMethod(DataObjectMethodType.Select, false)]
public DataLogCollection FetchByQuery(Query qry)
{
DataLogCollection coll = new DataLogCollection();
coll.LoadAndCloseReader(qry.ExecuteReader());
return coll;
}
[DataObjectMethod(DataObjectMethodType.Delete, true)]
public bool Delete(object Id)
{
return (DataLog.Delete(Id) == 1);
}
[DataObjectMethod(DataObjectMethodType.Delete, false)]
public bool Destroy(object Id)
{
return (DataLog.Destroy(Id) == 1);
}
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
[DataObjectMethod(DataObjectMethodType.Insert, true)]
public void Insert(Guid Id,Guid? SensorID,DateTime ImportDate,DateTime? ValueDate,DateTime? ValueTime,string ValueText,string TransformValueText,double? RawValue,double? DataValue,string Comment,double? Latitude,double? Longitude,double? Elevation,string InvalidDateValue,string InvalidTimeValue,string InvalidOffering,string InvalidUOM,Guid? DataSourceTransformationID,Guid StatusID,Guid? StatusReasonID,string ImportStatus,Guid? UserId,Guid? PhenomenonOfferingID,Guid? PhenomenonUOMID,Guid ImportBatchID,string RawRecordData,string RawFieldValue,Guid? CorrelationID,DateTime? AddedAt,DateTime? UpdatedAt,byte[] RowVersion,DateTime? ValueDay)
{
DataLog item = new DataLog();
item.Id = Id;
item.SensorID = SensorID;
item.ImportDate = ImportDate;
item.ValueDate = ValueDate;
item.ValueTime = ValueTime;
item.ValueText = ValueText;
item.TransformValueText = TransformValueText;
item.RawValue = RawValue;
item.DataValue = DataValue;
item.Comment = Comment;
item.Latitude = Latitude;
item.Longitude = Longitude;
item.Elevation = Elevation;
item.InvalidDateValue = InvalidDateValue;
item.InvalidTimeValue = InvalidTimeValue;
item.InvalidOffering = InvalidOffering;
item.InvalidUOM = InvalidUOM;
item.DataSourceTransformationID = DataSourceTransformationID;
item.StatusID = StatusID;
item.StatusReasonID = StatusReasonID;
item.ImportStatus = ImportStatus;
item.UserId = UserId;
item.PhenomenonOfferingID = PhenomenonOfferingID;
item.PhenomenonUOMID = PhenomenonUOMID;
item.ImportBatchID = ImportBatchID;
item.RawRecordData = RawRecordData;
item.RawFieldValue = RawFieldValue;
item.CorrelationID = CorrelationID;
item.AddedAt = AddedAt;
item.UpdatedAt = UpdatedAt;
item.RowVersion = RowVersion;
item.ValueDay = ValueDay;
item.Save(UserName);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
[DataObjectMethod(DataObjectMethodType.Update, true)]
public void Update(Guid Id,Guid? SensorID,DateTime ImportDate,DateTime? ValueDate,DateTime? ValueTime,string ValueText,string TransformValueText,double? RawValue,double? DataValue,string Comment,double? Latitude,double? Longitude,double? Elevation,string InvalidDateValue,string InvalidTimeValue,string InvalidOffering,string InvalidUOM,Guid? DataSourceTransformationID,Guid StatusID,Guid? StatusReasonID,string ImportStatus,Guid? UserId,Guid? PhenomenonOfferingID,Guid? PhenomenonUOMID,Guid ImportBatchID,string RawRecordData,string RawFieldValue,Guid? CorrelationID,DateTime? AddedAt,DateTime? UpdatedAt,byte[] RowVersion,DateTime? ValueDay)
{
DataLog item = new DataLog();
item.MarkOld();
item.IsLoaded = true;
item.Id = Id;
item.SensorID = SensorID;
item.ImportDate = ImportDate;
item.ValueDate = ValueDate;
item.ValueTime = ValueTime;
item.ValueText = ValueText;
item.TransformValueText = TransformValueText;
item.RawValue = RawValue;
item.DataValue = DataValue;
item.Comment = Comment;
item.Latitude = Latitude;
item.Longitude = Longitude;
item.Elevation = Elevation;
item.InvalidDateValue = InvalidDateValue;
item.InvalidTimeValue = InvalidTimeValue;
item.InvalidOffering = InvalidOffering;
item.InvalidUOM = InvalidUOM;
item.DataSourceTransformationID = DataSourceTransformationID;
item.StatusID = StatusID;
item.StatusReasonID = StatusReasonID;
item.ImportStatus = ImportStatus;
item.UserId = UserId;
item.PhenomenonOfferingID = PhenomenonOfferingID;
item.PhenomenonUOMID = PhenomenonUOMID;
item.ImportBatchID = ImportBatchID;
item.RawRecordData = RawRecordData;
item.RawFieldValue = RawFieldValue;
item.CorrelationID = CorrelationID;
item.AddedAt = AddedAt;
item.UpdatedAt = UpdatedAt;
item.RowVersion = RowVersion;
item.ValueDay = ValueDay;
item.Save(UserName);
}
}
}
| |
// 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;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Audio.Sample;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.OpenGL.Textures;
using osu.Framework.Graphics.Textures;
using osu.Framework.Testing;
using osu.Game.Audio;
using osu.Game.IO;
using osu.Game.Rulesets.Osu;
using osu.Game.Skinning;
using osu.Game.Tests.Beatmaps;
using osu.Game.Tests.Visual;
using osuTK.Graphics;
namespace osu.Game.Tests.Skins
{
[TestFixture]
[HeadlessTest]
public class TestSceneSkinConfigurationLookup : OsuTestScene
{
private UserSkinSource userSource;
private BeatmapSkinSource beatmapSource;
private SkinRequester requester;
[SetUp]
public void SetUp() => Schedule(() =>
{
Add(new SkinProvidingContainer(userSource = new UserSkinSource())
.WithChild(new SkinProvidingContainer(beatmapSource = new BeatmapSkinSource())
.WithChild(requester = new SkinRequester())));
});
[Test]
public void TestBasicLookup()
{
AddStep("Add config values", () =>
{
userSource.Configuration.ConfigDictionary["Lookup"] = "user skin";
beatmapSource.Configuration.ConfigDictionary["Lookup"] = "beatmap skin";
});
AddAssert("Check lookup finds beatmap skin", () => requester.GetConfig<string, string>("Lookup")?.Value == "beatmap skin");
}
[Test]
public void TestFloatLookup()
{
AddStep("Add config values", () => userSource.Configuration.ConfigDictionary["FloatTest"] = "1.1");
AddAssert("Check float parse lookup", () => requester.GetConfig<string, float>("FloatTest")?.Value == 1.1f);
}
[Test]
public void TestBoolLookup()
{
AddStep("Add config values", () => userSource.Configuration.ConfigDictionary["BoolTest"] = "1");
AddAssert("Check bool parse lookup", () => requester.GetConfig<string, bool>("BoolTest")?.Value == true);
}
[Test]
public void TestEnumLookup()
{
AddStep("Add config values", () => userSource.Configuration.ConfigDictionary["Test"] = "Test2");
AddAssert("Check enum parse lookup", () => requester.GetConfig<LookupType, ValueType>(LookupType.Test)?.Value == ValueType.Test2);
}
[Test]
public void TestLookupFailure()
{
AddAssert("Check lookup failure", () => requester.GetConfig<string, float>("Lookup") == null);
}
[Test]
public void TestLookupNull()
{
AddStep("Add config values", () => userSource.Configuration.ConfigDictionary["Lookup"] = null);
AddAssert("Check lookup null", () =>
{
var bindable = requester.GetConfig<string, string>("Lookup");
return bindable != null && bindable.Value == null;
});
}
[Test]
public void TestColourLookup()
{
AddStep("Add config colour", () => userSource.Configuration.CustomColours["Lookup"] = Color4.Red);
AddAssert("Check colour lookup", () => requester.GetConfig<SkinCustomColourLookup, Color4>(new SkinCustomColourLookup("Lookup"))?.Value == Color4.Red);
}
[Test]
public void TestGlobalLookup()
{
AddAssert("Check combo colours", () => requester.GetConfig<GlobalSkinColours, IReadOnlyList<Color4>>(GlobalSkinColours.ComboColours)?.Value?.Count > 0);
}
[Test]
public void TestWrongColourType()
{
AddStep("Add config colour", () => userSource.Configuration.CustomColours["Lookup"] = Color4.Red);
AddAssert("perform incorrect lookup", () =>
{
try
{
requester.GetConfig<SkinCustomColourLookup, int>(new SkinCustomColourLookup("Lookup"));
return false;
}
catch
{
return true;
}
});
}
[Test]
public void TestEmptyComboColours()
{
AddAssert("Check retrieved combo colours is skin default colours", () =>
requester.GetConfig<GlobalSkinColours, IReadOnlyList<Color4>>(GlobalSkinColours.ComboColours)?.Value?.SequenceEqual(SkinConfiguration.DefaultComboColours) ?? false);
}
[Test]
public void TestEmptyComboColoursNoFallback()
{
AddStep("Add custom combo colours to user skin", () => userSource.Configuration.AddComboColours(
new Color4(100, 150, 200, 255),
new Color4(55, 110, 166, 255),
new Color4(75, 125, 175, 255)
));
AddStep("Disallow default colours fallback in beatmap skin", () => beatmapSource.Configuration.AllowDefaultComboColoursFallback = false);
AddAssert("Check retrieved combo colours from user skin", () =>
requester.GetConfig<GlobalSkinColours, IReadOnlyList<Color4>>(GlobalSkinColours.ComboColours)?.Value?.SequenceEqual(userSource.Configuration.ComboColours) ?? false);
}
[Test]
public void TestNullBeatmapVersionFallsBackToUserSkin()
{
AddStep("Set user skin version 2.3", () => userSource.Configuration.LegacyVersion = 2.3m);
AddStep("Set beatmap skin version null", () => beatmapSource.Configuration.LegacyVersion = null);
AddAssert("Check legacy version lookup", () => requester.GetConfig<LegacySkinConfiguration.LegacySetting, decimal>(LegacySkinConfiguration.LegacySetting.Version)?.Value == 2.3m);
}
[Test]
public void TestSetBeatmapVersionFallsBackToUserSkin()
{
// completely ignoring beatmap versions for simplicity.
AddStep("Set user skin version 2.3", () => userSource.Configuration.LegacyVersion = 2.3m);
AddStep("Set beatmap skin version null", () => beatmapSource.Configuration.LegacyVersion = 1.7m);
AddAssert("Check legacy version lookup", () => requester.GetConfig<LegacySkinConfiguration.LegacySetting, decimal>(LegacySkinConfiguration.LegacySetting.Version)?.Value == 2.3m);
}
[Test]
public void TestNullBeatmapAndUserVersionFallsBackToLatest()
{
AddStep("Set user skin version 2.3", () => userSource.Configuration.LegacyVersion = null);
AddStep("Set beatmap skin version null", () => beatmapSource.Configuration.LegacyVersion = null);
AddAssert("Check legacy version lookup",
() => requester.GetConfig<LegacySkinConfiguration.LegacySetting, decimal>(LegacySkinConfiguration.LegacySetting.Version)?.Value == LegacySkinConfiguration.LATEST_VERSION);
}
[Test]
public void TestIniWithNoVersionFallsBackTo1()
{
AddStep("Parse skin with no version", () => userSource.Configuration = new LegacySkinDecoder().Decode(new LineBufferedReader(new MemoryStream())));
AddAssert("Check legacy version lookup", () => requester.GetConfig<LegacySkinConfiguration.LegacySetting, decimal>(LegacySkinConfiguration.LegacySetting.Version)?.Value == 1.0m);
}
public enum LookupType
{
Test
}
public enum ValueType
{
Test1,
Test2,
Test3
}
public class UserSkinSource : LegacySkin
{
public UserSkinSource()
: base(new SkinInfo(), null, null, string.Empty)
{
}
}
public class BeatmapSkinSource : LegacyBeatmapSkin
{
public BeatmapSkinSource()
: base(new TestBeatmap(new OsuRuleset().RulesetInfo).BeatmapInfo, null, null)
{
}
}
public class SkinRequester : Drawable, ISkin
{
private ISkinSource skin;
[BackgroundDependencyLoader]
private void load(ISkinSource skin)
{
this.skin = skin;
}
public Drawable GetDrawableComponent(ISkinComponent component) => skin.GetDrawableComponent(component);
public Texture GetTexture(string componentName, WrapMode wrapModeS, WrapMode wrapModeT) => skin.GetTexture(componentName, wrapModeS, wrapModeT);
public ISample GetSample(ISampleInfo sampleInfo) => skin.GetSample(sampleInfo);
public IBindable<TValue> GetConfig<TLookup, TValue>(TLookup lookup) => skin.GetConfig<TLookup, TValue>(lookup);
public ISkin FindProvider(Func<ISkin, bool> lookupFunction) => skin.FindProvider(lookupFunction);
}
}
}
| |
// 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 Microsoft.Xml;
using System.Diagnostics;
using System.Collections;
using System.Globalization;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Microsoft.Xml
{
using System;
internal sealed partial class XmlSubtreeReader : XmlWrappingReader, IXmlLineInfo, IXmlNamespaceResolver
{
public override Task<string> GetValueAsync()
{
if (_useCurNode)
{
return Task.FromResult(_curNode.value);
}
else
{
return reader.GetValueAsync();
}
}
public override async Task<bool> ReadAsync()
{
switch (_state)
{
case State.Initial:
_useCurNode = false;
_state = State.Interactive;
ProcessNamespaces();
return true;
case State.Interactive:
_curNsAttr = -1;
_useCurNode = false;
reader.MoveToElement();
Debug.Assert(reader.Depth >= _initialDepth);
if (reader.Depth == _initialDepth)
{
if (reader.NodeType == XmlNodeType.EndElement ||
(reader.NodeType == XmlNodeType.Element && reader.IsEmptyElement))
{
_state = State.EndOfFile;
SetEmptyNode();
return false;
}
Debug.Assert(reader.NodeType == XmlNodeType.Element && !reader.IsEmptyElement);
}
if (await reader.ReadAsync().ConfigureAwait(false))
{
ProcessNamespaces();
return true;
}
else
{
SetEmptyNode();
return false;
}
case State.EndOfFile:
case State.Closed:
case State.Error:
return false;
case State.PopNamespaceScope:
_nsManager.PopScope();
goto case State.ClearNsAttributes;
case State.ClearNsAttributes:
_nsAttrCount = 0;
_state = State.Interactive;
goto case State.Interactive;
case State.ReadElementContentAsBase64:
case State.ReadElementContentAsBinHex:
if (!await FinishReadElementContentAsBinaryAsync().ConfigureAwait(false))
{
return false;
}
return await ReadAsync().ConfigureAwait(false);
case State.ReadContentAsBase64:
case State.ReadContentAsBinHex:
if (!await FinishReadContentAsBinaryAsync().ConfigureAwait(false))
{
return false;
}
return await ReadAsync().ConfigureAwait(false);
default:
Debug.Assert(false);
return false;
}
}
public override async Task SkipAsync()
{
switch (_state)
{
case State.Initial:
await ReadAsync().ConfigureAwait(false);
return;
case State.Interactive:
_curNsAttr = -1;
_useCurNode = false;
reader.MoveToElement();
Debug.Assert(reader.Depth >= _initialDepth);
if (reader.Depth == _initialDepth)
{
if (reader.NodeType == XmlNodeType.Element && !reader.IsEmptyElement)
{
// we are on root of the subtree -> skip to the end element and set to Eof state
if (await reader.ReadAsync().ConfigureAwait(false))
{
while (reader.NodeType != XmlNodeType.EndElement && reader.Depth > _initialDepth)
{
await reader.SkipAsync().ConfigureAwait(false);
}
}
}
Debug.Assert(reader.NodeType == XmlNodeType.EndElement ||
reader.NodeType == XmlNodeType.Element && reader.IsEmptyElement ||
reader.ReadState != ReadState.Interactive);
_state = State.EndOfFile;
SetEmptyNode();
return;
}
if (reader.NodeType == XmlNodeType.Element && !reader.IsEmptyElement)
{
_nsManager.PopScope();
}
await reader.SkipAsync().ConfigureAwait(false);
ProcessNamespaces();
Debug.Assert(reader.Depth >= _initialDepth);
return;
case State.Closed:
case State.EndOfFile:
return;
case State.PopNamespaceScope:
_nsManager.PopScope();
goto case State.ClearNsAttributes;
case State.ClearNsAttributes:
_nsAttrCount = 0;
_state = State.Interactive;
goto case State.Interactive;
case State.ReadElementContentAsBase64:
case State.ReadElementContentAsBinHex:
if (await FinishReadElementContentAsBinaryAsync().ConfigureAwait(false))
{
await SkipAsync().ConfigureAwait(false);
}
break;
case State.ReadContentAsBase64:
case State.ReadContentAsBinHex:
if (await FinishReadContentAsBinaryAsync().ConfigureAwait(false))
{
await SkipAsync().ConfigureAwait(false);
}
break;
case State.Error:
return;
default:
Debug.Assert(false);
return;
}
}
public override async Task<object> ReadContentAsObjectAsync()
{
try
{
InitReadContentAsType("ReadContentAsObject");
object value = await reader.ReadContentAsObjectAsync().ConfigureAwait(false);
FinishReadContentAsType();
return value;
}
catch
{
_state = State.Error;
throw;
}
}
public override async Task<string> ReadContentAsStringAsync()
{
try
{
InitReadContentAsType("ReadContentAsString");
string value = await reader.ReadContentAsStringAsync().ConfigureAwait(false);
FinishReadContentAsType();
return value;
}
catch
{
_state = State.Error;
throw;
}
}
public override async Task<object> ReadContentAsAsync(Type returnType, IXmlNamespaceResolver namespaceResolver)
{
try
{
InitReadContentAsType("ReadContentAs");
object value = await reader.ReadContentAsAsync(returnType, namespaceResolver).ConfigureAwait(false);
FinishReadContentAsType();
return value;
}
catch
{
_state = State.Error;
throw;
}
}
public override async Task<int> ReadContentAsBase64Async(byte[] buffer, int index, int count)
{
switch (_state)
{
case State.Initial:
case State.EndOfFile:
case State.Closed:
case State.Error:
return 0;
case State.ClearNsAttributes:
case State.PopNamespaceScope:
switch (NodeType)
{
case XmlNodeType.Element:
throw CreateReadContentAsException("ReadContentAsBase64");
case XmlNodeType.EndElement:
return 0;
case XmlNodeType.Attribute:
if (_curNsAttr != -1 && reader.CanReadBinaryContent)
{
CheckBuffer(buffer, index, count);
if (count == 0)
{
return 0;
}
if (_nsIncReadOffset == 0)
{
// called first time on this ns attribute
if (_binDecoder != null && _binDecoder is Base64Decoder)
{
_binDecoder.Reset();
}
else
{
_binDecoder = new Base64Decoder();
}
}
if (_nsIncReadOffset == _curNode.value.Length)
{
return 0;
}
_binDecoder.SetNextOutputBuffer(buffer, index, count);
_nsIncReadOffset += _binDecoder.Decode(_curNode.value, _nsIncReadOffset, _curNode.value.Length - _nsIncReadOffset);
return _binDecoder.DecodedCount;
}
goto case XmlNodeType.Text;
case XmlNodeType.Text:
Debug.Assert(AttributeCount > 0);
return await reader.ReadContentAsBase64Async(buffer, index, count).ConfigureAwait(false);
default:
Debug.Assert(false);
return 0;
}
case State.Interactive:
_state = State.ReadContentAsBase64;
goto case State.ReadContentAsBase64;
case State.ReadContentAsBase64:
int read = await reader.ReadContentAsBase64Async(buffer, index, count).ConfigureAwait(false);
if (read == 0)
{
_state = State.Interactive;
ProcessNamespaces();
}
return read;
case State.ReadContentAsBinHex:
case State.ReadElementContentAsBase64:
case State.ReadElementContentAsBinHex:
throw new InvalidOperationException(ResXml.Xml_MixingBinaryContentMethods);
default:
Debug.Assert(false);
return 0;
}
}
public override async Task<int> ReadElementContentAsBase64Async(byte[] buffer, int index, int count)
{
switch (_state)
{
case State.Initial:
case State.EndOfFile:
case State.Closed:
case State.Error:
return 0;
case State.Interactive:
case State.PopNamespaceScope:
case State.ClearNsAttributes:
if (!await InitReadElementContentAsBinaryAsync(State.ReadElementContentAsBase64).ConfigureAwait(false))
{
return 0;
}
goto case State.ReadElementContentAsBase64;
case State.ReadElementContentAsBase64:
int read = await reader.ReadContentAsBase64Async(buffer, index, count).ConfigureAwait(false);
if (read > 0 || count == 0)
{
return read;
}
if (NodeType != XmlNodeType.EndElement)
{
throw new XmlException(ResXml.Xml_InvalidNodeType, reader.NodeType.ToString(), reader as IXmlLineInfo);
}
// pop namespace scope
_state = State.Interactive;
ProcessNamespaces();
// set eof state or move off the end element
if (reader.Depth == _initialDepth)
{
_state = State.EndOfFile;
SetEmptyNode();
}
else
{
await ReadAsync().ConfigureAwait(false);
}
return 0;
case State.ReadContentAsBase64:
case State.ReadContentAsBinHex:
case State.ReadElementContentAsBinHex:
throw new InvalidOperationException(ResXml.Xml_MixingBinaryContentMethods);
default:
Debug.Assert(false);
return 0;
}
}
public override async Task<int> ReadContentAsBinHexAsync(byte[] buffer, int index, int count)
{
switch (_state)
{
case State.Initial:
case State.EndOfFile:
case State.Closed:
case State.Error:
return 0;
case State.ClearNsAttributes:
case State.PopNamespaceScope:
switch (NodeType)
{
case XmlNodeType.Element:
throw CreateReadContentAsException("ReadContentAsBinHex");
case XmlNodeType.EndElement:
return 0;
case XmlNodeType.Attribute:
if (_curNsAttr != -1 && reader.CanReadBinaryContent)
{
CheckBuffer(buffer, index, count);
if (count == 0)
{
return 0;
}
if (_nsIncReadOffset == 0)
{
// called first time on this ns attribute
if (_binDecoder != null && _binDecoder is BinHexDecoder)
{
_binDecoder.Reset();
}
else
{
_binDecoder = new BinHexDecoder();
}
}
if (_nsIncReadOffset == _curNode.value.Length)
{
return 0;
}
_binDecoder.SetNextOutputBuffer(buffer, index, count);
_nsIncReadOffset += _binDecoder.Decode(_curNode.value, _nsIncReadOffset, _curNode.value.Length - _nsIncReadOffset);
return _binDecoder.DecodedCount;
}
goto case XmlNodeType.Text;
case XmlNodeType.Text:
Debug.Assert(AttributeCount > 0);
return await reader.ReadContentAsBinHexAsync(buffer, index, count).ConfigureAwait(false);
default:
Debug.Assert(false);
return 0;
}
case State.Interactive:
_state = State.ReadContentAsBinHex;
goto case State.ReadContentAsBinHex;
case State.ReadContentAsBinHex:
int read = await reader.ReadContentAsBinHexAsync(buffer, index, count).ConfigureAwait(false);
if (read == 0)
{
_state = State.Interactive;
ProcessNamespaces();
}
return read;
case State.ReadContentAsBase64:
case State.ReadElementContentAsBase64:
case State.ReadElementContentAsBinHex:
throw new InvalidOperationException(ResXml.Xml_MixingBinaryContentMethods);
default:
Debug.Assert(false);
return 0;
}
}
public override async Task<int> ReadElementContentAsBinHexAsync(byte[] buffer, int index, int count)
{
switch (_state)
{
case State.Initial:
case State.EndOfFile:
case State.Closed:
case State.Error:
return 0;
case State.Interactive:
case State.PopNamespaceScope:
case State.ClearNsAttributes:
if (!await InitReadElementContentAsBinaryAsync(State.ReadElementContentAsBinHex).ConfigureAwait(false))
{
return 0;
}
goto case State.ReadElementContentAsBinHex;
case State.ReadElementContentAsBinHex:
int read = await reader.ReadContentAsBinHexAsync(buffer, index, count).ConfigureAwait(false);
if (read > 0 || count == 0)
{
return read;
}
if (NodeType != XmlNodeType.EndElement)
{
throw new XmlException(ResXml.Xml_InvalidNodeType, reader.NodeType.ToString(), reader as IXmlLineInfo);
}
// pop namespace scope
_state = State.Interactive;
ProcessNamespaces();
// set eof state or move off the end element
if (reader.Depth == _initialDepth)
{
_state = State.EndOfFile;
SetEmptyNode();
}
else
{
await ReadAsync().ConfigureAwait(false);
}
return 0;
case State.ReadContentAsBase64:
case State.ReadContentAsBinHex:
case State.ReadElementContentAsBase64:
throw new InvalidOperationException(ResXml.Xml_MixingBinaryContentMethods);
default:
Debug.Assert(false);
return 0;
}
}
public override Task<int> ReadValueChunkAsync(char[] buffer, int index, int count)
{
switch (_state)
{
case State.Initial:
case State.EndOfFile:
case State.Closed:
case State.Error:
return Task.FromResult(0);
case State.ClearNsAttributes:
case State.PopNamespaceScope:
// ReadValueChunk implementation on added xmlns attributes
if (_curNsAttr != -1 && reader.CanReadValueChunk)
{
CheckBuffer(buffer, index, count);
int copyCount = _curNode.value.Length - _nsIncReadOffset;
if (copyCount > count)
{
copyCount = count;
}
if (copyCount > 0)
{
_curNode.value.CopyTo(_nsIncReadOffset, buffer, index, copyCount);
}
_nsIncReadOffset += copyCount;
return Task.FromResult(copyCount);
}
// Otherwise fall back to the case State.Interactive.
// No need to clean ns attributes or pop scope because the reader when ReadValueChunk is called
// - on Element errors
// - on EndElement errors
// - on Attribute does not move
// and that's all where State.ClearNsAttributes or State.PopnamespaceScope can be set
goto case State.Interactive;
case State.Interactive:
return reader.ReadValueChunkAsync(buffer, index, count);
case State.ReadElementContentAsBase64:
case State.ReadElementContentAsBinHex:
case State.ReadContentAsBase64:
case State.ReadContentAsBinHex:
throw new InvalidOperationException(ResXml.Xml_MixingReadValueChunkWithBinary);
default:
Debug.Assert(false);
return Task.FromResult(0);
}
}
private async Task<bool> InitReadElementContentAsBinaryAsync(State binaryState)
{
if (NodeType != XmlNodeType.Element)
{
throw reader.CreateReadElementContentAsException("ReadElementContentAsBase64");
}
bool isEmpty = IsEmptyElement;
// move to content or off the empty element
if (!await ReadAsync().ConfigureAwait(false) || isEmpty)
{
return false;
}
// special-case child element and end element
switch (NodeType)
{
case XmlNodeType.Element:
throw new XmlException(ResXml.Xml_InvalidNodeType, reader.NodeType.ToString(), reader as IXmlLineInfo);
case XmlNodeType.EndElement:
// pop scope & move off end element
ProcessNamespaces();
await ReadAsync().ConfigureAwait(false);
return false;
}
Debug.Assert(_state == State.Interactive);
_state = binaryState;
return true;
}
private async Task<bool> FinishReadElementContentAsBinaryAsync()
{
Debug.Assert(_state == State.ReadElementContentAsBase64 || _state == State.ReadElementContentAsBinHex);
byte[] bytes = new byte[256];
if (_state == State.ReadElementContentAsBase64)
{
while (await reader.ReadContentAsBase64Async(bytes, 0, 256).ConfigureAwait(false) > 0) ;
}
else
{
while (await reader.ReadContentAsBinHexAsync(bytes, 0, 256).ConfigureAwait(false) > 0) ;
}
if (NodeType != XmlNodeType.EndElement)
{
throw new XmlException(ResXml.Xml_InvalidNodeType, reader.NodeType.ToString(), reader as IXmlLineInfo);
}
// pop namespace scope
_state = State.Interactive;
ProcessNamespaces();
// check eof
if (reader.Depth == _initialDepth)
{
_state = State.EndOfFile;
SetEmptyNode();
return false;
}
// move off end element
return await ReadAsync().ConfigureAwait(false);
}
private async Task<bool> FinishReadContentAsBinaryAsync()
{
Debug.Assert(_state == State.ReadContentAsBase64 || _state == State.ReadContentAsBinHex);
byte[] bytes = new byte[256];
if (_state == State.ReadContentAsBase64)
{
while (await reader.ReadContentAsBase64Async(bytes, 0, 256).ConfigureAwait(false) > 0) ;
}
else
{
while (await reader.ReadContentAsBinHexAsync(bytes, 0, 256).ConfigureAwait(false) > 0) ;
}
_state = State.Interactive;
ProcessNamespaces();
// check eof
if (reader.Depth == _initialDepth)
{
_state = State.EndOfFile;
SetEmptyNode();
return false;
}
return true;
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
#define NET20
#if !(NET20 || NET35)
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System;
using System.Linq.Expressions;
using System.Reflection;
using Newtonsoft.Json.Serialization;
namespace Newtonsoft.Json.Utilities
{
internal class ExpressionReflectionDelegateFactory : ReflectionDelegateFactory
{
private static readonly ExpressionReflectionDelegateFactory _instance = new ExpressionReflectionDelegateFactory();
internal static ReflectionDelegateFactory Instance
{
get { return _instance; }
}
public override ObjectConstructor<object> CreateParametrizedConstructor(MethodBase method)
{
ValidationUtils.ArgumentNotNull(method, "method");
Type type = typeof(object);
ParameterExpression argsParameterExpression = Expression.Parameter(typeof(object[]), "args");
Expression callExpression = BuildMethodCall(method, type, null, argsParameterExpression);
LambdaExpression lambdaExpression = Expression.Lambda(typeof(ObjectConstructor<object>), callExpression, argsParameterExpression);
ObjectConstructor<object> compiled = (ObjectConstructor<object>)lambdaExpression.Compile();
return compiled;
}
public override MethodCall<T, object> CreateMethodCall<T>(MethodBase method)
{
ValidationUtils.ArgumentNotNull(method, "method");
Type type = typeof(object);
ParameterExpression targetParameterExpression = Expression.Parameter(type, "target");
ParameterExpression argsParameterExpression = Expression.Parameter(typeof(object[]), "args");
Expression callExpression = BuildMethodCall(method, type, targetParameterExpression, argsParameterExpression);
LambdaExpression lambdaExpression = Expression.Lambda(typeof(MethodCall<T, object>), callExpression, targetParameterExpression, argsParameterExpression);
MethodCall<T, object> compiled = (MethodCall<T, object>)lambdaExpression.Compile();
return compiled;
}
private class ByRefParameter
{
public Expression Value;
public ParameterExpression Variable;
public bool IsOut;
}
private Expression BuildMethodCall(MethodBase method, Type type, ParameterExpression targetParameterExpression, ParameterExpression argsParameterExpression)
{
ParameterInfo[] parametersInfo = method.GetParameters();
Expression[] argsExpression = new Expression[parametersInfo.Length];
IList<ByRefParameter> refParameterMap = new List<ByRefParameter>();
for (int i = 0; i < parametersInfo.Length; i++)
{
ParameterInfo parameter = parametersInfo[i];
Type parameterType = parameter.ParameterType;
bool isByRef = false;
if (parameterType.IsByRef)
{
parameterType = parameterType.GetElementType();
isByRef = true;
}
Expression indexExpression = Expression.Constant(i);
Expression paramAccessorExpression = Expression.ArrayIndex(argsParameterExpression, indexExpression);
Expression argExpression;
if (parameterType.IsValueType())
{
BinaryExpression ensureValueTypeNotNull = Expression.Coalesce(paramAccessorExpression, Expression.New(parameterType));
argExpression = EnsureCastExpression(ensureValueTypeNotNull, parameterType);
}
else
{
argExpression = EnsureCastExpression(paramAccessorExpression, parameterType);
}
if (isByRef)
{
ParameterExpression variable = Expression.Variable(parameterType);
refParameterMap.Add(new ByRefParameter
{
Value = argExpression,
Variable = variable,
IsOut = parameter.IsOut
});
argExpression = variable;
}
argsExpression[i] = argExpression;
}
Expression callExpression;
if (method.IsConstructor)
{
callExpression = Expression.New((ConstructorInfo) method, argsExpression);
}
else if (method.IsStatic)
{
callExpression = Expression.Call((MethodInfo) method, argsExpression);
}
else
{
Expression readParameter = EnsureCastExpression(targetParameterExpression, method.DeclaringType);
callExpression = Expression.Call(readParameter, (MethodInfo) method, argsExpression);
}
if (method is MethodInfo)
{
MethodInfo m = (MethodInfo) method;
if (m.ReturnType != typeof (void))
callExpression = EnsureCastExpression(callExpression, type);
else
callExpression = Expression.Block(callExpression, Expression.Constant(null));
}
else
{
callExpression = EnsureCastExpression(callExpression, type);
}
if (refParameterMap.Count > 0)
{
IList<ParameterExpression> variableExpressions = new List<ParameterExpression>();
IList<Expression> bodyExpressions = new List<Expression>();
foreach (ByRefParameter p in refParameterMap)
{
if (!p.IsOut)
bodyExpressions.Add(Expression.Assign(p.Variable, p.Value));
variableExpressions.Add(p.Variable);
}
bodyExpressions.Add(callExpression);
callExpression = Expression.Block(variableExpressions, bodyExpressions);
}
return callExpression;
}
public override Func<T> CreateDefaultConstructor<T>(Type type)
{
ValidationUtils.ArgumentNotNull(type, "type");
// avoid error from expressions compiler because of abstract class
if (type.IsAbstract())
return () => (T)Activator.CreateInstance(type);
try
{
Type resultType = typeof(T);
Expression expression = Expression.New(type);
expression = EnsureCastExpression(expression, resultType);
LambdaExpression lambdaExpression = Expression.Lambda(typeof(Func<T>), expression);
Func<T> compiled = (Func<T>)lambdaExpression.Compile();
return compiled;
}
catch
{
// an error can be thrown if constructor is not valid on Win8
// will have INVOCATION_FLAGS_NON_W8P_FX_API invocation flag
return () => (T)Activator.CreateInstance(type);
}
}
public override Func<T, object> CreateGet<T>(PropertyInfo propertyInfo)
{
ValidationUtils.ArgumentNotNull(propertyInfo, "propertyInfo");
Type instanceType = typeof(T);
Type resultType = typeof(object);
ParameterExpression parameterExpression = Expression.Parameter(instanceType, "instance");
Expression resultExpression;
MethodInfo getMethod = propertyInfo.GetGetMethod(true);
if (getMethod.IsStatic)
{
resultExpression = Expression.MakeMemberAccess(null, propertyInfo);
}
else
{
Expression readParameter = EnsureCastExpression(parameterExpression, propertyInfo.DeclaringType);
resultExpression = Expression.MakeMemberAccess(readParameter, propertyInfo);
}
resultExpression = EnsureCastExpression(resultExpression, resultType);
LambdaExpression lambdaExpression = Expression.Lambda(typeof(Func<T, object>), resultExpression, parameterExpression);
Func<T, object> compiled = (Func<T, object>)lambdaExpression.Compile();
return compiled;
}
public override Func<T, object> CreateGet<T>(FieldInfo fieldInfo)
{
ValidationUtils.ArgumentNotNull(fieldInfo, "fieldInfo");
ParameterExpression sourceParameter = Expression.Parameter(typeof(T), "source");
Expression fieldExpression;
if (fieldInfo.IsStatic)
{
fieldExpression = Expression.Field(null, fieldInfo);
}
else
{
Expression sourceExpression = EnsureCastExpression(sourceParameter, fieldInfo.DeclaringType);
fieldExpression = Expression.Field(sourceExpression, fieldInfo);
}
fieldExpression = EnsureCastExpression(fieldExpression, typeof(object));
Func<T, object> compiled = Expression.Lambda<Func<T, object>>(fieldExpression, sourceParameter).Compile();
return compiled;
}
public override Action<T, object> CreateSet<T>(FieldInfo fieldInfo)
{
ValidationUtils.ArgumentNotNull(fieldInfo, "fieldInfo");
// use reflection for structs
// expression doesn't correctly set value
if (fieldInfo.DeclaringType.IsValueType() || fieldInfo.IsInitOnly)
return LateBoundReflectionDelegateFactory.Instance.CreateSet<T>(fieldInfo);
ParameterExpression sourceParameterExpression = Expression.Parameter(typeof(T), "source");
ParameterExpression valueParameterExpression = Expression.Parameter(typeof(object), "value");
Expression fieldExpression;
if (fieldInfo.IsStatic)
{
fieldExpression = Expression.Field(null, fieldInfo);
}
else
{
Expression sourceExpression = EnsureCastExpression(sourceParameterExpression, fieldInfo.DeclaringType);
fieldExpression = Expression.Field(sourceExpression, fieldInfo);
}
Expression valueExpression = EnsureCastExpression(valueParameterExpression, fieldExpression.Type);
BinaryExpression assignExpression = Expression.Assign(fieldExpression, valueExpression);
LambdaExpression lambdaExpression = Expression.Lambda(typeof(Action<T, object>), assignExpression, sourceParameterExpression, valueParameterExpression);
Action<T, object> compiled = (Action<T, object>)lambdaExpression.Compile();
return compiled;
}
public override Action<T, object> CreateSet<T>(PropertyInfo propertyInfo)
{
ValidationUtils.ArgumentNotNull(propertyInfo, "propertyInfo");
// use reflection for structs
// expression doesn't correctly set value
if (propertyInfo.DeclaringType.IsValueType())
return LateBoundReflectionDelegateFactory.Instance.CreateSet<T>(propertyInfo);
Type instanceType = typeof(T);
Type valueType = typeof(object);
ParameterExpression instanceParameter = Expression.Parameter(instanceType, "instance");
ParameterExpression valueParameter = Expression.Parameter(valueType, "value");
Expression readValueParameter = EnsureCastExpression(valueParameter, propertyInfo.PropertyType);
MethodInfo setMethod = propertyInfo.GetSetMethod(true);
Expression setExpression;
if (setMethod.IsStatic)
{
setExpression = Expression.Call(setMethod, readValueParameter);
}
else
{
Expression readInstanceParameter = EnsureCastExpression(instanceParameter, propertyInfo.DeclaringType);
setExpression = Expression.Call(readInstanceParameter, setMethod, readValueParameter);
}
LambdaExpression lambdaExpression = Expression.Lambda(typeof(Action<T, object>), setExpression, instanceParameter, valueParameter);
Action<T, object> compiled = (Action<T, object>)lambdaExpression.Compile();
return compiled;
}
private Expression EnsureCastExpression(Expression expression, Type targetType)
{
Type expressionType = expression.Type;
// check if a cast or conversion is required
if (expressionType == targetType || (!expressionType.IsValueType() && targetType.IsAssignableFrom(expressionType)))
return expression;
return Expression.Convert(expression, targetType);
}
}
}
#endif
| |
// Graph Engine
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Trinity;
using Trinity.Network.Messaging;
using Trinity.Diagnostics;
using System.Runtime.CompilerServices;
using Trinity.Network;
using Trinity.Utilities;
namespace Trinity.Storage
{
/// <summary>
/// Provides methods for interacting with the distributed memory store.
/// </summary>
public unsafe partial class MemoryCloud
{
internal Storage[] StorageTable;
private ClusterConfig cluster_config;
private int server_count = -1;
private int my_server_id = -1;
private int my_proxy_id = -1;
internal MemoryCloud(ClusterConfig config)
{
this.cluster_config = config;
server_count = cluster_config.Servers.Count;
my_server_id = cluster_config.MyServerId;
my_proxy_id = cluster_config.MyProxyId;
}
public bool Open(bool nonblocking)
{
bool server_found = false;
StorageTable = new Storage[server_count];
if (server_count == 0)
goto server_not_found;
for (int i = 0; i < server_count; i++)
{
if (cluster_config.RunningMode == RunningMode.Server &&
(cluster_config.Servers[i].Has(Global.MyIPAddresses, Global.MyIPEndPoint.Port) || cluster_config.Servers[i].HasLoopBackEndpoint(Global.MyIPEndPoint.Port))
)
{
StorageTable[i] = Global.LocalStorage;
server_found = true;
}
else
{
StorageTable[i] = new RemoteStorage(cluster_config.Servers[i], TrinityConfig.ClientMaxConn, this, i, nonblocking);
}
}
if (cluster_config.RunningMode == RunningMode.Server && !server_found)
{
goto server_not_found;
}
StaticGetServerIdByCellId = this.GetServerIdByCellIdDefault;
if (!nonblocking) { CheckServerProtocolSignatures(); } // TODO should also check in nonblocking setup when any remote storage is connected
// else this.ServerConnected += (_, __) => {};
return true;
server_not_found:
if (cluster_config.RunningMode == RunningMode.Server || cluster_config.RunningMode == RunningMode.Client)
Log.WriteLine(LogLevel.Warning, "Incorrect server configuration. Message passing via CloudStorage not possible.");
else if (cluster_config.RunningMode == RunningMode.Proxy)
Log.WriteLine(LogLevel.Warning, "No servers are found. Message passing to servers via CloudStorage not possible.");
return false;
}
/// <summary>
/// Gets the ID of current server instance in the cluster.
/// </summary>
public int MyServerId
{
get
{
return my_server_id;
}
}
/// <summary>
/// Gets the ID of current proxy instance in the cluster.
/// </summary>
public int MyProxyId
{
get
{
return my_proxy_id;
}
}
private void CheckServerProtocolSignatures()
{
Log.WriteLine("Checking {0}-Server protocol signatures...", cluster_config.RunningMode);
int my_server_id = (cluster_config.RunningMode == RunningMode.Server) ? MyServerId : -1;
var storage = StorageTable.Where((_, idx) => idx != my_server_id).FirstOrDefault() as RemoteStorage;
CheckProtocolSignatures_impl(storage, cluster_config.RunningMode, RunningMode.Server);
}
private void CheckProxySignatures(IEnumerable<RemoteStorage> proxy_list)
{
Log.WriteLine("Checking {0}-Proxy protocol signatures...", cluster_config.RunningMode);
int my_proxy_id = (cluster_config.RunningMode == RunningMode.Proxy) ? MyProxyId : -1;
var storage = proxy_list.Where((_, idx) => idx != my_proxy_id).FirstOrDefault();
CheckProtocolSignatures_impl(storage, cluster_config.RunningMode, RunningMode.Proxy);
}
private unsafe void CheckProtocolSignatures_impl(RemoteStorage storage, RunningMode from, RunningMode to)
{
if (storage == null)
return;
string my_schema_name;
string my_schema_signature;
string remote_schema_name;
string remote_schema_signature;
ICommunicationSchema my_schema;
storage.GetCommunicationSchema(out remote_schema_name, out remote_schema_signature);
if (from != to)// Asymmetrical checking, need to scan for matching local comm schema first.
{
var local_candidate_schemas = Global.ScanForTSLCommunicationSchema(to);
/* If local or remote is default, we skip the verification. */
if (local_candidate_schemas.Count() == 0)
{
Log.WriteLine(LogLevel.Info, "{0}-{1}: Local instance has default communication capabilities.", from, to);
return;
}
if (remote_schema_name == DefaultCommunicationSchema.GetName() || remote_schema_signature == "{[][][]}")
{
Log.WriteLine(LogLevel.Info, "{0}-{1}: Remote cluster has default communication capabilities.", from, to);
return;
}
/* Both local and remote are not default instances. */
my_schema = local_candidate_schemas.FirstOrDefault(_ => _.Name == remote_schema_name);
if (my_schema == null)
{
Log.WriteLine(LogLevel.Fatal, "No candidate local communication schema signature matches the remote one.\r\n\tName: {0}\r\n\tSignature: {1}", remote_schema_name, remote_schema_signature);
Global.Exit(-1);
}
}
else
{
my_schema = Global.CommunicationSchema;
}
my_schema_name = my_schema.Name;
my_schema_signature = CommunicationSchemaSerializer.SerializeProtocols(my_schema);
if (my_schema_name != remote_schema_name)
{
Log.WriteLine(LogLevel.Error, "Local communication schema name not matching the remote one.\r\n\tLocal: {0}\r\n\tRemote: {1}", my_schema_name, remote_schema_name);
}
if (my_schema_signature != remote_schema_signature)
{
Log.WriteLine(LogLevel.Fatal, "Local communication schema signature not matching the remote one.\r\n\tLocal: {0}\r\n\tRemote: {1}", my_schema_signature, remote_schema_signature);
Global.Exit(-1);
}
}
/// <summary>
/// Gets an instance of a registered communication module on the started communication instance.
/// </summary>
/// <typeparam name="T">The type of the communication module.</typeparam>
/// <returns>A communication module object if a communication instance is started, and the module type is registered. Otherwise returns null.</returns>
public T GetCommunicationModule<T>() where T : CommunicationModule
{
var comm_instance = Global.CommunicationInstance;
if (comm_instance == null)
{
return default(T);
}
else
{
return comm_instance.GetCommunicationModule<T>();
}
}
/// <summary>
/// The number of servers in the cluster.
/// </summary>
public int ServerCount
{
get
{
return cluster_config.Servers.Count;
}
}
/// <summary>
/// Gets the number of proxies in the cluster.
/// </summary>
public int ProxyCount
{
get
{
return cluster_config.Proxies.Count;
}
}
internal int GetServerIdByIPE(IPEndPoint ipe)
{
for (int i = 0; i < cluster_config.Servers.Count; i++)
{
if (cluster_config.Servers[i].Has(ipe))
return i;
}
return -1;
}
private volatile bool disposed = false;
/// <summary>
/// Disposes current MemoryCloud instance.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Disposes current MemoryCloud instance.
/// </summary>
/// <param name="disposing">This parameter is not used.</param>
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
foreach (var storage in StorageTable)
{
if (storage != null && storage != Global.local_storage)
storage.Dispose();
}
this.disposed = true;
}
}
/// <summary>
/// The deconstruction method of MemoryCloud class.
/// </summary>
~MemoryCloud()
{
Dispose(false);
}
private Storage GetStorageByCellId(long cellId)
{
return StorageTable[GetServerIdByCellId(cellId)];
}
/// <summary>
/// Indicates whether the cell with the specified Id is a local cell.
/// </summary>
/// <param name="cellId">A 64-bit cell Id.</param>
/// <returns>true if the cell is in local storage; otherwise, false.</returns>
public bool IsLocalCell(long cellId)
{
return (StaticGetServerIdByCellId(cellId) == my_server_id);
}
/// <summary>
/// Gets the Id of the server on which the cell with the specified cell Id is located.
/// </summary>
/// <param name="cellId">A 64-bit cell Id.</param>
/// <returns>The Id of the server containing the specified cell.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private int GetServerIdByCellIdDefault(long cellId)
{
return (*(((byte*)&cellId) + 1)) % server_count;
}
/// <summary>
/// Gets the Id of the server on which the cell with the specified cell Id is located.
/// </summary>
public GetServerIdByCellIdDelegate StaticGetServerIdByCellId;
/// <summary>
/// Gets the Id of the server on which the cell with the specified cell Id is located.
/// </summary>
/// <param name="cellId">A 64-bit cell Id.</param>
/// <returns>A Trinity server Id.</returns>
public int GetServerIdByCellId(long cellId)
{
return StaticGetServerIdByCellId(cellId);
}
/// <summary>
/// Sets a user-defined data partitioning method.
/// </summary>
/// <param name="getServerIdByCellIdMethod">A method that transforms a 64-bit cell Id to a Trinity server Id.</param>
public void SetPartitionMethod(GetServerIdByCellIdDelegate getServerIdByCellIdMethod)
{
StaticGetServerIdByCellId = getServerIdByCellIdMethod;
}
}
}
| |
// 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: Class for creating and managing a threadpool
**
**
=============================================================================*/
#pragma warning disable 0420
/*
* Below you'll notice two sets of APIs that are separated by the
* use of 'Unsafe' in their names. The unsafe versions are called
* that because they do not propagate the calling stack onto the
* worker thread. This allows code to lose the calling stack and
* thereby elevate its security privileges. Note that this operation
* is much akin to the combined ability to control security policy
* and control security evidence. With these privileges, a person
* can gain the right to load assemblies that are fully trusted which
* then assert full trust and can call any code they want regardless
* of the previous stack information.
*/
using Internal.Runtime.Augments;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
namespace System.Threading
{
internal static class ThreadPoolGlobals
{
public static readonly int processorCount = Environment.ProcessorCount;
private static ThreadPoolWorkQueue _workQueue;
public static ThreadPoolWorkQueue workQueue
{
get
{
return LazyInitializer.EnsureInitialized(ref _workQueue, () => new ThreadPoolWorkQueue());
}
}
}
internal sealed class ThreadPoolWorkQueue
{
internal static class WorkStealingQueueList
{
private static volatile WorkStealingQueue[] _queues = new WorkStealingQueue[0];
public static WorkStealingQueue[] Queues => _queues;
// Track whether the WorkStealingQueueList is empty
// Three states simplifies race conditions. They may be considered.
// Now Active --> Maybe Inactive -> Confirmed Inactive
public const int WsqNowActive = 2;
public static int wsqActive;
public static void Add(WorkStealingQueue queue)
{
Debug.Assert(queue != null);
while (true)
{
WorkStealingQueue[] oldQueues = _queues;
Debug.Assert(Array.IndexOf(oldQueues, queue) == -1);
var newQueues = new WorkStealingQueue[oldQueues.Length + 1];
Array.Copy(oldQueues, 0, newQueues, 0, oldQueues.Length);
newQueues[newQueues.Length - 1] = queue;
if (Interlocked.CompareExchange(ref _queues, newQueues, oldQueues) == oldQueues)
{
break;
}
}
}
public static void Remove(WorkStealingQueue queue)
{
Debug.Assert(queue != null);
while (true)
{
WorkStealingQueue[] oldQueues = _queues;
if (oldQueues.Length == 0)
{
return;
}
int pos = Array.IndexOf(oldQueues, queue);
if (pos == -1)
{
Debug.Fail("Should have found the queue");
return;
}
var newQueues = new WorkStealingQueue[oldQueues.Length - 1];
if (pos == 0)
{
Array.Copy(oldQueues, 1, newQueues, 0, newQueues.Length);
}
else if (pos == oldQueues.Length - 1)
{
Array.Copy(oldQueues, 0, newQueues, 0, newQueues.Length);
}
else
{
Array.Copy(oldQueues, 0, newQueues, 0, pos);
Array.Copy(oldQueues, pos + 1, newQueues, pos, newQueues.Length - pos);
}
if (Interlocked.CompareExchange(ref _queues, newQueues, oldQueues) == oldQueues)
{
break;
}
}
}
}
internal sealed class WorkStealingQueue
{
private const int INITIAL_SIZE = 32;
internal volatile IThreadPoolWorkItem[] m_array = new IThreadPoolWorkItem[INITIAL_SIZE];
private volatile int m_mask = INITIAL_SIZE - 1;
#if DEBUG
// in debug builds, start at the end so we exercise the index reset logic.
private const int START_INDEX = int.MaxValue;
#else
private const int START_INDEX = 0;
#endif
private volatile int m_headIndex = START_INDEX;
private volatile int m_tailIndex = START_INDEX;
private SpinLock m_foreignLock = new SpinLock(enableThreadOwnerTracking: false);
public void LocalPush(IThreadPoolWorkItem obj)
{
int tail = m_tailIndex;
// We're going to increment the tail; if we'll overflow, then we need to reset our counts
if (tail == int.MaxValue)
{
bool lockTaken = false;
try
{
m_foreignLock.Enter(ref lockTaken);
if (m_tailIndex == int.MaxValue)
{
//
// Rather than resetting to zero, we'll just mask off the bits we don't care about.
// This way we don't need to rearrange the items already in the queue; they'll be found
// correctly exactly where they are. One subtlety here is that we need to make sure that
// if head is currently < tail, it remains that way. This happens to just fall out from
// the bit-masking, because we only do this if tail == int.MaxValue, meaning that all
// bits are set, so all of the bits we're keeping will also be set. Thus it's impossible
// for the head to end up > than the tail, since you can't set any more bits than all of
// them.
//
m_headIndex = m_headIndex & m_mask;
m_tailIndex = tail = m_tailIndex & m_mask;
Debug.Assert(m_headIndex <= m_tailIndex);
}
}
finally
{
if (lockTaken)
m_foreignLock.Exit(useMemoryBarrier: true);
}
}
// When there are at least 2 elements' worth of space, we can take the fast path.
if (tail < m_headIndex + m_mask)
{
Volatile.Write(ref m_array[tail & m_mask], obj);
m_tailIndex = tail + 1;
}
else
{
// We need to contend with foreign pops, so we lock.
bool lockTaken = false;
try
{
m_foreignLock.Enter(ref lockTaken);
int head = m_headIndex;
int count = m_tailIndex - m_headIndex;
// If there is still space (one left), just add the element.
if (count >= m_mask)
{
// We're full; expand the queue by doubling its size.
var newArray = new IThreadPoolWorkItem[m_array.Length << 1];
for (int i = 0; i < m_array.Length; i++)
newArray[i] = m_array[(i + head) & m_mask];
// Reset the field values, incl. the mask.
m_array = newArray;
m_headIndex = 0;
m_tailIndex = tail = count;
m_mask = (m_mask << 1) | 1;
}
Volatile.Write(ref m_array[tail & m_mask], obj);
m_tailIndex = tail + 1;
}
finally
{
if (lockTaken)
m_foreignLock.Exit(useMemoryBarrier: false);
}
}
}
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread safety")]
public bool LocalFindAndPop(IThreadPoolWorkItem obj)
{
// Fast path: check the tail. If equal, we can skip the lock.
if (m_array[(m_tailIndex - 1) & m_mask] == obj)
{
IThreadPoolWorkItem unused = LocalPop();
Debug.Assert(unused == null || unused == obj);
return unused != null;
}
// Else, do an O(N) search for the work item. The theory of work stealing and our
// inlining logic is that most waits will happen on recently queued work. And
// since recently queued work will be close to the tail end (which is where we
// begin our search), we will likely find it quickly. In the worst case, we
// will traverse the whole local queue; this is typically not going to be a
// problem (although degenerate cases are clearly an issue) because local work
// queues tend to be somewhat shallow in length, and because if we fail to find
// the work item, we are about to block anyway (which is very expensive).
for (int i = m_tailIndex - 2; i >= m_headIndex; i--)
{
if (m_array[i & m_mask] == obj)
{
// If we found the element, block out steals to avoid interference.
bool lockTaken = false;
try
{
m_foreignLock.Enter(ref lockTaken);
// If we encountered a race condition, bail.
if (m_array[i & m_mask] == null)
return false;
// Otherwise, null out the element.
Volatile.Write(ref m_array[i & m_mask], null);
// And then check to see if we can fix up the indexes (if we're at
// the edge). If we can't, we just leave nulls in the array and they'll
// get filtered out eventually (but may lead to superflous resizing).
if (i == m_tailIndex)
m_tailIndex -= 1;
else if (i == m_headIndex)
m_headIndex += 1;
return true;
}
finally
{
if (lockTaken)
m_foreignLock.Exit(useMemoryBarrier: false);
}
}
}
return false;
}
public IThreadPoolWorkItem LocalPop() => m_headIndex < m_tailIndex ? LocalPopCore() : null;
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread safety")]
private IThreadPoolWorkItem LocalPopCore()
{
while (true)
{
int tail = m_tailIndex;
if (m_headIndex >= tail)
{
return null;
}
// Decrement the tail using a fence to ensure subsequent read doesn't come before.
tail -= 1;
Interlocked.Exchange(ref m_tailIndex, tail);
// If there is no interaction with a take, we can head down the fast path.
if (m_headIndex <= tail)
{
int idx = tail & m_mask;
IThreadPoolWorkItem obj = Volatile.Read(ref m_array[idx]);
// Check for nulls in the array.
if (obj == null) continue;
m_array[idx] = null;
return obj;
}
else
{
// Interaction with takes: 0 or 1 elements left.
bool lockTaken = false;
try
{
m_foreignLock.Enter(ref lockTaken);
if (m_headIndex <= tail)
{
// Element still available. Take it.
int idx = tail & m_mask;
IThreadPoolWorkItem obj = Volatile.Read(ref m_array[idx]);
// Check for nulls in the array.
if (obj == null) continue;
m_array[idx] = null;
return obj;
}
else
{
// If we encountered a race condition and element was stolen, restore the tail.
m_tailIndex = tail + 1;
return null;
}
}
finally
{
if (lockTaken)
m_foreignLock.Exit(useMemoryBarrier: false);
}
}
}
}
public bool CanSteal => m_headIndex < m_tailIndex;
public IThreadPoolWorkItem TrySteal(ref bool missedSteal)
{
while (true)
{
if (CanSteal)
{
bool taken = false;
try
{
m_foreignLock.TryEnter(ref taken);
if (taken)
{
// Increment head, and ensure read of tail doesn't move before it (fence).
int head = m_headIndex;
Interlocked.Exchange(ref m_headIndex, head + 1);
if (head < m_tailIndex)
{
int idx = head & m_mask;
IThreadPoolWorkItem obj = Volatile.Read(ref m_array[idx]);
// Check for nulls in the array.
if (obj == null) continue;
m_array[idx] = null;
return obj;
}
else
{
// Failed, restore head.
m_headIndex = head;
}
}
}
finally
{
if (taken)
m_foreignLock.Exit(useMemoryBarrier: false);
}
missedSteal = true;
}
return null;
}
}
}
internal readonly LowLevelConcurrentQueue<IThreadPoolWorkItem> workItems = new LowLevelConcurrentQueue<IThreadPoolWorkItem>();
private volatile int numOutstandingThreadRequests = 0;
// The number of threads executing work items in the Dispatch method
internal volatile int numWorkingThreads;
public ThreadPoolWorkQueue()
{
}
public ThreadPoolWorkQueueThreadLocals EnsureCurrentThreadHasQueue() =>
ThreadPoolWorkQueueThreadLocals.threadLocals ??
(ThreadPoolWorkQueueThreadLocals.threadLocals = new ThreadPoolWorkQueueThreadLocals(this));
internal void EnsureThreadRequested()
{
//
// If we have not yet requested #procs threads, then request a new thread.
//
int count = numOutstandingThreadRequests;
while (count < ThreadPoolGlobals.processorCount)
{
int prev = Interlocked.CompareExchange(ref numOutstandingThreadRequests, count + 1, count);
if (prev == count)
{
ThreadPool.RequestWorkerThread();
break;
}
count = prev;
}
}
internal void MarkThreadRequestSatisfied()
{
//
// One of our outstanding thread requests has been satisfied.
// Decrement the count so that future calls to EnsureThreadRequested will succeed.
//
int count = numOutstandingThreadRequests;
while (count > 0)
{
int prev = Interlocked.CompareExchange(ref numOutstandingThreadRequests, count - 1, count);
if (prev == count)
{
break;
}
count = prev;
}
}
public void Enqueue(IThreadPoolWorkItem callback, bool forceGlobal)
{
ThreadPoolWorkQueueThreadLocals tl = null;
if (!forceGlobal)
tl = ThreadPoolWorkQueueThreadLocals.threadLocals;
if (null != tl)
{
tl.workStealingQueue.LocalPush(callback);
// We must guarantee wsqActive is set to WsqNowActive after we push
// The ordering must be global because we rely on other threads
// observing in this order
Interlocked.MemoryBarrier();
// We do not want to simply write. We want to prevent unnecessary writes
// which would invalidate reader's caches
if (WorkStealingQueueList.wsqActive != WorkStealingQueueList.WsqNowActive)
{
Volatile.Write(ref WorkStealingQueueList.wsqActive, WorkStealingQueueList.WsqNowActive);
}
}
else
{
workItems.Enqueue(callback);
}
EnsureThreadRequested();
}
internal bool LocalFindAndPop(IThreadPoolWorkItem callback)
{
ThreadPoolWorkQueueThreadLocals tl = ThreadPoolWorkQueueThreadLocals.threadLocals;
return tl != null && tl.workStealingQueue.LocalFindAndPop(callback);
}
public IThreadPoolWorkItem Dequeue(ThreadPoolWorkQueueThreadLocals tl, ref bool missedSteal)
{
IThreadPoolWorkItem callback;
int wsqActiveObserved = WorkStealingQueueList.wsqActive;
if (wsqActiveObserved > 0)
{
WorkStealingQueue localWsq = tl.workStealingQueue;
if ((callback = localWsq.LocalPop()) == null && // first try the local queue
!workItems.TryDequeue(out callback)) // then try the global queue
{
// finally try to steal from another thread's local queue
WorkStealingQueue[] queues = WorkStealingQueueList.Queues;
int c = queues.Length;
Debug.Assert(c > 0, "There must at least be a queue for this thread.");
int maxIndex = c - 1;
int i = tl.random.Next(c);
while (c > 0)
{
i = (i < maxIndex) ? i + 1 : 0;
WorkStealingQueue otherQueue = queues[i];
if (otherQueue != localWsq && otherQueue.CanSteal)
{
callback = otherQueue.TrySteal(ref missedSteal);
if (callback != null)
{
break;
}
}
c--;
}
if ((callback == null) && !missedSteal)
{
// Only decrement if the value is unchanged since we started looking for work
// This prevents multiple threads decrementing based on overlapping scans.
//
// When we decrement from active, the producer may have inserted a queue item during our scan
// therefore we cannot transition to empty
//
// When we decrement from Maybe Inactive, if the producer inserted a queue item during our scan,
// the producer must write Active. We may transition to empty briefly if we beat the
// producer's write, but the producer will then overwrite us before waking threads.
// So effectively we cannot mark the queue empty when an item is in the queue.
Interlocked.CompareExchange(ref WorkStealingQueueList.wsqActive, wsqActiveObserved - 1, wsqActiveObserved);
}
}
}
else
{
// We only need to look at the global queue since WorkStealingQueueList is inactive
workItems.TryDequeue(out callback);
}
return callback;
}
/// <summary>
/// Dispatches work items to this thread.
/// </summary>
/// <returns>
/// <c>true</c> if this thread did as much work as was available or its quantum expired.
/// <c>false</c> if this thread stopped working early.
/// </returns>
internal static bool Dispatch()
{
var workQueue = ThreadPoolGlobals.workQueue;
//
// Save the start time
//
int startTickCount = Environment.TickCount;
//
// Update our records to indicate that an outstanding request for a thread has now been fulfilled.
// From this point on, we are responsible for requesting another thread if we stop working for any
// reason, and we believe there might still be work in the queue.
//
workQueue.MarkThreadRequestSatisfied();
Interlocked.Increment(ref workQueue.numWorkingThreads);
//
// Assume that we're going to need another thread if this one returns to the VM. We'll set this to
// false later, but only if we're absolutely certain that the queue is empty.
//
bool needAnotherThread = true;
IThreadPoolWorkItem workItem = null;
try
{
//
// Set up our thread-local data
//
ThreadPoolWorkQueueThreadLocals tl = workQueue.EnsureCurrentThreadHasQueue();
//
// Loop until our quantum expires or there is no work.
//
while (ThreadPool.KeepDispatching(startTickCount))
{
bool missedSteal = false;
workItem = workQueue.Dequeue(tl, ref missedSteal);
if (workItem == null)
{
//
// No work.
// If we missed a steal, though, there may be more work in the queue.
// Instead of looping around and trying again, we'll just request another thread. Hopefully the thread
// that owns the contended work-stealing queue will pick up its own workitems in the meantime,
// which will be more efficient than this thread doing it anyway.
//
needAnotherThread = missedSteal;
// Tell the VM we're returning normally, not because Hill Climbing asked us to return.
return true;
}
//
// If we found work, there may be more work. Ask for another thread so that the other work can be processed
// in parallel. Note that this will only ask for a max of #procs threads, so it's safe to call it for every dequeue.
//
workQueue.EnsureThreadRequested();
try
{
SynchronizationContext.SetSynchronizationContext(null);
workItem.ExecuteWorkItem();
}
finally
{
workItem = null;
SynchronizationContext.SetSynchronizationContext(null);
}
RuntimeThread.CurrentThread.ResetThreadPoolThread();
if (!ThreadPool.NotifyWorkItemComplete())
return false;
}
// If we get here, it's because our quantum expired.
return true;
}
catch (Exception e)
{
// Work items should not allow exceptions to escape. For example, Task catches and stores any exceptions.
Environment.FailFast("Unhandled exception in ThreadPool dispatch loop", e);
return true; // Will never actually be executed because Environment.FailFast doesn't return
}
finally
{
int numWorkers = Interlocked.Decrement(ref workQueue.numWorkingThreads);
Debug.Assert(numWorkers >= 0);
//
// If we are exiting for any reason other than that the queue is definitely empty, ask for another
// thread to pick up where we left off.
//
if (needAnotherThread)
workQueue.EnsureThreadRequested();
}
}
}
// Simple random number generator. We don't need great randomness, we just need a little and for it to be fast.
internal struct FastRandom // xorshift prng
{
private uint _w, _x, _y, _z;
public FastRandom(int seed)
{
_x = (uint)seed;
_w = 88675123;
_y = 362436069;
_z = 521288629;
}
public int Next(int maxValue)
{
Debug.Assert(maxValue > 0);
uint t = _x ^ (_x << 11);
_x = _y; _y = _z; _z = _w;
_w = _w ^ (_w >> 19) ^ (t ^ (t >> 8));
return (int)(_w % (uint)maxValue);
}
}
// Holds a WorkStealingQueue, and remmoves it from the list when this object is no longer referened.
internal sealed class ThreadPoolWorkQueueThreadLocals
{
[ThreadStatic]
public static ThreadPoolWorkQueueThreadLocals threadLocals;
public readonly ThreadPoolWorkQueue workQueue;
public readonly ThreadPoolWorkQueue.WorkStealingQueue workStealingQueue;
public FastRandom random = new FastRandom(Environment.CurrentManagedThreadId); // mutable struct, do not copy or make readonly
public ThreadPoolWorkQueueThreadLocals(ThreadPoolWorkQueue tpq)
{
workQueue = tpq;
workStealingQueue = new ThreadPoolWorkQueue.WorkStealingQueue();
ThreadPoolWorkQueue.WorkStealingQueueList.Add(workStealingQueue);
}
private void CleanUp()
{
if (null != workStealingQueue)
{
if (null != workQueue)
{
IThreadPoolWorkItem cb;
while ((cb = workStealingQueue.LocalPop()) != null)
{
Debug.Assert(null != cb);
workQueue.Enqueue(cb, forceGlobal: true);
}
}
ThreadPoolWorkQueue.WorkStealingQueueList.Remove(workStealingQueue);
}
}
~ThreadPoolWorkQueueThreadLocals()
{
// Since the purpose of calling CleanUp is to transfer any pending workitems into the global
// queue so that they will be executed by another thread, there's no point in doing this cleanup
// if we're in the process of shutting down or unloading the AD. In those cases, the work won't
// execute anyway. And there are subtle races involved there that would lead us to do the wrong
// thing anyway. So we'll only clean up if this is a "normal" finalization.
if (!(Environment.HasShutdownStarted /*|| AppDomain.CurrentDomain.IsFinalizingForUnload()*/))
CleanUp();
}
}
public delegate void WaitCallback(Object state);
public delegate void WaitOrTimerCallback(Object state, bool timedOut); // signalled or timed out
//
// Interface to something that can be queued to the TP. This is implemented by
// QueueUserWorkItemCallback, Task, and potentially other internal types.
// For example, SemaphoreSlim represents callbacks using its own type that
// implements IThreadPoolWorkItem.
//
// If we decide to expose some of the workstealing
// stuff, this is NOT the thing we want to expose to the public.
//
internal interface IThreadPoolWorkItem
{
void ExecuteWorkItem();
}
internal sealed class QueueUserWorkItemCallback : IThreadPoolWorkItem
{
private WaitCallback callback;
private readonly ExecutionContext context;
private readonly Object state;
#if DEBUG
private volatile int executed;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1821:RemoveEmptyFinalizers")]
~QueueUserWorkItemCallback()
{
Debug.Assert(
executed != 0 || Environment.HasShutdownStarted /*|| AppDomain.CurrentDomain.IsFinalizingForUnload()*/,
"A QueueUserWorkItemCallback was never called!");
}
private void MarkExecuted()
{
GC.SuppressFinalize(this);
Debug.Assert(
0 == Interlocked.Exchange(ref executed, 1),
"A QueueUserWorkItemCallback was called twice!");
}
#endif
internal QueueUserWorkItemCallback(WaitCallback waitCallback, Object stateObj, ExecutionContext ec)
{
callback = waitCallback;
state = stateObj;
context = ec;
}
void IThreadPoolWorkItem.ExecuteWorkItem()
{
#if DEBUG
MarkExecuted();
#endif
try
{
if (context == null)
{
WaitCallback cb = callback;
callback = null;
cb(state);
}
else
ExecutionContext.Run(context, ccb, this);
}
catch (Exception e)
{
RuntimeAugments.ReportUnhandledException(e);
throw; //unreachable
}
}
internal static readonly ContextCallback ccb = new ContextCallback(WaitCallback_Context);
private static void WaitCallback_Context(Object state)
{
QueueUserWorkItemCallback obj = (QueueUserWorkItemCallback)state;
WaitCallback wc = obj.callback;
Debug.Assert(null != wc);
wc(obj.state);
}
}
internal sealed class QueueUserWorkItemCallbackDefaultContext : IThreadPoolWorkItem
{
private WaitCallback callback;
private readonly Object state;
#if DEBUG
private volatile int executed;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1821:RemoveEmptyFinalizers")]
~QueueUserWorkItemCallbackDefaultContext()
{
Debug.Assert(
executed != 0 || Environment.HasShutdownStarted /*|| AppDomain.CurrentDomain.IsFinalizingForUnload()*/,
"A QueueUserWorkItemCallbackDefaultContext was never called!");
}
private void MarkExecuted()
{
GC.SuppressFinalize(this);
Debug.Assert(
0 == Interlocked.Exchange(ref executed, 1),
"A QueueUserWorkItemCallbackDefaultContext was called twice!");
}
#endif
internal QueueUserWorkItemCallbackDefaultContext(WaitCallback waitCallback, Object stateObj)
{
callback = waitCallback;
state = stateObj;
}
void IThreadPoolWorkItem.ExecuteWorkItem()
{
#if DEBUG
MarkExecuted();
#endif
try
{
ExecutionContext.Run(ExecutionContext.Default, ccb, this);
}
catch (Exception e)
{
RuntimeAugments.ReportUnhandledException(e);
throw; //unreachable
}
}
internal static readonly ContextCallback ccb = new ContextCallback(WaitCallback_Context);
private static void WaitCallback_Context(Object state)
{
QueueUserWorkItemCallbackDefaultContext obj = (QueueUserWorkItemCallbackDefaultContext)state;
WaitCallback wc = obj.callback;
Debug.Assert(null != wc);
obj.callback = null;
wc(obj.state);
}
}
internal class _ThreadPoolWaitOrTimerCallback
{
private WaitOrTimerCallback _waitOrTimerCallback;
private ExecutionContext _executionContext;
private Object _state;
private static readonly ContextCallback _ccbt = new ContextCallback(WaitOrTimerCallback_Context_t);
private static readonly ContextCallback _ccbf = new ContextCallback(WaitOrTimerCallback_Context_f);
internal _ThreadPoolWaitOrTimerCallback(WaitOrTimerCallback waitOrTimerCallback, Object state, bool flowExecutionContext)
{
_waitOrTimerCallback = waitOrTimerCallback;
_state = state;
if (flowExecutionContext)
{
// capture the exection context
_executionContext = ExecutionContext.Capture();
}
}
private static void WaitOrTimerCallback_Context_t(Object state) =>
WaitOrTimerCallback_Context(state, timedOut: true);
private static void WaitOrTimerCallback_Context_f(Object state) =>
WaitOrTimerCallback_Context(state, timedOut: false);
private static void WaitOrTimerCallback_Context(Object state, bool timedOut)
{
_ThreadPoolWaitOrTimerCallback helper = (_ThreadPoolWaitOrTimerCallback)state;
helper._waitOrTimerCallback(helper._state, timedOut);
}
// call back helper
internal static void PerformWaitOrTimerCallback(_ThreadPoolWaitOrTimerCallback helper, bool timedOut)
{
Debug.Assert(helper != null, "Null state passed to PerformWaitOrTimerCallback!");
// call directly if it is an unsafe call OR EC flow is suppressed
if (helper._executionContext == null)
{
WaitOrTimerCallback callback = helper._waitOrTimerCallback;
callback(helper._state, timedOut);
}
else
{
ExecutionContext.Run(helper._executionContext, timedOut ? _ccbt : _ccbf, helper);
}
}
}
public static partial class ThreadPool
{
[CLSCompliant(false)]
public static RegisteredWaitHandle RegisterWaitForSingleObject(
WaitHandle waitObject,
WaitOrTimerCallback callBack,
Object state,
uint millisecondsTimeOutInterval,
bool executeOnlyOnce)
{
if (millisecondsTimeOutInterval > (uint)int.MaxValue && millisecondsTimeOutInterval != uint.MaxValue)
throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
return RegisterWaitForSingleObject(waitObject, callBack, state, millisecondsTimeOutInterval, executeOnlyOnce, true);
}
[CLSCompliant(false)]
public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject(
WaitHandle waitObject,
WaitOrTimerCallback callBack,
Object state,
uint millisecondsTimeOutInterval,
bool executeOnlyOnce)
{
if (millisecondsTimeOutInterval > (uint)int.MaxValue && millisecondsTimeOutInterval != uint.MaxValue)
throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
return RegisterWaitForSingleObject(waitObject, callBack, state, millisecondsTimeOutInterval, executeOnlyOnce, false);
}
public static RegisteredWaitHandle RegisterWaitForSingleObject(
WaitHandle waitObject,
WaitOrTimerCallback callBack,
Object state,
int millisecondsTimeOutInterval,
bool executeOnlyOnce)
{
if (millisecondsTimeOutInterval < -1)
throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
Contract.EndContractBlock();
return RegisterWaitForSingleObject(waitObject, callBack, state, (UInt32)millisecondsTimeOutInterval, executeOnlyOnce, true);
}
public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject(
WaitHandle waitObject,
WaitOrTimerCallback callBack,
Object state,
int millisecondsTimeOutInterval,
bool executeOnlyOnce)
{
if (millisecondsTimeOutInterval < -1)
throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
Contract.EndContractBlock();
return RegisterWaitForSingleObject(waitObject, callBack, state, (UInt32)millisecondsTimeOutInterval, executeOnlyOnce, false);
}
public static RegisteredWaitHandle RegisterWaitForSingleObject(
WaitHandle waitObject,
WaitOrTimerCallback callBack,
Object state,
long millisecondsTimeOutInterval,
bool executeOnlyOnce)
{
if (millisecondsTimeOutInterval < -1 || millisecondsTimeOutInterval > int.MaxValue)
throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
Contract.EndContractBlock();
return RegisterWaitForSingleObject(waitObject, callBack, state, (UInt32)millisecondsTimeOutInterval, executeOnlyOnce, true);
}
public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject(
WaitHandle waitObject,
WaitOrTimerCallback callBack,
Object state,
long millisecondsTimeOutInterval,
bool executeOnlyOnce)
{
if (millisecondsTimeOutInterval < -1 || millisecondsTimeOutInterval > int.MaxValue)
throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
Contract.EndContractBlock();
return RegisterWaitForSingleObject(waitObject, callBack, state, (UInt32)millisecondsTimeOutInterval, executeOnlyOnce, false);
}
public static RegisteredWaitHandle RegisterWaitForSingleObject(
WaitHandle waitObject,
WaitOrTimerCallback callBack,
Object state,
TimeSpan timeout,
bool executeOnlyOnce)
{
int tm = WaitHandle.ToTimeoutMilliseconds(timeout);
return RegisterWaitForSingleObject(waitObject, callBack, state, (UInt32)tm, executeOnlyOnce, true);
}
public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject(
WaitHandle waitObject,
WaitOrTimerCallback callBack,
Object state,
TimeSpan timeout,
bool executeOnlyOnce)
{
int tm = WaitHandle.ToTimeoutMilliseconds(timeout);
return RegisterWaitForSingleObject(waitObject, callBack, state, (UInt32)tm, executeOnlyOnce, false);
}
public static bool QueueUserWorkItem(WaitCallback callBack) =>
QueueUserWorkItem(callBack, null);
public static bool QueueUserWorkItem(WaitCallback callBack, object state)
{
if (callBack == null)
{
throw new ArgumentNullException(nameof(callBack));
}
ExecutionContext context = ExecutionContext.Capture();
IThreadPoolWorkItem tpcallBack = context == ExecutionContext.Default ?
new QueueUserWorkItemCallbackDefaultContext(callBack, state) :
(IThreadPoolWorkItem)new QueueUserWorkItemCallback(callBack, state, context);
ThreadPoolGlobals.workQueue.Enqueue(tpcallBack, forceGlobal: true);
return true;
}
public static bool UnsafeQueueUserWorkItem(WaitCallback callBack, Object state)
{
if (callBack == null)
{
throw new ArgumentNullException(nameof(callBack));
}
IThreadPoolWorkItem tpcallBack = new QueueUserWorkItemCallback(callBack, state, null);
ThreadPoolGlobals.workQueue.Enqueue(tpcallBack, forceGlobal: true);
return true;
}
internal static void UnsafeQueueCustomWorkItem(IThreadPoolWorkItem workItem, bool forceGlobal)
{
Debug.Assert(null != workItem);
ThreadPoolGlobals.workQueue.Enqueue(workItem, forceGlobal);
}
// This method tries to take the target callback out of the current thread's queue.
internal static bool TryPopCustomWorkItem(IThreadPoolWorkItem workItem)
{
Debug.Assert(null != workItem);
return ThreadPoolGlobals.workQueue.LocalFindAndPop(workItem);
}
// Get all workitems. Called by TaskScheduler in its debugger hooks.
internal static IEnumerable<IThreadPoolWorkItem> GetQueuedWorkItems()
{
// Enumerate the global queue
foreach (IThreadPoolWorkItem workItem in ThreadPoolGlobals.workQueue.workItems)
{
yield return workItem;
}
// Enumerate each local queue
foreach (ThreadPoolWorkQueue.WorkStealingQueue wsq in ThreadPoolWorkQueue.WorkStealingQueueList.Queues)
{
if (wsq != null && wsq.m_array != null)
{
IThreadPoolWorkItem[] items = wsq.m_array;
for (int i = 0; i < items.Length; i++)
{
IThreadPoolWorkItem item = items[i];
if (item != null)
{
yield return item;
}
}
}
}
}
internal static IEnumerable<IThreadPoolWorkItem> GetLocallyQueuedWorkItems()
{
ThreadPoolWorkQueue.WorkStealingQueue wsq = ThreadPoolWorkQueueThreadLocals.threadLocals.workStealingQueue;
if (wsq != null && wsq.m_array != null)
{
IThreadPoolWorkItem[] items = wsq.m_array;
for (int i = 0; i < items.Length; i++)
{
IThreadPoolWorkItem item = items[i];
if (item != null)
yield return item;
}
}
}
internal static IEnumerable<IThreadPoolWorkItem> GetGloballyQueuedWorkItems() => ThreadPoolGlobals.workQueue.workItems;
private static object[] ToObjectArray(IEnumerable<IThreadPoolWorkItem> workitems)
{
int i = 0;
foreach (IThreadPoolWorkItem item in workitems)
{
i++;
}
object[] result = new object[i];
i = 0;
foreach (IThreadPoolWorkItem item in workitems)
{
if (i < result.Length) //just in case someone calls us while the queues are in motion
result[i] = item;
i++;
}
return result;
}
// This is the method the debugger will actually call, if it ends up calling
// into ThreadPool directly. Tests can use this to simulate a debugger, as well.
internal static object[] GetQueuedWorkItemsForDebugger() =>
ToObjectArray(GetQueuedWorkItems());
internal static object[] GetGloballyQueuedWorkItemsForDebugger() =>
ToObjectArray(GetGloballyQueuedWorkItems());
internal static object[] GetLocallyQueuedWorkItemsForDebugger() =>
ToObjectArray(GetLocallyQueuedWorkItems());
unsafe private static void NativeOverlappedCallback(object obj)
{
NativeOverlapped* overlapped = (NativeOverlapped*)(IntPtr)obj;
_IOCompletionCallback.PerformIOCompletionCallback(0, 0, overlapped);
}
[CLSCompliant(false)]
unsafe public static bool UnsafeQueueNativeOverlapped(NativeOverlapped* overlapped)
{
// OS doesn't signal handle, so do it here (CoreCLR does this assignment in ThreadPoolNative::CorPostQueuedCompletionStatus)
overlapped->InternalLow = (IntPtr)0;
// Both types of callbacks are executed on the same thread pool
return UnsafeQueueUserWorkItem(NativeOverlappedCallback, (IntPtr)overlapped);
}
[Obsolete("ThreadPool.BindHandle(IntPtr) has been deprecated. Please use ThreadPool.BindHandle(SafeHandle) instead.", false)]
public static bool BindHandle(IntPtr osHandle)
{
throw new PlatformNotSupportedException(SR.Arg_PlatformNotSupported); // Replaced by ThreadPoolBoundHandle.BindHandle
}
public static bool BindHandle(SafeHandle osHandle)
{
throw new PlatformNotSupportedException(SR.Arg_PlatformNotSupported); // Replaced by ThreadPoolBoundHandle.BindHandle
}
internal static bool IsThreadPoolThread { get { return ThreadPoolWorkQueueThreadLocals.threadLocals != null; } }
}
}
| |
//
// Encog(tm) Core v3.2 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using System.IO;
using Encog.App.Analyst;
using Encog.App.Analyst.Script.Prop;
using Encog.App.Generate.Generators;
using Encog.App.Generate.Generators.CS;
using Encog.App.Generate.Generators.JS;
using Encog.App.Generate.Generators.Java;
using Encog.App.Generate.Generators.MQL4;
using Encog.App.Generate.Generators.NinjaScript;
using Encog.App.Generate.Program;
using Encog.ML;
using Encog.Neural.Networks;
using Encog.Persist;
namespace Encog.App.Generate
{
/// <summary>
/// Perform Encog code generation. Encog is capable of generating code from
/// several different objects. This code generation will be to the specified
/// target language.
/// </summary>
public class EncogCodeGeneration
{
/**
* The language specific code generator.
*/
private readonly ILanguageSpecificGenerator generator;
/**
* The program that we are generating.
*/
private readonly EncogGenProgram program = new EncogGenProgram();
/// <summary>
/// The target language for the code generation.
/// </summary>
private readonly TargetLanguage targetLanguage;
/**
* Construct the generation object.
*
* @param theTargetLanguage
* The target language.
*/
public EncogCodeGeneration(TargetLanguage theTargetLanguage)
{
targetLanguage = theTargetLanguage;
switch (theTargetLanguage)
{
case TargetLanguage.NoGeneration:
throw new AnalystCodeGenerationError(
"No target language has been specified for code generation.");
case TargetLanguage.Java:
generator = new GenerateEncogJava();
break;
case TargetLanguage.CSharp:
generator = new GenerateCS();
break;
case TargetLanguage.MQL4:
generator = new GenerateMQL4();
break;
case TargetLanguage.NinjaScript:
generator = new GenerateNinjaScript();
break;
case TargetLanguage.JavaScript:
generator = new GenerateEncogJavaScript();
break;
}
}
public bool EmbedData { get; set; }
public TargetLanguage TargetLanguage
{
get { return targetLanguage; }
}
/// <summary>
/// Is the specified method supported for code generation?
/// </summary>
/// <param name="method">The specified method.</param>
/// <returns>True, if the specified method is supported.</returns>
public static bool IsSupported(IMLMethod method)
{
if (method is BasicNetwork)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// Get the extension fot the specified language.
/// </summary>
/// <param name="lang">The specified language.</param>
/// <returns></returns>
public static string GetExtension(TargetLanguage lang)
{
if (lang == TargetLanguage.Java)
{
return "java";
}
else if (lang == TargetLanguage.JavaScript)
{
return "html";
}
else if (lang == TargetLanguage.CSharp)
{
return "cs";
}
else if (lang == TargetLanguage.MQL4)
{
return "mql4";
}
else if (lang == TargetLanguage.NinjaScript)
{
return "cs";
}
else
{
return "txt";
}
}
/**
* Generate the code from Encog Analyst.
*
* @param analyst
* The Encog Analyst object to use for code generation.
*/
public void Generate(EncogAnalyst analyst)
{
if (targetLanguage == TargetLanguage.MQL4
|| targetLanguage == TargetLanguage.NinjaScript)
{
if (!EmbedData)
{
throw new AnalystCodeGenerationError(
"MQL4 and Ninjascript must be embedded.");
}
}
if (generator is IProgramGenerator)
{
String methodID =
analyst.Script.Properties.GetPropertyString(ScriptProperties.MlConfigMachineLearningFile);
String trainingID = analyst.Script.Properties.GetPropertyString(ScriptProperties.MlConfigTrainingFile);
FileInfo methodFile = analyst.Script.ResolveFilename(methodID);
FileInfo trainingFile = analyst.Script.ResolveFilename(trainingID);
Generate(methodFile, trainingFile);
}
else
{
((ITemplateGenerator) generator).Generate(analyst);
}
}
/**
* Generate from a method and data.
*
* @param method
* The machine learning method to generate from.
* @param data
* The data to use perform generation.
*/
public void Generate(FileInfo method, FileInfo data)
{
EncogProgramNode createNetworkFunction = null;
program.AddComment("Code generated by Encog v"
+ EncogFramework.Instance.Properties[EncogFramework.EncogVersion]);
program.AddComment("Generation Date: " + new DateTime().ToString());
program.AddComment("Generated code may be used freely");
program.AddComment("http://www.heatonresearch.com/encog");
EncogProgramNode mainClass = program.CreateClass("EncogExample");
if (targetLanguage == TargetLanguage.MQL4
|| targetLanguage == TargetLanguage.NinjaScript)
{
throw new AnalystCodeGenerationError(
"MQL4 and Ninjascript can only be generated from Encog Analyst");
}
if (data != null)
{
mainClass.EmbedTraining(data);
if (!(generator is GenerateEncogJavaScript))
{
mainClass.GenerateLoadTraining(data);
}
}
if (method != null)
{
createNetworkFunction = GenerateForMethod(mainClass, method);
}
EncogProgramNode mainFunction = mainClass.CreateMainFunction();
if (createNetworkFunction != null)
{
mainFunction.CreateFunctionCall(createNetworkFunction, "MLMethod",
"method");
}
if (data != null)
{
if (!(generator is GenerateEncogJavaScript))
{
mainFunction.CreateFunctionCall("createTraining", "MLDataSet",
"training");
}
}
mainFunction
.AddComment("Network and/or data is now loaded, you can add code to train, evaluate, etc.");
((IProgramGenerator) generator).Generate(program, EmbedData);
}
/**
* GEnerate from a machine learning method.
*
* @param mainClass
* The main class.
* @param method
* The filename of the method.
* @return The newly created node.
*/
private EncogProgramNode GenerateForMethod(
EncogProgramNode mainClass, FileInfo method)
{
if (EmbedData)
{
var encodable = (IMLEncodable) EncogDirectoryPersistence
.LoadObject(method);
var weights = new double[encodable.EncodedArrayLength()];
encodable.EncodeToArray(weights);
mainClass.CreateArray("WEIGHTS", weights);
}
return mainClass.CreateNetworkFunction("createNetwork", method);
}
/**
* @return the targetLanguage
*/
/**
* Save the contents to a string.
*
* @return The contents.
*/
public String Save()
{
return generator.Contents;
}
/**
* Save the contents to the specified file.
*
* @param file
*/
public void Save(FileInfo file)
{
generator.WriteContents(file);
}
}
}
| |
// 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.
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Research.DataStructures;
using System.Diagnostics.Contracts;
namespace Microsoft.Research.Graphs
{
/// <summary>
/// A specialized graph based on a successor adjacency list.
///
/// This graph maintains only a single distinct edges between a pair of nodes.
/// It uses a composer provided on construction to compose edge information if
/// multiple edges are added between the same node.
/// </summary>
public class SingleEdgeGraph<Node, Info> : IGraphBuilder<Node, Info>
{
// invariant: if there exists an edge n1 -> n2, then n2 is in the domain of the edgemap
// this is important as we use that domain to characterize the set of nodes in our graph.
// and some nodes may not have outgoing edges.
private struct Edge
{
private readonly Node source;
private readonly Node target;
private readonly Info info;
public Edge(Node source, Info info, Node target)
{
this.source = source;
this.target = target;
this.info = info;
}
public Node Source
{
get { return this.source; }
}
public Node Target
{
get { return this.target; }
}
public Info Info { get { return this.info; } }
}
[ContractInvariantMethod]
private void ObjectInvariant()
{
Contract.Invariant(this.edgemap != null);
}
private readonly Dictionary<Node, Dictionary<Node, Edge>/*!*/>/*!*/ edgemap;
private readonly DComposer<Info, Info>/*!*/ composer;
private readonly IEqualityComparer<Node> nodeComparer;
private void Ignore(object ignore) { }
public SingleEdgeGraph(DComposer<Info, Info> edgeComposer, IEqualityComparer<Node> nodeComparer = null)
{
this.edgemap = new Dictionary<Node, Dictionary<Node, Edge>/*!*/>(nodeComparer);
this.composer = edgeComposer;
this.nodeComparer = nodeComparer;
}
public void AddNode(Node node)
{
// just materialize the node and edge list as a side
// effect of calling Edges
Ignore(Edges(node));
}
[ContractVerification(false)]
public void AddEdge(Node source, Info info, Node target)
{
Dictionary<Node, Edge> edges = Edges(source);
Edge existing;
if (edges.TryGetValue(target, out existing))
{
// compose info or ignore new edge
if (this.composer != null)
{
Info composed = this.composer(info, existing.Info);
edges[target] = new Edge(source, composed, target);
}
}
else
{
Edge edge = new Edge(source, info, target);
edges[target] = edge;
// Make sure target node is in graph
this.AddNode(target);
}
}
public SingleEdgeGraph<Node, Info> Reverse()
{
Contract.Ensures(Contract.Result<SingleEdgeGraph<Node, Info>>() != null);
var result = new SingleEdgeGraph<Node, Info>(this.composer, this.nodeComparer);
foreach (var pair in this.edgemap)
{
Contract.Assume(pair.Value != null);
foreach (var pair2 in pair.Value)
{
result.AddEdge(pair2.Key, pair2.Value.Info, pair.Key);
}
}
return result;
}
[ContractVerification(false)]
private Dictionary<Node, Edge>/*!*/ Edges(Node node)
{
Contract.Ensures(Contract.Result<Dictionary<Node, Edge>>() != null);
Dictionary<Node, Edge> result;
if (!this.edgemap.TryGetValue(node, out result))
{
result = new Dictionary<Node, Edge>(nodeComparer);
this.edgemap[node] = result;
}
else
{
Contract.Assume(result != null);
}
//^ assert result != null;
return result;
}
#region IGraph<Node,Edge> Members
public IEnumerable<Node>/*!*/ Nodes
{
get { return this.edgemap.Keys; }
}
[ContractVerification(false)]
public bool Contains(Node node)
{
return this.edgemap.ContainsKey(node);
}
#if false
public IEnumerable<IEdge<Node, EdgeInfo>/*!*/>/*!*/ Successors(Node node)
{
Dictionary<Node, Edge> edges = null;
this.edgemap.TryGetValue(node, out edges);
if (edges != null)
{
Dictionary<Node, Edge>/*!*/ nnedges = edges;
foreach (Node target in nnedges.Keys)
{
yield return nnedges[target];
}
}
else
{
throw new ArgumentException("Node is not in graph");
}
yield break;
}
#endif
#endregion
#region IGraph<Node,Edge> Members
public IEnumerable<Pair<Info, Node>> Successors(Node node)
{
Dictionary<Node, Edge> targets;
if (this.edgemap.TryGetValue(node, out targets))
{
foreach (Edge edge in targets.Values)
{
yield return new Pair<Info, Node>(edge.Info, edge.Target);
}
}
else
{
var n = node;
}
}
#endregion
}
}
| |
namespace fyiReporting.RdlDesign
{
public partial class DialogDatabase : System.Windows.Forms.Form
{
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(DialogDatabase));
this.splitContainer1 = new System.Windows.Forms.SplitContainer();
this.tvTablesColumns = new System.Windows.Forms.TreeView();
this.tbSQL = new System.Windows.Forms.TextBox();
this.bMove = new System.Windows.Forms.Button();
this.reportParameterCtl1 = new fyiReporting.RdlDesign.ReportParameterCtl();
this.tcDialog = new System.Windows.Forms.TabControl();
this.ReportType = new System.Windows.Forms.TabPage();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.rbSchema2005 = new System.Windows.Forms.RadioButton();
this.rbSchema2003 = new System.Windows.Forms.RadioButton();
this.rbSchemaNo = new System.Windows.Forms.RadioButton();
this.cbOrientation = new System.Windows.Forms.ComboBox();
this.label6 = new System.Windows.Forms.Label();
this.tbReportAuthor = new System.Windows.Forms.TextBox();
this.tbReportDescription = new System.Windows.Forms.TextBox();
this.tbReportName = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.rbChart = new System.Windows.Forms.RadioButton();
this.rbMatrix = new System.Windows.Forms.RadioButton();
this.rbList = new System.Windows.Forms.RadioButton();
this.rbTable = new System.Windows.Forms.RadioButton();
this.DBConnection = new System.Windows.Forms.TabPage();
this.groupBoxSqlServer = new System.Windows.Forms.GroupBox();
this.textBoxSqlPassword = new System.Windows.Forms.TextBox();
this.label11 = new System.Windows.Forms.Label();
this.textBoxSqlUser = new System.Windows.Forms.TextBox();
this.label10 = new System.Windows.Forms.Label();
this.label8 = new System.Windows.Forms.Label();
this.buttonDatabaseSearch = new System.Windows.Forms.Button();
this.comboServerList = new System.Windows.Forms.ComboBox();
this.label9 = new System.Windows.Forms.Label();
this.buttonSearchSqlServers = new System.Windows.Forms.Button();
this.comboDatabaseList = new System.Windows.Forms.ComboBox();
this.buttonSqliteSelectDatabase = new System.Windows.Forms.Button();
this.bShared = new System.Windows.Forms.Button();
this.bTestConnection = new System.Windows.Forms.Button();
this.cbOdbcNames = new System.Windows.Forms.ComboBox();
this.lODBC = new System.Windows.Forms.Label();
this.lConnection = new System.Windows.Forms.Label();
this.cbConnectionTypes = new System.Windows.Forms.ComboBox();
this.label7 = new System.Windows.Forms.Label();
this.tbConnection = new System.Windows.Forms.TextBox();
this.ReportParameters = new System.Windows.Forms.TabPage();
this.DBSql = new System.Windows.Forms.TabPage();
this.panel2 = new System.Windows.Forms.Panel();
this.TabularGroup = new System.Windows.Forms.TabPage();
this.clbSubtotal = new System.Windows.Forms.CheckedListBox();
this.ckbGrandTotal = new System.Windows.Forms.CheckBox();
this.label5 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.cbColumnList = new System.Windows.Forms.ComboBox();
this.ReportSyntax = new System.Windows.Forms.TabPage();
this.tbReportSyntax = new System.Windows.Forms.TextBox();
this.ReportPreview = new System.Windows.Forms.TabPage();
this.rdlViewer1 = new fyiReporting.RdlViewer.RdlViewer();
this.btnCancel = new System.Windows.Forms.Button();
this.panel1 = new System.Windows.Forms.Panel();
this.btnOK = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit();
this.splitContainer1.Panel1.SuspendLayout();
this.splitContainer1.Panel2.SuspendLayout();
this.splitContainer1.SuspendLayout();
this.tcDialog.SuspendLayout();
this.ReportType.SuspendLayout();
this.groupBox2.SuspendLayout();
this.groupBox1.SuspendLayout();
this.DBConnection.SuspendLayout();
this.groupBoxSqlServer.SuspendLayout();
this.ReportParameters.SuspendLayout();
this.DBSql.SuspendLayout();
this.panel2.SuspendLayout();
this.TabularGroup.SuspendLayout();
this.ReportSyntax.SuspendLayout();
this.ReportPreview.SuspendLayout();
this.panel1.SuspendLayout();
this.SuspendLayout();
//
// splitContainer1
//
resources.ApplyResources(this.splitContainer1, "splitContainer1");
this.splitContainer1.Name = "splitContainer1";
//
// splitContainer1.Panel1
//
resources.ApplyResources(this.splitContainer1.Panel1, "splitContainer1.Panel1");
this.splitContainer1.Panel1.Controls.Add(this.tvTablesColumns);
//
// splitContainer1.Panel2
//
resources.ApplyResources(this.splitContainer1.Panel2, "splitContainer1.Panel2");
this.splitContainer1.Panel2.Controls.Add(this.tbSQL);
this.splitContainer1.Panel2.Controls.Add(this.bMove);
//
// tvTablesColumns
//
resources.ApplyResources(this.tvTablesColumns, "tvTablesColumns");
this.tvTablesColumns.FullRowSelect = true;
this.tvTablesColumns.Name = "tvTablesColumns";
this.tvTablesColumns.BeforeExpand += new System.Windows.Forms.TreeViewCancelEventHandler(this.tvTablesColumns_BeforeExpand);
//
// tbSQL
//
resources.ApplyResources(this.tbSQL, "tbSQL");
this.tbSQL.AllowDrop = true;
this.tbSQL.Name = "tbSQL";
this.tbSQL.TextChanged += new System.EventHandler(this.tbSQL_TextChanged);
this.tbSQL.KeyDown += new System.Windows.Forms.KeyEventHandler(this.tbSQL_KeyDown);
//
// bMove
//
resources.ApplyResources(this.bMove, "bMove");
this.bMove.Name = "bMove";
this.bMove.Click += new System.EventHandler(this.bMove_Click);
//
// reportParameterCtl1
//
resources.ApplyResources(this.reportParameterCtl1, "reportParameterCtl1");
this.reportParameterCtl1.Name = "reportParameterCtl1";
//
// tcDialog
//
resources.ApplyResources(this.tcDialog, "tcDialog");
this.tcDialog.Controls.Add(this.ReportType);
this.tcDialog.Controls.Add(this.DBConnection);
this.tcDialog.Controls.Add(this.ReportParameters);
this.tcDialog.Controls.Add(this.DBSql);
this.tcDialog.Controls.Add(this.TabularGroup);
this.tcDialog.Controls.Add(this.ReportSyntax);
this.tcDialog.Controls.Add(this.ReportPreview);
this.tcDialog.Name = "tcDialog";
this.tcDialog.SelectedIndex = 0;
this.tcDialog.SelectedIndexChanged += new System.EventHandler(this.tabControl1_SelectedIndexChanged);
//
// ReportType
//
resources.ApplyResources(this.ReportType, "ReportType");
this.ReportType.Controls.Add(this.groupBox2);
this.ReportType.Controls.Add(this.cbOrientation);
this.ReportType.Controls.Add(this.label6);
this.ReportType.Controls.Add(this.tbReportAuthor);
this.ReportType.Controls.Add(this.tbReportDescription);
this.ReportType.Controls.Add(this.tbReportName);
this.ReportType.Controls.Add(this.label3);
this.ReportType.Controls.Add(this.label2);
this.ReportType.Controls.Add(this.label1);
this.ReportType.Controls.Add(this.groupBox1);
this.ReportType.Name = "ReportType";
this.ReportType.Tag = "type";
//
// groupBox2
//
resources.ApplyResources(this.groupBox2, "groupBox2");
this.groupBox2.Controls.Add(this.rbSchema2005);
this.groupBox2.Controls.Add(this.rbSchema2003);
this.groupBox2.Controls.Add(this.rbSchemaNo);
this.groupBox2.Name = "groupBox2";
this.groupBox2.TabStop = false;
//
// rbSchema2005
//
resources.ApplyResources(this.rbSchema2005, "rbSchema2005");
this.rbSchema2005.Checked = true;
this.rbSchema2005.Name = "rbSchema2005";
this.rbSchema2005.TabStop = true;
//
// rbSchema2003
//
resources.ApplyResources(this.rbSchema2003, "rbSchema2003");
this.rbSchema2003.Name = "rbSchema2003";
//
// rbSchemaNo
//
resources.ApplyResources(this.rbSchemaNo, "rbSchemaNo");
this.rbSchemaNo.Name = "rbSchemaNo";
//
// cbOrientation
//
resources.ApplyResources(this.cbOrientation, "cbOrientation");
this.cbOrientation.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbOrientation.Items.AddRange(new object[] {
resources.GetString("cbOrientation.Items"),
resources.GetString("cbOrientation.Items1")});
this.cbOrientation.Name = "cbOrientation";
this.cbOrientation.SelectedIndexChanged += new System.EventHandler(this.emptyReportSyntax);
//
// label6
//
resources.ApplyResources(this.label6, "label6");
this.label6.Name = "label6";
//
// tbReportAuthor
//
resources.ApplyResources(this.tbReportAuthor, "tbReportAuthor");
this.tbReportAuthor.Name = "tbReportAuthor";
this.tbReportAuthor.TextChanged += new System.EventHandler(this.tbReportAuthor_TextChanged);
//
// tbReportDescription
//
resources.ApplyResources(this.tbReportDescription, "tbReportDescription");
this.tbReportDescription.Name = "tbReportDescription";
this.tbReportDescription.TextChanged += new System.EventHandler(this.tbReportDescription_TextChanged);
//
// tbReportName
//
resources.ApplyResources(this.tbReportName, "tbReportName");
this.tbReportName.Name = "tbReportName";
this.tbReportName.TextChanged += new System.EventHandler(this.tbReportName_TextChanged);
//
// label3
//
resources.ApplyResources(this.label3, "label3");
this.label3.Name = "label3";
//
// label2
//
resources.ApplyResources(this.label2, "label2");
this.label2.Name = "label2";
//
// label1
//
resources.ApplyResources(this.label1, "label1");
this.label1.Name = "label1";
//
// groupBox1
//
resources.ApplyResources(this.groupBox1, "groupBox1");
this.groupBox1.Controls.Add(this.rbChart);
this.groupBox1.Controls.Add(this.rbMatrix);
this.groupBox1.Controls.Add(this.rbList);
this.groupBox1.Controls.Add(this.rbTable);
this.groupBox1.Name = "groupBox1";
this.groupBox1.TabStop = false;
//
// rbChart
//
resources.ApplyResources(this.rbChart, "rbChart");
this.rbChart.Name = "rbChart";
this.rbChart.CheckedChanged += new System.EventHandler(this.rbChart_CheckedChanged);
//
// rbMatrix
//
resources.ApplyResources(this.rbMatrix, "rbMatrix");
this.rbMatrix.Name = "rbMatrix";
this.rbMatrix.CheckedChanged += new System.EventHandler(this.rbMatrix_CheckedChanged);
//
// rbList
//
resources.ApplyResources(this.rbList, "rbList");
this.rbList.Name = "rbList";
this.rbList.CheckedChanged += new System.EventHandler(this.rbList_CheckedChanged);
//
// rbTable
//
resources.ApplyResources(this.rbTable, "rbTable");
this.rbTable.Checked = true;
this.rbTable.Name = "rbTable";
this.rbTable.TabStop = true;
this.rbTable.CheckedChanged += new System.EventHandler(this.rbTable_CheckedChanged);
//
// DBConnection
//
resources.ApplyResources(this.DBConnection, "DBConnection");
this.DBConnection.CausesValidation = false;
this.DBConnection.Controls.Add(this.groupBoxSqlServer);
this.DBConnection.Controls.Add(this.buttonSqliteSelectDatabase);
this.DBConnection.Controls.Add(this.bShared);
this.DBConnection.Controls.Add(this.bTestConnection);
this.DBConnection.Controls.Add(this.cbOdbcNames);
this.DBConnection.Controls.Add(this.lODBC);
this.DBConnection.Controls.Add(this.lConnection);
this.DBConnection.Controls.Add(this.cbConnectionTypes);
this.DBConnection.Controls.Add(this.label7);
this.DBConnection.Controls.Add(this.tbConnection);
this.DBConnection.Name = "DBConnection";
this.DBConnection.Tag = "connect";
this.DBConnection.Validating += new System.ComponentModel.CancelEventHandler(this.DBConnection_Validating);
//
// groupBoxSqlServer
//
resources.ApplyResources(this.groupBoxSqlServer, "groupBoxSqlServer");
this.groupBoxSqlServer.Controls.Add(this.textBoxSqlPassword);
this.groupBoxSqlServer.Controls.Add(this.label11);
this.groupBoxSqlServer.Controls.Add(this.textBoxSqlUser);
this.groupBoxSqlServer.Controls.Add(this.label10);
this.groupBoxSqlServer.Controls.Add(this.label8);
this.groupBoxSqlServer.Controls.Add(this.buttonDatabaseSearch);
this.groupBoxSqlServer.Controls.Add(this.comboServerList);
this.groupBoxSqlServer.Controls.Add(this.label9);
this.groupBoxSqlServer.Controls.Add(this.buttonSearchSqlServers);
this.groupBoxSqlServer.Controls.Add(this.comboDatabaseList);
this.groupBoxSqlServer.Name = "groupBoxSqlServer";
this.groupBoxSqlServer.TabStop = false;
//
// textBoxSqlPassword
//
resources.ApplyResources(this.textBoxSqlPassword, "textBoxSqlPassword");
this.textBoxSqlPassword.Name = "textBoxSqlPassword";
//
// label11
//
resources.ApplyResources(this.label11, "label11");
this.label11.Name = "label11";
//
// textBoxSqlUser
//
resources.ApplyResources(this.textBoxSqlUser, "textBoxSqlUser");
this.textBoxSqlUser.Name = "textBoxSqlUser";
//
// label10
//
resources.ApplyResources(this.label10, "label10");
this.label10.Name = "label10";
//
// label8
//
resources.ApplyResources(this.label8, "label8");
this.label8.Name = "label8";
//
// buttonDatabaseSearch
//
resources.ApplyResources(this.buttonDatabaseSearch, "buttonDatabaseSearch");
this.buttonDatabaseSearch.Name = "buttonDatabaseSearch";
this.buttonDatabaseSearch.UseVisualStyleBackColor = true;
this.buttonDatabaseSearch.Click += new System.EventHandler(this.buttonDatabaseSearch_Click);
//
// comboServerList
//
resources.ApplyResources(this.comboServerList, "comboServerList");
this.comboServerList.FormattingEnabled = true;
this.comboServerList.Name = "comboServerList";
//
// label9
//
resources.ApplyResources(this.label9, "label9");
this.label9.Name = "label9";
//
// buttonSearchSqlServers
//
resources.ApplyResources(this.buttonSearchSqlServers, "buttonSearchSqlServers");
this.buttonSearchSqlServers.Name = "buttonSearchSqlServers";
this.buttonSearchSqlServers.UseVisualStyleBackColor = true;
this.buttonSearchSqlServers.Click += new System.EventHandler(this.buttonSearchSqlServers_Click);
//
// comboDatabaseList
//
resources.ApplyResources(this.comboDatabaseList, "comboDatabaseList");
this.comboDatabaseList.FormattingEnabled = true;
this.comboDatabaseList.Name = "comboDatabaseList";
//
// buttonSqliteSelectDatabase
//
resources.ApplyResources(this.buttonSqliteSelectDatabase, "buttonSqliteSelectDatabase");
this.buttonSqliteSelectDatabase.Name = "buttonSqliteSelectDatabase";
this.buttonSqliteSelectDatabase.UseVisualStyleBackColor = true;
this.buttonSqliteSelectDatabase.Click += new System.EventHandler(this.buttonSqliteSelectDatabase_Click);
//
// bShared
//
resources.ApplyResources(this.bShared, "bShared");
this.bShared.Name = "bShared";
this.bShared.Click += new System.EventHandler(this.bShared_Click);
//
// bTestConnection
//
resources.ApplyResources(this.bTestConnection, "bTestConnection");
this.bTestConnection.Name = "bTestConnection";
this.bTestConnection.Click += new System.EventHandler(this.bTestConnection_Click);
//
// cbOdbcNames
//
resources.ApplyResources(this.cbOdbcNames, "cbOdbcNames");
this.cbOdbcNames.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbOdbcNames.Name = "cbOdbcNames";
this.cbOdbcNames.Sorted = true;
this.cbOdbcNames.SelectedIndexChanged += new System.EventHandler(this.cbOdbcNames_SelectedIndexChanged);
//
// lODBC
//
resources.ApplyResources(this.lODBC, "lODBC");
this.lODBC.Name = "lODBC";
//
// lConnection
//
resources.ApplyResources(this.lConnection, "lConnection");
this.lConnection.Name = "lConnection";
//
// cbConnectionTypes
//
resources.ApplyResources(this.cbConnectionTypes, "cbConnectionTypes");
this.cbConnectionTypes.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbConnectionTypes.Name = "cbConnectionTypes";
this.cbConnectionTypes.SelectedIndexChanged += new System.EventHandler(this.cbConnectionTypes_SelectedIndexChanged);
//
// label7
//
resources.ApplyResources(this.label7, "label7");
this.label7.Name = "label7";
//
// tbConnection
//
resources.ApplyResources(this.tbConnection, "tbConnection");
this.tbConnection.Name = "tbConnection";
this.tbConnection.TextChanged += new System.EventHandler(this.tbConnection_TextChanged);
//
// ReportParameters
//
resources.ApplyResources(this.ReportParameters, "ReportParameters");
this.ReportParameters.Controls.Add(this.reportParameterCtl1);
this.ReportParameters.Name = "ReportParameters";
this.ReportParameters.Tag = "parameters";
//
// DBSql
//
resources.ApplyResources(this.DBSql, "DBSql");
this.DBSql.Controls.Add(this.panel2);
this.DBSql.Name = "DBSql";
this.DBSql.Tag = "sql";
//
// panel2
//
resources.ApplyResources(this.panel2, "panel2");
this.panel2.Controls.Add(this.splitContainer1);
this.panel2.Name = "panel2";
//
// TabularGroup
//
resources.ApplyResources(this.TabularGroup, "TabularGroup");
this.TabularGroup.Controls.Add(this.clbSubtotal);
this.TabularGroup.Controls.Add(this.ckbGrandTotal);
this.TabularGroup.Controls.Add(this.label5);
this.TabularGroup.Controls.Add(this.label4);
this.TabularGroup.Controls.Add(this.cbColumnList);
this.TabularGroup.Name = "TabularGroup";
this.TabularGroup.Tag = "group";
//
// clbSubtotal
//
resources.ApplyResources(this.clbSubtotal, "clbSubtotal");
this.clbSubtotal.CheckOnClick = true;
this.clbSubtotal.Name = "clbSubtotal";
this.clbSubtotal.SelectedIndexChanged += new System.EventHandler(this.emptyReportSyntax);
//
// ckbGrandTotal
//
resources.ApplyResources(this.ckbGrandTotal, "ckbGrandTotal");
this.ckbGrandTotal.Name = "ckbGrandTotal";
this.ckbGrandTotal.CheckedChanged += new System.EventHandler(this.emptyReportSyntax);
//
// label5
//
resources.ApplyResources(this.label5, "label5");
this.label5.Name = "label5";
//
// label4
//
resources.ApplyResources(this.label4, "label4");
this.label4.Name = "label4";
//
// cbColumnList
//
resources.ApplyResources(this.cbColumnList, "cbColumnList");
this.cbColumnList.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbColumnList.Name = "cbColumnList";
this.cbColumnList.SelectedIndexChanged += new System.EventHandler(this.emptyReportSyntax);
//
// ReportSyntax
//
resources.ApplyResources(this.ReportSyntax, "ReportSyntax");
this.ReportSyntax.Controls.Add(this.tbReportSyntax);
this.ReportSyntax.Name = "ReportSyntax";
this.ReportSyntax.Tag = "syntax";
//
// tbReportSyntax
//
resources.ApplyResources(this.tbReportSyntax, "tbReportSyntax");
this.tbReportSyntax.Name = "tbReportSyntax";
this.tbReportSyntax.ReadOnly = true;
//
// ReportPreview
//
resources.ApplyResources(this.ReportPreview, "ReportPreview");
this.ReportPreview.Controls.Add(this.rdlViewer1);
this.ReportPreview.Name = "ReportPreview";
this.ReportPreview.Tag = "preview";
//
// rdlViewer1
//
resources.ApplyResources(this.rdlViewer1, "rdlViewer1");
this.rdlViewer1.Cursor = System.Windows.Forms.Cursors.Default;
this.rdlViewer1.Folder = null;
this.rdlViewer1.HighlightAll = false;
this.rdlViewer1.HighlightAllColor = System.Drawing.Color.Fuchsia;
this.rdlViewer1.HighlightCaseSensitive = false;
this.rdlViewer1.HighlightItemColor = System.Drawing.Color.Aqua;
this.rdlViewer1.HighlightPageItem = null;
this.rdlViewer1.HighlightText = null;
this.rdlViewer1.Name = "rdlViewer1";
this.rdlViewer1.PageCurrent = 1;
this.rdlViewer1.Parameters = "";
this.rdlViewer1.ReportName = null;
this.rdlViewer1.ScrollMode = fyiReporting.RdlViewer.ScrollModeEnum.Continuous;
this.rdlViewer1.SelectTool = false;
this.rdlViewer1.ShowFindPanel = false;
this.rdlViewer1.ShowParameterPanel = true;
this.rdlViewer1.ShowWaitDialog = true;
this.rdlViewer1.SourceFile = null;
this.rdlViewer1.SourceRdl = null;
this.rdlViewer1.UseTrueMargins = true;
this.rdlViewer1.Zoom = 0.7312694F;
this.rdlViewer1.ZoomMode = fyiReporting.RdlViewer.ZoomEnum.FitWidth;
//
// btnCancel
//
resources.ApplyResources(this.btnCancel, "btnCancel");
this.btnCancel.CausesValidation = false;
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnCancel.Name = "btnCancel";
//
// panel1
//
resources.ApplyResources(this.panel1, "panel1");
this.panel1.Controls.Add(this.btnOK);
this.panel1.Controls.Add(this.btnCancel);
this.panel1.Name = "panel1";
//
// btnOK
//
resources.ApplyResources(this.btnOK, "btnOK");
this.btnOK.Name = "btnOK";
this.btnOK.Click += new System.EventHandler(this.btnOK_Click);
//
// DialogDatabase
//
this.AcceptButton = this.btnOK;
resources.ApplyResources(this, "$this");
this.CancelButton = this.btnCancel;
this.Controls.Add(this.tcDialog);
this.Controls.Add(this.panel1);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "DialogDatabase";
this.ShowInTaskbar = false;
this.Closed += new System.EventHandler(this.DialogDatabase_Closed);
this.splitContainer1.Panel1.ResumeLayout(false);
this.splitContainer1.Panel2.ResumeLayout(false);
this.splitContainer1.Panel2.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).EndInit();
this.splitContainer1.ResumeLayout(false);
this.tcDialog.ResumeLayout(false);
this.ReportType.ResumeLayout(false);
this.ReportType.PerformLayout();
this.groupBox2.ResumeLayout(false);
this.groupBox1.ResumeLayout(false);
this.DBConnection.ResumeLayout(false);
this.DBConnection.PerformLayout();
this.groupBoxSqlServer.ResumeLayout(false);
this.groupBoxSqlServer.PerformLayout();
this.ReportParameters.ResumeLayout(false);
this.DBSql.ResumeLayout(false);
this.panel2.ResumeLayout(false);
this.TabularGroup.ResumeLayout(false);
this.ReportSyntax.ResumeLayout(false);
this.ReportSyntax.PerformLayout();
this.ReportPreview.ResumeLayout(false);
this.panel1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Button btnOK;
private System.Windows.Forms.TabPage DBConnection;
private System.Windows.Forms.TabPage DBSql;
private System.Windows.Forms.TabPage ReportType;
private System.ComponentModel.Container components = null;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.RadioButton rbTable;
private System.Windows.Forms.RadioButton rbList;
private System.Windows.Forms.RadioButton rbMatrix;
private System.Windows.Forms.RadioButton rbChart;
private System.Windows.Forms.TextBox tbConnection;
private System.Windows.Forms.TabPage ReportSyntax;
private System.Windows.Forms.TextBox tbReportSyntax;
private System.Windows.Forms.TabPage ReportPreview;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox tbReportName;
private System.Windows.Forms.TextBox tbReportDescription;
private System.Windows.Forms.TextBox tbReportAuthor;
private System.Windows.Forms.Panel panel2;
private fyiReporting.RdlViewer.RdlViewer rdlViewer1;
private System.Windows.Forms.TabPage ReportParameters;
private System.Windows.Forms.TabControl tcDialog;
private System.Windows.Forms.TabPage TabularGroup;
private System.Windows.Forms.ComboBox cbColumnList;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.CheckBox ckbGrandTotal;
private System.Windows.Forms.CheckedListBox clbSubtotal;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.ComboBox cbOrientation;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.ComboBox cbConnectionTypes;
private System.Windows.Forms.Label lODBC;
private System.Windows.Forms.ComboBox cbOdbcNames;
private System.Windows.Forms.Button bTestConnection;
private System.Windows.Forms.Label lConnection;
private System.Windows.Forms.Button bShared;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.RadioButton rbSchemaNo;
private System.Windows.Forms.RadioButton rbSchema2003;
private System.Windows.Forms.RadioButton rbSchema2005;
private System.Windows.Forms.SplitContainer splitContainer1;
private System.Windows.Forms.TreeView tvTablesColumns;
private System.Windows.Forms.Button bMove;
private System.Windows.Forms.TextBox tbSQL;
private System.Windows.Forms.Button buttonSqliteSelectDatabase;
internal System.Windows.Forms.Button buttonSearchSqlServers;
internal System.Windows.Forms.ComboBox comboServerList;
internal System.Windows.Forms.Label label8;
internal System.Windows.Forms.Button buttonDatabaseSearch;
internal System.Windows.Forms.Label label9;
internal System.Windows.Forms.ComboBox comboDatabaseList;
private System.Windows.Forms.GroupBox groupBoxSqlServer;
private System.Windows.Forms.Label label10;
private System.Windows.Forms.TextBox textBoxSqlPassword;
private System.Windows.Forms.Label label11;
private System.Windows.Forms.TextBox textBoxSqlUser;
private fyiReporting.RdlDesign.ReportParameterCtl reportParameterCtl1;
}
}
| |
// /*
// * Copyright (c) 2016, Alachisoft. All Rights Reserved.
// *
// * Licensed under the Apache License, Version 2.0 (the "License");
// * you may not use this file except in compliance with the License.
// * You may obtain a copy of the License at
// *
// * http://www.apache.org/licenses/LICENSE-2.0
// *
// * Unless required by applicable law or agreed to in writing, software
// * distributed under the License is distributed on an "AS IS" BASIS,
// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// * See the License for the specific language governing permissions and
// * limitations under the License.
// */
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Security;
namespace Alachisoft.NosDB.Common.DataStructures.Clustered
{
public static class ThrowHelper
{
internal static void ThrowArgumentOutOfRangeException()
{
throw new ArgumentOutOfRangeException(ThrowHelper.GetArgumentName(ExceptionArgument.index), ResourceHelper.GetResourceString(ThrowHelper.GetResourceName(ExceptionResource.ArgumentOutOfRange_Index)));
}
internal static void ThrowWrongKeyTypeArgumentException(object key, Type targetType)
{
throw new ArgumentException(ResourceHelper.GetResourceString("Arg_WrongType"));
}
internal static void ThrowWrongValueTypeArgumentException(object value, Type targetType)
{
throw new ArgumentException(ResourceHelper.GetResourceString("Arg_WrongType"));
}
internal static void ThrowKeyNotFoundException()
{
throw new KeyNotFoundException();
}
internal static void ThrowArgumentException(ExceptionResource resource)
{
throw new ArgumentException(ResourceHelper.GetResourceString(ThrowHelper.GetResourceName(resource)));
}
internal static void ThrowArgumentException(ExceptionResource resource, ExceptionArgument argument)
{
throw new ArgumentException(ResourceHelper.GetResourceString(ThrowHelper.GetResourceName(resource)), ThrowHelper.GetArgumentName(argument));
}
internal static void ThrowArgumentNullException(ExceptionArgument argument)
{
throw new ArgumentNullException(ThrowHelper.GetArgumentName(argument));
}
internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument)
{
throw new ArgumentOutOfRangeException(ThrowHelper.GetArgumentName(argument));
}
internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource)
{
throw new ArgumentOutOfRangeException(ThrowHelper.GetArgumentName(argument), ResourceHelper.GetResourceString(ThrowHelper.GetResourceName(resource)));
}
internal static void ThrowInvalidOperationException(ExceptionResource resource)
{
throw new InvalidOperationException(ResourceHelper.GetResourceString(ThrowHelper.GetResourceName(resource)));
}
internal static void ThrowSerializationException(ExceptionResource resource)
{
throw new SerializationException(ResourceHelper.GetResourceString(ThrowHelper.GetResourceName(resource)));
}
internal static void ThrowSecurityException(ExceptionResource resource)
{
throw new SecurityException(ResourceHelper.GetResourceString(ThrowHelper.GetResourceName(resource)));
}
internal static void ThrowNotSupportedException(ExceptionResource resource)
{
throw new NotSupportedException(ResourceHelper.GetResourceString(ThrowHelper.GetResourceName(resource)));
}
internal static void ThrowUnauthorizedAccessException(ExceptionResource resource)
{
throw new UnauthorizedAccessException(ResourceHelper.GetResourceString(ThrowHelper.GetResourceName(resource)));
}
internal static void ThrowObjectDisposedException(string objectName, ExceptionResource resource)
{
throw new ObjectDisposedException(objectName, ResourceHelper.GetResourceString(ThrowHelper.GetResourceName(resource)));
}
internal static void IfNullAndNullsAreIllegalThenThrow<T>(object value, ExceptionArgument argName)
{
if (value == null && default(T) != null)
{
ThrowHelper.ThrowArgumentNullException(argName);
}
}
internal static string GetArgumentName(ExceptionArgument argument)
{
string result;
switch (argument)
{
case ExceptionArgument.obj:
result = "obj";
break;
case ExceptionArgument.dictionary:
result = "dictionary";
break;
case ExceptionArgument.dictionaryCreationThreshold:
result = "dictionaryCreationThreshold";
break;
case ExceptionArgument.array:
result = "array";
break;
case ExceptionArgument.info:
result = "info";
break;
case ExceptionArgument.key:
result = "key";
break;
case ExceptionArgument.collection:
result = "collection";
break;
case ExceptionArgument.list:
result = "list";
break;
case ExceptionArgument.match:
result = "match";
break;
case ExceptionArgument.converter:
result = "converter";
break;
case ExceptionArgument.queue:
result = "queue";
break;
case ExceptionArgument.stack:
result = "stack";
break;
case ExceptionArgument.capacity:
result = "capacity";
break;
case ExceptionArgument.index:
result = "index";
break;
case ExceptionArgument.startIndex:
result = "startIndex";
break;
case ExceptionArgument.value:
result = "value";
break;
case ExceptionArgument.count:
result = "count";
break;
case ExceptionArgument.arrayIndex:
result = "arrayIndex";
break;
case ExceptionArgument.name:
result = "name";
break;
case ExceptionArgument.mode:
result = "mode";
break;
case ExceptionArgument.item:
result = "item";
break;
case ExceptionArgument.options:
result = "options";
break;
case ExceptionArgument.view:
result = "view";
break;
default:
return string.Empty;
}
return result;
}
internal static string GetResourceName(ExceptionResource resource)
{
string result;
switch (resource)
{
case ExceptionResource.Argument_ImplementIComparable:
result = "Argument_ImplementIComparable";
break;
case ExceptionResource.Argument_InvalidType:
result = "Argument_InvalidType";
break;
case ExceptionResource.Argument_InvalidArgumentForComparison:
result = "Argument_InvalidArgumentForComparison";
break;
case ExceptionResource.Argument_InvalidRegistryKeyPermissionCheck:
result = "Argument_InvalidRegistryKeyPermissionCheck";
break;
case ExceptionResource.ArgumentOutOfRange_NeedNonNegNum:
result = "ArgumentOutOfRange_NeedNonNegNum";
break;
case ExceptionResource.Arg_ArrayPlusOffTooSmall:
result = "Arg_ArrayPlusOffTooSmall";
break;
case ExceptionResource.Arg_NonZeroLowerBound:
result = "Arg_NonZeroLowerBound";
break;
case ExceptionResource.Arg_RankMultiDimNotSupported:
result = "Arg_RankMultiDimNotSupported";
break;
case ExceptionResource.Arg_RegKeyDelHive:
result = "Arg_RegKeyDelHive";
break;
case ExceptionResource.Arg_RegKeyStrLenBug:
result = "Arg_RegKeyStrLenBug";
break;
case ExceptionResource.Arg_RegSetStrArrNull:
result = "Arg_RegSetStrArrNull";
break;
case ExceptionResource.Arg_RegSetMismatchedKind:
result = "Arg_RegSetMismatchedKind";
break;
case ExceptionResource.Arg_RegSubKeyAbsent:
result = "Arg_RegSubKeyAbsent";
break;
case ExceptionResource.Arg_RegSubKeyValueAbsent:
result = "Arg_RegSubKeyValueAbsent";
break;
case ExceptionResource.Argument_AddingDuplicate:
result = "Argument_AddingDuplicate";
break;
case ExceptionResource.Serialization_InvalidOnDeser:
result = "Serialization_InvalidOnDeser";
break;
case ExceptionResource.Serialization_MissingKeys:
result = "Serialization_MissingKeys";
break;
case ExceptionResource.Serialization_NullKey:
result = "Serialization_NullKey";
break;
case ExceptionResource.Argument_InvalidArrayType:
result = "Argument_InvalidArrayType";
break;
case ExceptionResource.NotSupported_KeyCollectionSet:
result = "NotSupported_KeyCollectionSet";
break;
case ExceptionResource.NotSupported_ValueCollectionSet:
result = "NotSupported_ValueCollectionSet";
break;
case ExceptionResource.ArgumentOutOfRange_SmallCapacity:
result = "ArgumentOutOfRange_SmallCapacity";
break;
case ExceptionResource.ArgumentOutOfRange_Index:
result = "ArgumentOutOfRange_Index";
break;
case ExceptionResource.Argument_InvalidOffLen:
result = "Argument_InvalidOffLen";
break;
case ExceptionResource.Argument_ItemNotExist:
result = "Argument_ItemNotExist";
break;
case ExceptionResource.ArgumentOutOfRange_Count:
result = "ArgumentOutOfRange_Count";
break;
case ExceptionResource.ArgumentOutOfRange_InvalidThreshold:
result = "ArgumentOutOfRange_InvalidThreshold";
break;
case ExceptionResource.ArgumentOutOfRange_ListInsert:
result = "ArgumentOutOfRange_ListInsert";
break;
case ExceptionResource.NotSupported_ReadOnlyCollection:
result = "NotSupported_ReadOnlyCollection";
break;
case ExceptionResource.InvalidOperation_CannotRemoveFromStackOrQueue:
result = "InvalidOperation_CannotRemoveFromStackOrQueue";
break;
case ExceptionResource.InvalidOperation_EmptyQueue:
result = "InvalidOperation_EmptyQueue";
break;
case ExceptionResource.InvalidOperation_EnumOpCantHappen:
result = "InvalidOperation_EnumOpCantHappen";
break;
case ExceptionResource.InvalidOperation_EnumFailedVersion:
result = "InvalidOperation_EnumFailedVersion";
break;
case ExceptionResource.InvalidOperation_EmptyStack:
result = "InvalidOperation_EmptyStack";
break;
case ExceptionResource.ArgumentOutOfRange_BiggerThanCollection:
result = "ArgumentOutOfRange_BiggerThanCollection";
break;
case ExceptionResource.InvalidOperation_EnumNotStarted:
result = "InvalidOperation_EnumNotStarted";
break;
case ExceptionResource.InvalidOperation_EnumEnded:
result = "InvalidOperation_EnumEnded";
break;
case ExceptionResource.NotSupported_SortedListNestedWrite:
result = "NotSupported_SortedListNestedWrite";
break;
case ExceptionResource.InvalidOperation_NoValue:
result = "InvalidOperation_NoValue";
break;
case ExceptionResource.InvalidOperation_RegRemoveSubKey:
result = "InvalidOperation_RegRemoveSubKey";
break;
case ExceptionResource.Security_RegistryPermission:
result = "Security_RegistryPermission";
break;
case ExceptionResource.UnauthorizedAccess_RegistryNoWrite:
result = "UnauthorizedAccess_RegistryNoWrite";
break;
case ExceptionResource.ObjectDisposed_RegKeyClosed:
result = "ObjectDisposed_RegKeyClosed";
break;
case ExceptionResource.NotSupported_InComparableType:
result = "NotSupported_InComparableType";
break;
case ExceptionResource.Argument_InvalidRegistryOptionsCheck:
result = "Argument_InvalidRegistryOptionsCheck";
break;
case ExceptionResource.Argument_InvalidRegistryViewCheck:
result = "Argument_InvalidRegistryViewCheck";
break;
default:
return string.Empty;
}
return result;
}
}
}
| |
// 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.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics.Contracts;
using Microsoft.Cci.MutableCodeModel;
using Microsoft.Cci;
namespace CCDoc {
[ContractVerification(true)]
internal static class BooleanExpressionHelper
{
#region Code to negate predicates in bool expression strings
// Recognize some common predicate forms, and negate them. Also, fall back to a correct default.
public static String NegatePredicate(String predicate) {
if (String.IsNullOrEmpty(predicate)) return "";
if (predicate.Length < 2) return "!" + predicate;
// "(p)", but avoiding stuff like "(p && q) || (!p)"
if (predicate[0] == '(' && predicate[predicate.Length - 1] == ')') {
if (predicate.IndexOf('(', 1) == -1)
return '(' + NegatePredicate(predicate.Substring(1, predicate.Length - 2)) + ')';
}
// "!p"
if (predicate[0] == '!' && (ContainsNoOperators(predicate, 1, predicate.Length - 1) || IsSimpleFunctionCall(predicate, 1, predicate.Length - 1)))
return predicate.Substring(1);
// "a < b" or "a <= b"
int ltIndex = predicate.IndexOf('<');
if (ltIndex >= 0) {
int aStart = 0, aEnd, bStart, bEnd = predicate.Length;
bool ltOrEquals = ltIndex < bEnd - 1 ? predicate[ltIndex + 1] == '=' : false;
aEnd = ltIndex;
bStart = ltOrEquals ? ltIndex + 2 : ltIndex + 1;
String a = predicate.Substring(aStart, aEnd - aStart);
String b = predicate.Substring(bStart, bEnd - bStart);
if (ContainsNoOperators(a) && ContainsNoOperators(b))
return a + (ltOrEquals ? ">" : ">=") + b;
}
// "a > b" or "a >= b"
int gtIndex = predicate.IndexOf('>');
if (gtIndex >= 0) {
int aStart = 0, aEnd, bStart, bEnd = predicate.Length;
bool gtOrEquals = gtIndex < bEnd - 1 ? predicate[gtIndex + 1] == '=' : false;
aEnd = gtIndex;
bStart = gtOrEquals ? gtIndex + 2 : gtIndex + 1;
String a = predicate.Substring(aStart, aEnd - aStart);
String b = predicate.Substring(bStart, bEnd - bStart);
if (ContainsNoOperators(a) && ContainsNoOperators(b))
return a + (gtOrEquals ? "<" : "<=") + b;
}
// "a == b" or "a != b"
int eqIndex = predicate.IndexOf('=');
if (eqIndex >= 0) {
int aStart = 0, aEnd = -1, bStart = -1, bEnd = predicate.Length;
bool skip = false;
bool equalsOperator = false;
if (eqIndex > 0 && predicate[eqIndex - 1] == '!') {
aEnd = eqIndex - 1;
bStart = eqIndex + 1;
equalsOperator = false;
} else if (eqIndex < bEnd - 1 && predicate[eqIndex + 1] == '=') {
aEnd = eqIndex;
bStart = eqIndex + 2;
equalsOperator = true;
} else
skip = true;
if (!skip) {
String a = predicate.Substring(aStart, aEnd - aStart);
String b = predicate.Substring(bStart, bEnd - bStart);
if (ContainsNoOperators(a) && ContainsNoOperators(b))
return a + (equalsOperator ? "!=" : "==") + b;
}
}
return NegateConjunctsAndDisjuncts(predicate);
}
[ContractVerification(true)]
private static string NegateConjunctsAndDisjuncts(String predicate)
{
Contract.Requires(predicate != null);
if (predicate.Contains("&&") || predicate.Contains("||"))
{
// Consider predicates like "(P) && (Q)", "P || Q", "(P || Q) && R", etc.
// Apply DeMorgan's law, and recurse to negate both sides of the binary operator.
int aStart = 0, aEnd, bEnd = predicate.Length;
int parenCount = 0;
bool skip = false;
bool foundAnd = false, foundOr = false;
aEnd = 0;
while (aEnd < predicate.Length && ((predicate[aEnd] != '&' && predicate[aEnd] != '|') || parenCount > 0))
{
if (predicate[aEnd] == '(')
parenCount++;
else if (predicate[aEnd] == ')')
parenCount--;
aEnd++;
}
if (aEnd >= predicate.Length - 1)
skip = true;
else
{
if (aEnd + 1 < predicate.Length && predicate[aEnd] == '&' && predicate[aEnd + 1] == '&')
foundAnd = true;
else if (aEnd + 1 < predicate.Length && predicate[aEnd] == '|' && predicate[aEnd + 1] == '|')
foundOr = true;
if (!foundAnd && !foundOr)
skip = true;
}
if (!skip)
{
var bStart = aEnd + 2;
Contract.Assert(bStart <= bEnd);
while (aEnd > 0 && Char.IsWhiteSpace(predicate[aEnd - 1]))
aEnd--;
while (bStart < bEnd && Char.IsWhiteSpace(predicate[bStart]))
bStart++;
String a = predicate.Substring(aStart, aEnd - aStart);
String b = predicate.Substring(bStart, bEnd - bStart);
String op = foundAnd ? " || " : " && ";
return NegatePredicate(a) + op + NegatePredicate(b);
}
}
return String.Format("!({0})", predicate);
}
private static bool ContainsNoOperators(String s) {
Contract.Requires(s != null);
return ContainsNoOperators(s, 0, s.Length);
}
// These aren't operators like + per se, but ones that will cause evaluation order to possibly change,
// or alter the semantics of what might be in a predicate.
// @TODO: Consider adding '~'
static readonly String[] Operators = new String[] { "==", "!=", "=", "<", ">", "(", ")", "//", "/*", "*/" };
private static bool ContainsNoOperators(String s, int start, int end) {
Contract.Requires(s != null);
foreach (String op in Operators) {
Contract.Assume(op != null, "lack of contract support for collections");
if (s.IndexOf(op) >= 0)
return false;
}
return true;
}
private static bool ArrayContains<T>(T[] array, T item) {
Contract.Requires(array != null);
foreach (T x in array)
if (item.Equals(x))
return true;
return false;
}
// Recognize only SIMPLE method calls, like "System.String.Equals("", "")".
private static bool IsSimpleFunctionCall(String s, int start, int end) {
Contract.Requires(s != null);
Contract.Requires(start >= 0);
Contract.Requires(end <= s.Length);
Contract.Requires(end >= 0);
char[] badChars = { '+', '-', '*', '/', '~', '<', '=', '>', ';', '?', ':' };
int parenCount = 0;
int index = start;
bool foundMethod = false;
for (; index < end; index++) {
if (s[index] == '(')
{
parenCount++;
if (parenCount > 1)
return false;
if (foundMethod == true)
return false;
foundMethod = true;
} else if (s[index] == ')') {
parenCount--;
if (index != end - 1)
return false;
} else if (ArrayContains(badChars, s[index]))
return false;
}
return foundMethod;
}
#endregion Code from BrianGru to negate predicates coming from if-then-throw preconditions
public static IExpression Normalize(IExpression expression) {
LogicalNot/*?*/ logicalNot = expression as LogicalNot;
if (logicalNot != null) {
IExpression operand = logicalNot.Operand;
#region LogicalNot: !
LogicalNot/*?*/ operandAsLogicalNot = operand as LogicalNot;
if (operandAsLogicalNot != null) {
return Normalize(operandAsLogicalNot.Operand);
}
#endregion
#region BinaryOperations: ==, !=, <, <=, >, >=
BinaryOperation/*?*/ binOp = operand as BinaryOperation;
if (binOp != null) {
BinaryOperation/*?*/ result = null;
if (binOp is IEquality)
result = new NotEquality();
else if (binOp is INotEquality)
result = new Equality();
else if (binOp is ILessThan)
result = new GreaterThanOrEqual();
else if (binOp is ILessThanOrEqual)
result = new GreaterThan();
else if (binOp is IGreaterThan)
result = new LessThanOrEqual();
else if (binOp is IGreaterThanOrEqual)
result = new LessThan();
if (result != null) {
result.LeftOperand = Normalize(binOp.LeftOperand);
result.RightOperand = Normalize(binOp.RightOperand);
return result;
}
}
#endregion
#region Conditionals: &&, ||
Conditional/*?*/ conditional = operand as Conditional;
if (conditional != null) {
if (ExpressionHelper.IsIntegralNonzero(conditional.ResultIfTrue) ||
ExpressionHelper.IsIntegralZero(conditional.ResultIfFalse)) {
Conditional result = new Conditional();
LogicalNot not;
//invert condition
not = new LogicalNot();
not.Operand = conditional.Condition;
result.Condition = Normalize(not);
//invert false branch and switch with true branch
not = new LogicalNot();
not.Operand = conditional.ResultIfFalse;
result.ResultIfTrue = Normalize(not);
//invert true branch and switch with false branch
not = new LogicalNot();
not.Operand = conditional.ResultIfTrue;
result.ResultIfFalse = Normalize(not);
//return
result.Type = conditional.Type;
return result;
}
}
#endregion
#region Constants: true, false
CompileTimeConstant/*?*/ ctc = operand as CompileTimeConstant;
if (ctc != null) {
if (ExpressionHelper.IsIntegralNonzero(ctc)) { //Is true
var val = SetBooleanFalse(ctc);
if (val != null)
return val;
else
return expression;
} else if (ExpressionHelper.IsIntegralZero(ctc)) { //Is false
var val = SetBooleanTrue(ctc);
if (val != null)
return val;
else
return expression;
}
}
#endregion
}
return expression;
}
public static CompileTimeConstant/*?*/ SetBooleanFalse(ICompileTimeConstant constExpression) {
Contract.Requires(constExpression != null);
IConvertible/*?*/ ic = constExpression.Value as IConvertible;
if (ic == null) return null;
CompileTimeConstant result = new CompileTimeConstant(constExpression);
switch (ic.GetTypeCode()) {
case System.TypeCode.SByte: result.Value = (SByte)0; break;
case System.TypeCode.Int16: result.Value = (Int16)0; break;
case System.TypeCode.Int32: result.Value = (Int32)0; break;
case System.TypeCode.Int64: result.Value = (Int64)0; break;
case System.TypeCode.Byte: result.Value = (Byte)0; break;
case System.TypeCode.UInt16: result.Value = (UInt16)0; break;
case System.TypeCode.UInt32: result.Value = (UInt32)0; break;
case System.TypeCode.UInt64: result.Value = (UInt64)0; break;
default: return null;
}
return result;
}
public static CompileTimeConstant/*?*/ SetBooleanTrue(ICompileTimeConstant constExpression) {
Contract.Requires(constExpression != null);
IConvertible/*?*/ ic = constExpression.Value as IConvertible;
if (ic == null) return null;
CompileTimeConstant result = new CompileTimeConstant(constExpression);
switch (ic.GetTypeCode()) {
case System.TypeCode.SByte: result.Value = (SByte)1; break;
case System.TypeCode.Int16: result.Value = (Int16)1; break;
case System.TypeCode.Int32: result.Value = (Int32)1; break;
case System.TypeCode.Int64: result.Value = (Int64)1; break;
case System.TypeCode.Byte: result.Value = (Byte)1; break;
case System.TypeCode.UInt16: result.Value = (UInt16)1; break;
case System.TypeCode.UInt32: result.Value = (UInt32)1; break;
case System.TypeCode.UInt64: result.Value = (UInt64)1; break;
default: return null;
}
return result;
}
}
[ContractVerification(true)]
internal class ExpressionSimplifier : CodeRewriter {
public ExpressionSimplifier() : base(Dummy.CompilationHostEnvironment) { }
public override IExpression Rewrite(ILogicalNot logicalNot) {
var result = base.Rewrite(logicalNot);
return BooleanExpressionHelper.Normalize(result);
}
public override IExpression Rewrite(IConditional conditional) {
if (conditional.Type.TypeCode == PrimitiveTypeCode.Boolean && ExpressionHelper.IsIntegralZero(conditional.ResultIfTrue)) {
var not = new LogicalNot() { Operand = conditional.Condition, };
var c = new Conditional() {
Condition = BooleanExpressionHelper.Normalize(not),
ResultIfTrue = conditional.ResultIfFalse,
ResultIfFalse = new CompileTimeConstant() { Type = conditional.Type, Value = false, },
Type = conditional.Type,
};
return c;
}
return base.Rewrite(conditional);
}
}
}
| |
#region License
//
// The Open Toolkit Library License
//
// Copyright (c) 2006 - 2010 the Open Toolkit library.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
//
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
namespace OpenTK
{
/// <summary>
/// Defines a display device on the underlying system, and provides
/// methods to query and change its display parameters.
/// </summary>
public class DisplayDevice
{
// TODO: Add properties that describe the 'usable' size of the Display, i.e. the maximized size without the taskbar etc.
// TODO: Does not detect changes to primary device.
#region Fields
bool primary;
Rectangle bounds;
DisplayResolution current_resolution = new DisplayResolution(), original_resolution;
List<DisplayResolution> available_resolutions = new List<DisplayResolution>();
IList<DisplayResolution> available_resolutions_readonly;
internal object Id; // A platform-specific id for this monitor
static readonly object display_lock = new object();
static DisplayDevice primary_display;
static Platform.IDisplayDeviceDriver implementation;
#endregion
#region Constructors
static DisplayDevice()
{
implementation = Platform.Factory.Default.CreateDisplayDeviceDriver();
}
internal DisplayDevice()
{
available_resolutions_readonly = available_resolutions.AsReadOnly();
}
internal DisplayDevice(DisplayResolution currentResolution, bool primary,
IEnumerable<DisplayResolution> availableResolutions, Rectangle bounds,
object id)
: this()
{
#warning "Consolidate current resolution with bounds? Can they fall out of sync right now?"
this.current_resolution = currentResolution;
IsPrimary = primary;
this.available_resolutions.AddRange(availableResolutions);
this.bounds = bounds == Rectangle.Empty ? currentResolution.Bounds : bounds;
this.Id = id;
}
#endregion
#region --- Public Methods ---
#region public Rectangle Bounds
/// <summary>
/// Gets the bounds of this instance in pixel coordinates..
/// </summary>
public Rectangle Bounds
{
get { return bounds; }
internal set
{
bounds = value;
current_resolution.Height = bounds.Height;
current_resolution.Width = bounds.Width;
}
}
#endregion
#region public int Width
/// <summary>Gets a System.Int32 that contains the width of this display in pixels.</summary>
public int Width { get { return current_resolution.Width; } }
#endregion
#region public int Height
/// <summary>Gets a System.Int32 that contains the height of this display in pixels.</summary>
public int Height { get { return current_resolution.Height; } }
#endregion
#region public int BitsPerPixel
/// <summary>Gets a System.Int32 that contains number of bits per pixel of this display. Typical values include 8, 16, 24 and 32.</summary>
public int BitsPerPixel
{
get { return current_resolution.BitsPerPixel; }
internal set { current_resolution.BitsPerPixel = value; }
}
#endregion
#region public float RefreshRate
/// <summary>
/// Gets a System.Single representing the vertical refresh rate of this display.
/// </summary>
public float RefreshRate
{
get { return current_resolution.RefreshRate; }
internal set { current_resolution.RefreshRate = value; }
}
#endregion
#region public bool IsPrimary
/// <summary>Gets a System.Boolean that indicates whether this Display is the primary Display in systems with multiple Displays.</summary>
public bool IsPrimary
{
get { return primary; }
internal set
{
if (value && primary_display != null && primary_display != this)
primary_display.IsPrimary = false;
lock (display_lock)
{
primary = value;
if (value)
primary_display = this;
}
}
}
#endregion
#region public DisplayResolution SelectResolution(int width, int height, int bitsPerPixel, float refreshRate)
/// <summary>
/// Selects an available resolution that matches the specified parameters.
/// </summary>
/// <param name="width">The width of the requested resolution in pixels.</param>
/// <param name="height">The height of the requested resolution in pixels.</param>
/// <param name="bitsPerPixel">The bits per pixel of the requested resolution.</param>
/// <param name="refreshRate">The refresh rate of the requested resolution in hertz.</param>
/// <returns>The requested DisplayResolution or null if the parameters cannot be met.</returns>
/// <remarks>
/// <para>If a matching resolution is not found, this function will retry ignoring the specified refresh rate,
/// bits per pixel and resolution, in this order. If a matching resolution still doesn't exist, this function will
/// return the current resolution.</para>
/// <para>A parameter set to 0 or negative numbers will not be used in the search (e.g. if refreshRate is 0,
/// any refresh rate will be considered valid).</para>
/// <para>This function allocates memory.</para>
/// </remarks>
public DisplayResolution SelectResolution(int width, int height, int bitsPerPixel, float refreshRate)
{
DisplayResolution resolution = FindResolution(width, height, bitsPerPixel, refreshRate);
if (resolution == null)
resolution = FindResolution(width, height, bitsPerPixel, 0);
if (resolution == null)
resolution = FindResolution(width, height, 0, 0);
if (resolution == null)
return current_resolution;
return resolution;
}
#endregion
#region public IList<DisplayResolution> AvailableResolutions
/// <summary>
/// Gets the list of <see cref="DisplayResolution"/> objects available on this device.
/// </summary>
public IList<DisplayResolution> AvailableResolutions
{
get { return available_resolutions_readonly; }
internal set
{
available_resolutions = (List<DisplayResolution>)value;
available_resolutions_readonly = available_resolutions.AsReadOnly();
}
}
#endregion
#region public void ChangeResolution(DisplayResolution resolution)
/// <summary>Changes the resolution of the DisplayDevice.</summary>
/// <param name="resolution">The resolution to set. <see cref="DisplayDevice.SelectResolution"/></param>
/// <exception cref="Graphics.GraphicsModeException">Thrown if the requested resolution could not be set.</exception>
/// <remarks>If the specified resolution is null, this function will restore the original DisplayResolution.</remarks>
public void ChangeResolution(DisplayResolution resolution)
{
if (resolution == null)
this.RestoreResolution();
if (resolution == current_resolution)
return;
//effect.FadeOut();
if (implementation.TryChangeResolution(this, resolution))
{
if (original_resolution == null)
original_resolution = current_resolution;
current_resolution = resolution;
}
else throw new Graphics.GraphicsModeException(String.Format("Device {0}: Failed to change resolution to {1}.",
this, resolution));
//effect.FadeIn();
}
#endregion
#region public void ChangeResolution(int width, int height, int bitsPerPixel, float refreshRate)
/// <summary>Changes the resolution of the DisplayDevice.</summary>
/// <param name="width">The new width of the DisplayDevice.</param>
/// <param name="height">The new height of the DisplayDevice.</param>
/// <param name="bitsPerPixel">The new bits per pixel of the DisplayDevice.</param>
/// <param name="refreshRate">The new refresh rate of the DisplayDevice.</param>
/// <exception cref="Graphics.GraphicsModeException">Thrown if the requested resolution could not be set.</exception>
public void ChangeResolution(int width, int height, int bitsPerPixel, float refreshRate)
{
this.ChangeResolution(this.SelectResolution(width, height, bitsPerPixel, refreshRate));
}
#endregion
#region public void RestoreResolution()
/// <summary>Restores the original resolution of the DisplayDevice.</summary>
/// <exception cref="Graphics.GraphicsModeException">Thrown if the original resolution could not be restored.</exception>
public void RestoreResolution()
{
if (original_resolution != null)
{
//effect.FadeOut();
if (implementation.TryRestoreResolution(this))
{
current_resolution = original_resolution;
original_resolution = null;
}
else throw new Graphics.GraphicsModeException(String.Format("Device {0}: Failed to restore resolution.", this));
//effect.FadeIn();
}
}
#endregion
#region public static IList<DisplayDevice> AvailableDisplays
/// <summary>
/// Gets the list of available <see cref="DisplayDevice"/> objects.
/// This function allocates memory.
/// </summary>
[Obsolete("Use GetDisplay(DisplayIndex) instead.")]
public static IList<DisplayDevice> AvailableDisplays
{
get
{
List<DisplayDevice> displays = new List<DisplayDevice>();
for (int i = 0; i < 6; i++)
{
DisplayDevice dev = GetDisplay(DisplayIndex.First + i);
if (dev != null)
displays.Add(dev);
}
return displays.AsReadOnly();
}
}
#endregion
#region public static DisplayDevice Default
/// <summary>Gets the default (primary) display of this system.</summary>
public static DisplayDevice Default
{
get { return implementation.GetDisplay(DisplayIndex.Primary); }
}
#endregion
#region GetDisplay
/// <summary>
/// Gets the <see cref="DisplayDevice"/> for the specified <see cref="DeviceIndex"/>.
/// </summary>
/// <param name="index">The <see cref="DeviceIndex"/> that defines the desired display.</param>
/// <returns>A <see cref="DisplayDevice"/> or null, if no device corresponds to the specified index.</returns>
public static DisplayDevice GetDisplay(DisplayIndex index)
{
return implementation.GetDisplay(index);
}
#endregion
#endregion
#region --- Private Methods ---
#region DisplayResolution FindResolution(int width, int height, int bitsPerPixel, float refreshRate)
DisplayResolution FindResolution(int width, int height, int bitsPerPixel, float refreshRate)
{
return available_resolutions.Find(delegate(DisplayResolution test)
{
return
((width > 0 && width == test.Width) || width == 0) &&
((height > 0 && height == test.Height) || height == 0) &&
((bitsPerPixel > 0 && bitsPerPixel == test.BitsPerPixel) || bitsPerPixel == 0) &&
((refreshRate > 0 && System.Math.Abs(refreshRate - test.RefreshRate) < 1.0) || refreshRate == 0);
});
}
#endregion
#endregion
#region --- Overrides ---
#region public override string ToString()
/// <summary>
/// Returns a System.String representing this DisplayDevice.
/// </summary>
/// <returns>A System.String representing this DisplayDevice.</returns>
public override string ToString()
{
return String.Format("{0}: {1} ({2} modes available)", IsPrimary ? "Primary" : "Secondary",
Bounds.ToString(), available_resolutions.Count);
}
#endregion
#region public override bool Equals(object obj)
///// <summary>Determines whether the specified DisplayDevices are equal.</summary>
///// <param name="obj">The System.Object to check against.</param>
///// <returns>True if the System.Object is an equal DisplayDevice; false otherwise.</returns>
//public override bool Equals(object obj)
//{
// if (obj is DisplayDevice)
// {
// DisplayDevice dev = (DisplayDevice)obj;
// return
// IsPrimary == dev.IsPrimary &&
// current_resolution == dev.current_resolution &&
// available_resolutions.Count == dev.available_resolutions.Count;
// }
// return false;
//}
#endregion
#region public override int GetHashCode()
///// <summary>Returns a unique hash representing this DisplayDevice.</summary>
///// <returns>A System.Int32 that may serve as a hash code for this DisplayDevice.</returns>
////public override int GetHashCode()
//{
// return current_resolution.GetHashCode() ^ IsPrimary.GetHashCode() ^ available_resolutions.Count;
//}
#endregion
#endregion
}
#region --- FadeEffect ---
#if false
class FadeEffect : IDisposable
{
List<Form> forms = new List<Form>();
double opacity_step = 0.04;
int sleep_step;
internal FadeEffect()
{
foreach (Screen s in Screen.AllScreens)
{
Form form = new Form();
form.ShowInTaskbar = false;
form.StartPosition = FormStartPosition.Manual;
form.WindowState = FormWindowState.Maximized;
form.FormBorderStyle = FormBorderStyle.None;
form.TopMost = true;
form.BackColor = System.Drawing.Color.Black;
forms.Add(form);
}
sleep_step = 10 / forms.Count;
MoveToStartPositions();
}
void MoveToStartPositions()
{
int count = 0;
foreach (Screen s in Screen.AllScreens)
{
// forms[count++].Location = new System.Drawing.Point(s.Bounds.X, s.Bounds.Y);
//forms[count].Size = new System.Drawing.Size(4096, 4096);
count++;
}
}
bool FadedOut
{
get
{
bool ready = true;
foreach (Form form in forms)
ready = ready && form.Opacity >= 1.0;
return ready;
}
}
bool FadedIn
{
get
{
bool ready = true;
foreach (Form form in forms)
ready = ready && form.Opacity <= 0.0;
return ready;
}
}
internal void FadeOut()
{
MoveToStartPositions();
foreach (Form form in forms)
{
form.Opacity = 0.0;
form.Visible = true;
}
while (!FadedOut)
{
foreach (Form form in forms)
{
form.Opacity += opacity_step;
form.Refresh();
}
Thread.Sleep(sleep_step);
}
}
internal void FadeIn()
{
MoveToStartPositions();
foreach (Form form in forms)
form.Opacity = 1.0;
while (!FadedIn)
{
foreach (Form form in forms)
{
form.Opacity -= opacity_step;
form.Refresh();
}
Thread.Sleep(sleep_step);
}
foreach (Form form in forms)
form.Visible = false;
}
#region IDisposable Members
public void Dispose()
{
foreach (Form form in forms)
form.Dispose();
}
#endregion
}
#endif
#endregion
}
| |
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class Backoffice_Referensi_JadwalDokter_List : System.Web.UI.Page
{
public int NoKe = 0;
protected string dsReportSessionName = "dsListRefJadwalDokter";
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Session["SIMRS.UserId"] == null)
{
Response.Redirect(Request.ApplicationPath + "/Backoffice/login.aspx");
}
int UserId = (int)Session["SIMRS.UserId"];
if (Session["JadwalDokterManagement"] != null)
{
btnNew.Text = "<img alt=\"New\" src=\"" + Request.ApplicationPath + "/images/new_f2.gif\" align=\"middle\" border=\"0\" name=\"new\" value=\"new\">" + Resources.GetString("Referensi", "AddJadwalDokter");
}
//else
//{
// Response.Redirect(Request.ApplicationPath + "/Backoffice/UnAuthorize.aspx");
//}
btnSearch.Text = Resources.GetString("", "Search");
ImageButtonFirst.ImageUrl = Request.ApplicationPath + "/images/navigator/nbFirst.gif";
ImageButtonPrev.ImageUrl = Request.ApplicationPath + "/images/navigator/nbPrevpage.gif";
ImageButtonNext.ImageUrl = Request.ApplicationPath + "/images/navigator/nbNextpage.gif";
ImageButtonLast.ImageUrl = Request.ApplicationPath + "/images/navigator/nbLast.gif";
GetListPoliklinik();
GetListDokter();
UpdateDataView(true);
}
}
public void GetListPoliklinik()
{
string PoliklinikId = "";
SIMRS.DataAccess.RS_Poliklinik myObj = new SIMRS.DataAccess.RS_Poliklinik();
DataTable dt = myObj.GetList();
cmbPoliklinik.Items.Clear();
int i = 0;
cmbPoliklinik.Items.Add("");
cmbPoliklinik.Items[i].Text = "";
cmbPoliklinik.Items[i].Value = "";
i++;
foreach (DataRow dr in dt.Rows)
{
cmbPoliklinik.Items.Add("");
cmbPoliklinik.Items[i].Text = "[" + dr["Kode"].ToString() + "] " + dr["Nama"].ToString();
cmbPoliklinik.Items[i].Value = dr["Id"].ToString();
if (dr["Id"].ToString() == PoliklinikId)
cmbPoliklinik.SelectedIndex = i;
i++;
}
}
public void GetListDokter()
{
string DokterId = "";
SIMRS.DataAccess.RS_Dokter myObj = new SIMRS.DataAccess.RS_Dokter();
DataTable dt = myObj.GetList();
cmbDokter.Items.Clear();
int i = 0;
cmbDokter.Items.Add("");
cmbDokter.Items[i].Text = "";
cmbDokter.Items[i].Value = "";
i++;
foreach (DataRow dr in dt.Rows)
{
cmbDokter.Items.Add("");
cmbDokter.Items[i].Text = dr["Nama"].ToString() + " [" + dr["SpesialisNama"].ToString() + "]";
cmbDokter.Items[i].Value = dr["DokterId"].ToString();
if (dr["DokterId"].ToString() == DokterId)
cmbDokter.SelectedIndex = i;
i++;
}
}
#region .Update View Data
//////////////////////////////////////////////////////////////////////
// PhysicalDataRead
// ------------------------------------------------------------------
/// <summary>
/// This function is responsible for loading data from database.
/// </summary>
/// <returns>DataSet</returns>
public DataSet PhysicalDataRead()
{
// Local variables
DataSet oDS = new DataSet();
// Get Data
SIMRS.DataAccess.RS_JadwalDokter myObj = new SIMRS.DataAccess.RS_JadwalDokter();
DataTable myData = myObj.SelectAllView();
oDS.Tables.Add(myData);
return oDS;
}
/// <summary>
/// This function is responsible for binding data to Datagrid.
/// </summary>
/// <param name="dv"></param>
private void BindData(DataView dv)
{
// Sets the sorting order
dv.Sort = DataGridList.Attributes["SortField"];
if (DataGridList.Attributes["SortAscending"] == "no")
dv.Sort += " DESC";
if (dv.Count > 0)
{
DataGridList.ShowFooter = false;
int intRowCount = dv.Count;
int intPageSaze = DataGridList.PageSize;
int intPageCount = intRowCount / intPageSaze;
if (intRowCount - (intPageCount * intPageSaze) > 0)
intPageCount = intPageCount + 1;
if (DataGridList.CurrentPageIndex >= intPageCount)
DataGridList.CurrentPageIndex = intPageCount - 1;
}
else
{
DataGridList.ShowFooter = true;
DataGridList.CurrentPageIndex = 0;
}
// Re-binds the grid
NoKe = DataGridList.PageSize * DataGridList.CurrentPageIndex;
DataGridList.DataSource = dv;
DataGridList.DataBind();
int CurrentPage = DataGridList.CurrentPageIndex + 1;
lblCurrentPage.Text = CurrentPage.ToString();
lblTotalPage.Text = DataGridList.PageCount.ToString();
lblTotalRecord.Text = dv.Count.ToString();
}
/// <summary>
/// This function is responsible for loading data from database and store to Session.
/// </summary>
/// <param name="strDataSessionName"></param>
public void DataFromSourceToMemory(String strDataSessionName)
{
// Gets rows from the data source
DataSet oDS = PhysicalDataRead();
// Stores it in the session cache
Session[strDataSessionName] = oDS;
}
/// <summary>
/// This function is responsible for update data view from datagrid.
/// </summary>
/// <param name="requery">true = get data from database, false= get data from session</param>
public void UpdateDataView(bool requery)
{
// Retrieves the data
if ((Session[dsReportSessionName] == null) || (requery))
{
if (Request.QueryString["CurrentPage"] != null && Request.QueryString["CurrentPage"].ToString() != "")
DataGridList.CurrentPageIndex = int.Parse(Request.QueryString["CurrentPage"].ToString());
DataFromSourceToMemory(dsReportSessionName);
}
DataSet ds = (DataSet)Session[dsReportSessionName];
BindData(ds.Tables[0].DefaultView);
}
public void UpdateDataView()
{
// Retrieves the data
if ((Session[dsReportSessionName] == null))
{
DataFromSourceToMemory(dsReportSessionName);
}
DataSet ds = (DataSet)Session[dsReportSessionName];
BindData(ds.Tables[0].DefaultView);
}
#endregion
#region .Event DataGridList
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// HANDLERs //
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a new page.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void PageChanged(Object sender, DataGridPageChangedEventArgs e)
{
DataGridList.CurrentPageIndex = e.NewPageIndex;
DataGridList.SelectedIndex = -1;
UpdateDataView();
}
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a new page.
/// </summary>
/// <param name="sender"></param>
/// <param name="nPageIndex"></param>
public void GoToPage(Object sender, int nPageIndex)
{
DataGridPageChangedEventArgs evPage;
evPage = new DataGridPageChangedEventArgs(sender, nPageIndex);
PageChanged(sender, evPage);
}
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a first page.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void GoToFirst(Object sender, ImageClickEventArgs e)
{
GoToPage(sender, 0);
}
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a previous page.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void GoToPrev(Object sender, ImageClickEventArgs e)
{
if (DataGridList.CurrentPageIndex > 0)
{
GoToPage(sender, DataGridList.CurrentPageIndex - 1);
}
else
{
GoToPage(sender, 0);
}
}
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a next page.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void GoToNext(Object sender, System.Web.UI.ImageClickEventArgs e)
{
if (DataGridList.CurrentPageIndex < (DataGridList.PageCount - 1))
{
GoToPage(sender, DataGridList.CurrentPageIndex + 1);
}
}
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a last page.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void GoToLast(Object sender, ImageClickEventArgs e)
{
GoToPage(sender, DataGridList.PageCount - 1);
}
/// <summary>
/// This function is invoked when you click on a column's header to
/// sort by that. It just saves the current sort field name and
/// refreshes the grid.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void SortByColumn(Object sender, DataGridSortCommandEventArgs e)
{
String strSortBy = DataGridList.Attributes["SortField"];
String strSortAscending = DataGridList.Attributes["SortAscending"];
// Sets the new sorting field
DataGridList.Attributes["SortField"] = e.SortExpression;
// Sets the order (defaults to ascending). If you click on the
// sorted column, the order reverts.
DataGridList.Attributes["SortAscending"] = "yes";
if (e.SortExpression == strSortBy)
DataGridList.Attributes["SortAscending"] = (strSortAscending == "yes" ? "no" : "yes");
// Refreshes the view
OnClearSelection(null, null);
UpdateDataView();
}
/// <summary>
/// The function gets invoked when a new item is being created in
/// the datagrid. This applies to pager, header, footer, regular
/// and alternating items.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void PageItemCreated(Object sender, DataGridItemEventArgs e)
{
// Get the newly created item
ListItemType itemType = e.Item.ItemType;
//////////////////////////////////////////////////////////
// Is it the HEADER?
if (itemType == ListItemType.Header)
{
for (int i = 0; i < DataGridList.Columns.Count; i++)
{
// draw to reflect sorting
if (DataGridList.Attributes["SortField"] == DataGridList.Columns[i].SortExpression)
{
//////////////////////////////////////////////
// Should be much easier this way:
// ------------------------------------------
// TableCell cell = e.Item.Cells[i];
// Label lblSorted = new Label();
// lblSorted.Font = "webdings";
// lblSorted.Text = strOrder;
// cell.Controls.Add(lblSorted);
//
// but it seems it doesn't work <g>
//////////////////////////////////////////////
// Add a non-clickable triangle to mean desc or asc.
// The </a> ensures that what follows is non-clickable
TableCell cell = e.Item.Cells[i];
LinkButton lb = (LinkButton)cell.Controls[0];
//lb.Text += "</a> <span style=font-family:webdings;>" + GetOrderSymbol() + "</span>";
lb.Text += "</a> <img src=" + Request.ApplicationPath + "/images/icons/" + GetOrderSymbol() + " >";
}
}
}
//////////////////////////////////////////////////////////
// Is it the PAGER?
if (itemType == ListItemType.Pager)
{
// There's just one control in the list...
TableCell pager = (TableCell)e.Item.Controls[0];
// Enumerates all the items in the pager...
for (int i = 0; i < pager.Controls.Count; i += 2)
{
// It can be either a Label or a Link button
try
{
Label l = (Label)pager.Controls[i];
l.Text = "Hal " + l.Text;
l.CssClass = "CurrentPage";
}
catch
{
LinkButton h = (LinkButton)pager.Controls[i];
h.Text = "[ " + h.Text + " ]";
h.CssClass = "HotLink";
}
}
}
}
/// <summary>
/// Verifies whether the current sort is ascending or descending and
/// returns an appropriate display text (i.e., a webding)
/// </summary>
/// <returns></returns>
private String GetOrderSymbol()
{
bool bDescending = (bool)(DataGridList.Attributes["SortAscending"] == "no");
//return (bDescending ? " 6" : " 5");
return (bDescending ? "downbr.gif" : "upbr.gif");
}
/// <summary>
/// When clicked clears the current selection if any
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void OnClearSelection(Object sender, EventArgs e)
{
DataGridList.SelectedIndex = -1;
}
#endregion
#region .Event Button
/// <summary>
/// When clicked, redirect to form add for inserts a new record to the database
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void OnNewRecord(Object sender, EventArgs e)
{
string CurrentPage = DataGridList.CurrentPageIndex.ToString();
Response.Redirect("Add.aspx?CurrentPage=" + CurrentPage);
}
/// <summary>
/// When clicked, filter data.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void OnSearch(Object sender, System.EventArgs e)
{
FilterData();
}
public void FilterData()
{
if ((Session[dsReportSessionName] == null))
{
DataFromSourceToMemory(dsReportSessionName);
}
DataSet ds = (DataSet)Session[dsReportSessionName];
DataView dv = ds.Tables[0].DefaultView;
if (cmbFilterBy.SelectedValue == "Poliklinik" && cmbPoliklinik.SelectedIndex > 0)
dv.RowFilter = " PoliklinikId = " + cmbPoliklinik.SelectedValue ;
else if (cmbFilterBy.SelectedValue == "Dokter" && cmbDokter.SelectedIndex > 0)
dv.RowFilter = " DokterId = " + cmbDokter.SelectedValue;
else
dv.RowFilter = "";
BindData(dv);
}
#endregion
#region .Update Link Item Butom
public string GetJamPraktek(string JamPraktek)
{
string szResult = JamPraktek.Replace("\\r\\n","<br />");
return szResult;
}
public string GetJamPraktekSenin(string DokterId,string PoliklinikId, string JamPraktek, string CurrentPage )
{
string szResult = "";
string[] szResulTemp ;
if (JamPraktek != "")
{
if (JamPraktek.IndexOf("\\hr\\") > 0)
{
JamPraktek = JamPraktek.Replace("\\hr\\","#");
string[] temp = JamPraktek.Split('#');
for (int i = 0; i < temp.Length; i++)
{
szResulTemp = temp[i].Split('|');
if (szResult != "")
szResult += "<hr />";
szResult += szResulTemp[1] + "<br />" + szResulTemp[2];
if (Session["JadwalDokterManagement"] != null)
{
szResult += "<br /><a class=\"toolbar\" href=\"Edit.aspx?CurrentPage=" + CurrentPage + "&JadwalDokterId=" + szResulTemp[0] + "\" ";
szResult += ">" + Resources.GetString("", "Edit") + "</a>";
szResult += "<a class=\"toolbar\" href=\"Delete.aspx?CurrentPage=" + CurrentPage + "&JadwalDokterId=" + szResulTemp[0] + "\" ";
szResult += ">" + Resources.GetString("", "Delete") + "</a>";
}
}
}
else {
szResulTemp = JamPraktek.Split('|');
szResult += szResulTemp[1] + "<br />" + szResulTemp[2] ;
if (Session["JadwalDokterManagement"] != null)
{
szResult += "<br /><a class=\"toolbar\" href=\"Edit.aspx?CurrentPage=" + CurrentPage + "&JadwalDokterId=" + szResulTemp[0] + "\" ";
szResult += ">" + Resources.GetString("", "Edit") + "</a>";
szResult += "<a class=\"toolbar\" href=\"Delete.aspx?CurrentPage=" + CurrentPage + "&JadwalDokterId=" + szResulTemp[0] + "\" ";
szResult += ">" + Resources.GetString("", "Delete") + "</a>";
}
}
}
return szResult;
}
public string GetLinkButton(string JadwalDokterId, string RuangNama, string CurrentPage)
{
string szResult = "";
if (Session["JadwalDokterManagement"] != null)
{
szResult += "<a class=\"toolbar\" href=\"Edit.aspx?CurrentPage=" + CurrentPage + "&JadwalDokterId=" + JadwalDokterId + "\" ";
szResult += ">" + Resources.GetString("", "Edit") + "</a>";
szResult += "<a class=\"toolbar\" href=\"Delete.aspx?CurrentPage=" + CurrentPage + "&JadwalDokterId=" + JadwalDokterId + "\" ";
szResult += ">" + Resources.GetString("", "Delete") + "</a>";
}
return szResult;
}
#endregion
protected void cmbPoliklinik_SelectedIndexChanged(object sender, EventArgs e)
{
FilterData();
}
protected void cmbDokter_SelectedIndexChanged(object sender, EventArgs e)
{
FilterData();
}
protected void cmbFilterBy_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbFilterBy.SelectedValue == "Poliklinik")
{
cmbPoliklinik.Visible = true;
cmbDokter.Visible = false;
}
else if (cmbFilterBy.SelectedValue == "Dokter")
{
cmbPoliklinik.Visible = false;
cmbDokter.Visible = true;
}
FilterData();
}
}
| |
namespace Gu.Inject.Tests
{
using System;
using Gu.Inject.Tests.Types;
using Moq;
using NUnit.Framework;
public static class BindTests
{
private static readonly TestCaseData[] ConcreteAndInterface =
{
new(typeof(C), typeof(C)),
new(typeof(C), typeof(I1)),
new(typeof(I1), typeof(C)),
new(typeof(I1), typeof(I1)),
};
private static readonly TestCaseData[] ConcreteAndTwoInterfaces =
{
new(typeof(C), typeof(C)),
new(typeof(C), typeof(I1)),
new(typeof(C), typeof(I2)),
new(typeof(I1), typeof(C)),
new(typeof(I2), typeof(C)),
new(typeof(I1), typeof(I1)),
new(typeof(I1), typeof(I2)),
new(typeof(I2), typeof(I1)),
new(typeof(I2), typeof(I2)),
};
private static readonly TestCaseData[] ConcreteAndThreeInterfaces =
{
new(typeof(C), typeof(C)),
new(typeof(C), typeof(I1)),
new(typeof(C), typeof(I2)),
new(typeof(C), typeof(I3)),
new(typeof(I1), typeof(C)),
new(typeof(I2), typeof(C)),
new(typeof(I3), typeof(C)),
new(typeof(I1), typeof(I1)),
new(typeof(I1), typeof(I2)),
new(typeof(I1), typeof(I3)),
new(typeof(I2), typeof(I1)),
new(typeof(I2), typeof(I2)),
new(typeof(I2), typeof(I3)),
new(typeof(I3), typeof(I1)),
new(typeof(I3), typeof(I2)),
new(typeof(I3), typeof(I3)),
};
[TestCase(typeof(I1), typeof(C))]
[TestCase(typeof(I2), typeof(C))]
[TestCase(typeof(I3), typeof(C))]
[TestCase(typeof(IWith), typeof(With<DefaultCtor>))]
[TestCase(typeof(OneToMany.Abstract), typeof(OneToMany.Concrete1))]
[TestCase(typeof(OneToMany.Abstract), typeof(OneToMany.Concrete2))]
[TestCase(typeof(OneToMany.IAbstract), typeof(OneToMany.Concrete1))]
[TestCase(typeof(OneToMany.IAbstract), typeof(OneToMany.Concrete2))]
[TestCase(typeof(OneToMany.IConcrete), typeof(OneToMany.Concrete1))]
[TestCase(typeof(OneToMany.IConcrete), typeof(OneToMany.Concrete2))]
[TestCase(typeof(OneToMany.IConcrete), typeof(OneToMany.Concrete2))]
[TestCase(typeof(With<OneToMany.IConcrete>), typeof(With<OneToMany.Concrete2>))]
[TestCase(typeof(IWith<OneToMany.IConcrete>), typeof(With<OneToMany.Concrete2>))]
[TestCase(typeof(InheritNonAbstract.Foo), typeof(InheritNonAbstract.FooDerived))]
public static void BindThenGet(Type from, Type to)
{
using var kernel = new Kernel();
kernel.Bind(@from, to);
var actual = kernel.Get(@from);
Assert.AreSame(actual, kernel.Get(to));
}
[TestCaseSource(nameof(ConcreteAndInterface))]
public static void BindConcreteAndInterfaceThenGet(Type type1, Type type2)
{
using var kernel = new Kernel();
kernel.Bind<I1, C>();
Assert.AreSame(kernel.Get(type1), kernel.Get(type2));
Assert.AreSame(kernel.Get(type2), kernel.Get(type1));
}
[TestCaseSource(nameof(ConcreteAndTwoInterfaces))]
public static void BindConcreteAndTwoInterfacesThenGet(Type type1, Type type2)
{
using var kernel = new Kernel();
kernel.Bind<I1, I2, C>();
Assert.AreSame(kernel.Get(type1), kernel.Get(type2));
Assert.AreSame(kernel.Get(type2), kernel.Get(type1));
}
[TestCaseSource(nameof(ConcreteAndTwoInterfaces))]
public static void BindConcreteAndTwoInterfacesInTwoStepsThenGet(Type type1, Type type2)
{
using var kernel = new Kernel();
kernel.Bind<I1, C>();
kernel.Bind<I2, C>();
Assert.AreSame(kernel.Get(type1), kernel.Get(type2));
Assert.AreSame(kernel.Get(type2), kernel.Get(type1));
}
[TestCaseSource(nameof(ConcreteAndThreeInterfaces))]
public static void BindConcreteAndThreeInterfacesThenGet(Type type1, Type type2)
{
using var kernel = new Kernel();
kernel.Bind<I1, I2, I3, C>();
Assert.AreSame(kernel.Get(type1), kernel.Get(type2));
Assert.AreSame(kernel.Get(type2), kernel.Get(type1));
}
[TestCaseSource(nameof(ConcreteAndThreeInterfaces))]
public static void BindConcreteAndThreeInterfacesInTwoStepsThenGet(Type type1, Type type2)
{
using var kernel = new Kernel();
kernel.Bind<I1, C>();
kernel.Bind<I2, C>();
kernel.Bind<I3, C>();
Assert.AreSame(kernel.Get(type1), kernel.Get(type2));
Assert.AreSame(kernel.Get(type2), kernel.Get(type1));
}
[TestCaseSource(nameof(ConcreteAndThreeInterfaces))]
public static void BindConcreteAndThreeInterfacesRecursiveThenGet(Type type1, Type type2)
{
using var kernel = new Kernel();
kernel.Bind<I3, C>();
kernel.Bind<I1, I2>();
kernel.Bind<I2, I3>();
Assert.AreSame(kernel.Get(type1), kernel.Get(type2));
Assert.AreSame(kernel.Get(type2), kernel.Get(type1));
}
[Test]
public static void BindGenericAndTwoInterfacesThenGet()
{
using var kernel = new Kernel();
kernel.Bind<IWith, IWith<DefaultCtor>, With<DefaultCtor>>();
Assert.AreSame(kernel.Get<IWith<DefaultCtor>>(), kernel.Get<With<DefaultCtor>>());
Assert.AreSame(kernel.Get<IWith>(), kernel.Get<With<DefaultCtor>>());
}
[Test]
public static void BindInstanceThenGet()
{
using var kernel = new Kernel();
var instance = new C();
kernel.Bind(instance);
var actual = kernel.Get<C>();
Assert.AreSame(actual, instance);
}
[Test]
public static void BindMockObjectThenGet()
{
using var kernel = new Kernel();
var instance = new Mock<I1>().Object;
kernel.Bind<I1>(instance);
var actual = kernel.Get<I1>();
Assert.AreSame(actual, instance);
}
[Test]
public static void BindResolveGetThenGet()
{
using var kernel = new Kernel();
kernel.Bind<I1>(x => x.Get<C>());
var actual = kernel.Get<I1>();
Assert.AreSame(actual, kernel.Get<I1>());
}
[Test]
public static void BindFuncGetThenGet()
{
using var kernel = new Kernel();
//// ReSharper disable once AccessToDisposedClosure
kernel.Bind<I1>(() => kernel.Get<C>());
var actual = kernel.Get<I1>();
Assert.AreSame(actual, kernel.Get<I1>());
}
[TestCaseSource(nameof(ConcreteAndInterface))]
public static void BindInstanceAndInterfaceThenGet(Type type1, Type type2)
{
using var kernel = new Kernel();
kernel.Bind<I1>(new C());
Assert.AreSame(kernel.Get(type1), kernel.Get(type2));
Assert.AreSame(kernel.Get(type2), kernel.Get(type1));
}
[TestCaseSource(nameof(ConcreteAndInterface))]
public static void BindInstanceAndInterfaceExplicitThenGet(Type type1, Type type2)
{
using var kernel = new Kernel();
kernel.Bind<I1, C>(new C());
Assert.AreSame(kernel.Get(type1), kernel.Get(type2));
Assert.AreSame(kernel.Get(type2), kernel.Get(type1));
}
[TestCaseSource(nameof(ConcreteAndTwoInterfaces))]
public static void BindInstanceAndTwoInterfacesThenGet(Type type1, Type type2)
{
using var kernel = new Kernel();
kernel.Bind<I1, I2>(new C());
Assert.AreSame(kernel.Get(type1), kernel.Get(type2));
Assert.AreSame(kernel.Get(type2), kernel.Get(type1));
}
[TestCaseSource(nameof(ConcreteAndTwoInterfaces))]
public static void BindInstanceAndTwoInterfacesExplicitThenGet(Type type1, Type type2)
{
using var kernel = new Kernel();
kernel.Bind<I1, I2, C>(new C());
Assert.AreSame(kernel.Get(type1), kernel.Get(type2));
Assert.AreSame(kernel.Get(type2), kernel.Get(type1));
}
[TestCaseSource(nameof(ConcreteAndTwoInterfaces))]
public static void BindInstanceAndTwoInterfacesInStepsThenGet(Type type1, Type type2)
{
using var kernel = new Kernel();
kernel.Bind<I1, C>();
kernel.Bind<I2, C>(new C());
Assert.AreSame(kernel.Get(type1), kernel.Get(type2));
Assert.AreSame(kernel.Get(type2), kernel.Get(type1));
}
[TestCaseSource(nameof(ConcreteAndTwoInterfaces))]
public static void BindInstanceAndTwoInterfacesInStepsAndExplicitThenGet(Type type1, Type type2)
{
using var kernel = new Kernel();
kernel.Bind<I1, C>();
kernel.Bind<I2, C>();
kernel.Bind(new C());
Assert.AreSame(kernel.Get(type1), kernel.Get(type2));
Assert.AreSame(kernel.Get(type2), kernel.Get(type1));
}
[TestCaseSource(nameof(ConcreteAndInterface))]
public static void BindFuncAndInterfaceThenGet(Type type1, Type type2)
{
using var kernel = new Kernel();
kernel.Bind<I1>(() => new C());
if (type1.IsClass && type2.IsInterface)
{
_ = kernel.Get(type1);
Assert.AreEqual(
"An instance of type C was already created.\r\n" +
"The existing instance was created via constructor.\r\n" +
"This can happen by doing:\r\n" +
"1. Bind<I>(() => new C())\r\n" +
"2. Get<C>() this creates an instance of C using the constructor.\r\n" +
"3. Get<I>() this creates an instance of C using the bound Func<C> and then detects the instance created in 2.\r\n" +
"\r\n" +
"Specify explicit binding for the concrete type.\r\n" +
"For example by:\r\n" +
"Bind<I, C>(() => new C())\r\n" +
"or\r\n" +
"Bind<I, C>()\r\n" +
"Bind<C>(() => new C())",
Assert.Throws<ResolveException>(() => kernel.Get(type2))?.Message);
}
else
{
Assert.AreSame(kernel.Get(type1), kernel.Get(type2));
Assert.AreSame(kernel.Get(type2), kernel.Get(type1));
}
}
[TestCaseSource(nameof(ConcreteAndInterface))]
public static void BindFuncAndInterfaceExplicitThenGe(Type type1, Type type2)
{
using var kernel = new Kernel();
kernel.Bind<I1, C>(() => new C());
Assert.AreSame(kernel.Get(type1), kernel.Get(type2));
Assert.AreSame(kernel.Get(type2), kernel.Get(type1));
}
[TestCaseSource(nameof(ConcreteAndTwoInterfaces))]
public static void BindFuncAndTwoInterfacesThenGet(Type type1, Type type2)
{
using var kernel = new Kernel();
kernel.Bind<I1, I2>(() => new C());
if (type1.IsClass && type2.IsInterface)
{
_ = kernel.Get(type1);
Assert.AreEqual(
"An instance of type C was already created.\r\n" +
"The existing instance was created via constructor.\r\n" +
"This can happen by doing:\r\n" +
"1. Bind<I>(() => new C())\r\n" +
"2. Get<C>() this creates an instance of C using the constructor.\r\n" +
"3. Get<I>() this creates an instance of C using the bound Func<C> and then detects the instance created in 2.\r\n" +
"\r\n" +
"Specify explicit binding for the concrete type.\r\n" +
"For example by:\r\n" +
"Bind<I, C>(() => new C())\r\n" +
"or\r\n" +
"Bind<I, C>()\r\n" +
"Bind<C>(() => new C())",
Assert.Throws<ResolveException>(() => kernel.Get(type2))?.Message);
}
else
{
Assert.AreSame(kernel.Get(type1), kernel.Get(type2));
Assert.AreSame(kernel.Get(type2), kernel.Get(type1));
}
}
[TestCaseSource(nameof(ConcreteAndTwoInterfaces))]
public static void BindFuncAndTwoInterfacesExplicitThenGet(Type type1, Type type2)
{
using var kernel = new Kernel();
kernel.Bind<I1, I2, C>(() => new C());
Assert.AreSame(kernel.Get(type1), kernel.Get(type2));
Assert.AreSame(kernel.Get(type2), kernel.Get(type1));
}
[TestCaseSource(nameof(ConcreteAndTwoInterfaces))]
public static void BindFuncAndTwoInterfacesInStepsThenGet(Type type1, Type type2)
{
using var kernel = new Kernel();
kernel.Bind<I1, I2>();
kernel.Bind<I2, C>(() => new C());
Assert.AreSame(kernel.Get(type1), kernel.Get(type2));
Assert.AreSame(kernel.Get(type2), kernel.Get(type1));
}
[Test]
public static void BindResolver()
{
using var kernel = new Kernel();
kernel.Bind<C>(c => new C());
Assert.AreSame(kernel.Get<C>(), kernel.Get<C>());
}
[TestCaseSource(nameof(ConcreteAndInterface))]
public static void BindResolverAndInterface(Type type1, Type type2)
{
using var kernel = new Kernel();
kernel.Bind<I1>(_ => new C());
if (type1.IsClass && type2.IsInterface)
{
_ = kernel.Get(type1);
Assert.AreEqual(
"An instance of type C was already created.\r\n" +
"The existing instance was created via constructor.\r\n" +
"This can happen by doing:\r\n" +
"1. Bind<I>(x => new C(...))\r\n" +
"2. Get<C>() this creates an instance of C using the constructor.\r\n" +
"3. Get<I>() this creates an instance of C using the bound Func<IReadOnlyKernel, C> and then detects the instance created in 2.\r\n" +
"\r\n" +
"Specify explicit binding for the concrete type.\r\n" +
"For example by:\r\n" +
"Bind<I, C>(x => new C(...))\r\n" +
"or\r\n" +
"Bind<I, C>()\r\n" +
"Bind<C>(x => new C(...))",
Assert.Throws<ResolveException>(() => kernel.Get(type2))?.Message);
}
else
{
Assert.AreSame(kernel.Get(type1), kernel.Get(type2));
Assert.AreSame(kernel.Get(type2), kernel.Get(type1));
}
}
[TestCaseSource(nameof(ConcreteAndInterface))]
public static void BindResolverAndInterfaceExplicit(Type type1, Type type2)
{
using var kernel = new Kernel();
kernel.Bind<I1, C>(_ => new C());
Assert.AreSame(kernel.Get(type1), kernel.Get(type2));
Assert.AreSame(kernel.Get(type2), kernel.Get(type1));
}
[TestCaseSource(nameof(ConcreteAndInterface))]
public static void BindResolverAndInterfaceInSteps(Type type1, Type type2)
{
using var kernel = new Kernel();
kernel.Bind<I1, C>();
kernel.Bind(_ => new C());
Assert.AreSame(kernel.Get(type1), kernel.Get(type2));
Assert.AreSame(kernel.Get(type2), kernel.Get(type1));
}
[TestCaseSource(nameof(ConcreteAndTwoInterfaces))]
public static void BindResolverAndTwoInterfaces(Type type1, Type type2)
{
using var kernel = new Kernel();
kernel.Bind<I1, I2>(_ => new C());
if (type1.IsClass && type2.IsInterface)
{
_ = kernel.Get(type1);
Assert.AreEqual(
"An instance of type C was already created.\r\n" +
"The existing instance was created via constructor.\r\n" +
"This can happen by doing:\r\n" +
"1. Bind<I>(x => new C(...))\r\n" +
"2. Get<C>() this creates an instance of C using the constructor.\r\n" +
"3. Get<I>() this creates an instance of C using the bound Func<IReadOnlyKernel, C> and then detects the instance created in 2.\r\n" +
"\r\n" +
"Specify explicit binding for the concrete type.\r\n" +
"For example by:\r\n" +
"Bind<I, C>(x => new C(...))\r\n" +
"or\r\n" +
"Bind<I, C>()\r\n" +
"Bind<C>(x => new C(...))",
Assert.Throws<ResolveException>(() => kernel.Get(type2))?.Message);
}
else
{
Assert.AreSame(kernel.Get(type1), kernel.Get(type2));
Assert.AreSame(kernel.Get(type2), kernel.Get(type1));
}
}
[TestCaseSource(nameof(ConcreteAndTwoInterfaces))]
public static void BindResolverAndTwoInterfacesExplicit(Type type1, Type type2)
{
using var kernel = new Kernel();
kernel.Bind<I1, I2, C>(_ => new C());
Assert.AreSame(kernel.Get(type1), kernel.Get(type2));
Assert.AreSame(kernel.Get(type2), kernel.Get(type1));
}
[TestCaseSource(nameof(ConcreteAndTwoInterfaces))]
public static void BindResolverAndTwoInterfacesInSteps(Type type1, Type type2)
{
using var kernel = new Kernel();
kernel.Bind<I1, I2>();
kernel.Bind<I2, C>(_ => new C());
Assert.AreSame(kernel.Get(type1), kernel.Get(type2));
Assert.AreSame(kernel.Get(type2), kernel.Get(type1));
}
[Test]
public static void BindUninitializedThenGetCircularSimple()
{
using var kernel = new Kernel();
kernel.BindUninitialized<SimpleCircular.A>();
var a = kernel.Get<SimpleCircular.A>();
var b = kernel.Get<SimpleCircular.B>();
Assert.AreSame(a.B, b);
Assert.AreSame(a, b.A);
}
[Test]
public static void BindUninitializedTheGetCircularComplex()
{
using var kernel = new Kernel();
kernel.BindUninitialized<ComplexCircular.A>();
var a = kernel.Get<ComplexCircular.A>();
var b = kernel.Get<ComplexCircular.B>();
var c = kernel.Get<ComplexCircular.C>();
var d = kernel.Get<ComplexCircular.D>();
var e = kernel.Get<ComplexCircular.E>();
var f = kernel.Get<ComplexCircular.F>();
var g = kernel.Get<ComplexCircular.G>();
Assert.AreSame(a.B, b);
Assert.AreSame(a.E, e);
Assert.AreSame(b.C, c);
Assert.AreSame(b.D, d);
Assert.AreSame(c, kernel.Get<ComplexCircular.C>());
Assert.AreSame(d, kernel.Get<ComplexCircular.D>());
Assert.AreSame(e.F, f);
Assert.AreSame(e.G, g);
}
}
}
| |
// $Id$
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
using System;
using System.Threading;
using NUnit.Framework;
namespace Org.Apache.Etch.Bindings.Csharp.Util
{
internal delegate void run();
[TestFixture]
public class TestCircularQueue
{
[TestFixtureSetUp]
public void First()
{
Console.WriteLine();
Console.Write("TestCircularQueue");
}
[Test]
[ExpectedException( typeof( ArgumentOutOfRangeException ) )]
public void construct1()
{
new CircularQueue<int?>( 0 );
}
[Test]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void construct2()
{
new CircularQueue<int?>( -1 );
}
[Test]
public void construct3()
{
CircularQueue<int?> queue = new CircularQueue<int?>( 1 );
Assert.AreEqual( 1, queue.Size() );
}
[Test]
public void construct4()
{
CircularQueue<int?> queue = new CircularQueue<int?>( 2 );
Assert.AreEqual( 2, queue.Size() );
}
[Test]
public void construct5()
{
CircularQueue<int?> queue = new CircularQueue<int?>();
Assert.AreEqual( 10, queue.Size() );
}
[Test]
public void putget1()
{
CircularQueue<int?> queue = new CircularQueue<int?>();
Assert.AreEqual( 0, queue.Count() );
Assert.IsTrue( queue.IsEmpty() );
Assert.IsFalse( queue.IsFull() );
for (int i = 0; i < 10000; i++)
{
queue.Put( i );
Assert.AreEqual( 1, queue.Count() );
Assert.IsFalse( queue.IsEmpty() );
Assert.AreEqual( i, queue.Get() );
Assert.AreEqual( 0, queue.Count() );
Assert.IsTrue( queue.IsEmpty() );
}
}
[Test]
public void putget2()
{
CircularQueue<int?> queue = new CircularQueue<int?>();
Assert.IsNull( queue.Get( 1 ) );
Assert.IsNull( queue.Get( -1 ) );
Assert.IsNull( queue.Get( 10 ) );
queue.Put( 9 );
Assert.AreEqual( 9, queue.Get( 1 ) );
queue.Put( 9 );
Assert.AreEqual( 9, queue.Get( -1 ) );
queue.Put( 9 );
Assert.AreEqual( 9, queue.Get( 10 ) );
Assert.IsNull( queue.Get( 1 ) );
Assert.IsNull( queue.Get( -1 ) );
Assert.IsNull( queue.Get( 10 ) );
/* long t0;
double t;
t0 = HPTimer.Now();
Assert.IsNull(queue.Get(10));
t = ( HPTimer.Now() - t0) / 1000000.0;
assertRelError( 10, t, 1 );
t0 = HPTimer.Now();
Assert.IsNull(queue.Get(20));
t = (HPTimer.Now() - t0) / 1000000.0;
assertRelError( 20, t, 1 );
t0 = HPTimer.Now();
Assert.IsNull( queue.Get( 30 ) );
t = (HPTimer.Now() - t0) / 1000000.0;
assertRelError( 30, t, 1 ); */
}
[Test]
public void putget3()
{
CircularQueue<int?> queue = new CircularQueue<int?>();
Assert.IsTrue( queue.Put( 1 ) );
Assert.IsTrue( queue.Put( 2 ) );
Assert.IsTrue( queue.Put( 3 ) );
Assert.AreEqual( 1, queue.Get() );
Assert.AreEqual( 2, queue.Get() );
Assert.AreEqual( 3, queue.Get() );
Assert.IsTrue( queue.Put( 1, 0 ) );
Assert.IsTrue( queue.Put( 2, 0 ) );
Assert.IsTrue( queue.Put( 3, 0 ) );
Assert.AreEqual( 1, queue.Get( 0 ) );
Assert.AreEqual( 2, queue.Get( 0 ) );
Assert.AreEqual( 3, queue.Get( 0 ) );
Assert.IsTrue( queue.Put( 1, -1 ) );
Assert.IsTrue( queue.Put( 2, -1 ) );
Assert.IsTrue( queue.Put( 3, -1 ) );
Assert.AreEqual( 1, queue.Get( -1 ) );
Assert.AreEqual( 2, queue.Get( -1 ) );
Assert.AreEqual( 3, queue.Get( -1 ) );
Assert.IsTrue( queue.Put( 1, 1 ) );
Assert.IsTrue( queue.Put( 2, 1 ) );
Assert.IsTrue( queue.Put( 3, 1 ) );
Assert.AreEqual( 1, queue.Get( 1 ) );
Assert.AreEqual( 2, queue.Get( 1 ) );
Assert.AreEqual( 3, queue.Get( 1 ) );
}
[Test]
public void get()
{
CircularQueue<int?> queue = new CircularQueue<int?>( 1 );
// System.nanoTime();
HPTimer.Now();
Assert.IsNull( queue.Get( 10 ) );
assertRelError( 1, 1, 1 );
foreach (int i in new int[] { 10, 20, 30, 50, 80, 130, 210, 340, 550, 890, 1440 })
{
// Console.WriteLine( "get delay = {0}\n", i );
long t0 = HPTimer.Now();
Assert.IsNull( queue.Get( i ) );
/* double t = (HPTimer.Now() - t0) / 1000000.0;
assertRelError( i, t, 2 ); */
}
}
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void put()
{
CircularQueue<int?> queue = new CircularQueue<int?>();
queue.Put( null );
}
[Test]
public void full()
{
CircularQueue<int?> queue = new CircularQueue<int?>( 1 );
Assert.IsFalse( queue.IsFull() );
Assert.IsTrue( queue.Put( 0 ) );
Assert.IsTrue( queue.IsFull() );
Assert.AreEqual( 0, queue.Get() );
Assert.IsFalse( queue.IsFull() );
Assert.IsTrue( queue.Put( 0 ) );
Assert.IsFalse( queue.Put( 0, -1 ) );
Assert.IsFalse( queue.Put( 0, 1 ) );
Assert.IsFalse( queue.Put( 0, 10 ) );
}
[Test]
public void close1()
{
CircularQueue<int?> queue = new CircularQueue<int?>();
Assert.IsFalse( queue.IsClosed() );
queue.Close();
Assert.IsTrue( queue.IsClosed() );
Assert.IsNull( queue.Get() );
Assert.IsNull( queue.Get( -1 ) );
Assert.IsNull( queue.Get( 0 ) );
Assert.IsNull( queue.Get( 1 ) );
queue.Close();
Assert.IsTrue( queue.IsClosed() );
}
[Test]
public void close2()
{
CircularQueue<int?> queue = new CircularQueue<int?>();
Assert.IsFalse( queue.IsClosed() );
queue.Close();
Assert.IsTrue( queue.IsClosed() );
Assert.IsFalse( queue.Put( 0 ) );
Assert.IsFalse( queue.Put( 0, -1 ) );
Assert.IsFalse( queue.Put( 0, 0 ) );
Assert.IsFalse( queue.Put( 0, 1 ) );
queue.Close();
Assert.IsTrue( queue.IsClosed() );
}
[Test]
public void close3()
{
CircularQueue<int?> queue = new CircularQueue<int?>();
queue.Put( 1 );
queue.Put( 2 );
queue.Put( 3 );
queue.Close();
Assert.AreEqual( 1, queue.Get() );
Assert.AreEqual( 2, queue.Get() );
Assert.AreEqual( 3, queue.Get() );
Assert.IsNull( queue.Get() );
}
[Test]
public void delay1()
{
CircularQueue<int?> queue = new CircularQueue<int?>();
Delay( 10, delegate() {queue.Put( 99 ); } );
Assert.AreEqual( 99, queue.Get() );
Delay( 10, delegate() { queue.Close(); } );
Assert.IsNull( queue.Get() );
}
[Test]
public void delay2()
{
CircularQueue<int?> queue = new CircularQueue<int?>( 1 );
Assert.IsTrue( queue.Put( 1 ) );
Delay( 10, delegate() { Assert.AreEqual( 1, queue.Get() ); } );
Assert.IsTrue( queue.Put( 2 ) );
Assert.AreEqual( 2, queue.Get() );
Assert.IsTrue( queue.Put( 1 ) );
Delay(10, delegate() { queue.Close(); });
Assert.IsFalse( queue.Put( 2 ) );
Assert.AreEqual( 1, queue.Get() );
Assert.IsNull( queue.Get() );
}
[Test]
public void stress1()
{
CircularQueue<int?> queue = new CircularQueue<int?>( 1 );
int n = 10000;
Thread t = new Thread(
delegate()
{
for (int i = 0; i < n; i++)
{
try
{
queue.Put( i );
}
catch ( ThreadInterruptedException e )
{
Console.WriteLine(e);
}
}
}
);
t.Start();
for (int i = 0; i < n; i++)
Assert.AreEqual(i, queue.Get());
}
[Test]
public void stress2()
{
CircularQueue<int?> queue = new CircularQueue<int?>(1);
int n = 1000;
Thread t = new Thread(
delegate()
{
for (int i = 0; i < n; i++)
{
try
{
Thread.Sleep(5);
queue.Put(i);
}
catch (ThreadInterruptedException e)
{
Console.WriteLine(e);
}
}
}
);
t.Start();
for (int i = 0; i < n; i++)
Assert.AreEqual(i, queue.Get());
}
[Test]
public void stress3()
{
CircularQueue<int?> queue = new CircularQueue<int?>(1);
int n = 1000;
Thread t = new Thread(
delegate()
{
for (int i = 0; i < n; i++)
{
try
{
queue.Put(i);
}
catch (ThreadInterruptedException e)
{
Console.WriteLine(e);
}
}
}
);
t.Start();
for (int i = 0; i < n; i++)
{
Thread.Sleep(5);
Assert.AreEqual(i, queue.Get());
}
}
[Test]
public void stress4()
{
CircularQueue<int?> queue = new CircularQueue<int?>();
// we will setup two threads waiting to get and
// then in a single synchronized step put two
// items in the queue. the first thread will be
// woken to get, and once done the second thread
// should be woken by the first.
Thread t1 = new Thread(
delegate()
{
try
{
Assert.IsNotNull( queue.Get() );
}
catch ( ThreadInterruptedException e )
{
Console.WriteLine(e);
}
}
);
Thread t2 = new Thread(
delegate()
{
try
{
Assert.IsNotNull(queue.Get());
}
catch (ThreadInterruptedException e)
{
Console.WriteLine(e);
}
}
);
t1.Start();
t2.Start();
// wait until both threads are waiting on queue...
Thread.Sleep(100);
lock (queue)
{
queue.Put(1);
queue.Put(2);
}
harvest(t1);
harvest(t2);
}
[Test]
public void stress5()
{
CircularQueue<int?> queue = new CircularQueue<int?>( 3 );
// we will setup two threads waiting to put to the queue,
// then in a single synchronized step, read two items from
// the queue. the first thread will be woken to put, and
// once done the second thread should be woken by the first.
queue.Put( 0 );
queue.Put( 1 );
queue.Put( 2 );
Assert.IsTrue( queue.IsFull() );
Thread t1 = new Thread(
delegate()
{
try
{
Assert.IsTrue( queue.Put( 3 ) );
}
catch ( ThreadInterruptedException e )
{
Console.WriteLine(e);
}
}
);
Thread t2 = new Thread(
delegate()
{
try
{
Assert.IsTrue( queue.Put( 4 ) );
}
catch ( ThreadInterruptedException e )
{
Console.WriteLine(e);
}
}
);
t1.Start();
t2.Start();
// wait until both threads are waiting on queue...
Thread.Sleep(100);
lock (queue)
{
Assert.IsNotNull(queue.Get());
Assert.IsNotNull(queue.Get());
}
harvest(t1);
harvest(t2);
}
[Test]
public void stress6()
{
CircularQueue<int?> queue = new CircularQueue<int?>(5);
// start two getters and two putters and let 'em duke it out...
Thread t1 = new Thread(
delegate()
{
try
{
for (int i = 0; i < 100; i++)
Assert.IsTrue(queue.Put(i));
}
catch (ThreadInterruptedException e)
{
Console.WriteLine(e);
}
}
);
Thread t2 = new Thread(
delegate()
{
try
{
for (int i = 0; i < 100; i++)
Assert.IsTrue(queue.Put(i));
}
catch (ThreadInterruptedException e)
{
Console.WriteLine(e);
}
}
);
Thread t3 = new Thread(
delegate()
{
try
{
for (int i = 0; i < 100; i++)
Assert.IsNotNull(queue.Get());
}
catch (ThreadInterruptedException e)
{
Console.WriteLine(e);
}
}
);
Thread t4 = new Thread(
delegate()
{
try
{
for (int i = 0; i < 100; i++)
Assert.IsNotNull(queue.Get());
}
catch (ThreadInterruptedException e)
{
Console.WriteLine(e);
}
}
);
t1.Start();
t2.Start();
t3.Start();
t4.Start();
harvest(t1);
harvest(t2);
harvest(t3);
harvest(t4);
}
[Test]
public void harvest1()
{
Thread t = new Thread(
delegate()
{
}
);
t.Start();
harvest(t);
}
[Test]
[ExpectedException(typeof(TimeoutException))]
public void harvest2()
{
Thread t = new Thread(
delegate()
{
try
{
Thread.Sleep(10000);
}
catch (ThreadInterruptedException e)
{
Console.WriteLine(e);
}
}
);
t.Start();
harvest(t);
}
private void harvest(Thread t)
{
t.Join(1000);
if (t.IsAlive)
{
t.Interrupt();
throw new TimeoutException(t.Name + " is stuck");
}
}
[Test]
public void testRelError1()
{
assertRelError(10, 9, .11);
assertRelError(10, 11, .14);
assertRelError(20, 19, .07);
assertRelError(19, 23, .22);
}
[Test]
[ExpectedException(typeof(AssertionException))]
public void testRelError2()
{
assertRelError(9, 8, .1);
}
[Test]
[ExpectedException(typeof(AssertionException))]
public void testRelError3()
{
assertRelError(9, 10, .1);
}
[Test]
public void testAbsError1()
{
AssertAbsError(11, 15, 4);
AssertAbsError(15, 10, 5);
AssertAbsError(5, 3, 2);
AssertAbsError(4, 7, 3);
}
[Test]
[ExpectedException(typeof(AssertionException))]
public void testAbsError2()
{
AssertAbsError(11, 15, 3);
}
[Test]
[ExpectedException(typeof(AssertionException))]
public void testAbsError3()
{
AssertAbsError(19, 15, 3);
}
private void Delay( int delay, run del )
{
Thread t = new Thread(delegate()
{
try
{
Thread.Sleep(delay);
del();
}
catch (Exception e)
{
Console.WriteLine(e);
}
});
t.Start();
}
private void assertRelError( double expected, double actual, double error )
{
double relError = RelError( expected, actual );
if (relError > error)
Assert.Fail( String.Format( "expected: {0} but was: {1} relative error: {2}", expected, actual, relError ) );
}
private void AssertAbsError( double expected, double actual, double error )
{
double absError = AbsError( expected, actual );
if (absError > error)
Assert.Fail( String.Format( "expected: {0} but was: {1} absolute error: {2}", expected, actual, absError ) );
}
private double RelError( double expected, double actual )
{
return AbsError( expected, actual ) / expected;
}
private double AbsError( double expected, double actual )
{
return Math.Abs( expected - actual );
}
}
}
| |
// This source code is dual-licensed under the Apache License, version
// 2.0, and the Mozilla Public License, version 1.1.
//
// The APL v2.0:
//
//---------------------------------------------------------------------------
// Copyright (C) 2007-2014 GoPivotal, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//---------------------------------------------------------------------------
//
// The MPL v1.1:
//
//---------------------------------------------------------------------------
// The contents of this file are subject to the Mozilla Public License
// Version 1.1 (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.mozilla.org/MPL/
//
// Software distributed under the License is distributed on an "AS IS"
// basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
// the License for the specific language governing rights and
// limitations under the License.
//
// The Original Code is RabbitMQ.
//
// The Initial Developer of the Original Code is GoPivotal, Inc.
// Copyright (c) 2007-2014 GoPivotal, Inc. All rights reserved.
//---------------------------------------------------------------------------
using System;
using System.Net;
using System.Text;
using System.IO;
using RabbitMQ.Client;
using RabbitMQ.Util;
namespace RabbitMQ.Client.Content {
///<summary>Tags used in parsing and generating StreamWireFormatting message bodies.</summary>
public enum StreamWireFormattingTag {
Bool = 0x01,
Byte = 0x02,
Bytes = 0x03,
Int16 = 0x04,
Char = 0x05,
Int32 = 0x06,
Int64 = 0x07,
Single = 0x08,
Double = 0x09,
String = 0x0A,
Null = 0x0B
};
///<summary>Internal support class for use in reading and writing
///information binary-compatible with QPid's "StreamMessage" wire
///encoding.</summary>
public class StreamWireFormatting {
public static bool ReadBool(NetworkBinaryReader reader) {
object value = ReadNonnullObject("bool", reader);
if (value is bool) {
return (bool) value;
}
if (value is string) {
return PrimitiveParser.ParseBool((string) value);
}
PrimitiveParser.InvalidConversion("bool", value);
return false;
}
public static int ReadInt32(NetworkBinaryReader reader) {
object value = ReadNonnullObject("int", reader);
if (value is int || value is short || value is byte) {
return (int) value;
}
if (value is string) {
return PrimitiveParser.ParseInt((string) value);
}
PrimitiveParser.InvalidConversion("int", value);
return 0;
}
public static short ReadInt16(NetworkBinaryReader reader) {
object value = ReadNonnullObject("short", reader);
if (value is short || value is byte) {
return (short) value;
}
if (value is string) {
return PrimitiveParser.ParseShort((string) value);
}
PrimitiveParser.InvalidConversion("short", value);
return 0;
}
public static byte ReadByte(NetworkBinaryReader reader) {
object value = ReadNonnullObject("byte", reader);
if (value is byte) {
return (byte) value;
}
if (value is string) {
return PrimitiveParser.ParseByte((string) value);
}
PrimitiveParser.InvalidConversion("byte", value);
return 0;
}
public static char ReadChar(NetworkBinaryReader reader) {
object value = ReadNonnullObject("char", reader);
if (value is char) {
return (char) value;
}
PrimitiveParser.InvalidConversion("char", value);
return (char) 0;
}
public static long ReadInt64(NetworkBinaryReader reader) {
object value = ReadNonnullObject("long", reader);
if (value is long || value is int || value is short || value is byte) {
return (long) value;
}
if (value is string) {
return PrimitiveParser.ParseLong((string) value);
}
PrimitiveParser.InvalidConversion("long", value);
return 0;
}
public static float ReadSingle(NetworkBinaryReader reader) {
object value = ReadNonnullObject("float", reader);
if (value is float) {
return (float) value;
}
if (value is string) {
return PrimitiveParser.ParseFloat((string) value);
}
PrimitiveParser.InvalidConversion("float", value);
return 0;
}
public static double ReadDouble(NetworkBinaryReader reader) {
object value = ReadNonnullObject("double", reader);
if (value is double || value is float) {
return (double) value;
}
if (value is string) {
return PrimitiveParser.ParseDouble((string) value);
}
PrimitiveParser.InvalidConversion("double", value);
return 0;
}
public static byte[] ReadBytes(NetworkBinaryReader reader) {
object value = ReadObject(reader);
if (value == null) {
return null;
}
if (value is byte[]) {
return (byte[]) value;
}
PrimitiveParser.InvalidConversion("byte[]", value);
return null;
}
public static string ReadString(NetworkBinaryReader reader) {
object value = ReadObject(reader);
if (value == null) {
return null;
}
if (value is byte[]) {
PrimitiveParser.InvalidConversion("string", value);
return null;
}
return value.ToString();
}
///<exception cref="ProtocolViolationException"/>
public static object ReadNonnullObject(string target, NetworkBinaryReader reader) {
object value = ReadObject(reader);
if (value == null) {
throw new ProtocolViolationException(string.Format("Null {0} value not permitted",
target));
}
return value;
}
///<exception cref="EndOfStreamException"/>
///<exception cref="ProtocolViolationException"/>
public static object ReadObject(NetworkBinaryReader reader) {
int typeTag = reader.ReadByte();
switch (typeTag) {
case -1:
throw new EndOfStreamException("End of StreamMessage reached");
case (int) StreamWireFormattingTag.Bool: {
byte value = reader.ReadByte();
switch (value) {
case 0x00: return false;
case 0x01: return true;
default: {
string message =
string.Format("Invalid boolean value in StreamMessage: {0}", value);
throw new ProtocolViolationException(message);
}
}
}
case (int) StreamWireFormattingTag.Byte:
return reader.ReadByte();
case (int) StreamWireFormattingTag.Bytes: {
int length = reader.ReadInt32();
if (length == -1) {
return null;
} else {
return reader.ReadBytes(length);
}
}
case (int) StreamWireFormattingTag.Int16:
return reader.ReadInt16();
case (int) StreamWireFormattingTag.Char:
return (char) reader.ReadUInt16();
case (int) StreamWireFormattingTag.Int32:
return reader.ReadInt32();
case (int) StreamWireFormattingTag.Int64:
return reader.ReadInt64();
case (int) StreamWireFormattingTag.Single:
return reader.ReadSingle();
case (int) StreamWireFormattingTag.Double:
return reader.ReadDouble();
case (int) StreamWireFormattingTag.String:
return ReadUntypedString(reader);
case (int) StreamWireFormattingTag.Null:
return null;
default: {
string message = string.Format("Invalid type tag in StreamMessage: {0}",
typeTag);
throw new ProtocolViolationException(message);
}
}
}
public static string ReadUntypedString(NetworkBinaryReader reader) {
BinaryWriter buffer = NetworkBinaryWriter.TemporaryBinaryWriter(256);
while (true) {
byte b = reader.ReadByte();
if (b == 0) {
return Encoding.UTF8.GetString(NetworkBinaryWriter.TemporaryContents(buffer));
} else {
buffer.Write(b);
}
}
}
public static void WriteBool(NetworkBinaryWriter writer, bool value) {
writer.Write((byte) StreamWireFormattingTag.Bool);
writer.Write(value ? (byte) 0x01 : (byte) 0x00);
}
public static void WriteInt32(NetworkBinaryWriter writer, int value) {
writer.Write((byte) StreamWireFormattingTag.Int32);
writer.Write(value);
}
public static void WriteInt16(NetworkBinaryWriter writer, short value) {
writer.Write((byte) StreamWireFormattingTag.Int16);
writer.Write(value);
}
public static void WriteByte(NetworkBinaryWriter writer, byte value) {
writer.Write((byte) StreamWireFormattingTag.Byte);
writer.Write(value);
}
public static void WriteChar(NetworkBinaryWriter writer, char value) {
writer.Write((byte) StreamWireFormattingTag.Char);
writer.Write((ushort) value);
}
public static void WriteInt64(NetworkBinaryWriter writer, long value) {
writer.Write((byte) StreamWireFormattingTag.Int64);
writer.Write(value);
}
public static void WriteSingle(NetworkBinaryWriter writer, float value) {
writer.Write((byte) StreamWireFormattingTag.Single);
writer.Write(value);
}
public static void WriteDouble(NetworkBinaryWriter writer, double value) {
writer.Write((byte) StreamWireFormattingTag.Double);
writer.Write(value);
}
public static void WriteBytes(NetworkBinaryWriter writer,
byte[] value,
int offset,
int length)
{
writer.Write((byte) StreamWireFormattingTag.Bytes);
writer.Write(length);
writer.Write(value, offset, length);
}
public static void WriteBytes(NetworkBinaryWriter writer, byte[] value) {
WriteBytes(writer, value, 0, value.Length);
}
public static void WriteString(NetworkBinaryWriter writer, string value) {
writer.Write((byte) StreamWireFormattingTag.String);
WriteUntypedString(writer, value);
}
///<exception cref="ProtocolViolationException"/>
public static void WriteObject(NetworkBinaryWriter writer, object value) {
if (value is bool) { WriteBool(writer, (bool) value); }
else if (value is int) { WriteInt32(writer, (int) value); }
else if (value is short) { WriteInt16(writer, (short) value); }
else if (value is byte) { WriteByte(writer, (byte) value); }
else if (value is char) { WriteChar(writer, (char) value); }
else if (value is long) { WriteInt64(writer, (long) value); }
else if (value is float) { WriteSingle(writer, (float) value); }
else if (value is double) { WriteDouble(writer, (double) value); }
else if (value is byte[]) { WriteBytes(writer, (byte[]) value); }
else if (value is BinaryTableValue) { WriteBytes(writer,
((BinaryTableValue) value).Bytes); }
else if (value is string) { WriteString(writer, (string) value); }
else {
string message = string.Format("Invalid object in StreamMessage.WriteObject: {0}",
value);
throw new ProtocolViolationException(message);
}
}
public static void WriteUntypedString(NetworkBinaryWriter writer, string value) {
writer.Write(Encoding.UTF8.GetBytes(value));
writer.Write((byte) 0);
}
}
}
| |
using System.Collections.Generic;
using System.Linq;
using System.Text;
using StructuredLogViewer;
namespace Microsoft.Build.Logging.StructuredLogger
{
public class ProxyNode : TextNode
{
public BaseNode Original { get; set; }
public SearchResult SearchResult { get; set; }
private List<object> highlights;
public List<object> Highlights
{
get
{
if (highlights == null)
{
highlights = new List<object>();
Populate(SearchResult);
}
return highlights;
}
}
public static string GetNodeText(BaseNode node)
{
if (node is Target t)
{
return t.Name;
}
else if (node is Project project)
{
return $"{project.Name} {project.TargetFramework}{project.TargetsDisplayText}";
}
else if (node is ProjectEvaluation evaluation)
{
return $"{evaluation.Name} {evaluation.EvaluationText}";
}
return node.ToString();
}
public void Populate(SearchResult result)
{
if (result == null)
{
return;
}
var node = result.Node;
if (result.WordsInFields.Count == 0)
{
if (result.MatchedByType)
{
Highlights.Add(new HighlightedText { Text = OriginalType });
}
Highlights.Add((Highlights.Count > 0 ? " " : "") + TextUtilities.ShortenValue(GetNodeText(node), "..."));
AddDuration(result);
return;
}
string typePrefix = OriginalType;
if (typePrefix != Strings.Folder)
{
Highlights.Add(typePrefix);
}
// NameValueNode is special case: have to show name=value when searched only in one (name or value)
var nameValueNode = node as NameValueNode;
var namedNode = node as NamedNode;
bool nameFound = false;
bool valueFound = false;
bool namedNodeNameFound = false;
foreach (var fieldText in result.WordsInFields)
{
if (nameValueNode != null)
{
if (!nameFound && fieldText.field.Equals(nameValueNode.Name))
{
nameFound = true;
}
if (!valueFound && fieldText.field.Equals(nameValueNode.Value))
{
valueFound = true;
}
}
else if (namedNode != null && !namedNodeNameFound)
{
if (fieldText.field.Equals(namedNode.Name))
{
namedNodeNameFound = true;
}
}
}
if (namedNode != null && !namedNodeNameFound)
{
Highlights.Add((Highlights.Count > 0 ? " " : "") + namedNode.Name);
if (GetNodeDifferentiator(node) is object differentiator)
{
Highlights.Add(differentiator);
}
}
foreach (var wordsInField in result.WordsInFields.GroupBy(t => t.field, t => t.match))
{
var fieldText = wordsInField.Key;
if (fieldText == OriginalType || (node is Task task && task.IsDerivedTask))
{
// OriginalType already added above
continue;
}
if (Highlights.Count > 0)
{
Highlights.Add(" ");
}
if (nameValueNode != null && fieldText.Equals(nameValueNode.Value) && !nameFound)
{
Highlights.Add(nameValueNode.Name + " = ");
}
fieldText = TextUtilities.ShortenValue(fieldText, "...");
var highlightSpans = TextUtilities.GetHighlightedSpansInText(fieldText, wordsInField);
int index = 0;
foreach (var span in highlightSpans)
{
if (span.Start > index)
{
Highlights.Add(fieldText.Substring(index, span.Start - index));
}
Highlights.Add(new HighlightedText { Text = fieldText.Substring(span.Start, span.Length) });
index = span.End;
}
if (index < fieldText.Length)
{
Highlights.Add(fieldText.Substring(index, fieldText.Length - index));
}
if (nameValueNode != null && wordsInField.Key.Equals(nameValueNode.Name))
{
if (!valueFound)
{
Highlights.Add(" = " + TextUtilities.ShortenValue(nameValueNode.Value, "..."));
}
else
{
Highlights.Add(" = ");
}
}
if (namedNode != null && namedNode.Name == wordsInField.Key)
{
if (GetNodeDifferentiator(node) is object differentiator)
{
Highlights.Add(differentiator);
}
}
}
AddDuration(result);
}
private object GetNodeDifferentiator(BaseNode node)
{
if (node is Project project)
{
var result = "";
if (!string.IsNullOrEmpty(project.TargetFramework))
{
result += " " + project.TargetFramework;
}
if (!string.IsNullOrEmpty(project.TargetsDisplayText))
{
result += " " + project.TargetsDisplayText;
}
if (!string.IsNullOrEmpty(result))
{
return result;
}
}
return null;
}
private void AddDuration(SearchResult result)
{
if (result.StartTime != default)
{
Highlights.Add(new HighlightedText { Text = " " + TextUtilities.Display(result.StartTime), Style = "time" });
}
if (result.EndTime != default)
{
Highlights.Add(new HighlightedText { Text = " " + TextUtilities.Display(result.EndTime), Style = "time" });
}
if (result.Duration != default)
{
Highlights.Add(new HighlightedText { Text = " " + TextUtilities.DisplayDuration(result.Duration), Style = "time" });
}
}
public string OriginalType
{
get
{
if (Original is Task)
{
return nameof(Task);
}
return Original.GetType().Name;
}
}
public string ProjectExtension => GetProjectFileExtension();
private string GetProjectFileExtension()
{
string result = null;
if (Original is Project project)
{
result = project.ProjectFileExtension;
}
else if (Original is ProjectEvaluation evaluation)
{
result = evaluation.ProjectFileExtension;
}
if (result != null && result != ".sln" && result != ".csproj")
{
result = "other";
}
return result;
}
public override string TypeName => nameof(ProxyNode);
public override string ToString()
{
var sb = new StringBuilder();
foreach (var highlight in Highlights)
{
sb.Append(highlight.ToString());
}
return sb.ToString();
}
}
}
| |
using System;
using System.Text;
namespace Mictlanix.BE.Web.Utils
{
public enum CodeSet
{
CodeA
,CodeB
// ,CodeC // not supported
}
/// <summary>
/// Represent the set of code values to be output into barcode form
/// </summary>
public class Code128Content
{
private int[] mCodeList;
/// <summary>
/// Create content based on a string of ASCII data
/// </summary>
/// <param name="AsciiData">the string that should be represented</param>
public Code128Content( string AsciiData )
{
mCodeList = StringToCode128(AsciiData);
}
/// <summary>
/// Provides the Code128 code values representing the object's string
/// </summary>
public int[] Codes
{
get
{
return mCodeList;
}
}
/// <summary>
/// Transform the string into integers representing the Code128 codes
/// necessary to represent it
/// </summary>
/// <param name="AsciiData">String to be encoded</param>
/// <returns>Code128 representation</returns>
private int[] StringToCode128( string AsciiData )
{
// turn the string into ascii byte data
byte[] asciiBytes = Encoding.ASCII.GetBytes( AsciiData );
// decide which codeset to start with
Code128Code.CodeSetAllowed csa1 = asciiBytes.Length>0 ? Code128Code.CodesetAllowedForChar( asciiBytes[0] ) : Code128Code.CodeSetAllowed.CodeAorB;
Code128Code.CodeSetAllowed csa2 = asciiBytes.Length>0 ? Code128Code.CodesetAllowedForChar( asciiBytes[1] ) : Code128Code.CodeSetAllowed.CodeAorB;
CodeSet currcs = GetBestStartSet(csa1,csa2);
// set up the beginning of the barcode
System.Collections.ArrayList codes = new System.Collections.ArrayList(asciiBytes.Length + 3); // assume no codeset changes, account for start, checksum, and stop
codes.Add(Code128Code.StartCodeForCodeSet(currcs));
// add the codes for each character in the string
for (int i = 0; i < asciiBytes.Length; i++)
{
int thischar = asciiBytes[i];
int nextchar = asciiBytes.Length>(i+1) ? asciiBytes[i+1] : -1;
codes.AddRange( Code128Code.CodesForChar(thischar, nextchar, ref currcs) );
}
// calculate the check digit
int checksum = (int)(codes[0]);
for (int i = 1; i < codes.Count; i++)
{
checksum += i * (int)(codes[i]);
}
codes.Add( checksum % 103 );
codes.Add( Code128Code.StopCode() );
int[] result = codes.ToArray(typeof(int)) as int[];
return result;
}
/// <summary>
/// Determines the best starting code set based on the the first two
/// characters of the string to be encoded
/// </summary>
/// <param name="csa1">First character of input string</param>
/// <param name="csa2">Second character of input string</param>
/// <returns>The codeset determined to be best to start with</returns>
private CodeSet GetBestStartSet( Code128Code.CodeSetAllowed csa1, Code128Code.CodeSetAllowed csa2 )
{
int vote = 0;
vote += (csa1==Code128Code.CodeSetAllowed.CodeA) ? 1 : 0;
vote += (csa1==Code128Code.CodeSetAllowed.CodeB) ? -1 : 0;
vote += (csa2==Code128Code.CodeSetAllowed.CodeA) ? 1 : 0;
vote += (csa2==Code128Code.CodeSetAllowed.CodeB) ? -1 : 0;
return (vote>0) ? CodeSet.CodeA : CodeSet.CodeB; // ties go to codeB due to my own prejudices
}
}
/// <summary>
/// Static tools for determining codes for individual characters in the content
/// </summary>
public static class Code128Code
{
#region Constants
private const int cSHIFT = 98;
private const int cCODEA = 101;
private const int cCODEB = 100;
private const int cSTARTA = 103;
private const int cSTARTB = 104;
private const int cSTOP = 106;
#endregion
/// <summary>
/// Get the Code128 code value(s) to represent an ASCII character, with
/// optional look-ahead for length optimization
/// </summary>
/// <param name="CharAscii">The ASCII value of the character to translate</param>
/// <param name="LookAheadAscii">The next character in sequence (or -1 if none)</param>
/// <param name="CurrCodeSet">The current codeset, that the returned codes need to follow;
/// if the returned codes change that, then this value will be changed to reflect it</param>
/// <returns>An array of integers representing the codes that need to be output to produce the
/// given character</returns>
public static int[] CodesForChar(int CharAscii, int LookAheadAscii, ref CodeSet CurrCodeSet)
{
int[] result;
int shifter = -1;
if (!CharCompatibleWithCodeset(CharAscii,CurrCodeSet))
{
// if we have a lookahead character AND if the next character is ALSO not compatible
if ( (LookAheadAscii != -1) && !CharCompatibleWithCodeset(LookAheadAscii,CurrCodeSet) )
{
// we need to switch code sets
switch (CurrCodeSet)
{
case CodeSet.CodeA:
shifter = cCODEB;
CurrCodeSet = CodeSet.CodeB;
break;
case CodeSet.CodeB:
shifter = cCODEA;
CurrCodeSet = CodeSet.CodeA;
break;
}
}
else
{
// no need to switch code sets, a temporary SHIFT will suffice
shifter = cSHIFT;
}
}
if (shifter!=-1)
{
result = new int[2];
result[0] = shifter;
result[1] = CodeValueForChar(CharAscii);
}
else
{
result = new int[1];
result[0] = CodeValueForChar(CharAscii);
}
return result;
}
/// <summary>
/// Tells us which codesets a given character value is allowed in
/// </summary>
/// <param name="CharAscii">ASCII value of character to look at</param>
/// <returns>Which codeset(s) can be used to represent this character</returns>
public static CodeSetAllowed CodesetAllowedForChar(int CharAscii)
{
if (CharAscii>=32 && CharAscii<=95)
{
return CodeSetAllowed.CodeAorB;
}
else
{
return (CharAscii<32) ? CodeSetAllowed.CodeA : CodeSetAllowed.CodeB;
}
}
/// <summary>
/// Determine if a character can be represented in a given codeset
/// </summary>
/// <param name="CharAscii">character to check for</param>
/// <param name="currcs">codeset context to test</param>
/// <returns>true if the codeset contains a representation for the ASCII character</returns>
public static bool CharCompatibleWithCodeset(int CharAscii, CodeSet currcs)
{
CodeSetAllowed csa = CodesetAllowedForChar(CharAscii);
return csa==CodeSetAllowed.CodeAorB
|| (csa==CodeSetAllowed.CodeA && currcs==CodeSet.CodeA)
|| (csa==CodeSetAllowed.CodeB && currcs==CodeSet.CodeB);
}
/// <summary>
/// Gets the integer code128 code value for a character (assuming the appropriate code set)
/// </summary>
/// <param name="CharAscii">character to convert</param>
/// <returns>code128 symbol value for the character</returns>
public static int CodeValueForChar(int CharAscii)
{
return (CharAscii>=32) ? CharAscii-32 : CharAscii+64;
}
/// <summary>
/// Return the appropriate START code depending on the codeset we want to be in
/// </summary>
/// <param name="cs">The codeset you want to start in</param>
/// <returns>The code128 code to start a barcode in that codeset</returns>
public static int StartCodeForCodeSet(CodeSet cs)
{
return cs==CodeSet.CodeA ? cSTARTA : cSTARTB;
}
/// <summary>
/// Return the Code128 stop code
/// </summary>
/// <returns>the stop code</returns>
public static int StopCode()
{
return cSTOP;
}
/// <summary>
/// Indicates which code sets can represent a character -- CodeA, CodeB, or either
/// </summary>
public enum CodeSetAllowed
{
CodeA,
CodeB,
CodeAorB
}
}
}
| |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
namespace System.Data.Entity.SqlServer
{
using System.Data.Common;
using System.Data.Entity.Core.Common;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Infrastructure.DependencyResolution;
using System.Data.Entity.Infrastructure.Interception;
using System.Data.Entity.Migrations.History;
using System.Data.SqlClient;
using System.Reflection;
using Xunit;
public class DatabaseExistsInInitializerTests : FunctionalTestBase, IDisposable
{
private const string Password = "Password1";
private const string NormalUser = "EFGooseWithDbVisibility";
private const string ImpairedUser = "EFGooseWithoutDbVisibility";
private const string DatabaseWithMigrationHistory = "MigratoryGoose";
private const string DatabaseWithoutMigrationHistory = "NonMigratoryGoose";
private const string DatabaseOutOfDate = "MigratedGoose";
public DatabaseExistsInInitializerTests()
{
EnsureDatabaseExists(DatabaseWithMigrationHistory, drophistoryTable: false, outOfDate: false);
EnsureUserExists(DatabaseWithMigrationHistory, NormalUser, allowMasterQuery: true);
EnsureUserExists(DatabaseWithMigrationHistory, ImpairedUser, allowMasterQuery: false);
EnsureDatabaseExists(DatabaseWithoutMigrationHistory, drophistoryTable: true, outOfDate: false);
EnsureUserExists(DatabaseWithoutMigrationHistory, NormalUser, allowMasterQuery: true);
EnsureUserExists(DatabaseWithoutMigrationHistory, ImpairedUser, allowMasterQuery: false);
EnsureDatabaseExists(DatabaseOutOfDate, drophistoryTable: false, outOfDate: true);
EnsureUserExists(DatabaseOutOfDate, NormalUser, allowMasterQuery: true);
EnsureUserExists(DatabaseOutOfDate, ImpairedUser, allowMasterQuery: false);
MutableResolver.AddResolver<IManifestTokenResolver>(
new SingletonDependencyResolver<IManifestTokenResolver>(new BasicManifestTokenResolver()));
}
private static void AssertDoesNotExist(string connectionString)
{
using (var context = ExistsContext.Create(connectionString))
{
context.Database.Initialize(force: false);
Assert.True(context.InitializerCalled, "Expected initializer to be called");
Assert.False(context.Exists);
}
context.Database.Initialize(force: false);
Assert.True(context.InitializerCalled, "Expected initializer to be called");
Assert.True(context.Exists);
}
public void Dispose()
{
MutableResolver.ClearResolvers();
}
[Fact]
public void Exists_check_with_master_persist_info()
{
ExistsTest(DatabaseWithMigrationHistory, NormalUser, persistSecurityInfo: true);
}
[Fact]
public void Exists_check_with_master_no_persist_info()
{
ExistsTest(DatabaseWithMigrationHistory, NormalUser, persistSecurityInfo: false);
}
[Fact]
public void Exists_check_without_master_persist_info()
{
ExistsTestNoMaster(DatabaseWithMigrationHistory, NormalUser, persistSecurityInfo: true);
}
[Fact]
public void Exists_check_without_master_no_persist_info()
{
ExistsTestNoMaster(DatabaseWithMigrationHistory, NormalUser, persistSecurityInfo: false);
}
[Fact] // CodePlex 2113
public void Exists_check_with_no_master_query_persist_info()
{
ExistsTest(DatabaseWithMigrationHistory, ImpairedUser, persistSecurityInfo: true);
}
[Fact] // CodePlex 2113
public void Exists_check_with_no_master_query_no_persist_info()
{
ExistsTest(DatabaseWithMigrationHistory, ImpairedUser, persistSecurityInfo: false);
}
[Fact]
public void Exists_check_with_master_persist_info_no_MigrationHistory()
{
ExistsTest(DatabaseWithoutMigrationHistory, NormalUser, persistSecurityInfo: true);
}
[Fact]
public void Exists_check_with_master_no_persist_info_no_MigrationHistory()
{
ExistsTest(DatabaseWithoutMigrationHistory, NormalUser, persistSecurityInfo: false);
}
[Fact]
public void Exists_check_without_master_persist_info_no_MigrationHistory()
{
ExistsTestNoMaster(DatabaseWithoutMigrationHistory, NormalUser, persistSecurityInfo: true);
}
[Fact]
public void Exists_check_without_master_no_persist_info_no_MigrationHistory()
{
ExistsTestNoMaster(DatabaseWithoutMigrationHistory, NormalUser, persistSecurityInfo: false);
}
[Fact] // CodePlex 2113
public void Exists_check_with_no_master_query_persist_info_no_MigrationHistory()
{
ExistsTest(DatabaseWithoutMigrationHistory, ImpairedUser, persistSecurityInfo: true);
}
[Fact] // CodePlex 2113
public void Exists_check_with_no_master_query_no_persist_info_no_MigrationHistory()
{
ExistsTest(DatabaseWithoutMigrationHistory, ImpairedUser, persistSecurityInfo: false);
}
[Fact]
public void Exists_check_with_master_persist_info_out_of_date()
{
ExistsTest(DatabaseOutOfDate, NormalUser, persistSecurityInfo: true);
}
[Fact]
public void Exists_check_with_master_no_persist_info_out_of_date()
{
ExistsTest(DatabaseOutOfDate, NormalUser, persistSecurityInfo: false);
}
[Fact]
public void Exists_check_without_master_persist_info_out_of_date()
{
ExistsTestNoMaster(DatabaseOutOfDate, NormalUser, persistSecurityInfo: true);
}
[Fact]
public void Exists_check_without_master_no_persist_info_out_of_date()
{
ExistsTestNoMaster(DatabaseOutOfDate, NormalUser, persistSecurityInfo: false);
}
[Fact] // CodePlex 2113
public void Exists_check_with_no_master_query_persist_info_out_of_date()
{
ExistsTest(DatabaseOutOfDate, ImpairedUser, persistSecurityInfo: true);
}
[Fact] // CodePlex 2113
public void Exists_check_with_no_master_query_no_persist_info_out_of_date()
{
ExistsTest(DatabaseOutOfDate, ImpairedUser, persistSecurityInfo: false);
}
[Fact]
public void Not_exists_check_with_master_persist_info()
{
NotExistsTest(NormalUser, persistSecurityInfo: true);
}
[Fact]
public void Not_exists_check_with_master_no_persist_info()
{
NotExistsTest(NormalUser, persistSecurityInfo: false);
}
[Fact]
public void Not_exists_check_without_master_persist_info()
{
NotExistsTestNoMaster(NormalUser, persistSecurityInfo: true);
}
[Fact]
public void Not_exists_check_without_master_no_persist_info()
{
NotExistsTestNoMaster(NormalUser, persistSecurityInfo: false);
}
[Fact] // CodePlex 2113
public void Not_exists_check_with_no_master_query_persist_info()
{
NotExistsTest(ImpairedUser, persistSecurityInfo: true);
}
[Fact] // CodePlex 2113
public void Not_exists_check_with_no_master_query_no_persist_info()
{
NotExistsTest(ImpairedUser, persistSecurityInfo: false);
}
[Fact] // CodePlex 2068
public void Exists_check_with_master_persist_info_open_connection()
{
ExistsTestWithConnection(DatabaseWithMigrationHistory, NormalUser, persistSecurityInfo: true, openConnection: true);
}
[Fact] // CodePlex 2068
public void Exists_check_with_master_no_persist_info_open_connection()
{
ExistsTestWithConnection(DatabaseWithMigrationHistory, NormalUser, persistSecurityInfo: false, openConnection: true);
}
[Fact] // CodePlex 2068
public void Exists_check_without_master_persist_info_open_connection()
{
ExistsTestNoMasterWithConnection(DatabaseWithMigrationHistory, NormalUser, persistSecurityInfo: true, openConnection: true);
}
[Fact] // CodePlex 2068
public void Exists_check_without_master_no_persist_info_open_connection()
{
ExistsTestNoMasterWithConnection(DatabaseWithMigrationHistory, NormalUser, persistSecurityInfo: false, openConnection: true);
}
[Fact] // CodePlex 2113, 2068
public void Exists_check_with_no_master_query_persist_info_open_connection()
{
ExistsTestWithConnection(DatabaseWithMigrationHistory, ImpairedUser, persistSecurityInfo: true, openConnection: true);
}
[Fact] // CodePlex 2113, 2068
public void Exists_check_with_no_master_query_no_persist_info_open_connection()
{
ExistsTestWithConnection(DatabaseWithMigrationHistory, ImpairedUser, persistSecurityInfo: false, openConnection: true);
}
[Fact]
public void Exists_check_with_master_persist_info_closed_connection()
{
ExistsTestWithConnection(DatabaseWithMigrationHistory, NormalUser, persistSecurityInfo: true, openConnection: false);
}
[Fact]
public void Exists_check_with_master_no_persist_info_closed_connection()
{
ExistsTestWithConnection(DatabaseWithMigrationHistory, NormalUser, persistSecurityInfo: false, openConnection: false);
}
[Fact]
public void Exists_check_without_master_persist_info_closed_connection()
{
ExistsTestNoMasterWithConnection(DatabaseWithMigrationHistory, NormalUser, persistSecurityInfo: true, openConnection: false);
}
[Fact]
public void Exists_check_without_master_no_persist_info_closed_connection()
{
ExistsTestNoMasterWithConnection(DatabaseWithMigrationHistory, NormalUser, persistSecurityInfo: false, openConnection: false);
}
[Fact] // CodePlex 2113
public void Exists_check_with_no_master_query_persist_info_closed_connection()
{
ExistsTestWithConnection(DatabaseWithMigrationHistory, ImpairedUser, persistSecurityInfo: true, openConnection: false);
}
[Fact] // CodePlex 2113
public void Exists_check_with_no_master_query_no_persist_info_closed_connection()
{
ExistsTestWithConnection(DatabaseWithMigrationHistory, ImpairedUser, persistSecurityInfo: false, openConnection: false);
}
[Fact] // CodePlex 2068
public void Exists_check_with_master_persist_info_open_connection_no_MigrationHistory()
{
ExistsTestWithConnection(DatabaseWithoutMigrationHistory, NormalUser, persistSecurityInfo: true, openConnection: true);
}
[Fact] // CodePlex 2068
public void Exists_check_with_master_no_persist_info_open_connection_no_MigrationHistory()
{
ExistsTestWithConnection(DatabaseWithoutMigrationHistory, NormalUser, persistSecurityInfo: false, openConnection: true);
}
[Fact] // CodePlex 2068
public void Exists_check_without_master_persist_info_open_connection_no_MigrationHistory()
{
ExistsTestNoMasterWithConnection(DatabaseWithoutMigrationHistory, NormalUser, persistSecurityInfo: true, openConnection: true);
}
[Fact] // CodePlex 2068
public void Exists_check_without_master_no_persist_info_open_connection_no_MigrationHistory()
{
ExistsTestNoMasterWithConnection(DatabaseWithoutMigrationHistory, NormalUser, persistSecurityInfo: false, openConnection: true);
}
[Fact] // CodePlex 2113, 2068
public void Exists_check_with_no_master_query_persist_info_open_connection_no_MigrationHistory()
{
ExistsTestWithConnection(DatabaseWithoutMigrationHistory, ImpairedUser, persistSecurityInfo: true, openConnection: true);
}
[Fact] // CodePlex 2113, 2068
public void Exists_check_with_no_master_query_no_persist_info_open_connection_no_MigrationHistory()
{
ExistsTestWithConnection(DatabaseWithoutMigrationHistory, ImpairedUser, persistSecurityInfo: false, openConnection: true);
}
[Fact]
public void Exists_check_with_master_persist_info_closed_connection_no_MigrationHistory()
{
ExistsTestWithConnection(DatabaseWithoutMigrationHistory, NormalUser, persistSecurityInfo: true, openConnection: false);
}
[Fact]
public void Exists_check_with_master_no_persist_info_closed_connection_no_MigrationHistory()
{
ExistsTestWithConnection(DatabaseWithoutMigrationHistory, NormalUser, persistSecurityInfo: false, openConnection: false);
}
[Fact]
public void Exists_check_without_master_persist_info_closed_connection_no_MigrationHistory()
{
ExistsTestNoMasterWithConnection(DatabaseWithoutMigrationHistory, NormalUser, persistSecurityInfo: true, openConnection: false);
}
[Fact]
public void Exists_check_without_master_no_persist_info_closed_connection_no_MigrationHistory()
{
ExistsTestNoMasterWithConnection(DatabaseWithoutMigrationHistory, NormalUser, persistSecurityInfo: false, openConnection: false);
}
[Fact] // CodePlex 2113
public void Exists_check_with_no_master_query_persist_info_closed_connection_no_MigrationHistory()
{
ExistsTestWithConnection(DatabaseWithoutMigrationHistory, ImpairedUser, persistSecurityInfo: true, openConnection: false);
}
[Fact] // CodePlex 2113
public void Exists_check_with_no_master_query_no_persist_info_closed_connection_no_MigrationHistory()
{
ExistsTestWithConnection(DatabaseWithoutMigrationHistory, ImpairedUser, persistSecurityInfo: false, openConnection: false);
}
[Fact] // CodePlex 2068
public void Exists_check_with_master_persist_info_open_connection_out_of_date()
{
ExistsTestWithConnection(DatabaseOutOfDate, NormalUser, persistSecurityInfo: true, openConnection: true);
}
[Fact] // CodePlex 2068
public void Exists_check_with_master_no_persist_info_open_connection_out_of_date()
{
ExistsTestWithConnection(DatabaseOutOfDate, NormalUser, persistSecurityInfo: false, openConnection: true);
}
[Fact] // CodePlex 2068
public void Exists_check_without_master_persist_info_open_connection_out_of_date()
{
ExistsTestNoMasterWithConnection(DatabaseOutOfDate, NormalUser, persistSecurityInfo: true, openConnection: true);
}
[Fact] // CodePlex 2068
public void Exists_check_without_master_no_persist_info_open_connection_out_of_date()
{
ExistsTestNoMasterWithConnection(DatabaseOutOfDate, NormalUser, persistSecurityInfo: false, openConnection: true);
}
[Fact] // CodePlex 2113, 2068
public void Exists_check_with_no_master_query_persist_info_open_connection_out_of_date()
{
ExistsTestWithConnection(DatabaseOutOfDate, ImpairedUser, persistSecurityInfo: true, openConnection: true);
}
[Fact] // CodePlex 2113, 2068
public void Exists_check_with_no_master_query_no_persist_info_open_connection_out_of_date()
{
ExistsTestWithConnection(DatabaseOutOfDate, ImpairedUser, persistSecurityInfo: false, openConnection: true);
}
[Fact]
public void Exists_check_with_master_persist_info_closed_connection_out_of_date()
{
ExistsTestWithConnection(DatabaseOutOfDate, NormalUser, persistSecurityInfo: true, openConnection: false);
}
[Fact]
public void Exists_check_with_master_no_persist_info_closed_connection_out_of_date()
{
ExistsTestWithConnection(DatabaseOutOfDate, NormalUser, persistSecurityInfo: false, openConnection: false);
}
[Fact]
public void Exists_check_without_master_persist_info_closed_connection_out_of_date()
{
ExistsTestNoMasterWithConnection(DatabaseOutOfDate, NormalUser, persistSecurityInfo: true, openConnection: false);
}
[Fact]
public void Exists_check_without_master_no_persist_info_closed_connection_out_of_date()
{
ExistsTestNoMasterWithConnection(DatabaseOutOfDate, NormalUser, persistSecurityInfo: false, openConnection: false);
}
[Fact] // CodePlex 2113
public void Exists_check_with_no_master_query_persist_info_closed_connection_out_of_date()
{
ExistsTestWithConnection(DatabaseOutOfDate, ImpairedUser, persistSecurityInfo: true, openConnection: false);
}
[Fact] // CodePlex 2113
public void Exists_check_with_no_master_query_no_persist_info_closed_connection_out_of_date()
{
ExistsTestWithConnection(DatabaseOutOfDate, ImpairedUser, persistSecurityInfo: false, openConnection: false);
}
[Fact]
public void Not_exists_check_with_master_persist_info_closed_connection()
{
NotExistsTestWithConnection(NormalUser, persistSecurityInfo: true, openConnection: false);
}
[Fact]
public void Not_exists_check_with_master_no_persist_info_closed_connection()
{
NotExistsTestWithConnection(NormalUser, persistSecurityInfo: false, openConnection: false);
}
[Fact]
public void Not_exists_check_without_master_persist_info_closed_connection()
{
NotExistsTestNoMasterWithConnection(NormalUser, persistSecurityInfo: true, openConnection: false);
}
[Fact]
public void Not_exists_check_without_master_no_persist_info_closed_connection()
{
NotExistsTestNoMasterWithConnection(NormalUser, persistSecurityInfo: false, openConnection: false);
}
[Fact] // CodePlex 2113
public void Not_exists_check_with_no_master_query_persist_info_closed_connection()
{
NotExistsTestWithConnection(ImpairedUser, persistSecurityInfo: true, openConnection: false);
}
[Fact] // CodePlex 2113
public void Not_exists_check_with_no_master_query_no_persist_info_closed_connection()
{
NotExistsTestWithConnection(ImpairedUser, persistSecurityInfo: false, openConnection: false);
}
private void ExistsTest(string databaseName, string username, bool persistSecurityInfo)
{
AssertExists(
databaseName,
ModelHelpers.SimpleConnectionStringWithCredentials(
databaseName, username, Password, persistSecurityInfo));
}
private void ExistsTestNoMaster(string databaseName, string username, bool persistSecurityInfo)
{
var interceptor = new NoMasterInterceptor();
try
{
DbInterception.Add(interceptor);
AssertExists(
databaseName,
ModelHelpers.SimpleConnectionStringWithCredentials(
databaseName, username, Password, persistSecurityInfo));
}
finally
{
DbInterception.Remove(interceptor);
}
}
private void NotExistsTest(string username, bool persistSecurityInfo)
{
AssertDoesNotExist(
ModelHelpers.SimpleConnectionStringWithCredentials(
"IDoNotExist", username, Password, persistSecurityInfo));
}
private void NotExistsTestNoMaster(string username, bool persistSecurityInfo)
{
var interceptor = new NoMasterInterceptor();
try
{
DbInterception.Add(interceptor);
AssertDoesNotExist(
ModelHelpers.SimpleConnectionStringWithCredentials(
"IDoNotExist", username, Password, persistSecurityInfo));
}
finally
{
DbInterception.Remove(interceptor);
}
}
private void ExistsTestWithConnection(string databaseName, string username, bool persistSecurityInfo, bool openConnection)
{
AssertExistsWithConnection(
databaseName,
ModelHelpers.SimpleConnectionStringWithCredentials(
databaseName, username, Password, persistSecurityInfo), openConnection);
}
private void ExistsTestNoMasterWithConnection(string databaseName, string username, bool persistSecurityInfo, bool openConnection)
{
var interceptor = new NoMasterInterceptor();
try
{
DbInterception.Add(interceptor);
AssertExistsWithConnection(
databaseName,
ModelHelpers.SimpleConnectionStringWithCredentials(
databaseName, username, Password, persistSecurityInfo), openConnection);
}
finally
{
DbInterception.Remove(interceptor);
}
}
private void NotExistsTestWithConnection(string username, bool persistSecurityInfo, bool openConnection)
{
AssertDoesNotExistWithConnection(
ModelHelpers.SimpleConnectionStringWithCredentials(
"IDoNotExist", username, Password, persistSecurityInfo), openConnection);
}
private void NotExistsTestNoMasterWithConnection(string username, bool persistSecurityInfo, bool openConnection)
{
var interceptor = new NoMasterInterceptor();
try
{
DbInterception.Add(interceptor);
AssertDoesNotExistWithConnection(
ModelHelpers.SimpleConnectionStringWithCredentials(
"IDoNotExist", username, Password, persistSecurityInfo), openConnection);
}
finally
{
DbInterception.Remove(interceptor);
}
}
private static void AssertExists(string databaseName, string connectionString)
{
using (var context = ExistsContext.Create(connectionString))
{
AssertExists(databaseName, context);
}
}
private static void AssertExistsWithConnection(string databaseName, string connectionString, bool openConnection)
{
using (var connection = new SqlConnection(connectionString))
{
if (openConnection)
{
connection.Open();
}
using (var context = ExistsContext.Create(connection))
{
AssertExists(databaseName, context);
}
connection.Close();
}
}
private static void AssertExists(string databaseName, ExistsContext context)
{
context.Database.Initialize(force: false);
Assert.True(context.InitializerCalled);
Assert.True(context.Exists);
if (databaseName == DatabaseWithMigrationHistory)
{
context.SetDropCreateIfNotExists();
context.Database.Initialize(force: true);
context.Database.Initialize(force: true);
context.SetDropCreateIfModelChanges();
context.Database.Initialize(force: true);
context.Database.Initialize(force: true);
}
else if (databaseName == DatabaseWithoutMigrationHistory)
{
context.SetDropCreateIfNotExists();
context.Database.Initialize(force: true);
context.Database.Initialize(force: true);
context.SetDropCreateIfModelChanges();
Assert.Throws<NotSupportedException>(() => context.Database.Initialize(force: true))
.ValidateMessage("Database_NoDatabaseMetadata");
}
else if (databaseName == DatabaseOutOfDate)
{
context.SetDropCreateIfNotExists();
Assert.Throws<InvalidOperationException>(() => context.Database.Initialize(force: true))
.ValidateMessage("DatabaseInitializationStrategy_ModelMismatch", context.GetType().Name);
}
}
private static void AssertDoesNotExistWithConnection(string connectionString, bool openConnection)
{
using (var connection = new SqlConnection(connectionString))
{
if (openConnection)
{
connection.Open();
}
using (var context = ExistsContext.Create(connection))
{
context.Database.Initialize(force: false);
Assert.True(context.InitializerCalled);
Assert.False(context.Exists);
}
connection.Close();
}
}
private static void EnsureDatabaseExists(string databaseName, bool drophistoryTable, bool outOfDate)
{
using (var context = outOfDate
? new ExistsContextModelChanged(SimpleConnectionString(databaseName))
: new ExistsContext(SimpleConnectionString(databaseName)))
{
if (!context.Database.Exists())
{
context.Database.Create();
if (drophistoryTable)
{
context.Database.ExecuteSqlCommand("DROP TABLE " + HistoryContext.DefaultTableName);
}
else
{
context.Database.ExecuteSqlCommand(@"UPDATE __MigrationHistory SET ContextKey = 'TestContextKey'");
}
}
}
}
private void EnsureUserExists(string databaseName, string username, bool allowMasterQuery)
{
using (var connection = new SqlConnection(SimpleConnectionString("master")))
{
connection.Open();
var loginExists = ExecuteScalarReturnsOne(
connection,
"SELECT COUNT(*) FROM sys.sql_logins WHERE name = N'{0}'", username);
if (!loginExists)
{
ExecuteNonQuery(connection, "CREATE LOGIN [{0}] WITH PASSWORD=N'{1}'", username, Password);
}
var userExists = ExecuteScalarReturnsOne(
connection,
"SELECT COUNT(*) FROM sys.sysusers WHERE name = N'{0}'", username);
if (!userExists)
{
ExecuteNonQuery(connection, "CREATE USER [{0}] FROM LOGIN [{0}]", username);
if (!allowMasterQuery)
{
ExecuteNonQuery(connection, "DENY VIEW ANY DATABASE TO [{0}]", username);
}
}
connection.Close();
}
using (var connection = new SqlConnection(SimpleConnectionString(databaseName)))
{
connection.Open();
var userExists = ExecuteScalarReturnsOne(
connection,
"SELECT COUNT(*) FROM sys.sysusers WHERE name = N'{0}'", username);
if (!userExists)
{
ExecuteNonQuery(connection, "CREATE USER [{0}] FROM LOGIN [{0}]", username);
ExecuteNonQuery(connection, "GRANT VIEW DEFINITION TO [{0}]", username);
ExecuteNonQuery(connection, "GRANT SELECT TO [{0}]", username);
}
connection.Close();
}
}
private static void ExecuteNonQuery(SqlConnection connection, string commandText, params object[] args)
{
using (var command = connection.CreateCommand())
{
command.CommandText = string.Format(commandText, args);
command.ExecuteNonQuery();
}
}
private static bool ExecuteScalarReturnsOne(SqlConnection connection, string commandText, params object[] args)
{
using (var command = connection.CreateCommand())
{
try
{
command.CommandText = string.Format(commandText, args);
return (int)command.ExecuteScalar() == 1;
}
catch (Exception)
{
return false;
}
}
}
public class NoMasterInterceptor : IDbConnectionInterceptor
{
public void BeginningTransaction(DbConnection connection, BeginTransactionInterceptionContext interceptionContext)
{
}
public void BeganTransaction(DbConnection connection, BeginTransactionInterceptionContext interceptionContext)
{
}
public void Closing(DbConnection connection, DbConnectionInterceptionContext interceptionContext)
{
}
public void Closed(DbConnection connection, DbConnectionInterceptionContext interceptionContext)
{
}
public void ConnectionStringGetting(DbConnection connection, DbConnectionInterceptionContext<string> interceptionContext)
{
}
public void ConnectionStringGot(DbConnection connection, DbConnectionInterceptionContext<string> interceptionContext)
{
}
public void ConnectionStringSetting(
DbConnection connection, DbConnectionPropertyInterceptionContext<string> interceptionContext)
{
}
public void ConnectionStringSet(DbConnection connection, DbConnectionPropertyInterceptionContext<string> interceptionContext)
{
}
public void ConnectionTimeoutGetting(DbConnection connection, DbConnectionInterceptionContext<int> interceptionContext)
{
}
public void ConnectionTimeoutGot(DbConnection connection, DbConnectionInterceptionContext<int> interceptionContext)
{
}
public void DatabaseGetting(DbConnection connection, DbConnectionInterceptionContext<string> interceptionContext)
{
}
public void DatabaseGot(DbConnection connection, DbConnectionInterceptionContext<string> interceptionContext)
{
}
public void DataSourceGetting(DbConnection connection, DbConnectionInterceptionContext<string> interceptionContext)
{
}
public void DataSourceGot(DbConnection connection, DbConnectionInterceptionContext<string> interceptionContext)
{
}
public void Disposing(DbConnection connection, DbConnectionInterceptionContext interceptionContext)
{
}
public void Disposed(DbConnection connection, DbConnectionInterceptionContext interceptionContext)
{
}
public void EnlistingTransaction(DbConnection connection, EnlistTransactionInterceptionContext interceptionContext)
{
}
public void EnlistedTransaction(DbConnection connection, EnlistTransactionInterceptionContext interceptionContext)
{
}
public void Opening(DbConnection connection, DbConnectionInterceptionContext interceptionContext)
{
if (connection.Database == "master")
{
interceptionContext.Exception =
(SqlException)Activator.CreateInstance(
typeof(SqlException), BindingFlags.Instance | BindingFlags.NonPublic, null,
new object[] { "No master for you!", null, null, Guid.NewGuid() }, null);
}
}
public void Opened(DbConnection connection, DbConnectionInterceptionContext interceptionContext)
{
}
public void ServerVersionGetting(DbConnection connection, DbConnectionInterceptionContext<string> interceptionContext)
{
}
public void ServerVersionGot(DbConnection connection, DbConnectionInterceptionContext<string> interceptionContext)
{
}
public void StateGetting(DbConnection connection, DbConnectionInterceptionContext<ConnectionState> interceptionContext)
{
}
public void StateGot(DbConnection connection, DbConnectionInterceptionContext<ConnectionState> interceptionContext)
{
}
}
public class ExistsContext : DbContext
{
public bool InitializerCalled { get; set; }
public bool Exists { get; set; }
private static int _typeCount;
static ExistsContext()
{
Database.SetInitializer<ExistsContext>(null);
}
public ExistsContext(string connectionString)
: base(connectionString)
{
SetContextKey();
}
public ExistsContext(DbConnection connection)
: base(connection, contextOwnsConnection: false)
{
SetContextKey();
}
private void SetContextKey()
{
var internalContext = typeof(DbContext)
.GetField("_internalContext", BindingFlags.Instance | BindingFlags.NonPublic)
.GetValue(this);
internalContext.GetType().BaseType
.GetField("_defaultContextKey", BindingFlags.Instance | BindingFlags.NonPublic)
.SetValue(internalContext, "TestContextKey");
}
public DbSet<ExistsEntity> Entities { get; set; }
public static ExistsContext Create(string connectionString)
{
return (ExistsContext)Activator.CreateInstance(GetNewContxtType(), connectionString);
}
public static ExistsContext Create(DbConnection connection)
{
return (ExistsContext)Activator.CreateInstance(GetNewContxtType(), connection);
}
private static Type GetNewContxtType()
{
var typeNumber = _typeCount++;
var typeBits = new Type[8];
for (var bit = 0; bit < 8; bit++)
{
typeBits[bit] = ((typeNumber & 1) == 1) ? typeof(int) : typeof(string);
typeNumber >>= 1;
}
return typeof(ExistsContext<>).MakeGenericType(typeof(Tuple<,,,,,,,>).MakeGenericType(typeBits));
}
public virtual void SetDropCreateIfNotExists()
{
throw new NotImplementedException();
}
public virtual void SetDropCreateIfModelChanges()
{
throw new NotImplementedException();
}
}
public class ExistsContextModelChanged : ExistsContext
{
static ExistsContextModelChanged()
{
Database.SetInitializer<ExistsContextModelChanged>(null);
}
public ExistsContextModelChanged(string connectionString)
: base(connectionString)
{
}
public ExistsContextModelChanged(DbConnection connection)
: base(connection)
{
}
public DbSet<ModelChangedEntity> ModelChangedEntities { get; set; }
}
public class ExistsContext<T> : ExistsContext
{
private static readonly ExistsInitializer<T> _initializer = new ExistsInitializer<T>();
private static readonly CreateDatabaseIfNotExists<ExistsContext<T>> _dropCreateIfNotExists
= new CreateDatabaseIfNotExists<ExistsContext<T>>();
private static readonly DropCreateDatabaseIfModelChanges<ExistsContext<T>> _dropCreateIfModelChanges
= new DropCreateDatabaseIfModelChanges<ExistsContext<T>>();
private static readonly DropCreateDatabaseAlways<ExistsContext<T>> _dropCreateAlways
= new DropCreateDatabaseAlways<ExistsContext<T>>();
static ExistsContext()
{
Database.SetInitializer(_initializer);
}
public ExistsContext(string connectionString)
: base(connectionString)
{
}
public ExistsContext(DbConnection connection)
: base(connection)
{
}
public override void SetDropCreateIfNotExists()
{
Database.SetInitializer(_dropCreateIfNotExists);
}
public override void SetDropCreateIfModelChanges()
{
Database.SetInitializer(_dropCreateIfModelChanges);
}
}
public class BasicManifestTokenResolver : IManifestTokenResolver
{
public string ResolveManifestToken(DbConnection connection)
{
return DbProviderServices.GetProviderServices(connection).GetProviderManifestToken(connection);
}
}
public class ExistsInitializer<T> : IDatabaseInitializer<ExistsContext<T>>
{
public void InitializeDatabase(ExistsContext<T> context)
{
context.InitializerCalled = true;
context.Exists = context.Database.Exists();
}
}
public class ExistsEntity
{
public int Id { get; set; }
}
public class ModelChangedEntity
{
public int Id { get; set; }
}
}
}
| |
using NAME.ConnectionStrings;
using NAME.Core;
using NAME.Core.Exceptions;
using NAME.Dependencies;
using NAME.Json;
using NAME.Tests.ConnectionStrings;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace NAME.Tests
{
[TestCaseOrderer("NAME.Tests.PriorityOrderer", "NAME.Tests")]
public class ConfigurationReaderTests : IClassFixture<CreateConfigurationFileFixture>
{
#region configuration
public static string CONFIGURATION_FILE = Guid.NewGuid() + ".json";
public const string CONFIGURATION_CONTENTS =
@"{
""infrastructure_dependencies"": [
{
""oneOf"": [
{
""os_name"": ""Ubuntu"",
""type"": ""OperatingSystem"",
""min_version"": ""16.04"",
""max_version"": ""14.04""
},
{
""os_name"": ""Windows"",
""type"": ""OperatingSystem"",
""min_version"": ""WindowsServer2008R2"",
""max_version"": ""*""
}
]
},
{
""type"": ""MongoDb"",
""min_version"": ""2.6"",
""max_version"": ""4.0"",
""connection_string"": ""mongodb://some-mongodb-instance:27017/some-db""
},
{
""type"": ""Elasticsearch"",
""min_version"": ""2.6"",
""max_version"": ""4.*"",
""connection_string"": ""http://some-elasticsearch-instance:9200""
}"
#if NET452
+ @",{
""type"": ""RabbitMq"",
""name"": ""rabbitmq"",
""min_version"": ""2.0"",
""max_version"": ""3.3"",
""connection_string"": {
""locator"": ""ConnectionStrings"",
""key"": ""RabbitMQConnectionString""
}
}"
#endif
+ @"],
""service_dependencies"": [
{
""name"": ""Some Service"",
""min_version"": ""0.3"",
""max_version"": ""*"",
""connection_string"": ""http://some-services/api/""
},
{
""name"": ""The other service"",
""min_version"": ""1.0"",
""max_version"": ""*"",
""connection_string"": ""http://other-service/api/""
}
]
}";
#endregion
[Fact]
[Trait("TestCategory", "Unit")]
public void ReadConfiguration_CallsMultipleTimes_ConnectionStringProviderOverride()
{
string fileContents = @"{
""infrastructure_dependencies"": [
],
""service_dependencies"": [
{
""name"": ""Some Service0"",
""min_version"": ""0.3"",
""max_version"": ""*"",
""connection_string"": {
""unrecognizedString"": 0
}
},
{
""name"": ""Some Service1"",
""min_version"": ""0.3"",
""max_version"": ""*"",
""connection_string"": {
""unrecognizedString"": 1
}
}
]
}";
string fileName = Guid.NewGuid() + ".json";
File.WriteAllText(fileName, fileContents);
try
{
int iterationsCount = 0;
var settings = new NAMESettings()
{
ConnectionStringProviderOverride = (node) =>
{
Assert.Equal(iterationsCount, node["unrecognizedString"].AsInt);
iterationsCount++;
return new StaticConnectionStringProvider(iterationsCount.ToString());
}
};
ParsedDependencies configuration = DependenciesReader.ReadDependencies(fileName, new DummyFilePathMapper(), settings, new NAMEContext());
Assert.Equal(0, configuration.InfrastructureDependencies.Count());
Assert.Equal(2, configuration.ServiceDependencies.Count());
Assert.Equal(2, iterationsCount);
var firstDependency = (ConnectedDependency)configuration.ServiceDependencies.First();
var secondDependency = (ConnectedDependency)configuration.ServiceDependencies.Skip(1).First();
Assert.IsType<StaticConnectionStringProvider>(firstDependency.ConnectionStringProvider);
Assert.IsType<StaticConnectionStringProvider>(secondDependency.ConnectionStringProvider);
}
finally
{
File.Delete(fileName);
}
}
[Fact]
[Trait("TestCategory", "Unit")]
public void ReadConfiguration_UsesConnectionStringProviderReturnedFromOverride()
{
string fileContents = @"{
""infrastructure_dependencies"": [
{
""type"": ""RabbitMq"",
""name"": ""rabbitmq"",
""min_version"": ""2.0"",
""max_version"": ""3.3"",
""connection_string"": {
""locator"": ""JSONPath"",
""key"": ""shouldn't matter""
}
}
],
""service_dependencies"": [
]
}";
string fileName = Guid.NewGuid() + ".json";
File.WriteAllText(fileName, fileContents);
try
{
int iterationsCount = 0;
var settings = new NAMESettings()
{
ConnectionStringProviderOverride = (node) =>
{
iterationsCount++;
return new StaticConnectionStringProvider(string.Empty);
}
};
ParsedDependencies configuration = DependenciesReader.ReadDependencies(fileName, new DummyFilePathMapper(), settings, new NAMEContext());
Assert.Equal(1, configuration.InfrastructureDependencies.Count());
Assert.Equal(0, configuration.ServiceDependencies.Count());
Assert.Equal(1, iterationsCount);
var firstDependency = (ConnectedDependency)configuration.InfrastructureDependencies.First();
Assert.IsType<StaticConnectionStringProvider>(firstDependency.ConnectionStringProvider);
}
finally
{
File.Delete(fileName);
}
}
[Fact]
[Trait("TestCategory", "Unit")]
public void ReadConfiguration_UsesStaticConnectionStringProvider()
{
string fileContents = @"{
""infrastructure_dependencies"": [
{
""type"": ""RabbitMq"",
""name"": ""rabbitmq"",
""min_version"": ""2.0"",
""max_version"": ""3.3"",
""connection_string"": ""some-connection-string""
}
],
""service_dependencies"": [
]
}";
string fileName = Guid.NewGuid() + ".json";
File.WriteAllText(fileName, fileContents);
try
{
int iterationsCount = 0;
var settings = new NAMESettings()
{
ConnectionStringProviderOverride = (node) =>
{
iterationsCount++;
return null;
}
};
ParsedDependencies configuration = DependenciesReader.ReadDependencies(fileName, new DummyFilePathMapper(), settings, new NAMEContext());
Assert.Equal(1, configuration.InfrastructureDependencies.Count());
Assert.Equal(0, configuration.ServiceDependencies.Count());
Assert.Equal(0, iterationsCount);
var firstDependency = (ConnectedDependency)configuration.InfrastructureDependencies.First();
Assert.IsType<StaticConnectionStringProvider>(firstDependency.ConnectionStringProvider);
}
finally
{
File.Delete(fileName);
}
}
[Fact]
[Trait("TestCategory", "Unit")]
public void ReadConfiguration_OperatingSystemDependency_SkipsOverride()
{
string fileContents = @"{
""infrastructure_dependencies"": [
{
""os_name"": ""Ubuntu"",
""type"": ""OperatingSystem"",
""min_version"": ""16.04"",
""max_version"": ""14.04""
}
],
""service_dependencies"": [
]
}";
string fileName = Guid.NewGuid() + ".json";
File.WriteAllText(fileName, fileContents);
try
{
int iterationsCount = 0;
var settings = new NAMESettings()
{
ConnectionStringProviderOverride = (node) =>
{
iterationsCount++;
return null;
}
};
ParsedDependencies configuration = DependenciesReader.ReadDependencies(fileName, new DummyFilePathMapper(), settings, new NAMEContext());
Assert.Equal(1, configuration.InfrastructureDependencies.Count());
Assert.Equal(0, configuration.ServiceDependencies.Count());
Assert.Equal(0, iterationsCount);
}
finally
{
File.Delete(fileName);
}
}
[Fact]
[Trait("TestCategory", "Unit")]
public void ReadConfiguration_EmptyArrays()
{
string fileContents = @"{
""infrastructure_dependencies"": [
],
""service_dependencies"": [
]
}";
string fileName = Guid.NewGuid() + ".json";
File.WriteAllText(fileName, fileContents);
try
{
ParsedDependencies configuration = DependenciesReader.ReadDependencies(fileName, new DummyFilePathMapper(), new NAMESettings(), new NAMEContext());
Assert.Equal(0, configuration.InfrastructureDependencies.Count());
Assert.Equal(0, configuration.ServiceDependencies.Count());
}
finally
{
File.Delete(fileName);
}
}
[Fact]
[Trait("TestCategory", "Unit")]
public void ReadConfiguration_FileAllCommented()
{
string fileContents = @"//{
//""$schema"": ""./config-manifest.schema.json"",
//""infrastructure_dependencies"": [
//],
//""service_dependencies"": [
//]
//}";
string fileName = Guid.NewGuid() + ".json";
File.WriteAllText(fileName, fileContents);
try
{
ParsedDependencies configuration = DependenciesReader.ReadDependencies(fileName, new DummyFilePathMapper(), new NAMESettings(), new NAMEContext());
Assert.Equal(0, configuration.InfrastructureDependencies.Count());
Assert.Equal(0, configuration.ServiceDependencies.Count());
}
finally
{
File.Delete(fileName);
}
}
[Fact]
[Trait("TestCategory", "Unit")]
public void ReadConfiguration_WithSomeComments()
{
string fileContents = @"{
""$schema"": ""./config-manifest.schema.json"",
""infrastructure_dependencies"": [
//Comment this yeah!
],
""service_dependencies"": [
//Comment this yeah!
]
//}";
string fileName = Guid.NewGuid() + ".json";
File.WriteAllText(fileName, fileContents);
try
{
ParsedDependencies configuration = DependenciesReader.ReadDependencies(fileName, new DummyFilePathMapper(), new NAMESettings(), new NAMEContext());
Assert.Equal(0, configuration.InfrastructureDependencies.Count());
Assert.Equal(0, configuration.ServiceDependencies.Count());
}
finally
{
File.Delete(fileName);
}
}
[Fact]
[Trait("TestCategory", "Unit")]
public void ReadConfiguration_WithTabulationComments()
{
string fileContents = @"{
""$schema"": ""./config-manifest.schema.json"",
""infrastructure_dependencies"": [
//Comment this yeah!
],
""service_dependencies"": [
//Comment this yeah!
]
//}";
string fileName = Guid.NewGuid() + ".json";
File.WriteAllText(fileName, fileContents);
try
{
ParsedDependencies configuration = DependenciesReader.ReadDependencies(fileName, new DummyFilePathMapper(), new NAMESettings(), new NAMEContext());
Assert.Equal(0, configuration.InfrastructureDependencies.Count());
Assert.Equal(0, configuration.ServiceDependencies.Count());
}
finally
{
File.Delete(fileName);
}
}
[Fact]
[Trait("TestCategory", "Unit")]
public void ReadConfiguration_WithAllOverrides()
{
string fileContents = @"{
""$schema"": ""./config-manifest.schema.json"",
""Overrides"": {
""RunningMode"": ""NAMEDisabled"",
""RegistryEndpoints"": [
""http://name:80/api"",
""http://name2:80/api""
],
""SelfHostPortRangeFirst"": 1,
""SelfHostPortRangeLast"": 10,
""ServiceDependencyMaxHops"": 2,
""ConnectedDependencyShowConnectionString"": false,
""DependencyConnectTimeout"": 429496721,
""DependencyReadWriteTimeout"": 429496722,
""RegistryBootstrapRetryFrequency"": ""00.02:00:00"",
""RegistryBootstrapTimeout"": ""00.00:00:31""
},
""infrastructure_dependencies"": [
],
""service_dependencies"": [
]
}";
string fileName = Guid.NewGuid() + ".json";
File.WriteAllText(fileName, fileContents);
try
{
NAMESettings settings = DependenciesReader.ReadNAMESettingsOverrides(fileName, new DummyFilePathMapper());
ParsedDependencies configuration = DependenciesReader.ReadDependencies(fileName, new DummyFilePathMapper(), settings, new NAMEContext());
Assert.Equal(0, configuration.InfrastructureDependencies.Count());
Assert.Equal(0, configuration.ServiceDependencies.Count());
Assert.Equal(SupportedNAMEBehaviours.NAMEDisabled, settings.RunningMode);
Assert.Equal(new[] { "http://name:80/api", "http://name2:80/api" }, settings.RegistryEndpoints);
Assert.Equal(1, settings.SelfHostPortRangeFirst);
Assert.Equal(10, settings.SelfHostPortRangeLast);
Assert.Equal(2, settings.ServiceDependencyMaxHops);
Assert.False(settings.ConnectedDependencyShowConnectionString);
Assert.Equal(429496721, settings.DependencyConnectTimeout);
Assert.Equal(429496722, settings.DependencyReadWriteTimeout);
Assert.Equal(TimeSpan.FromHours(2), settings.RegistryBootstrapRetryFrequency);
Assert.Equal(TimeSpan.FromSeconds(31), settings.RegistryBootstrapTimeout);
}
finally
{
File.Delete(fileName);
}
}
[Fact]
[Trait("TestCategory", "Unit")]
[TestPriority(2)]
public void ReadConfiguration()
{
#if NET452
System.Configuration.ConfigurationManager.ConnectionStrings.SetWritable().Add(new System.Configuration.ConnectionStringSettings("RabbitMQConnectionString", "ConnString"));
#endif
int overrideCallsCount = 0;
var settings = new NAMESettings()
{
ConnectionStringProviderOverride = (node) =>
{
overrideCallsCount = overrideCallsCount + 1;
return null;
}
};
ParsedDependencies configuration = DependenciesReader.ReadDependencies(CONFIGURATION_FILE, new DummyFilePathMapper(), settings, new NAMEContext());
#if NET452
Assert.Equal(4, configuration.InfrastructureDependencies.Count());
Assert.Equal(2, configuration.ServiceDependencies.Count());
Assert.Equal(1, overrideCallsCount);
#else
Assert.Equal(3, configuration.InfrastructureDependencies.Count());
Assert.Equal(2, configuration.ServiceDependencies.Count());
Assert.Equal(0, overrideCallsCount);
#endif
var elasticsearchDependency = configuration.InfrastructureDependencies.OfType<VersionedDependency>().Single(d => d.Type == SupportedDependencies.Elasticsearch);
var castedMaxVersion = Assert.IsAssignableFrom<WildcardDependencyVersion>(elasticsearchDependency.MaximumVersion);
Assert.False(castedMaxVersion.IsMajorWildcard);
Assert.True(castedMaxVersion.IsMinorWildcard);
}
#if NET452
[Fact]
[Trait("TestCategory", "Unit")]
[TestPriority(1)]
public void ReadConfiguration_ConnectionStringNotFound()
{
System.Configuration.ConfigurationManager.ConnectionStrings.SetWritable().Remove("RabbitMQConnectionString");
DependenciesReader.ReadDependencies(CONFIGURATION_FILE, new DummyFilePathMapper(), new NAMESettings(), new NAMEContext());
}
#endif
}
public class CreateConfigurationFileFixture : IDisposable
{
public CreateConfigurationFileFixture()
{
if (File.Exists(ConfigurationReaderTests.CONFIGURATION_FILE))
File.Delete(ConfigurationReaderTests.CONFIGURATION_FILE);
File.WriteAllText(ConfigurationReaderTests.CONFIGURATION_FILE, ConfigurationReaderTests.CONFIGURATION_CONTENTS);
}
public void Dispose()
{
File.Delete(ConfigurationReaderTests.CONFIGURATION_FILE);
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using PSDocs.Configuration;
using PSDocs.Data;
using PSDocs.Models;
using PSDocs.Processor;
using PSDocs.Processor.Markdown;
using PSDocs.Runtime;
using System.Collections.Generic;
namespace PSDocs.Pipeline
{
public interface IInvokePipelineBuilder : IPipelineBuilder
{
void InstanceName(string[] instanceName);
void Convention(string[] convention);
}
/// <summary>
/// The pipeline builder for Invoke-PSDocument.
/// </summary>
internal sealed class InvokePipelineBuilder : PipelineBuilderBase, IInvokePipelineBuilder
{
private string[] _InstanceName;
private string[] _Convention;
private InputFileInfo[] _InputPath;
internal InvokePipelineBuilder(Source[] source, HostContext hostContext)
: base(source, hostContext)
{
_InputPath = null;
}
public void InputPath(string[] path)
{
if (path == null || path.Length == 0)
return;
var basePath = PSDocumentOption.GetWorkingPath();
var filter = PathFilterBuilder.Create(basePath, Option.Input.PathIgnore);
filter.UseGitIgnore();
var builder = new InputPathBuilder(Writer, basePath, "*", filter.Build());
builder.Add(path);
_InputPath = builder.Build();
}
public void InstanceName(string[] instanceName)
{
if (instanceName == null || instanceName.Length == 0)
return;
_InstanceName = instanceName;
}
public void Convention(string[] convention)
{
if (convention == null || convention.Length == 0)
return;
_Convention = convention;
}
public override IPipeline Build()
{
if (RequireSources() || RequireCulture())
return null;
return new InvokePipeline(PrepareContext(), Source);
}
protected override PipelineContext PrepareContext()
{
var instanceNameBinder = new InstanceNameBinder(_InstanceName);
var context = new PipelineContext(GetOptionContext(), PrepareStream(), Writer, OutputVisitor, instanceNameBinder, _Convention);
return context;
}
protected override PipelineStream PrepareStream()
{
if (!string.IsNullOrEmpty(Option.Input.ObjectPath))
{
AddVisitTargetObjectAction((targetObject, next) =>
{
return PipelineReceiverActions.ReadObjectPath(targetObject, next, Option.Input.ObjectPath, true);
});
}
if (Option.Input.Format == InputFormat.Yaml)
{
AddVisitTargetObjectAction((targetObject, next) =>
{
return PipelineReceiverActions.ConvertFromYaml(targetObject, next);
});
}
else if (Option.Input.Format == InputFormat.Json)
{
AddVisitTargetObjectAction((targetObject, next) =>
{
return PipelineReceiverActions.ConvertFromJson(targetObject, next);
});
}
else if (Option.Input.Format == InputFormat.PowerShellData)
{
AddVisitTargetObjectAction((targetObject, next) =>
{
return PipelineReceiverActions.ConvertFromPowerShellData(targetObject, next);
});
}
else if (Option.Input.Format == InputFormat.Detect && _InputPath != null)
{
AddVisitTargetObjectAction((targetObject, next) =>
{
return PipelineReceiverActions.DetectInputFormat(targetObject, next);
});
}
return new PipelineStream(VisitTargetObject, _InputPath);
}
}
/// <summary>
/// The pipeline for Invoke-PSDocument.
/// </summary>
internal sealed class InvokePipeline : StreamPipeline, IPipeline
{
private readonly List<IDocumentResult> _Completed;
private IDocumentBuilder[] _Builder;
private MarkdownProcessor _Processor;
private RunspaceContext _Runspace;
internal InvokePipeline(PipelineContext context, Source[] source)
: base(context, source)
{
_Runspace = new RunspaceContext(Context);
HostHelper.ImportResource(Source, _Runspace);
_Builder = HostHelper.GetDocumentBuilder(_Runspace, Source);
_Processor = new MarkdownProcessor();
_Completed = new List<IDocumentResult>();
}
protected override void ProcessObject(TargetObject targetObject)
{
try
{
var doc = BuildDocument(targetObject);
for (var i = 0; doc != null && i < doc.Length; i++)
{
var result = WriteDocument(doc[i]);
if (result != null)
{
Context.WriteOutput(result);
_Completed.Add(result);
}
}
}
finally
{
_Runspace.ExitTargetObject();
}
}
public override void End()
{
if (_Completed.Count == 0)
return;
var completed = _Completed.ToArray();
_Runspace.SetOutput(completed);
try
{
for (var i = 0; i < _Builder.Length; i++)
{
_Builder[i].End(_Runspace, completed);
}
}
finally
{
_Runspace.ClearOutput();
}
}
private IDocumentResult WriteDocument(Document document)
{
return _Processor.Process(Context.Option, document);
}
internal Document[] BuildDocument(TargetObject targetObject)
{
_Runspace.EnterTargetObject(targetObject);
var result = new List<Document>();
for (var c = 0; c < Context.Option.Output.Culture.Length; c++)
{
_Runspace.EnterCulture(Context.Option.Output.Culture[c]);
for (var i = 0; i < _Builder.Length; i++)
{
foreach (var instanceName in Context.InstanceNameBinder.GetInstanceName(_Builder[i].Name))
{
_Runspace.EnterDocument(instanceName);
try
{
var document = _Builder[i].Process(_Runspace, targetObject.Value);
if (document != null)
result.Add(document);
}
finally
{
_Runspace.ExitDocument();
}
}
}
}
return result.ToArray();
}
#region IDisposable
protected override void Dispose(bool disposing)
{
if (disposing)
{
_Processor = null;
if (_Builder != null)
{
for (var i = 0; i < _Builder.Length; i++)
_Builder[i].Dispose();
_Builder = null;
}
_Runspace.Dispose();
_Runspace = null;
}
base.Dispose(disposing);
}
#endregion IDisposable
}
}
| |
using UnityEngine;
public enum MegaWeightChannel
{
Red,
Green,
Blue,
Alpha,
None,
}
public enum MegaModChannel
{
None = 0,
Verts = 1,
UV = 2,
UV1 = 4,
UV2 = 8,
Normals = 16,
Tris = 32,
Col = 64,
Selection = 128,
All = 32767,
}
[RequireComponent(typeof(MegaModifyObject))]
public class MegaModifier : MonoBehaviour
{
[HideInInspector]
public bool ModEnabled = true;
[HideInInspector]
public bool DisplayGizmo = true;
[HideInInspector]
public int Order = -1;
[HideInInspector]
public Vector3 Offset = Vector3.zero;
[HideInInspector]
public Vector3 gizmoPos = Vector3.zero;
[HideInInspector]
public Vector3 gizmoRot = Vector3.zero;
[HideInInspector]
public Vector3 gizmoScale = Vector3.one;
[HideInInspector]
public Color gizCol1 = Color.yellow;
[HideInInspector]
public Color gizCol2 = Color.green;
[HideInInspector]
[System.NonSerialized]
public Matrix4x4 tm = new Matrix4x4();
[System.NonSerialized]
public Matrix4x4 invtm = new Matrix4x4();
[HideInInspector]
public MegaBox3 bbox = new MegaBox3();
[HideInInspector]
public Vector3[] corners = new Vector3[8];
//[HideInInspector]
//public bool useWeights = false;
//[HideInInspector]
//public MegaWeightChannel weightChannel = MegaWeightChannel.Red;
[HideInInspector]
public int steps = 50; // How many steps for the gizmo boxes
// new for mt
[HideInInspector]
public Vector3[] verts;
[HideInInspector]
public Vector3[] sverts;
[HideInInspector]
public bool valid;
[HideInInspector]
public float[] selection;
[HideInInspector]
public MegaModifier instance; // For groups this is the mod to use will be same type
public bool limitchandisplay = false;
public int startchannel = 0;
public int displaychans = 10;
#if UNITY_4_3 || UNITY_4_5 || UNITY_4_6 || UNITY_5_0 || UNITY_5_1 || UNITY_5 || UNITY_2017
public bool useUndo = false;
#else
public bool useUndo = true;
#endif
[HideInInspector]
public string Label = "";
[HideInInspector]
public int MaxLOD = 0;
public virtual MegaModChannel ChannelsReq() { return MegaModChannel.Verts; }
public virtual MegaModChannel ChannelsChanged() { return MegaModChannel.Verts; }
public virtual float GizmoSize() { return bbox.Radius() * 0.05f; }
public virtual void ModStart(MegaModifiers ms) { }
public virtual void ModUpdate() { }
public virtual bool ModLateUpdate(MegaModContext mc) { return true; } // TODO: Do we need mc now?
public virtual Vector3 Map(int i, Vector3 p) { return p; }
public virtual void ShowGUI() { }
public virtual string ModName() { return "Missing Name"; }
public virtual bool InitMod(MegaModifiers mc) { return true; }
public virtual bool Prepare(MegaModContext mc) { return true; }
public virtual void ModEnd(MegaModifiers ms) { }
public virtual string GetHelpURL() { return "?page_id=377"; }
public virtual void PrepareMT(MegaModifiers mc, int cores) { }
public virtual void DoneMT(MegaModifiers mc) {}
public virtual void SetValues(MegaModifier mod) {}
public virtual bool CanThread() { return true; }
// Used for copying and prefabs
public virtual void Copy(MegaModifier dst)
{
dst.Label = Label;
dst.MaxLOD = MaxLOD;
dst.ModEnabled = ModEnabled;
dst.DisplayGizmo = DisplayGizmo;
dst.Order = Order;
dst.Offset = Offset;
dst.gizmoPos = gizmoPos;
dst.gizmoRot = gizmoRot;
dst.gizmoScale = gizmoScale;
dst.gizCol1 = gizCol1;
dst.gizCol2 = gizCol2;
}
public virtual void PostCopy(MegaModifier dst)
{
}
public virtual void DoWork(MegaModifiers mc, int index, int start, int end, int cores)
{
//if ( useWeights )
if ( selection != null )
{
DoWorkWeighted(mc, index, start, end, cores);
return;
}
for ( int i = start; i < end; i++ )
sverts[i] = Map(i, verts[i]);
}
public virtual void DoWorkWeighted(MegaModifiers mc, int index, int start, int end, int cores)
{
for ( int i = start; i < end; i++ )
{
Vector3 p = verts[i];
float w = selection[i]; //[(int)weightChannel];
if ( w > 0.001f )
{
Vector3 mp = Map(i, verts[i]);
sverts[i].x = p.x + (mp.x - p.x) * w;
sverts[i].y = p.y + (mp.y - p.y) * w;
sverts[i].z = p.z + (mp.z - p.z) * w;
}
else
sverts[i] = p; //verts[i];
}
}
// This is never called
void Awake()
{
MegaModifyObject modobj = (MegaModifyObject)gameObject.GetComponent<MegaModifyObject>();
if ( modobj != null )
modobj.ModReset(this);
}
void Reset()
{
MegaModifyObject modobj = (MegaModifyObject)gameObject.GetComponent<MegaModifyObject>();
if ( modobj != null )
modobj.ModReset(this);
}
[ContextMenu("Help")]
public void Help()
{
Application.OpenURL("http://www.west-racing.com/mf/" + GetHelpURL());
}
[ContextMenu("Reset Offset")]
public void ResetOffset()
{
Offset = Vector3.zero;
}
Vector3 GetCentre()
{
MegaModifyObject modobj = (MegaModifyObject)gameObject.GetComponent<MegaModifyObject>();
if ( modobj != null && modobj.cachedMesh != null )
return modobj.cachedMesh.bounds.center;
return Vector3.zero;
}
[ContextMenu("Reset GizmoPos")]
public void ResetGizmoPos()
{
gizmoPos = Vector3.zero;
}
[ContextMenu("Reset GizmoRot")]
public void ResetGizmoRot()
{
gizmoRot = Vector3.zero;
}
[ContextMenu("Reset GizmoScale")]
public void ResetGizmoScale()
{
gizmoScale = Vector3.one;
}
[ContextMenu("Center Offset")]
public void CentreOffset()
{
Offset = -GetCentre();
}
[ContextMenu("Center GizmoPos")]
public void CentreGizmoPos()
{
gizmoPos = -GetCentre();
}
// TODO: This is wrong, Offset should be 0
public void SetModMesh(Mesh ms)
{
if ( ms != null )
{
Bounds b = ms.bounds;
//Offset = -b.center;
bbox.min = b.center - b.extents;
bbox.max = b.center + b.extents;
verts = ms.vertices;
MeshChanged();
}
}
public virtual void MeshChanged()
{
}
public void SetTM()
{
tm = Matrix4x4.identity;
Quaternion rot = Quaternion.Euler(-gizmoRot);
tm.SetTRS(gizmoPos + Offset, rot, gizmoScale);
invtm = tm.inverse;
}
public void SetTM(Vector3 off)
{
tm = Matrix4x4.identity;
Quaternion rot = Quaternion.Euler(-gizmoRot);
tm.SetTRS(gizmoPos + off, rot, gizmoScale);
invtm = tm.inverse;
}
public void SetAxis(Matrix4x4 tmAxis)
{
Matrix4x4 itm = tmAxis.inverse;
tm = tmAxis * tm;
invtm = invtm * itm;
}
public virtual void Modify(ref Vector3[] sverts, ref Vector3[] verts)
{
for ( int i = 0; i < verts.Length; i++ )
sverts[i] = Map(i, verts[i]);
}
public virtual void Modify(Vector3[] sverts, Vector3[] verts)
{
for ( int i = 0; i < verts.Length; i++ )
sverts[i] = Map(i, verts[i]);
}
public virtual void Modify(MegaModifiers mc)
{
if ( verts != null )
{
for ( int i = 0; i < verts.Length; i++ )
sverts[i] = Map(i, verts[i]);
}
}
// Weighted version
// Only be here if weights are being used
public virtual void ModifyWeighted(MegaModifiers mc)
{
for ( int i = 0; i < verts.Length; i++ )
{
Vector3 p = verts[i];
float w = mc.selection[i];
if ( w > 0.001f )
{
Vector3 mp = Map(i, verts[i]);
sverts[i].x = p.x + (mp.x - p.x) * w;
sverts[i].y = p.y + (mp.y - p.y) * w;
sverts[i].z = p.z + (mp.z - p.z) * w;
}
else
sverts[i] = verts[i];
}
}
public void DrawEdge(Vector3 p1, Vector3 p2)
{
Vector3 last = Map(-1, p1);
Vector3 pos = Vector3.zero;
for ( int i = 1; i <= steps; i++ )
{
pos = p1 + ((p2 - p1) * ((float)i / (float)steps));
pos = Map(-1, pos);
if ( (i & 4) == 0 )
Gizmos.color = gizCol1;
else
Gizmos.color = gizCol2;
Gizmos.DrawLine(last, pos);
last = pos;
}
Gizmos.color = gizCol1;
}
public void DrawEdgeCol(Vector3 p1, Vector3 p2)
{
Vector3 last = Map(-1, p1);
Vector3 pos = Vector3.zero;
for ( int i = 1; i <= steps; i++ )
{
pos = p1 + ((p2 - p1) * ((float)i / (float)steps));
pos = Map(-1, pos);
Gizmos.DrawLine(last, pos);
last = pos;
}
}
// TODO: If we draw like warps do we know if we are the current edited script?
public virtual void DrawGizmo(MegaModContext context)
{
tm = Matrix4x4.identity;
MegaMatrix.Translate(ref tm, context.Offset);
invtm = tm.inverse;
if ( !Prepare(context) )
return;
Vector3 min = context.bbox.min;
Vector3 max = context.bbox.max;
Matrix4x4 gtm = Matrix4x4.identity;
Vector3 pos = gizmoPos;
pos.x = -pos.x;
pos.y = -pos.y;
pos.z = -pos.z;
Vector3 scl = gizmoScale;
scl.x = 1.0f - (scl.x - 1.0f);
scl.y = 1.0f - (scl.y - 1.0f);
gtm.SetTRS(pos, Quaternion.Euler(gizmoRot), scl);
// put sourceObj into context
if ( context.mod.sourceObj != null )
Gizmos.matrix = context.mod.sourceObj.transform.localToWorldMatrix * gtm;
else
Gizmos.matrix = context.go.transform.localToWorldMatrix * gtm;
//Gizmos.color = ModCol(); //Color.yellow;
corners[0] = new Vector3(min.x, min.y, min.z);
corners[1] = new Vector3(min.x, max.y, min.z);
corners[2] = new Vector3(max.x, max.y, min.z);
corners[3] = new Vector3(max.x, min.y, min.z);
corners[4] = new Vector3(min.x, min.y, max.z);
corners[5] = new Vector3(min.x, max.y, max.z);
corners[6] = new Vector3(max.x, max.y, max.z);
corners[7] = new Vector3(max.x, min.y, max.z);
DrawEdge(corners[0], corners[1]);
DrawEdge(corners[1], corners[2]);
DrawEdge(corners[2], corners[3]);
DrawEdge(corners[3], corners[0]);
DrawEdge(corners[4], corners[5]);
DrawEdge(corners[5], corners[6]);
DrawEdge(corners[6], corners[7]);
DrawEdge(corners[7], corners[4]);
DrawEdge(corners[0], corners[4]);
DrawEdge(corners[1], corners[5]);
DrawEdge(corners[2], corners[6]);
DrawEdge(corners[3], corners[7]);
ExtraGizmo(context);
}
public virtual void ExtraGizmo(MegaModContext mc)
{
}
public void DrawFromTo(MegaAxis axis, float from, float to, MegaModContext mc)
{
Vector3 min = mc.bbox.min;
Vector3 max = mc.bbox.max;
switch ( axis )
{
case MegaAxis.X:
corners[0] = new Vector3(-from, min.y, min.z);
corners[1] = new Vector3(-from, max.y, min.z);
corners[2] = new Vector3(-from, max.y, max.z);
corners[3] = new Vector3(-from, min.y, max.z);
corners[4] = new Vector3(-to, min.y, min.z);
corners[5] = new Vector3(-to, max.y, min.z);
corners[6] = new Vector3(-to, max.y, max.z);
corners[7] = new Vector3(-to, min.y, max.z);
break;
case MegaAxis.Y:
corners[0] = new Vector3(min.x, min.y, -from);
corners[1] = new Vector3(min.x, max.y, -from);
corners[2] = new Vector3(max.x, max.y, -from);
corners[3] = new Vector3(max.x, min.y, -from);
corners[4] = new Vector3(min.x, min.y, -to);
corners[5] = new Vector3(min.x, max.y, -to);
corners[6] = new Vector3(max.x, max.y, -to);
corners[7] = new Vector3(max.x, min.y, -to);
break;
case MegaAxis.Z:
corners[0] = new Vector3(min.x, from, min.z);
corners[1] = new Vector3(min.x, from, max.z);
corners[2] = new Vector3(max.x, from, max.z);
corners[3] = new Vector3(max.x, from, min.z);
corners[4] = new Vector3(min.x, to, min.z);
corners[5] = new Vector3(min.x, to, max.z);
corners[6] = new Vector3(max.x, to, max.z);
corners[7] = new Vector3(max.x, to, min.z);
break;
}
Color c = Color.red;
c.a = gizCol1.a;
Gizmos.color = c;
Vector3 offset = Vector3.zero; //mc.Offset;
DrawEdgeCol(corners[0] - offset, corners[1] - offset);
DrawEdgeCol(corners[1] - offset, corners[2] - offset);
DrawEdgeCol(corners[2] - offset, corners[3] - offset);
DrawEdgeCol(corners[3] - offset, corners[0] - offset);
c = Color.green;
c.a = gizCol1.a;
Gizmos.color = c;
DrawEdgeCol(corners[4] - offset, corners[5] - offset);
DrawEdgeCol(corners[5] - offset, corners[6] - offset);
DrawEdgeCol(corners[6] - offset, corners[7] - offset);
DrawEdgeCol(corners[7] - offset, corners[4] - offset);
}
void OnDrawGizmosSelected()
{
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Runtime.InteropServices;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class MissingAssemblyTests : ExpressionCompilerTestBase
{
[Fact]
public void ErrorsWithAssemblyIdentityArguments()
{
var identity = new AssemblyIdentity(GetUniqueName());
Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_NoTypeDef, identity));
}
[Fact]
public void ErrorsWithAssemblySymbolArguments()
{
var assembly = CreateCompilation("").Assembly;
var identity = assembly.Identity;
Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_GlobalSingleTypeNameNotFoundFwd, assembly));
Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_DottedTypeNameNotFoundInNSFwd, assembly));
Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_SingleTypeNameNotFoundFwd, assembly));
Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_NameNotInContextPossibleMissingReference, assembly));
}
[Fact]
public void ErrorsRequiringSystemCore()
{
var identity = EvaluationContextBase.SystemCoreIdentity;
Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_DynamicAttributeMissing));
Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_DynamicRequiredTypesMissing));
Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_QueryNoProviderStandard));
Assert.Same(identity, GetMissingAssemblyIdentity(ErrorCode.ERR_ExtensionAttrNotFound));
}
[Fact]
public void MultipleAssemblyArguments()
{
var identity1 = new AssemblyIdentity(GetUniqueName());
var identity2 = new AssemblyIdentity(GetUniqueName());
Assert.Equal(identity1, GetMissingAssemblyIdentity(ErrorCode.ERR_NoTypeDef, identity1, identity2));
Assert.Equal(identity2, GetMissingAssemblyIdentity(ErrorCode.ERR_NoTypeDef, identity2, identity1));
}
[Fact]
public void NoAssemblyArguments()
{
Assert.Null(GetMissingAssemblyIdentity(ErrorCode.ERR_NoTypeDef));
Assert.Null(GetMissingAssemblyIdentity(ErrorCode.ERR_NoTypeDef, "Not an assembly"));
}
[Fact]
public void ERR_NoTypeDef()
{
var libSource = @"
public class Missing { }
";
var source = @"
public class C
{
public void M(Missing parameter)
{
}
}
";
var libRef = CreateCompilationWithMscorlib(libSource, assemblyName: "Lib").EmitToImageReference();
var comp = CreateCompilationWithMscorlib(source, new[] { libRef }, TestOptions.DebugDll);
var context = CreateMethodContextWithReferences(comp, "C.M", MscorlibRef);
var expectedError = "error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.";
var expectedMissingAssemblyIdentity = new AssemblyIdentity("Lib");
ResultProperties resultProperties;
string actualError;
ImmutableArray<AssemblyIdentity> actualMissingAssemblyIdentities;
context.CompileExpression(
DefaultInspectionContext.Instance,
"parameter",
DkmEvaluationFlags.TreatAsExpression,
DiagnosticFormatter.Instance,
out resultProperties,
out actualError,
out actualMissingAssemblyIdentities,
EnsureEnglishUICulture.PreferredOrNull,
testData: null);
Assert.Equal(expectedError, actualError);
Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single());
}
[Fact]
public void ERR_QueryNoProviderStandard()
{
var source = @"
public class C
{
public void M(int[] array)
{
}
}
";
var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef }, TestOptions.DebugDll);
var context = CreateMethodContextWithReferences(comp, "C.M", MscorlibRef);
var expectedError = "(1,11): error CS1935: Could not find an implementation of the query pattern for source type 'int[]'. 'Select' not found. Are you missing a reference to 'System.Core.dll' or a using directive for 'System.Linq'?";
var expectedMissingAssemblyIdentity = EvaluationContextBase.SystemCoreIdentity;
ResultProperties resultProperties;
string actualError;
ImmutableArray<AssemblyIdentity> actualMissingAssemblyIdentities;
context.CompileExpression(
DefaultInspectionContext.Instance,
"from i in array select i",
DkmEvaluationFlags.TreatAsExpression,
DiagnosticFormatter.Instance,
out resultProperties,
out actualError,
out actualMissingAssemblyIdentities,
EnsureEnglishUICulture.PreferredOrNull,
testData: null);
Assert.Equal(expectedError, actualError);
Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single());
}
[Fact]
public void ForwardingErrors()
{
var il = @"
.assembly extern mscorlib { }
.assembly extern pe2 { }
.assembly pe1 { }
.class extern forwarder Forwarded
{
.assembly extern pe2
}
.class extern forwarder NS.Forwarded
{
.assembly extern pe2
}
.class public auto ansi beforefieldinit Dummy
extends [mscorlib]System.Object
{
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
}
";
var csharp = @"
class C
{
static void M(Dummy d)
{
}
}
";
var ilRef = CompileIL(il, appendDefaultHeader: false);
var comp = CreateCompilationWithMscorlib(csharp, new[] { ilRef });
var runtime = CreateRuntimeInstance(comp);
var context = CreateMethodContext(runtime, "C.M");
var expectedMissingAssemblyIdentity = new AssemblyIdentity("pe2");
ResultProperties resultProperties;
string actualError;
ImmutableArray<AssemblyIdentity> actualMissingAssemblyIdentities;
context.CompileExpression(
DefaultInspectionContext.Instance,
"new global::Forwarded()",
DkmEvaluationFlags.TreatAsExpression,
DiagnosticFormatter.Instance,
out resultProperties,
out actualError,
out actualMissingAssemblyIdentities,
EnsureEnglishUICulture.PreferredOrNull,
testData: null);
Assert.Equal(
"error CS1068: The type name 'Forwarded' could not be found in the global namespace. This type has been forwarded to assembly 'pe2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' Consider adding a reference to that assembly.",
actualError);
Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single());
context.CompileExpression(
DefaultInspectionContext.Instance,
"new Forwarded()",
DkmEvaluationFlags.TreatAsExpression,
DiagnosticFormatter.Instance,
out resultProperties,
out actualError,
out actualMissingAssemblyIdentities,
EnsureEnglishUICulture.PreferredOrNull,
testData: null);
Assert.Equal(
"error CS1070: The type name 'Forwarded' could not be found. This type has been forwarded to assembly 'pe2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Consider adding a reference to that assembly.",
actualError);
Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single());
context.CompileExpression(
DefaultInspectionContext.Instance,
"new NS.Forwarded()",
DkmEvaluationFlags.TreatAsExpression,
DiagnosticFormatter.Instance,
out resultProperties,
out actualError,
out actualMissingAssemblyIdentities,
EnsureEnglishUICulture.PreferredOrNull,
testData: null);
Assert.Equal(
"error CS1069: The type name 'Forwarded' could not be found in the namespace 'NS'. This type has been forwarded to assembly 'pe2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' Consider adding a reference to that assembly.",
actualError);
Assert.Equal(expectedMissingAssemblyIdentity, actualMissingAssemblyIdentities.Single());
}
[Fact]
public unsafe void ShouldTryAgain_Success()
{
var comp = CreateCompilationWithMscorlib("public class C { }");
using (var pinned = new PinnedMetadata(GetMetadataBytes(comp)))
{
DkmUtilities.GetMetadataBytesPtrFunction gmdbpf = (AssemblyIdentity assemblyIdentity, out uint uSize) =>
{
uSize = (uint)pinned.Size;
return pinned.Pointer;
};
var references = ImmutableArray<MetadataBlock>.Empty;
var missingAssemblyIdentity = new AssemblyIdentity("A");
var missingAssemblyIdentities = ImmutableArray.Create(missingAssemblyIdentity);
Assert.True(ExpressionCompiler.ShouldTryAgainWithMoreMetadataBlocks(gmdbpf, missingAssemblyIdentities, ref references));
var newReference = references.Single();
Assert.Equal(pinned.Pointer, newReference.Pointer);
Assert.Equal(pinned.Size, newReference.Size);
}
}
[Fact]
public unsafe void ShouldTryAgain_Mixed()
{
var comp1 = CreateCompilationWithMscorlib("public class C { }", assemblyName: GetUniqueName());
var comp2 = CreateCompilationWithMscorlib("public class D { }", assemblyName: GetUniqueName());
using (PinnedMetadata pinned1 = new PinnedMetadata(GetMetadataBytes(comp1)),
pinned2 = new PinnedMetadata(GetMetadataBytes(comp2)))
{
var assemblyIdentity1 = comp1.Assembly.Identity;
var assemblyIdentity2 = comp2.Assembly.Identity;
Assert.NotEqual(assemblyIdentity1, assemblyIdentity2);
DkmUtilities.GetMetadataBytesPtrFunction gmdbpf = (AssemblyIdentity assemblyIdentity, out uint uSize) =>
{
if (assemblyIdentity == assemblyIdentity1)
{
uSize = (uint)pinned1.Size;
return pinned1.Pointer;
}
else if (assemblyIdentity == assemblyIdentity2)
{
uSize = (uint)pinned2.Size;
return pinned2.Pointer;
}
else
{
Marshal.ThrowExceptionForHR(unchecked((int)MetadataUtilities.CORDBG_E_MISSING_METADATA));
throw ExceptionUtilities.Unreachable;
}
};
var references = ImmutableArray.Create(default(MetadataBlock));
var unknownAssemblyIdentity = new AssemblyIdentity(GetUniqueName());
var missingAssemblyIdentities = ImmutableArray.Create(assemblyIdentity1, unknownAssemblyIdentity, assemblyIdentity2);
Assert.True(ExpressionCompiler.ShouldTryAgainWithMoreMetadataBlocks(gmdbpf, missingAssemblyIdentities, ref references));
Assert.Equal(3, references.Length);
Assert.Equal(default(MetadataBlock), references[0]);
Assert.Equal(pinned1.Pointer, references[1].Pointer);
Assert.Equal(pinned1.Size, references[1].Size);
Assert.Equal(pinned2.Pointer, references[2].Pointer);
Assert.Equal(pinned2.Size, references[2].Size);
}
}
[Fact]
public void ShouldTryAgain_CORDBG_E_MISSING_METADATA()
{
DkmUtilities.GetMetadataBytesPtrFunction gmdbpf = (AssemblyIdentity assemblyIdentity, out uint uSize) =>
{
Marshal.ThrowExceptionForHR(unchecked((int)MetadataUtilities.CORDBG_E_MISSING_METADATA));
throw ExceptionUtilities.Unreachable;
};
var references = ImmutableArray<MetadataBlock>.Empty;
var missingAssemblyIdentities = ImmutableArray.Create(new AssemblyIdentity("A"));
Assert.False(ExpressionCompiler.ShouldTryAgainWithMoreMetadataBlocks(gmdbpf, missingAssemblyIdentities, ref references));
Assert.Empty(references);
}
[Fact]
public void ShouldTryAgain_COR_E_BADIMAGEFORMAT()
{
DkmUtilities.GetMetadataBytesPtrFunction gmdbpf = (AssemblyIdentity assemblyIdentity, out uint uSize) =>
{
Marshal.ThrowExceptionForHR(unchecked((int)MetadataUtilities.COR_E_BADIMAGEFORMAT));
throw ExceptionUtilities.Unreachable;
};
var references = ImmutableArray<MetadataBlock>.Empty;
var missingAssemblyIdentities = ImmutableArray.Create(new AssemblyIdentity("A"));
Assert.False(ExpressionCompiler.ShouldTryAgainWithMoreMetadataBlocks(gmdbpf, missingAssemblyIdentities, ref references));
Assert.Empty(references);
}
[Fact]
public void ShouldTryAgain_OtherException()
{
DkmUtilities.GetMetadataBytesPtrFunction gmdbpf = (AssemblyIdentity assemblyIdentity, out uint uSize) =>
{
throw new Exception();
};
var references = ImmutableArray<MetadataBlock>.Empty;
var missingAssemblyIdentities = ImmutableArray.Create(new AssemblyIdentity("A"));
Assert.Throws<Exception>(() => ExpressionCompiler.ShouldTryAgainWithMoreMetadataBlocks(gmdbpf, missingAssemblyIdentities, ref references));
}
private EvaluationContext CreateMethodContextWithReferences(Compilation comp, string methodName, params MetadataReference[] references)
{
byte[] exeBytes;
byte[] pdbBytes;
ImmutableArray<MetadataReference> unusedReferences;
var result = comp.EmitAndGetReferences(out exeBytes, out pdbBytes, out unusedReferences);
Assert.True(result);
var runtime = CreateRuntimeInstance(GetUniqueName(), ImmutableArray.CreateRange(references), exeBytes, new SymReader(pdbBytes));
return CreateMethodContext(runtime, methodName);
}
private static AssemblyIdentity GetMissingAssemblyIdentity(ErrorCode code, params object[] arguments)
{
var missingAssemblyIdentities = EvaluationContext.GetMissingAssemblyIdentitiesHelper(code, arguments);
return missingAssemblyIdentities.IsDefault ? null : missingAssemblyIdentities.Single();
}
private static ImmutableArray<byte> GetMetadataBytes(Compilation comp)
{
var imageReference = (MetadataImageReference)comp.EmitToImageReference();
var assemblyMetadata = (AssemblyMetadata)imageReference.GetMetadata();
var moduleMetadata = assemblyMetadata.GetModules()[0];
return moduleMetadata.Module.PEReaderOpt.GetMetadata().GetContent();
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace AldursLab.WurmAssistantWebService.Areas.HelpPage.SampleGeneration
{
/// <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);
}
}
}
}
| |
namespace FakeItEasy.Specs
{
using System;
using FakeItEasy.Configuration;
using FakeItEasy.Tests.TestHelpers;
using FluentAssertions;
using Xbehave;
using Xunit;
public static class WrappingFakeSpecs
{
public interface IFoo
{
int NonVoidMethod(string? parameter);
void VoidMethod(string? parameter);
void OutAndRefMethod(ref int @ref, out int @out);
}
public interface IBar
{
int Id { get; }
}
[Scenario]
public static void NonVoidSuccess(
Foo realObject,
IFoo wrapper,
int result)
{
"Given a real object"
.x(() => realObject = new Foo());
"And a fake wrapping this object"
.x(() => wrapper = A.Fake<IFoo>(o => o.Wrapping(realObject)));
"When a non-void method is called on the wrapper"
.x(() => result = wrapper.NonVoidMethod("hello"));
"Then the real object's method is called"
.x(() => realObject.NonVoidMethodCalled.Should().BeTrue());
"And the wrapper returns the value returned by the real object's method"
.x(() => result.Should().Be(5));
}
[Scenario]
public static void NonVoidException(
Foo realObject,
IFoo wrapper,
Exception exception)
{
"Given a real object"
.x(() => realObject = new Foo());
"And a fake wrapping this object"
.x(() => wrapper = A.Fake<IFoo>(o => o.Wrapping(realObject)));
"When a non-void method is called on the wrapper"
.x(() => exception = Record.Exception(() => wrapper.NonVoidMethod(null)));
"Then the real object's method is called"
.x(() => realObject.NonVoidMethodCalled.Should().BeTrue());
"And the wrapper throws the exception thrown by the real object's method"
.x(() => exception.Should().BeAnExceptionOfType<ArgumentNullException>());
"And the exception stack trace is preserved"
.x(() => exception.StackTrace.Should().Contain("FakeItEasy.Specs.WrappingFakeSpecs.Foo.NonVoidMethod"));
}
[Scenario]
public static void VoidSuccess(
Foo realObject,
IFoo wrapper)
{
"Given a real object"
.x(() => realObject = new Foo());
"And a fake wrapping this object"
.x(() => wrapper = A.Fake<IFoo>(o => o.Wrapping(realObject)));
"When a void method is called on the wrapper"
.x(() => wrapper.VoidMethod("hello"));
"Then the real object's method is called"
.x(() => realObject.VoidMethodCalled.Should().BeTrue());
}
[Scenario]
public static void VoidException(
Foo realObject,
IFoo wrapper,
Exception exception)
{
"Given a real object"
.x(() => realObject = new Foo());
"And a fake wrapping this object"
.x(() => wrapper = A.Fake<IFoo>(o => o.Wrapping(realObject)));
"When a void method is called on the wrapper"
.x(() => exception = Record.Exception(() => wrapper.VoidMethod(null)));
"Then the real object's method is called"
.x(() => realObject.VoidMethodCalled.Should().BeTrue());
"And the wrapper throws the exception thrown by the real object's method"
.x(() => exception.Should().BeAnExceptionOfType<ArgumentNullException>());
"And the exception stack trace is preserved"
.x(() => exception.StackTrace.Should().Contain("FakeItEasy.Specs.WrappingFakeSpecs.Foo.VoidMethod"));
}
[Scenario]
public static void OutAndRef(
Foo realObject,
IFoo wrapper,
int @ref,
int @out)
{
"Given a real object"
.x(() => realObject = new Foo());
"And a fake wrapping this object"
.x(() => wrapper = A.Fake<IFoo>(o => o.Wrapping(realObject)));
"And a @ref variable with an initial value of 1"
.x(() => @ref = 1);
"When a method with out and ref parameters is called on the wrapper"
.x(() => wrapper.OutAndRefMethod(ref @ref, out @out));
"Then the real object's method is called"
.x(() => realObject.OutAndRefMethodCalled.Should().BeTrue());
"And the value of @ref is incremented"
.x(() => @ref.Should().Be(2));
"And the value of @out is set"
.x(() => @out.Should().Be(42));
}
[Scenario]
public static void FakeEqualsFake(Foo realObject, IFoo wrapper, bool equals)
{
"Given a real object"
.x(() => realObject = new Foo());
"And a fake wrapping this object"
.x(() => wrapper = A.Fake<IFoo>(o => o.Wrapping(realObject)));
"When Equals is called on the fake with itself as the argument"
.x(() => equals = wrapper.Equals(wrapper));
"Then it should return true"
.x(() => equals.Should().BeTrue());
}
[Scenario]
public static void FakeEqualsWrappedObject(Foo realObject, IFoo wrapper, bool equals)
{
"Given a real object"
.x(() => realObject = new Foo());
"And a fake wrapping this object"
.x(() => wrapper = A.Fake<IFoo>(o => o.Wrapping(realObject)));
"When Equals is called on the fake with the real object as the argument"
.x(() => equals = wrapper.Equals(realObject));
"Then it should return false"
.x(() => equals.Should().BeFalse());
}
[Scenario]
public static void FakeEqualsFakeWithValueSemantics(Bar realObject, IBar wrapper, bool equals)
{
"Given a real object that overrides Equals with value semantics"
.x(() => realObject = new Bar(42));
"And a fake wrapping this object"
.x(() => wrapper = A.Fake<IBar>(o => o.Wrapping(realObject)));
"When Equals is called on the fake with itself as the argument"
.x(() => equals = wrapper.Equals(wrapper));
"Then it should return true"
.x(() => equals.Should().BeTrue());
}
[Scenario]
public static void FakeEqualsWrappedObjectWithValueSemantics(Bar realObject, IBar wrapper, bool equals)
{
"Given a real object that overrides Equals with value semantics"
.x(() => realObject = new Bar(42));
"And a fake wrapping this object"
.x(() => wrapper = A.Fake<IBar>(o => o.Wrapping(realObject)));
"When Equals is called on the fake with the real object as the argument"
.x(() => equals = wrapper.Equals(realObject));
"Then it should return true"
.x(() => equals.Should().BeTrue());
}
[Scenario]
public static void VoidCallsWrappedMethod(Foo realObject, IFoo wrapper, bool callbackWasCalled)
{
"Given a real object"
.x(() => realObject = new Foo());
"And a fake wrapping this object"
.x(() => wrapper = A.Fake<IFoo>(o => o.Wrapping(realObject)));
"When a void method on the fake is configured to invoke a callback and call the wrapped method"
.x(() => A.CallTo(() => wrapper.VoidMethod("hello"))
.Invokes(() => callbackWasCalled = true)
.CallsWrappedMethod());
"And the configured method is called on the fake"
.x(() => wrapper.VoidMethod("hello"));
"Then the callback is invoked"
.x(() => callbackWasCalled.Should().BeTrue());
"And the real object's method is called"
.x(() => realObject.VoidMethodCalled.Should().BeTrue());
}
[Scenario]
public static void NonVoidCallsWrappedMethod(Foo realObject, IFoo wrapper, bool callbackWasCalled, int returnValue)
{
"Given a real object"
.x(() => realObject = new Foo());
"And a fake wrapping this object"
.x(() => wrapper = A.Fake<IFoo>(o => o.Wrapping(realObject)));
"When a non-void method on the fake is configured to invoke a callback and call the wrapped method"
.x(() => A.CallTo(() => wrapper.NonVoidMethod("hello"))
.Invokes(() => callbackWasCalled = true)
.CallsWrappedMethod());
"And the configured method is called on the fake"
.x(() => returnValue = wrapper.NonVoidMethod("hello"));
"Then the callback is invoked"
.x(() => callbackWasCalled.Should().BeTrue());
"And the real object's method is called"
.x(() => realObject.NonVoidMethodCalled.Should().BeTrue());
"And the wrapper returns the value returned by the real object's method"
.x(() => returnValue.Should().Be(5));
}
[Scenario]
public static void NotAWrappingFakeCallsWrappedMethod(IFoo fake, Exception exception)
{
"Given a non-wrapping fake"
.x(() => fake = A.Fake<IFoo>());
"When a method on the fake is configured to call the wrapped method"
.x(() => exception = Record.Exception(() => A.CallTo(() => fake.VoidMethod("hello")).CallsWrappedMethod()));
"Then it throws a FakeConfigurationException"
.x(() => exception.Should()
.BeAnExceptionOfType<FakeConfigurationException>()
.WithMessage("The configured fake is not a wrapping fake."));
}
public class Foo : IFoo
{
public bool NonVoidMethodCalled { get; private set; }
public bool VoidMethodCalled { get; private set; }
public bool OutAndRefMethodCalled { get; private set; }
public int NonVoidMethod(string? parameter)
{
this.NonVoidMethodCalled = true;
if (parameter is null)
{
throw new ArgumentNullException(nameof(parameter));
}
return parameter.Length;
}
public void VoidMethod(string? parameter)
{
this.VoidMethodCalled = true;
if (parameter is null)
{
throw new ArgumentNullException(nameof(parameter));
}
}
public void OutAndRefMethod(ref int @ref, out int @out)
{
this.OutAndRefMethodCalled = true;
@ref += 1;
@out = 42;
}
}
public class Bar : IBar
{
public Bar(int id)
{
this.Id = id;
}
public int Id { get; }
public override bool Equals(object? obj)
{
return obj is IBar other && other.Id == this.Id;
}
public override int GetHashCode()
{
return this.Id.GetHashCode();
}
}
}
}
| |
/*
* 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 Nini.Config;
using log4net;
using System;
using System.Reflection;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Serialization;
using System.Collections.Generic;
using OpenSim.Server.Base;
using OpenSim.Services.Interfaces;
using FriendInfo = OpenSim.Services.Interfaces.FriendInfo;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using OpenSim.Framework;
using OpenSim.Framework.Servers.HttpServer;
using OpenMetaverse;
namespace OpenSim.Server.Handlers.Hypergrid
{
public class HGFriendsServerPostHandler : BaseStreamHandler
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private IUserAgentService m_UserAgentService;
private IFriendsSimConnector m_FriendsLocalSimConnector;
private IHGFriendsService m_TheService;
public HGFriendsServerPostHandler(IHGFriendsService service, IUserAgentService uas, IFriendsSimConnector friendsConn) :
base("POST", "/hgfriends")
{
m_TheService = service;
m_UserAgentService = uas;
m_FriendsLocalSimConnector = friendsConn;
m_log.DebugFormat("[HGFRIENDS HANDLER]: HGFriendsServerPostHandler is On ({0})",
(m_FriendsLocalSimConnector == null ? "robust" : "standalone"));
if (m_TheService == null)
m_log.ErrorFormat("[HGFRIENDS HANDLER]: TheService is null!");
}
protected override byte[] ProcessRequest(string path, Stream requestData,
IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
{
string body;
using(StreamReader sr = new StreamReader(requestData))
body = sr.ReadToEnd();
body = body.Trim();
//m_log.DebugFormat("[XXX]: query String: {0}", body);
try
{
Dictionary<string, object> request =
ServerUtils.ParseQueryString(body);
if (!request.ContainsKey("METHOD"))
return FailureResult();
string method = request["METHOD"].ToString();
switch (method)
{
case "getfriendperms":
return GetFriendPerms(request);
case "newfriendship":
return NewFriendship(request);
case "deletefriendship":
return DeleteFriendship(request);
/* Same as inter-sim */
case "friendship_offered":
return FriendshipOffered(request);
case "validate_friendship_offered":
return ValidateFriendshipOffered(request);
case "statusnotification":
return StatusNotification(request);
/*
case "friendship_approved":
return FriendshipApproved(request);
case "friendship_denied":
return FriendshipDenied(request);
case "friendship_terminated":
return FriendshipTerminated(request);
case "grant_rights":
return GrantRights(request);
*/
}
m_log.DebugFormat("[HGFRIENDS HANDLER]: unknown method {0}", method);
}
catch (Exception e)
{
m_log.DebugFormat("[HGFRIENDS HANDLER]: Exception {0}", e);
}
return FailureResult();
}
#region Method-specific handlers
byte[] GetFriendPerms(Dictionary<string, object> request)
{
if (!VerifyServiceKey(request))
return FailureResult();
UUID principalID = UUID.Zero;
if (request.ContainsKey("PRINCIPALID"))
UUID.TryParse(request["PRINCIPALID"].ToString(), out principalID);
else
{
m_log.WarnFormat("[HGFRIENDS HANDLER]: no principalID in request to get friend perms");
return FailureResult();
}
UUID friendID = UUID.Zero;
if (request.ContainsKey("FRIENDID"))
UUID.TryParse(request["FRIENDID"].ToString(), out friendID);
else
{
m_log.WarnFormat("[HGFRIENDS HANDLER]: no friendID in request to get friend perms");
return FailureResult();
}
int perms = m_TheService.GetFriendPerms(principalID, friendID);
if (perms < 0)
return FailureResult("Friend not found");
return SuccessResult(perms.ToString());
}
byte[] NewFriendship(Dictionary<string, object> request)
{
bool verified = VerifyServiceKey(request);
FriendInfo friend = new FriendInfo(request);
bool success = m_TheService.NewFriendship(friend, verified);
if (success)
return SuccessResult();
else
return FailureResult();
}
byte[] DeleteFriendship(Dictionary<string, object> request)
{
FriendInfo friend = new FriendInfo(request);
string secret = string.Empty;
if (request.ContainsKey("SECRET"))
secret = request["SECRET"].ToString();
if (secret == string.Empty)
return BoolResult(false);
bool success = m_TheService.DeleteFriendship(friend, secret);
return BoolResult(success);
}
byte[] FriendshipOffered(Dictionary<string, object> request)
{
UUID fromID = UUID.Zero;
UUID toID = UUID.Zero;
string message = string.Empty;
string name = string.Empty;
if (!request.ContainsKey("FromID") || !request.ContainsKey("ToID"))
return BoolResult(false);
if (!UUID.TryParse(request["ToID"].ToString(), out toID))
return BoolResult(false);
message = request["Message"].ToString();
if (!UUID.TryParse(request["FromID"].ToString(), out fromID))
return BoolResult(false);
if (request.ContainsKey("FromName"))
name = request["FromName"].ToString();
bool success = m_TheService.FriendshipOffered(fromID, name, toID, message);
return BoolResult(success);
}
byte[] ValidateFriendshipOffered(Dictionary<string, object> request)
{
FriendInfo friend = new FriendInfo(request);
UUID friendID = UUID.Zero;
if (!UUID.TryParse(friend.Friend, out friendID))
return BoolResult(false);
bool success = m_TheService.ValidateFriendshipOffered(friend.PrincipalID, friendID);
return BoolResult(success);
}
byte[] StatusNotification(Dictionary<string, object> request)
{
UUID principalID = UUID.Zero;
if (request.ContainsKey("userID"))
UUID.TryParse(request["userID"].ToString(), out principalID);
else
{
m_log.WarnFormat("[HGFRIENDS HANDLER]: no userID in request to notify");
return FailureResult();
}
bool online = true;
if (request.ContainsKey("online"))
Boolean.TryParse(request["online"].ToString(), out online);
else
{
m_log.WarnFormat("[HGFRIENDS HANDLER]: no online in request to notify");
return FailureResult();
}
List<string> friends = new List<string>();
int i = 0;
foreach (KeyValuePair<string, object> kvp in request)
{
if (kvp.Key.Equals("friend_" + i.ToString()))
{
friends.Add(kvp.Value.ToString());
i++;
}
}
List<UUID> onlineFriends = m_TheService.StatusNotification(friends, principalID, online);
Dictionary<string, object> result = new Dictionary<string, object>();
if ((onlineFriends == null) || ((onlineFriends != null) && (onlineFriends.Count == 0)))
result["RESULT"] = "NULL";
else
{
i = 0;
foreach (UUID f in onlineFriends)
{
result["friend_" + i] = f.ToString();
i++;
}
}
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString);
return Util.UTF8NoBomEncoding.GetBytes(xmlString);
}
#endregion
#region Misc
private bool VerifyServiceKey(Dictionary<string, object> request)
{
if (!request.ContainsKey("KEY") || !request.ContainsKey("SESSIONID"))
{
m_log.WarnFormat("[HGFRIENDS HANDLER]: ignoring request without Key or SessionID");
return false;
}
if (request["KEY"] == null || request["SESSIONID"] == null)
return false;
string serviceKey = request["KEY"].ToString();
string sessionStr = request["SESSIONID"].ToString();
UUID sessionID;
if (!UUID.TryParse(sessionStr, out sessionID) || serviceKey == string.Empty)
return false;
if (!m_UserAgentService.VerifyAgent(sessionID, serviceKey))
{
m_log.WarnFormat("[HGFRIENDS HANDLER]: Key {0} for session {1} did not match existing key. Ignoring request", serviceKey, sessionID);
return false;
}
m_log.DebugFormat("[HGFRIENDS HANDLER]: Verification ok");
return true;
}
private byte[] SuccessResult()
{
XmlDocument doc = new XmlDocument();
XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
doc.AppendChild(xmlnode);
XmlElement rootElement = doc.CreateElement("", "ServerResponse",
"");
doc.AppendChild(rootElement);
XmlElement result = doc.CreateElement("", "Result", "");
result.AppendChild(doc.CreateTextNode("Success"));
rootElement.AppendChild(result);
return Util.DocToBytes(doc);
}
private byte[] SuccessResult(string value)
{
XmlDocument doc = new XmlDocument();
XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
doc.AppendChild(xmlnode);
XmlElement rootElement = doc.CreateElement("", "ServerResponse",
"");
doc.AppendChild(rootElement);
XmlElement result = doc.CreateElement("", "RESULT", "");
result.AppendChild(doc.CreateTextNode("Success"));
rootElement.AppendChild(result);
XmlElement message = doc.CreateElement("", "Value", "");
message.AppendChild(doc.CreateTextNode(value));
rootElement.AppendChild(message);
return Util.DocToBytes(doc);
}
private byte[] FailureResult()
{
return FailureResult(String.Empty);
}
private byte[] FailureResult(string msg)
{
XmlDocument doc = new XmlDocument();
XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
doc.AppendChild(xmlnode);
XmlElement rootElement = doc.CreateElement("", "ServerResponse",
"");
doc.AppendChild(rootElement);
XmlElement result = doc.CreateElement("", "RESULT", "");
result.AppendChild(doc.CreateTextNode("Failure"));
rootElement.AppendChild(result);
XmlElement message = doc.CreateElement("", "Message", "");
message.AppendChild(doc.CreateTextNode(msg));
rootElement.AppendChild(message);
return Util.DocToBytes(doc);
}
private byte[] BoolResult(bool value)
{
XmlDocument doc = new XmlDocument();
XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
doc.AppendChild(xmlnode);
XmlElement rootElement = doc.CreateElement("", "ServerResponse",
"");
doc.AppendChild(rootElement);
XmlElement result = doc.CreateElement("", "RESULT", "");
result.AppendChild(doc.CreateTextNode(value.ToString()));
rootElement.AppendChild(result);
return Util.DocToBytes(doc);
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text;
internal static partial class Interop
{
internal static partial class procfs
{
internal const string RootPath = "/proc/";
internal const string SelfExeFilePath = RootPath + "self/exe";
internal const string ProcUptimeFilePath = RootPath + "uptime";
private const string StatFileName = "/stat";
private const string MapsFileName = "/maps";
private const string TaskDirectoryName = "/task/";
internal struct ParsedStat
{
// Commented out fields are available in the stat data file but
// are currently not used. If/when needed, they can be uncommented,
// and the corresponding entry can be added back to StatParser, replacing
// the MoveNext() with the appropriate ParseNext* call and assignment.
internal int pid;
internal string comm;
internal char state;
//internal int ppid;
//internal int pgrp;
internal int session;
//internal int tty_nr;
//internal int tpgid;
//internal uint flags;
//internal ulong minflt;
//internal ulong cminflt;
//internal ulong majflt;
//internal ulong cmajflt;
internal ulong utime;
internal ulong stime;
//internal long cutime;
//internal long cstime;
//internal long priority;
internal long nice;
//internal long num_threads;
//internal long itrealvalue;
internal ulong starttime;
internal ulong vsize;
internal long rss;
internal ulong rsslim;
//internal ulong startcode;
//internal ulong endcode;
internal ulong startstack;
//internal ulong kstkesp;
//internal ulong kstkeip;
//internal ulong signal;
//internal ulong blocked;
//internal ulong sigignore;
//internal ulong sigcatch;
//internal ulong wchan;
//internal ulong nswap;
//internal ulong cnswap;
//internal int exit_signal;
//internal int processor;
//internal uint rt_priority;
//internal uint policy;
//internal ulong delayacct_blkio_ticks;
//internal ulong guest_time;
//internal long cguest_time;
}
internal struct ParsedMapsModule
{
internal string FileName;
internal KeyValuePair<long, long> AddressRange;
}
internal static string GetStatFilePathForProcess(int pid)
{
return RootPath + pid.ToString(CultureInfo.InvariantCulture) + StatFileName;
}
internal static string GetMapsFilePathForProcess(int pid)
{
return RootPath + pid.ToString(CultureInfo.InvariantCulture) + MapsFileName;
}
internal static string GetTaskDirectoryPathForProcess(int pid)
{
return RootPath + pid.ToString(CultureInfo.InvariantCulture) + TaskDirectoryName;
}
internal static IEnumerable<ParsedMapsModule> ParseMapsModules(int pid)
{
try
{
return ParseMapsModulesCore(File.ReadLines(GetMapsFilePathForProcess(pid)));
}
catch (IOException) { }
catch (UnauthorizedAccessException) { }
return Array.Empty<ParsedMapsModule>();
}
private static IEnumerable<ParsedMapsModule> ParseMapsModulesCore(IEnumerable<string> lines)
{
Debug.Assert(lines != null);
// Parse each line from the maps file into a ParsedMapsModule result
foreach (string line in lines)
{
// Use a StringParser to avoid string.Split costs
var parser = new StringParser(line, separator: ' ', skipEmpty: true);
// Parse the address range
KeyValuePair<long, long> addressRange =
parser.ParseRaw(delegate (string s, ref int start, ref int end)
{
long startingAddress = 0, endingAddress = 0;
int pos = s.IndexOf('-', start, end - start);
if (pos > 0)
{
string startingString = s.Substring(start, pos);
if (long.TryParse(startingString, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out startingAddress))
{
string endingString = s.Substring(pos + 1, end - (pos + 1));
long.TryParse(endingString, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out endingAddress);
}
}
return new KeyValuePair<long, long>(startingAddress, endingAddress);
});
// Parse the permissions (we only care about entries with 'r' and 'x' set)
if (!parser.ParseRaw(delegate (string s, ref int start, ref int end)
{
bool sawRead = false, sawExec = false;
for (int i = start; i < end; i++)
{
if (s[i] == 'r')
sawRead = true;
else if (s[i] == 'x')
sawExec = true;
}
return sawRead & sawExec;
}))
{
continue;
}
// Skip past the offset, dev, and inode fields
parser.MoveNext();
parser.MoveNext();
parser.MoveNext();
// Parse the pathname
if (!parser.MoveNext())
{
continue;
}
string pathname = parser.ExtractCurrent();
// We only get here if a we have a non-empty pathname and
// the permissions included both readability and executability.
// Yield the result.
yield return new ParsedMapsModule { FileName = pathname, AddressRange = addressRange };
}
}
private static string GetStatFilePathForThread(int pid, int tid)
{
// Perf note: Calling GetTaskDirectoryPathForProcess will allocate a string,
// which we then use in another Concat call to produce another string. The straightforward alternative,
// though, since we have five input strings, is to use the string.Concat overload that takes a params array.
// This results in allocating not only the params array but also a defensive copy inside of Concat,
// which means allocating two five-element arrays. This two-string approach will result not only in fewer
// allocations, but also typically in less memory allocated, and it's a bit more maintainable.
return GetTaskDirectoryPathForProcess(pid) + tid.ToString(CultureInfo.InvariantCulture) + StatFileName;
}
internal static bool TryReadStatFile(int pid, out ParsedStat result, ReusableTextReader reusableReader)
{
bool b = TryParseStatFile(GetStatFilePathForProcess(pid), out result, reusableReader);
Debug.Assert(!b || result.pid == pid, "Expected process ID from stat file to match supplied pid");
return b;
}
internal static bool TryReadStatFile(int pid, int tid, out ParsedStat result, ReusableTextReader reusableReader)
{
bool b = TryParseStatFile(GetStatFilePathForThread(pid, tid), out result, reusableReader);
Debug.Assert(!b || result.pid == tid, "Expected thread ID from stat file to match supplied tid");
return b;
}
private static bool TryParseStatFile(string statFilePath, out ParsedStat result, ReusableTextReader reusableReader)
{
string statFileContents;
try
{
using (var source = new FileStream(statFilePath, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 1, useAsync: false))
{
statFileContents = reusableReader.ReadAllText(source);
}
}
catch (IOException)
{
// Between the time that we get an ID and the time that we try to read the associated stat
// file(s), the process could be gone.
result = default(ParsedStat);
return false;
}
var parser = new StringParser(statFileContents, ' ');
var results = default(ParsedStat);
results.pid = parser.ParseNextInt32();
results.comm = parser.ParseRaw(delegate (string str, ref int startIndex, ref int endIndex)
{
if (str[startIndex] == '(')
{
int i;
for (i = endIndex; i < str.Length && str[i - 1] != ')'; i++) ;
if (str[i - 1] == ')')
{
endIndex = i;
return str.Substring(startIndex + 1, i - startIndex - 2);
}
}
throw new InvalidDataException();
});
results.state = parser.ParseNextChar();
parser.MoveNextOrFail(); // ppid
parser.MoveNextOrFail(); // pgrp
results.session = parser.ParseNextInt32();
parser.MoveNextOrFail(); // tty_nr
parser.MoveNextOrFail(); // tpgid
parser.MoveNextOrFail(); // flags
parser.MoveNextOrFail(); // majflt
parser.MoveNextOrFail(); // cmagflt
parser.MoveNextOrFail(); // minflt
parser.MoveNextOrFail(); // cminflt
results.utime = parser.ParseNextUInt64();
results.stime = parser.ParseNextUInt64();
parser.MoveNextOrFail(); // cutime
parser.MoveNextOrFail(); // cstime
parser.MoveNextOrFail(); // priority
results.nice = parser.ParseNextInt64();
parser.MoveNextOrFail(); // num_threads
parser.MoveNextOrFail(); // itrealvalue
results.starttime = parser.ParseNextUInt64();
results.vsize = parser.ParseNextUInt64();
results.rss = parser.ParseNextInt64();
results.rsslim = parser.ParseNextUInt64();
parser.MoveNextOrFail(); // startcode
parser.MoveNextOrFail(); // endcode
results.startstack = parser.ParseNextUInt64();
parser.MoveNextOrFail(); // kstkesp
parser.MoveNextOrFail(); // kstkeip
parser.MoveNextOrFail(); // signal
parser.MoveNextOrFail(); // blocked
parser.MoveNextOrFail(); // sigignore
parser.MoveNextOrFail(); // sigcatch
parser.MoveNextOrFail(); // wchan
parser.MoveNextOrFail(); // nswap
parser.MoveNextOrFail(); // cnswap
parser.MoveNextOrFail(); // exit_signal
parser.MoveNextOrFail(); // processor
parser.MoveNextOrFail(); // rt_priority
parser.MoveNextOrFail(); // policy
parser.MoveNextOrFail(); // delayacct_blkio_ticks
parser.MoveNextOrFail(); // guest_time
parser.MoveNextOrFail(); // cguest_time
result = results;
return true;
}
}
}
| |
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlTypes;
public partial class Backoffice_Controls_EditDepositRI : System.Web.UI.UserControl
{
public int NoKe = 0;
public decimal TotalDeposit = 0;
protected void Page_Load(object sender, EventArgs e)
{
}
private void ModeEditForm()
{
pnlList.Visible = false;
pnlEdit.Visible = true;
pnlView.Visible = false;
btnAdd.Visible = false;
lblError.Text = "";
lblWarning.Text = "";
}
private void ModeListForm()
{
pnlList.Visible = true;
pnlEdit.Visible = false;
pnlView.Visible = false;
btnAdd.Visible = true;
}
private void ModeViewForm()
{
lblWarning.Text = "";
GV.EditIndex = -1;
pnlList.Visible = false;
pnlEdit.Visible = false;
pnlView.Visible = true;
btnAdd.Visible = false;
}
protected void GV_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
GV.SelectedIndex = e.NewSelectedIndex;
FillFormView(GV.DataKeys[e.NewSelectedIndex].Value.ToString());
ModeViewForm();
}
protected void GV_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GV.PageIndex = e.NewPageIndex;
GV.SelectedIndex = -1;
BindDataGrid();
}
protected void GV_Sorting(object sender, GridViewSortEventArgs e)
{
String strSortBy = GV.Attributes["SortField"];
String strSortAscending = GV.Attributes["SortAscending"];
// Sets the new sorting field
GV.Attributes["SortField"] = e.SortExpression;
// Sets the order (defaults to ascending). If you click on the
// sorted column, the order reverts.
GV.Attributes["SortAscending"] = "yes";
if (e.SortExpression == strSortBy)
GV.Attributes["SortAscending"] = (strSortAscending == "yes" ? "no" : "yes");
// Refreshes the view
GV.SelectedIndex = -1;
BindDataGrid();
}
protected void GV_RowEditing(object sender, GridViewEditEventArgs e)
{
lblTitleEditForm.Text = "EDIT DEPOSIT";
GV.SelectedIndex = e.NewEditIndex;
string key = GV.DataKeys[e.NewEditIndex].Value.ToString();
FillFormEdit(key);
ModeEditForm();
}
protected void btnEditDetil_Click(object sender, EventArgs e)
{
FillFormEdit(txtKuitansiId.Text);
lblTitleEditForm.Text = "EDIT DEPOSIT";
ModeEditForm();
}
protected void GV_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int i = e.RowIndex;
DeleteData(GV.DataKeys[i].Value.ToString());
}
protected void btnAdd_Click(object sender, EventArgs e)
{
lblTitleEditForm.Text = "TAMBAH DEPOSIT";
ModeEditForm();
EmptyFormEdit();
}
protected void btnCancel_Click(object sender, EventArgs e)
{
ModeListForm();
}
protected void btnSave_Click(object sender, EventArgs e)
{
SaveData();
}
protected void btnBack_Click(object sender, EventArgs e)
{
ModeListForm();
}
protected void btnDeleteDetil_Click(object sender, EventArgs e)
{
DeleteData(lblKuitansiId.Text);
}
public void BindDataGrid()
{
DataView dv = GetData();
dv.Sort = GV.Attributes["SortField"];
if (GV.Attributes["SortAscending"] == "no")
dv.Sort += " DESC";
if (dv.Count > 0)
{
int intRowCount = dv.Count;
int intPageSaze = GV.PageSize;
int intPageCount = intRowCount / intPageSaze;
if (intRowCount - (intPageCount * intPageSaze) > 0)
intPageCount = intPageCount + 1;
if (GV.PageIndex >= intPageCount)
GV.PageIndex = intPageCount - 1;
TotalDeposit = 0;
//bool statusbayar = true;
//bool statusBelumBayar = false;
foreach (DataRow dr in dv.Table.Rows)
{
//statusBelumBayar = dr["StatusBayar"].ToString() == "0" ? true : false;
//if (statusBelumBayar)
// statusbayar = false;
TotalDeposit += (decimal)dr["JumlahBiaya"];
}
//if (!statusbayar && Session["KasirRI"] != null)
//{
// btnKuitansi.Visible = true;
// btnKuitansi.Attributes.Remove("onclick");
// btnKuitansi.Attributes.Add("onclick", "displayPopup_scroll(2,'PrintKuitansiDepositRI.aspx?KuitansiId=" + txtRawatInapId.Text + "','Pasien',600,800,(version4 ? event : null));");
//}
//else {
// btnKuitansi.Visible = false;
//}
}
else
{
//btnKuitansi.Visible = false;
GV.PageIndex = 0;
}
NoKe = GV.PageSize * GV.PageIndex;
GV.DataSource = dv;
GV.DataBind();
ModeListForm();
}
//===================================================================
public void SetDataRawatInap(string RawatInapId, string KelasId, string NamaPasien)
{
txtRawatInapId.Text = RawatInapId;
txtNamaPasien.Text = NamaPasien;
txtKelasId.Text = KelasId;
}
public DataView GetData()
{
SIMRS.DataAccess.RS_RIKuitansi objData = new SIMRS.DataAccess.RS_RIKuitansi();
objData.RawatInapId = Int64.Parse(txtRawatInapId.Text);
DataTable dt = objData.SelectAllDepositWRawatInapIdLogic();
return dt.DefaultView;
}
private void GetNomorKuitansi()
{
SIMRS.DataAccess.RS_RIKuitansi myObj = new SIMRS.DataAccess.RS_RIKuitansi();
txtNoKuitansi.Text = myObj.GetNomorKuitansi();
}
private void EmptyFormEdit()
{
txtKuitansiId.Text = "0";
GetNomorKuitansi();
txtTanggalBayar.Text = DateTime.Now.ToString("dd/MM/yyyy");
txtDiterimaDari.Text = txtNamaPasien.Text;
txtJumlahBiaya.Text = "";
txtJumlahBiayaText.Text = "";
txtUntukpembayaran.Text = "Uang Muka Rawat Inap Nama Pasien "+txtNamaPasien.Text;
txtKeterangan.Text = "";
}
private void FillFormEdit(string KuitansiId)
{
SIMRS.DataAccess.RS_RIKuitansi myObj = new SIMRS.DataAccess.RS_RIKuitansi();
myObj.KuitansiId = Int64.Parse(KuitansiId);
DataTable dt = myObj.SelectOne();
if (dt.Rows.Count > 0)
{
DataRow dr = dt.Rows[0];
txtKuitansiId.Text = dr["KuitansiId"].ToString();
txtNoKuitansi.Text = dr["NomorKuitansi"].ToString();
txtTanggalBayar.Text = dr["TanggalBayar"].ToString() != "" ? ((DateTime)dr["TanggalBayar"]).ToString("dd/MM/yyyy") : "";
txtDiterimaDari.Text = dr["DiterimaDari"].ToString();
txtJumlahBiaya.Text = dr["JumlahBiaya"].ToString() != "" ? ((Decimal)dr["JumlahBiaya"]).ToString("#,###.###.###.###") : "";
txtJumlahBiayaText.Text = dr["JumlahBiayaText"].ToString();
txtUntukpembayaran.Text = dr["Untukpembayaran"].ToString();
txtKeterangan.Text = dr["Keterangan"].ToString();
}
}
private void FillFormView(string KuitansiId)
{
SIMRS.DataAccess.RS_RIKuitansi myObj = new SIMRS.DataAccess.RS_RIKuitansi();
myObj.KuitansiId = Int64.Parse(KuitansiId);
DataTable dt = myObj.SelectOne();
if (dt.Rows.Count > 0)
{
DataRow dr = dt.Rows[0];
lblKuitansiId.Text = dr["KuitansiId"].ToString();
//lblTanggalTransaksi.Text = dr["TanggalTransaksi"].ToString() != "" ? ((DateTime)dr["TanggalTransaksi"]).ToString("dd/MM/yyyy HH:mm") : "";
//lblDeposit.Text = dr["Deposit"].ToString() != "" ? ((Decimal)dr["Deposit"]).ToString("#,###.###.###.###") : "";
//lblKeterangan.Text = dr["Keterangan"].ToString().Replace("\r\n","<br />");
//lblKuitansiId.Text = dr["KuitansiId"].ToString();
//lblNoKuitansi.Text = dr["NoKuitansi"].ToString();
//lblTanggalBayar.Text = dr["TanggalBayar"].ToString() != "" ? ((DateTime)dr["TanggalBayar"]).ToString("dd/MM/yyyy") : "";
//lblDiterimaDari.Text = dr["DiterimaDari"].ToString();
//lblJumlahBiaya.Text = dr["JumlahBiaya"].ToString() != "" ? ((Decimal)dr["JumlahBiaya"]).ToString("#,###.###.###.###") : "";
//lblJumlahBiayaText.Text = dr["JumlahBiayaText"].ToString().Replace("\r\n", "<br />");
//lblUntukpembayaran.Text = dr["Untukpembayaran"].ToString().Replace("\r\n", "<br />");
//lblKeterangan.Text = dr["Keterangan"].ToString().Replace("\r\n","<br />");
}
}
private void SaveData()
{
if (Session["SIMRS.UserId"] == null)
{
Response.Redirect(Request.ApplicationPath + "/Backoffice/login.aspx");
}
if (!Page.IsValid)
{
return;
}
int UserId = (int)Session["SIMRS.UserId"];
SIMRS.DataAccess.RS_RIKuitansi myObj = new SIMRS.DataAccess.RS_RIKuitansi();
myObj.KuitansiId = Int64.Parse(txtKuitansiId.Text);
if (myObj.KuitansiId > 0)
myObj.SelectOne();
myObj.RawatInapId = Int64.Parse(txtRawatInapId.Text);
myObj.JenisKuitansiId = 1 ;//Deposit
myObj.NomorKuitansi = txtNoKuitansi.Text;
myObj.DiterimaDari = txtDiterimaDari.Text;
if (txtTanggalBayar.Text != "")
{
myObj.TanggalBayar = DateTime.Parse(txtTanggalBayar.Text);
}
myObj.JumlahBiaya = decimal.Parse(txtJumlahBiaya.Text);
myObj.JumlahBiayaText = txtJumlahBiayaText.Text;
myObj.UntukPembayaran = txtUntukpembayaran.Text;
myObj.Keterangan = txtKeterangan.Text;
if (myObj.KuitansiId == 0)
{
//Kondisi Insert Data
myObj.CreatedBy = UserId;
myObj.CreatedDate = DateTime.Now;
myObj.Insert();
lblWarning.Text = Resources.GetString("", "WarSuccessSave");
}
else
{
//Kondisi Update Data
myObj.ModifiedBy = UserId;
myObj.ModifiedDate = DateTime.Now;
myObj.Update();
lblWarning.Text = Resources.GetString("", "WarSuccessSave");
}
BindDataGrid();
ModeListForm();
}
private void DeleteData(string KuitansiId)
{
SIMRS.DataAccess.RS_RIKuitansi myObj = new SIMRS.DataAccess.RS_RIKuitansi();
myObj.KuitansiId = int.Parse(KuitansiId);
try
{
myObj.Delete();
GV.SelectedIndex = -1;
BindDataGrid();
lblWarning.Text = Resources.GetString("", "WarSuccessDelete");
ModeListForm();
}
catch
{
lblWarning.Text = Resources.GetString("", "WarAlreadyUsed");
}
}
protected void txtJumlahBiaya_TextChanged(object sender, EventArgs e)
{
if (REVJumlahBiaya.IsValid && txtJumlahBiaya.Text != "")
{
if (txtJumlahBiaya.Text != "0")
{
txtJumlahBiaya.Text = (decimal.Parse(txtJumlahBiaya.Text)).ToString("#,###.###.###.###");
string jumlahBiaya = (decimal.Parse(txtJumlahBiaya.Text)).ToString("#");
txtJumlahBiayaText.Text = Resources.Number2Word(long.Parse(jumlahBiaya)) + " Rupiah";
}
else
{
txtJumlahBiayaText.Text = "";
}
}
else
{
txtJumlahBiayaText.Text = "";
}
}
public string getlinkPrint(string KuitansiId)
{
return "displayPopup_scroll(2,'../Pasien/KuitansiRI.aspx?KuitansiId=" + KuitansiId + "','kuitansi',600,800,(version4 ? event : null));";
//return "displayPopup_scroll(2,'PrintKuitansiDepositRI.aspx?KuitansiId=" + kuitansiId + "','Pasien',600,800,(version4 ? event : null));";
}
}
| |
namespace WLWPluginBase.Win32
{
/// <summary>
/// Grouping of Win32 messages.
/// </summary>
/// <remarks>
/// Definitions have been scanvenged from the net, but mostly come from PInvoke (www.pinvoke.net).
/// </remarks>
public enum Win32Messages : int
{
WM_NULL = 0x0000,
WM_CREATE = 0x0001,
WM_DESTROY = 0x0002,
WM_MOVE = 0x0003,
WM_SIZE = 0x0005,
WM_ACTIVATE = 0x0006,
WM_SETFOCUS = 0x0007,
WM_KILLFOCUS = 0x0008,
WM_ENABLE = 0x000A,
WM_SETREDRAW = 0x000B,
WM_SETTEXT = 0x000C,
WM_GETTEXT = 0x000D,
WM_GETTEXTLENGTH = 0x000E,
WM_PAINT = 0x000F,
WM_CLOSE = 0x0010,
WM_QUERYENDSESSION = 0x0011,
WM_QUERYOPEN = 0x0013,
WM_ENDSESSION = 0x0016,
WM_QUIT = 0x0012,
WM_ERASEBKGND = 0x0014,
WM_SYSCOLORCHANGE = 0x0015,
WM_SHOWWINDOW = 0x0018,
WM_WININICHANGE = 0x001A,
WM_SETTINGCHANGE = 0x001A,
WM_DEVMODECHANGE = 0x001B,
WM_ACTIVATEAPP = 0x001C,
WM_FONTCHANGE = 0x001D,
WM_TIMECHANGE = 0x001E,
WM_CANCELMODE = 0x001F,
WM_SETCURSOR = 0x0020,
WM_MOUSEACTIVATE = 0x0021,
WM_CHILDACTIVATE = 0x0022,
WM_QUEUESYNC = 0x0023,
WM_GETMINMAXINFO = 0x0024,
WM_PAINTICON = 0x0026,
WM_ICONERASEBKGND = 0x0027,
WM_NEXTDLGCTL = 0x0028,
WM_SPOOLERSTATUS = 0x002A,
WM_DRAWITEM = 0x002B,
WM_MEASUREITEM = 0x002C,
WM_DELETEITEM = 0x002D,
WM_VKEYTOITEM = 0x002E,
WM_CHARTOITEM = 0x002F,
WM_SETFONT = 0x0030,
WM_GETFONT = 0x0031,
WM_SETHOTKEY = 0x0032,
WM_GETHOTKEY = 0x0033,
WM_QUERYDRAGICON = 0x0037,
WM_COMPAREITEM = 0x0039,
WM_GETOBJECT = 0x003D,
WM_COMPACTING = 0x0041,
WM_COMMNOTIFY = 0x0044,
WM_WINDOWPOSCHANGING = 0x0046,
WM_WINDOWPOSCHANGED = 0x0047,
WM_POWER = 0x0048,
WM_COPYDATA = 0x004A,
WM_CANCELJOURNAL = 0x004B,
WM_NOTIFY = 0x004E,
WM_INPUTLANGCHANGEREQUEST = 0x0050,
WM_INPUTLANGCHANGE = 0x0051,
WM_TCARD = 0x0052,
WM_HELP = 0x0053,
WM_USERCHANGED = 0x0054,
WM_NOTIFYFORMAT = 0x0055,
WM_CONTEXTMENU = 0x007B,
WM_STYLECHANGING = 0x007C,
WM_STYLECHANGED = 0x007D,
WM_DISPLAYCHANGE = 0x007E,
WM_GETICON = 0x007F,
WM_SETICON = 0x0080,
WM_NCCREATE = 0x0081,
WM_NCDESTROY = 0x0082,
WM_NCCALCSIZE = 0x0083,
WM_NCHITTEST = 0x0084,
WM_NCPAINT = 0x0085,
WM_NCACTIVATE = 0x0086,
WM_GETDLGCODE = 0x0087,
WM_SYNCPAINT = 0x0088,
WM_NCMOUSEMOVE = 0x00A0,
WM_NCLBUTTONDOWN = 0x00A1,
WM_NCLBUTTONUP = 0x00A2,
WM_NCLBUTTONDBLCLK = 0x00A3,
WM_NCRBUTTONDOWN = 0x00A4,
WM_NCRBUTTONUP = 0x00A5,
WM_NCRBUTTONDBLCLK = 0x00A6,
WM_NCMBUTTONDOWN = 0x00A7,
WM_NCMBUTTONUP = 0x00A8,
WM_NCMBUTTONDBLCLK = 0x00A9,
WM_NCXBUTTONDOWN = 0x00AB,
WM_NCXBUTTONUP = 0x00AC,
WM_NCXBUTTONDBLCLK = 0x00AD,
WM_INPUT = 0x00FF,
WM_KEYFIRST = 0x0100,
WM_KEYDOWN = 0x0100,
WM_KEYUP = 0x0101,
WM_CHAR = 0x0102,
WM_DEADCHAR = 0x0103,
WM_SYSKEYDOWN = 0x0104,
WM_SYSKEYUP = 0x0105,
WM_SYSCHAR = 0x0106,
WM_SYSDEADCHAR = 0x0107,
WM_UNICHAR = 0x0109,
WM_KEYLAST_NT501 = 0x0109,
UNICODE_NOCHAR = 0xFFFF,
WM_KEYLAST_PRE501 = 0x0108,
WM_IME_STARTCOMPOSITION = 0x010D,
WM_IME_ENDCOMPOSITION = 0x010E,
WM_IME_COMPOSITION = 0x010F,
WM_IME_KEYLAST = 0x010F,
WM_INITDIALOG = 0x0110,
WM_COMMAND = 0x0111,
WM_SYSCOMMAND = 0x0112,
WM_TIMER = 0x0113,
WM_HSCROLL = 0x0114,
WM_VSCROLL = 0x0115,
WM_INITMENU = 0x0116,
WM_INITMENUPOPUP = 0x0117,
WM_MENUSELECT = 0x011F,
WM_MENUCHAR = 0x0120,
WM_ENTERIDLE = 0x0121,
WM_MENURBUTTONUP = 0x0122,
WM_MENUDRAG = 0x0123,
WM_MENUGETOBJECT = 0x0124,
WM_UNINITMENUPOPUP = 0x0125,
WM_MENUCOMMAND = 0x0126,
WM_CHANGEUISTATE = 0x0127,
WM_UPDATEUISTATE = 0x0128,
WM_QUERYUISTATE = 0x0129,
WM_CTLCOLORMSGBOX = 0x0132,
WM_CTLCOLOREDIT = 0x0133,
WM_CTLCOLORLISTBOX = 0x0134,
WM_CTLCOLORBTN = 0x0135,
WM_CTLCOLORDLG = 0x0136,
WM_CTLCOLORSCROLLBAR = 0x0137,
WM_CTLCOLORSTATIC = 0x0138,
WM_MOUSEFIRST = 0x0200,
WM_MOUSEMOVE = 0x0200,
WM_LBUTTONDOWN = 0x0201,
WM_LBUTTONUP = 0x0202,
WM_LBUTTONDBLCLK = 0x0203,
WM_RBUTTONDOWN = 0x0204,
WM_RBUTTONUP = 0x0205,
WM_RBUTTONDBLCLK = 0x0206,
WM_MBUTTONDOWN = 0x0207,
WM_MBUTTONUP = 0x0208,
WM_MBUTTONDBLCLK = 0x0209,
WM_MOUSEWHEEL = 0x020A,
WM_XBUTTONDOWN = 0x020B,
WM_XBUTTONUP = 0x020C,
WM_XBUTTONDBLCLK = 0x020D,
WM_MOUSELAST_5 = 0x020D,
WM_MOUSELAST_4 = 0x020A,
WM_MOUSELAST_PRE_4 = 0x0209,
WM_PARENTNOTIFY = 0x0210,
WM_ENTERMENULOOP = 0x0211,
WM_EXITMENULOOP = 0x0212,
WM_NEXTMENU = 0x0213,
WM_SIZING = 0x0214,
WM_CAPTURECHANGED = 0x0215,
WM_MOVING = 0x0216,
WM_POWERBROADCAST = 0x0218,
WM_DEVICECHANGE = 0x0219,
WM_MDICREATE = 0x0220,
WM_MDIDESTROY = 0x0221,
WM_MDIACTIVATE = 0x0222,
WM_MDIRESTORE = 0x0223,
WM_MDINEXT = 0x0224,
WM_MDIMAXIMIZE = 0x0225,
WM_MDITILE = 0x0226,
WM_MDICASCADE = 0x0227,
WM_MDIICONARRANGE = 0x0228,
WM_MDIGETACTIVE = 0x0229,
WM_MDISETMENU = 0x0230,
WM_ENTERSIZEMOVE = 0x0231,
WM_EXITSIZEMOVE = 0x0232,
WM_DROPFILES = 0x0233,
WM_MDIREFRESHMENU = 0x0234,
WM_IME_SETCONTEXT = 0x0281,
WM_IME_NOTIFY = 0x0282,
WM_IME_CONTROL = 0x0283,
WM_IME_COMPOSITIONFULL = 0x0284,
WM_IME_SELECT = 0x0285,
WM_IME_CHAR = 0x0286,
WM_IME_REQUEST = 0x0288,
WM_IME_KEYDOWN = 0x0290,
WM_IME_KEYUP = 0x0291,
WM_MOUSEHOVER = 0x02A1,
WM_MOUSELEAVE = 0x02A3,
WM_NCMOUSEHOVER = 0x02A0,
WM_NCMOUSELEAVE = 0x02A2,
WM_WTSSESSION_CHANGE = 0x02B1,
WM_TABLET_FIRST = 0x02c0,
WM_TABLET_LAST = 0x02df,
WM_CUT = 0x0300,
WM_COPY = 0x0301,
WM_PASTE = 0x0302,
WM_CLEAR = 0x0303,
WM_UNDO = 0x0304,
WM_RENDERFORMAT = 0x0305,
WM_RENDERALLFORMATS = 0x0306,
WM_DESTROYCLIPBOARD = 0x0307,
WM_DRAWCLIPBOARD = 0x0308,
WM_PAINTCLIPBOARD = 0x0309,
WM_VSCROLLCLIPBOARD = 0x030A,
WM_SIZECLIPBOARD = 0x030B,
WM_ASKCBFORMATNAME = 0x030C,
WM_CHANGECBCHAIN = 0x030D,
WM_HSCROLLCLIPBOARD = 0x030E,
WM_QUERYNEWPALETTE = 0x030F,
WM_PALETTEISCHANGING = 0x0310,
WM_PALETTECHANGED = 0x0311,
WM_HOTKEY = 0x0312,
WM_PRINT = 0x0317,
WM_PRINTCLIENT = 0x0318,
WM_APPCOMMAND = 0x0319,
WM_THEMECHANGED = 0x031A,
WM_HANDHELDFIRST = 0x0358,
WM_HANDHELDLAST = 0x035F,
WM_AFXFIRST = 0x0360,
WM_AFXLAST = 0x037F,
WM_PENWINFIRST = 0x0380,
WM_PENWINLAST = 0x038F,
WM_APP = 0x8000,
WM_USER = 0x0400,
EM_GETSEL = 0x00B0,
EM_SETSEL = 0x00B1,
EM_GETRECT = 0x00B2,
EM_SETRECT = 0x00B3,
EM_SETRECTNP = 0x00B4,
EM_SCROLL = 0x00B5,
EM_LINESCROLL = 0x00B6,
EM_SCROLLCARET = 0x00B7,
EM_GETMODIFY = 0x00B8,
EM_SETMODIFY = 0x00B9,
EM_GETLINECOUNT = 0x00BA,
EM_LINEINDEX = 0x00BB,
EM_SETHANDLE = 0x00BC,
EM_GETHANDLE = 0x00BD,
EM_GETTHUMB = 0x00BE,
EM_LINELENGTH = 0x00C1,
EM_REPLACESEL = 0x00C2,
EM_GETLINE = 0x00C4,
EM_LIMITTEXT = 0x00C5,
EM_CANUNDO = 0x00C6,
EM_UNDO = 0x00C7,
EM_FMTLINES = 0x00C8,
EM_LINEFROMCHAR = 0x00C9,
EM_SETTABSTOPS = 0x00CB,
EM_SETPASSWORDCHAR = 0x00CC,
EM_EMPTYUNDOBUFFER = 0x00CD,
EM_GETFIRSTVISIBLELINE = 0x00CE,
EM_SETREADONLY = 0x00CF,
EM_SETWORDBREAKPROC = 0x00D0,
EM_GETWORDBREAKPROC = 0x00D1,
EM_GETPASSWORDCHAR = 0x00D2,
EM_SETMARGINS = 0x00D3,
EM_GETMARGINS = 0x00D4,
EM_SETLIMITTEXT = EM_LIMITTEXT,
EM_GETLIMITTEXT = 0x00D5,
EM_POSFROMCHAR = 0x00D6,
EM_CHARFROMPOS = 0x00D7,
EM_SETIMESTATUS = 0x00D8,
EM_GETIMESTATUS = 0x00D9,
BM_GETCHECK= 0x00F0,
BM_SETCHECK= 0x00F1,
BM_GETSTATE= 0x00F2,
BM_SETSTATE= 0x00F3,
BM_SETSTYLE= 0x00F4,
BM_CLICK = 0x00F5,
BM_GETIMAGE= 0x00F6,
BM_SETIMAGE= 0x00F7,
STM_SETICON = 0x0170,
STM_GETICON = 0x0171,
STM_SETIMAGE = 0x0172,
STM_GETIMAGE = 0x0173,
STM_MSGMAX = 0x0174,
DM_GETDEFID = (WM_USER+0),
DM_SETDEFID = (WM_USER+1),
DM_REPOSITION = (WM_USER+2),
LB_ADDSTRING = 0x0180,
LB_INSERTSTRING = 0x0181,
LB_DELETESTRING = 0x0182,
LB_SELITEMRANGEEX= 0x0183,
LB_RESETCONTENT = 0x0184,
LB_SETSEL = 0x0185,
LB_SETCURSEL = 0x0186,
LB_GETSEL = 0x0187,
LB_GETCURSEL = 0x0188,
LB_GETTEXT = 0x0189,
LB_GETTEXTLEN = 0x018A,
LB_GETCOUNT = 0x018B,
LB_SELECTSTRING = 0x018C,
LB_DIR = 0x018D,
LB_GETTOPINDEX = 0x018E,
LB_FINDSTRING = 0x018F,
LB_GETSELCOUNT = 0x0190,
LB_GETSELITEMS = 0x0191,
LB_SETTABSTOPS = 0x0192,
LB_GETHORIZONTALEXTENT = 0x0193,
LB_SETHORIZONTALEXTENT = 0x0194,
LB_SETCOLUMNWIDTH = 0x0195,
LB_ADDFILE = 0x0196,
LB_SETTOPINDEX = 0x0197,
LB_GETITEMRECT = 0x0198,
LB_GETITEMDATA = 0x0199,
LB_SETITEMDATA = 0x019A,
LB_SELITEMRANGE = 0x019B,
LB_SETANCHORINDEX = 0x019C,
LB_GETANCHORINDEX = 0x019D,
LB_SETCARETINDEX = 0x019E,
LB_GETCARETINDEX = 0x019F,
LB_SETITEMHEIGHT = 0x01A0,
LB_GETITEMHEIGHT = 0x01A1,
LB_FINDSTRINGEXACT = 0x01A2,
LB_SETLOCALE = 0x01A5,
LB_GETLOCALE = 0x01A6,
LB_SETCOUNT = 0x01A7,
LB_INITSTORAGE = 0x01A8,
LB_ITEMFROMPOINT = 0x01A9,
LB_MULTIPLEADDSTRING = 0x01B1,
LB_GETLISTBOXINFO= 0x01B2,
LB_MSGMAX_501 = 0x01B3,
LB_MSGMAX_WCE4 = 0x01B1,
LB_MSGMAX_4 = 0x01B0,
LB_MSGMAX_PRE4 = 0x01A8,
CB_GETEDITSEL = 0x0140,
CB_LIMITTEXT = 0x0141,
CB_SETEDITSEL = 0x0142,
CB_ADDSTRING = 0x0143,
CB_DELETESTRING = 0x0144,
CB_DIR = 0x0145,
CB_GETCOUNT = 0x0146,
CB_GETCURSEL = 0x0147,
CB_GETLBTEXT = 0x0148,
CB_GETLBTEXTLEN = 0x0149,
CB_INSERTSTRING = 0x014A,
CB_RESETCONTENT = 0x014B,
CB_FINDSTRING = 0x014C,
CB_SELECTSTRING = 0x014D,
CB_SETCURSEL = 0x014E,
CB_SHOWDROPDOWN = 0x014F,
CB_GETITEMDATA = 0x0150,
CB_SETITEMDATA = 0x0151,
CB_GETDROPPEDCONTROLRECT = 0x0152,
CB_SETITEMHEIGHT = 0x0153,
CB_GETITEMHEIGHT = 0x0154,
CB_SETEXTENDEDUI = 0x0155,
CB_GETEXTENDEDUI = 0x0156,
CB_GETDROPPEDSTATE = 0x0157,
CB_FINDSTRINGEXACT = 0x0158,
CB_SETLOCALE = 0x0159,
CB_GETLOCALE = 0x015A,
CB_GETTOPINDEX = 0x015B,
CB_SETTOPINDEX = 0x015C,
CB_GETHORIZONTALEXTENT = 0x015d,
CB_SETHORIZONTALEXTENT = 0x015e,
CB_GETDROPPEDWIDTH = 0x015f,
CB_SETDROPPEDWIDTH = 0x0160,
CB_INITSTORAGE = 0x0161,
CB_MULTIPLEADDSTRING = 0x0163,
CB_GETCOMBOBOXINFO = 0x0164,
CB_MSGMAX_501 = 0x0165,
CB_MSGMAX_WCE400 = 0x0163,
CB_MSGMAX_400 = 0x0162,
CB_MSGMAX_PRE400 = 0x015B,
SBM_SETPOS = 0x00E0,
SBM_GETPOS = 0x00E1,
SBM_SETRANGE = 0x00E2,
SBM_SETRANGEREDRAW = 0x00E6,
SBM_GETRANGE = 0x00E3,
SBM_ENABLE_ARROWS = 0x00E4,
SBM_SETSCROLLINFO = 0x00E9,
SBM_GETSCROLLINFO = 0x00EA,
SBM_GETSCROLLBARINFO= 0x00EB,
LVM_FIRST = 0x1000,// ListView messages
TV_FIRST = 0x1100,// TreeView messages
HDM_FIRST = 0x1200,// Header messages
TCM_FIRST = 0x1300,// Tab control messages
PGM_FIRST = 0x1400,// Pager control messages
ECM_FIRST = 0x1500,// Edit control messages
BCM_FIRST = 0x1600,// Button control messages
CBM_FIRST = 0x1700,// Combobox control messages
CCM_FIRST = 0x2000,// Common control shared messages
CCM_LAST =(CCM_FIRST + 0x200),
CCM_SETBKCOLOR = (CCM_FIRST + 1),
CCM_SETCOLORSCHEME = (CCM_FIRST + 2),
CCM_GETCOLORSCHEME = (CCM_FIRST + 3),
CCM_GETDROPTARGET = (CCM_FIRST + 4),
CCM_SETUNICODEFORMAT = (CCM_FIRST + 5),
CCM_GETUNICODEFORMAT = (CCM_FIRST + 6),
CCM_SETVERSION = (CCM_FIRST + 0x7),
CCM_GETVERSION = (CCM_FIRST + 0x8),
CCM_SETNOTIFYWINDOW = (CCM_FIRST + 0x9),
CCM_SETWINDOWTHEME = (CCM_FIRST + 0xb),
CCM_DPISCALE = (CCM_FIRST + 0xc),
HDM_GETITEMCOUNT = (HDM_FIRST + 0),
HDM_INSERTITEMA = (HDM_FIRST + 1),
HDM_INSERTITEMW = (HDM_FIRST + 10),
HDM_DELETEITEM = (HDM_FIRST + 2),
HDM_GETITEMA = (HDM_FIRST + 3),
HDM_GETITEMW = (HDM_FIRST + 11),
HDM_SETITEMA = (HDM_FIRST + 4),
HDM_SETITEMW = (HDM_FIRST + 12),
HDM_LAYOUT = (HDM_FIRST + 5),
HDM_HITTEST = (HDM_FIRST + 6),
HDM_GETITEMRECT = (HDM_FIRST + 7),
HDM_SETIMAGELIST = (HDM_FIRST + 8),
HDM_GETIMAGELIST = (HDM_FIRST + 9),
HDM_ORDERTOINDEX = (HDM_FIRST + 15),
HDM_CREATEDRAGIMAGE = (HDM_FIRST + 16),
HDM_GETORDERARRAY = (HDM_FIRST + 17),
HDM_SETORDERARRAY = (HDM_FIRST + 18),
HDM_SETHOTDIVIDER = (HDM_FIRST + 19),
HDM_SETBITMAPMARGIN = (HDM_FIRST + 20),
HDM_GETBITMAPMARGIN = (HDM_FIRST + 21),
HDM_SETUNICODEFORMAT = CCM_SETUNICODEFORMAT,
HDM_GETUNICODEFORMAT = CCM_GETUNICODEFORMAT,
HDM_SETFILTERCHANGETIMEOUT = (HDM_FIRST+22),
HDM_EDITFILTER = (HDM_FIRST+23),
HDM_CLEARFILTER = (HDM_FIRST+24),
TB_ENABLEBUTTON = (WM_USER + 1),
TB_CHECKBUTTON = (WM_USER + 2),
TB_PRESSBUTTON = (WM_USER + 3),
TB_HIDEBUTTON = (WM_USER + 4),
TB_INDETERMINATE = (WM_USER + 5),
TB_MARKBUTTON = (WM_USER + 6),
TB_ISBUTTONENABLED = (WM_USER + 9),
TB_ISBUTTONCHECKED = (WM_USER + 10),
TB_ISBUTTONPRESSED = (WM_USER + 11),
TB_ISBUTTONHIDDEN = (WM_USER + 12),
TB_ISBUTTONINDETERMINATE = (WM_USER + 13),
TB_ISBUTTONHIGHLIGHTED = (WM_USER + 14),
TB_SETSTATE = (WM_USER + 17),
TB_GETSTATE = (WM_USER + 18),
TB_ADDBITMAP = (WM_USER + 19),
TB_ADDBUTTONSA = (WM_USER + 20),
TB_INSERTBUTTONA = (WM_USER + 21),
TB_ADDBUTTONS = (WM_USER + 20),
TB_INSERTBUTTON = (WM_USER + 21),
TB_DELETEBUTTON = (WM_USER + 22),
TB_GETBUTTON = (WM_USER + 23),
TB_BUTTONCOUNT = (WM_USER + 24),
TB_COMMANDTOINDEX = (WM_USER + 25),
TB_SAVERESTOREA = (WM_USER + 26),
TB_SAVERESTOREW = (WM_USER + 76),
TB_CUSTOMIZE = (WM_USER + 27),
TB_ADDSTRINGA = (WM_USER + 28),
TB_ADDSTRINGW = (WM_USER + 77),
TB_GETITEMRECT = (WM_USER + 29),
TB_BUTTONSTRUCTSIZE = (WM_USER + 30),
TB_SETBUTTONSIZE = (WM_USER + 31),
TB_SETBITMAPSIZE = (WM_USER + 32),
TB_AUTOSIZE = (WM_USER + 33),
TB_GETTOOLTIPS = (WM_USER + 35),
TB_SETTOOLTIPS = (WM_USER + 36),
TB_SETPARENT = (WM_USER + 37),
TB_SETROWS = (WM_USER + 39),
TB_GETROWS = (WM_USER + 40),
TB_SETCMDID = (WM_USER + 42),
TB_CHANGEBITMAP = (WM_USER + 43),
TB_GETBITMAP = (WM_USER + 44),
TB_GETBUTTONTEXTA = (WM_USER + 45),
TB_GETBUTTONTEXTW = (WM_USER + 75),
TB_REPLACEBITMAP = (WM_USER + 46),
TB_SETINDENT = (WM_USER + 47),
TB_SETIMAGELIST = (WM_USER + 48),
TB_GETIMAGELIST = (WM_USER + 49),
TB_LOADIMAGES = (WM_USER + 50),
TB_GETRECT = (WM_USER + 51),
TB_SETHOTIMAGELIST = (WM_USER + 52),
TB_GETHOTIMAGELIST = (WM_USER + 53),
TB_SETDISABLEDIMAGELIST = (WM_USER + 54),
TB_GETDISABLEDIMAGELIST = (WM_USER + 55),
TB_SETSTYLE = (WM_USER + 56),
TB_GETSTYLE = (WM_USER + 57),
TB_GETBUTTONSIZE = (WM_USER + 58),
TB_SETBUTTONWIDTH = (WM_USER + 59),
TB_SETMAXTEXTROWS = (WM_USER + 60),
TB_GETTEXTROWS = (WM_USER + 61),
TB_GETOBJECT = (WM_USER + 62),
TB_GETHOTITEM = (WM_USER + 71),
TB_SETHOTITEM = (WM_USER + 72),
TB_SETANCHORHIGHLIGHT = (WM_USER + 73),
TB_GETANCHORHIGHLIGHT = (WM_USER + 74),
TB_MAPACCELERATORA = (WM_USER + 78),
TB_GETINSERTMARK = (WM_USER + 79),
TB_SETINSERTMARK = (WM_USER + 80),
TB_INSERTMARKHITTEST = (WM_USER + 81),
TB_MOVEBUTTON = (WM_USER + 82),
TB_GETMAXSIZE = (WM_USER + 83),
TB_SETEXTENDEDSTYLE = (WM_USER + 84),
TB_GETEXTENDEDSTYLE = (WM_USER + 85),
TB_GETPADDING = (WM_USER + 86),
TB_SETPADDING = (WM_USER + 87),
TB_SETINSERTMARKCOLOR = (WM_USER + 88),
TB_GETINSERTMARKCOLOR = (WM_USER + 89),
TB_SETCOLORSCHEME = CCM_SETCOLORSCHEME,
TB_GETCOLORSCHEME = CCM_GETCOLORSCHEME,
TB_SETUNICODEFORMAT = CCM_SETUNICODEFORMAT,
TB_GETUNICODEFORMAT = CCM_GETUNICODEFORMAT,
TB_MAPACCELERATORW = (WM_USER + 90),
TB_GETBITMAPFLAGS = (WM_USER + 41),
TB_GETBUTTONINFOW = (WM_USER + 63),
TB_SETBUTTONINFOW = (WM_USER + 64),
TB_GETBUTTONINFOA = (WM_USER + 65),
TB_SETBUTTONINFOA = (WM_USER + 66),
TB_INSERTBUTTONW = (WM_USER + 67),
TB_ADDBUTTONSW = (WM_USER + 68),
TB_HITTEST = (WM_USER + 69),
TB_SETDRAWTEXTFLAGS = (WM_USER + 70),
TB_GETSTRINGW = (WM_USER + 91),
TB_GETSTRINGA = (WM_USER + 92),
TB_GETMETRICS = (WM_USER + 101),
TB_SETMETRICS = (WM_USER + 102),
TB_SETWINDOWTHEME = CCM_SETWINDOWTHEME,
RB_INSERTBANDA = (WM_USER + 1),
RB_DELETEBAND = (WM_USER + 2),
RB_GETBARINFO = (WM_USER + 3),
RB_SETBARINFO = (WM_USER + 4),
RB_GETBANDINFO = (WM_USER + 5),
RB_SETBANDINFOA = (WM_USER + 6),
RB_SETPARENT = (WM_USER + 7),
RB_HITTEST = (WM_USER + 8),
RB_GETRECT = (WM_USER + 9),
RB_INSERTBANDW = (WM_USER + 10),
RB_SETBANDINFOW = (WM_USER + 11),
RB_GETBANDCOUNT = (WM_USER + 12),
RB_GETROWCOUNT = (WM_USER + 13),
RB_GETROWHEIGHT = (WM_USER + 14),
RB_IDTOINDEX = (WM_USER + 16),
RB_GETTOOLTIPS = (WM_USER + 17),
RB_SETTOOLTIPS = (WM_USER + 18),
RB_SETBKCOLOR = (WM_USER + 19),
RB_GETBKCOLOR = (WM_USER + 20),
RB_SETTEXTCOLOR = (WM_USER + 21),
RB_GETTEXTCOLOR = (WM_USER + 22),
RB_SIZETORECT = (WM_USER + 23),
RB_SETCOLORSCHEME = CCM_SETCOLORSCHEME,
RB_GETCOLORSCHEME = CCM_GETCOLORSCHEME,
RB_BEGINDRAG = (WM_USER + 24),
RB_ENDDRAG = (WM_USER + 25),
RB_DRAGMOVE = (WM_USER + 26),
RB_GETBARHEIGHT = (WM_USER + 27),
RB_GETBANDINFOW = (WM_USER + 28),
RB_GETBANDINFOA = (WM_USER + 29),
RB_MINIMIZEBAND = (WM_USER + 30),
RB_MAXIMIZEBAND = (WM_USER + 31),
RB_GETDROPTARGET = (CCM_GETDROPTARGET),
RB_GETBANDBORDERS = (WM_USER + 34),
RB_SHOWBAND = (WM_USER + 35),
RB_SETPALETTE = (WM_USER + 37),
RB_GETPALETTE = (WM_USER + 38),
RB_MOVEBAND = (WM_USER + 39),
RB_SETUNICODEFORMAT = CCM_SETUNICODEFORMAT,
RB_GETUNICODEFORMAT = CCM_GETUNICODEFORMAT,
RB_GETBANDMARGINS = (WM_USER + 40),
RB_SETWINDOWTHEME = CCM_SETWINDOWTHEME,
RB_PUSHCHEVRON = (WM_USER + 43),
TTM_ACTIVATE = (WM_USER + 1),
TTM_SETDELAYTIME = (WM_USER + 3),
TTM_ADDTOOLA = (WM_USER + 4),
TTM_ADDTOOLW = (WM_USER + 50),
TTM_DELTOOLA = (WM_USER + 5),
TTM_DELTOOLW = (WM_USER + 51),
TTM_NEWTOOLRECTA = (WM_USER + 6),
TTM_NEWTOOLRECTW = (WM_USER + 52),
TTM_RELAYEVENT = (WM_USER + 7),
TTM_GETTOOLINFOA = (WM_USER + 8),
TTM_GETTOOLINFOW = (WM_USER + 53),
TTM_SETTOOLINFOA = (WM_USER + 9),
TTM_SETTOOLINFOW = (WM_USER + 54),
TTM_HITTESTA = (WM_USER +10),
TTM_HITTESTW = (WM_USER +55),
TTM_GETTEXTA = (WM_USER +11),
TTM_GETTEXTW = (WM_USER +56),
TTM_UPDATETIPTEXTA = (WM_USER +12),
TTM_UPDATETIPTEXTW = (WM_USER +57),
TTM_GETTOOLCOUNT = (WM_USER +13),
TTM_ENUMTOOLSA = (WM_USER +14),
TTM_ENUMTOOLSW = (WM_USER +58),
TTM_GETCURRENTTOOLA = (WM_USER + 15),
TTM_GETCURRENTTOOLW = (WM_USER + 59),
TTM_WINDOWFROMPOINT = (WM_USER + 16),
TTM_TRACKACTIVATE = (WM_USER + 17),
TTM_TRACKPOSITION = (WM_USER + 18),
TTM_SETTIPBKCOLOR = (WM_USER + 19),
TTM_SETTIPTEXTCOLOR = (WM_USER + 20),
TTM_GETDELAYTIME = (WM_USER + 21),
TTM_GETTIPBKCOLOR = (WM_USER + 22),
TTM_GETTIPTEXTCOLOR = (WM_USER + 23),
TTM_SETMAXTIPWIDTH = (WM_USER + 24),
TTM_GETMAXTIPWIDTH = (WM_USER + 25),
TTM_SETMARGIN = (WM_USER + 26),
TTM_GETMARGIN = (WM_USER + 27),
TTM_POP = (WM_USER + 28),
TTM_UPDATE = (WM_USER + 29),
TTM_GETBUBBLESIZE = (WM_USER + 30),
TTM_ADJUSTRECT = (WM_USER + 31),
TTM_SETTITLEA = (WM_USER + 32),
TTM_SETTITLEW = (WM_USER + 33),
TTM_POPUP = (WM_USER + 34),
TTM_GETTITLE = (WM_USER + 35),
TTM_SETWINDOWTHEME = CCM_SETWINDOWTHEME,
SB_SETTEXTA = (WM_USER+1),
SB_SETTEXTW = (WM_USER+11),
SB_GETTEXTA = (WM_USER+2),
SB_GETTEXTW = (WM_USER+13),
SB_GETTEXTLENGTHA = (WM_USER+3),
SB_GETTEXTLENGTHW = (WM_USER+12),
SB_SETPARTS = (WM_USER+4),
SB_GETPARTS = (WM_USER+6),
SB_GETBORDERS = (WM_USER+7),
SB_SETMINHEIGHT = (WM_USER+8),
SB_SIMPLE = (WM_USER+9),
SB_GETRECT = (WM_USER+10),
SB_ISSIMPLE = (WM_USER+14),
SB_SETICON = (WM_USER+15),
SB_SETTIPTEXTA = (WM_USER+16),
SB_SETTIPTEXTW = (WM_USER+17),
SB_GETTIPTEXTA = (WM_USER+18),
SB_GETTIPTEXTW = (WM_USER+19),
SB_GETICON = (WM_USER+20),
SB_SETUNICODEFORMAT = CCM_SETUNICODEFORMAT,
SB_GETUNICODEFORMAT = CCM_GETUNICODEFORMAT,
SB_SETBKCOLOR = CCM_SETBKCOLOR,
SB_SIMPLEID = 0x00ff,
TBM_GETPOS = (WM_USER),
TBM_GETRANGEMIN = (WM_USER+1),
TBM_GETRANGEMAX = (WM_USER+2),
TBM_GETTIC = (WM_USER+3),
TBM_SETTIC = (WM_USER+4),
TBM_SETPOS = (WM_USER+5),
TBM_SETRANGE = (WM_USER+6),
TBM_SETRANGEMIN = (WM_USER+7),
TBM_SETRANGEMAX = (WM_USER+8),
TBM_CLEARTICS = (WM_USER+9),
TBM_SETSEL = (WM_USER+10),
TBM_SETSELSTART = (WM_USER+11),
TBM_SETSELEND = (WM_USER+12),
TBM_GETPTICS = (WM_USER+14),
TBM_GETTICPOS = (WM_USER+15),
TBM_GETNUMTICS = (WM_USER+16),
TBM_GETSELSTART = (WM_USER+17),
TBM_GETSELEND = (WM_USER+18),
TBM_CLEARSEL = (WM_USER+19),
TBM_SETTICFREQ = (WM_USER+20),
TBM_SETPAGESIZE = (WM_USER+21),
TBM_GETPAGESIZE = (WM_USER+22),
TBM_SETLINESIZE = (WM_USER+23),
TBM_GETLINESIZE = (WM_USER+24),
TBM_GETTHUMBRECT = (WM_USER+25),
TBM_GETCHANNELRECT = (WM_USER+26),
TBM_SETTHUMBLENGTH = (WM_USER+27),
TBM_GETTHUMBLENGTH = (WM_USER+28),
TBM_SETTOOLTIPS = (WM_USER+29),
TBM_GETTOOLTIPS = (WM_USER+30),
TBM_SETTIPSIDE = (WM_USER+31),
TBM_SETBUDDY = (WM_USER+32),
TBM_GETBUDDY = (WM_USER+33),
TBM_SETUNICODEFORMAT = CCM_SETUNICODEFORMAT,
TBM_GETUNICODEFORMAT = CCM_GETUNICODEFORMAT,
DL_BEGINDRAG = (WM_USER+133),
DL_DRAGGING = (WM_USER+134),
DL_DROPPED = (WM_USER+135),
DL_CANCELDRAG = (WM_USER+136),
UDM_SETRANGE = (WM_USER+101),
UDM_GETRANGE = (WM_USER+102),
UDM_SETPOS = (WM_USER+103),
UDM_GETPOS = (WM_USER+104),
UDM_SETBUDDY = (WM_USER+105),
UDM_GETBUDDY = (WM_USER+106),
UDM_SETACCEL = (WM_USER+107),
UDM_GETACCEL = (WM_USER+108),
UDM_SETBASE = (WM_USER+109),
UDM_GETBASE = (WM_USER+110),
UDM_SETRANGE32 = (WM_USER+111),
UDM_GETRANGE32 = (WM_USER+112),
UDM_SETUNICODEFORMAT = CCM_SETUNICODEFORMAT,
UDM_GETUNICODEFORMAT = CCM_GETUNICODEFORMAT,
UDM_SETPOS32 = (WM_USER+113),
UDM_GETPOS32 = (WM_USER+114),
PBM_SETRANGE = (WM_USER+1),
PBM_SETPOS = (WM_USER+2),
PBM_DELTAPOS = (WM_USER+3),
PBM_SETSTEP = (WM_USER+4),
PBM_STEPIT = (WM_USER+5),
PBM_SETRANGE32 = (WM_USER+6),
PBM_GETRANGE = (WM_USER+7),
PBM_GETPOS = (WM_USER+8),
PBM_SETBARCOLOR = (WM_USER+9),
PBM_SETBKCOLOR = CCM_SETBKCOLOR,
HKM_SETHOTKEY = (WM_USER+1),
HKM_GETHOTKEY = (WM_USER+2),
HKM_SETRULES = (WM_USER+3),
LVM_SETUNICODEFORMAT = CCM_SETUNICODEFORMAT,
LVM_GETUNICODEFORMAT = CCM_GETUNICODEFORMAT,
LVM_GETBKCOLOR = (LVM_FIRST + 0),
LVM_SETBKCOLOR = (LVM_FIRST + 1),
LVM_GETIMAGELIST = (LVM_FIRST + 2),
LVM_SETIMAGELIST = (LVM_FIRST + 3),
LVM_GETITEMCOUNT = (LVM_FIRST + 4),
LVM_GETITEMA = (LVM_FIRST + 5),
LVM_GETITEMW = (LVM_FIRST + 75),
LVM_SETITEMA = (LVM_FIRST + 6),
LVM_SETITEMW = (LVM_FIRST + 76),
LVM_INSERTITEMA = (LVM_FIRST + 7),
LVM_INSERTITEMW = (LVM_FIRST + 77),
LVM_DELETEITEM = (LVM_FIRST + 8),
LVM_DELETEALLITEMS = (LVM_FIRST + 9),
LVM_GETCALLBACKMASK = (LVM_FIRST + 10),
LVM_SETCALLBACKMASK = (LVM_FIRST + 11),
LVM_FINDITEMA = (LVM_FIRST + 13),
LVM_FINDITEMW = (LVM_FIRST + 83),
LVM_GETITEMRECT = (LVM_FIRST + 14),
LVM_SETITEMPOSITION = (LVM_FIRST + 15),
LVM_GETITEMPOSITION = (LVM_FIRST + 16),
LVM_GETSTRINGWIDTHA = (LVM_FIRST + 17),
LVM_GETSTRINGWIDTHW = (LVM_FIRST + 87),
LVM_HITTEST = (LVM_FIRST + 18),
LVM_ENSUREVISIBLE = (LVM_FIRST + 19),
LVM_SCROLL = (LVM_FIRST + 20),
LVM_REDRAWITEMS = (LVM_FIRST + 21),
LVM_ARRANGE = (LVM_FIRST + 22),
LVM_EDITLABELA = (LVM_FIRST + 23),
LVM_EDITLABELW = (LVM_FIRST + 118),
LVM_GETEDITCONTROL = (LVM_FIRST + 24),
LVM_GETCOLUMNA = (LVM_FIRST + 25),
LVM_GETCOLUMNW = (LVM_FIRST + 95),
LVM_SETCOLUMNA = (LVM_FIRST + 26),
LVM_SETCOLUMNW = (LVM_FIRST + 96),
LVM_INSERTCOLUMNA = (LVM_FIRST + 27),
LVM_INSERTCOLUMNW = (LVM_FIRST + 97),
LVM_DELETECOLUMN = (LVM_FIRST + 28),
LVM_GETCOLUMNWIDTH = (LVM_FIRST + 29),
LVM_SETCOLUMNWIDTH = (LVM_FIRST + 30),
LVM_CREATEDRAGIMAGE = (LVM_FIRST + 33),
LVM_GETVIEWRECT = (LVM_FIRST + 34),
LVM_GETTEXTCOLOR = (LVM_FIRST + 35),
LVM_SETTEXTCOLOR = (LVM_FIRST + 36),
LVM_GETTEXTBKCOLOR = (LVM_FIRST + 37),
LVM_SETTEXTBKCOLOR = (LVM_FIRST + 38),
LVM_GETTOPINDEX = (LVM_FIRST + 39),
LVM_GETCOUNTPERPAGE = (LVM_FIRST + 40),
LVM_GETORIGIN = (LVM_FIRST + 41),
LVM_UPDATE = (LVM_FIRST + 42),
LVM_SETITEMSTATE = (LVM_FIRST + 43),
LVM_GETITEMSTATE = (LVM_FIRST + 44),
LVM_GETITEMTEXTA = (LVM_FIRST + 45),
LVM_GETITEMTEXTW = (LVM_FIRST + 115),
LVM_SETITEMTEXTA = (LVM_FIRST + 46),
LVM_SETITEMTEXTW = (LVM_FIRST + 116),
LVM_SETITEMCOUNT = (LVM_FIRST + 47),
LVM_SORTITEMS = (LVM_FIRST + 48),
LVM_SETITEMPOSITION32 = (LVM_FIRST + 49),
LVM_GETSELECTEDCOUNT = (LVM_FIRST + 50),
LVM_GETITEMSPACING = (LVM_FIRST + 51),
LVM_GETISEARCHSTRINGA = (LVM_FIRST + 52),
LVM_GETISEARCHSTRINGW = (LVM_FIRST + 117),
LVM_SETICONSPACING = (LVM_FIRST + 53),
LVM_SETEXTENDEDLISTVIEWSTYLE = (LVM_FIRST + 54),
LVM_GETEXTENDEDLISTVIEWSTYLE = (LVM_FIRST + 55),
LVM_GETSUBITEMRECT = (LVM_FIRST + 56),
LVM_SUBITEMHITTEST = (LVM_FIRST + 57),
LVM_SETCOLUMNORDERARRAY = (LVM_FIRST + 58),
LVM_GETCOLUMNORDERARRAY = (LVM_FIRST + 59),
LVM_SETHOTITEM = (LVM_FIRST + 60),
LVM_GETHOTITEM = (LVM_FIRST + 61),
LVM_SETHOTCURSOR = (LVM_FIRST + 62),
LVM_GETHOTCURSOR = (LVM_FIRST + 63),
LVM_APPROXIMATEVIEWRECT = (LVM_FIRST + 64),
LVM_SETWORKAREAS = (LVM_FIRST + 65),
LVM_GETWORKAREAS = (LVM_FIRST + 70),
LVM_GETNUMBEROFWORKAREAS = (LVM_FIRST + 73),
LVM_GETSELECTIONMARK = (LVM_FIRST + 66),
LVM_SETSELECTIONMARK = (LVM_FIRST + 67),
LVM_SETHOVERTIME = (LVM_FIRST + 71),
LVM_GETHOVERTIME = (LVM_FIRST + 72),
LVM_SETTOOLTIPS = (LVM_FIRST + 74),
LVM_GETTOOLTIPS = (LVM_FIRST + 78),
LVM_SORTITEMSEX = (LVM_FIRST + 81),
LVM_SETBKIMAGEA = (LVM_FIRST + 68),
LVM_SETBKIMAGEW = (LVM_FIRST + 138),
LVM_GETBKIMAGEA = (LVM_FIRST + 69),
LVM_GETBKIMAGEW = (LVM_FIRST + 139),
LVM_SETSELECTEDCOLUMN = (LVM_FIRST + 140),
LVM_SETTILEWIDTH = (LVM_FIRST + 141),
LVM_SETVIEW = (LVM_FIRST + 142),
LVM_GETVIEW = (LVM_FIRST + 143),
LVM_INSERTGROUP = (LVM_FIRST + 145),
LVM_SETGROUPINFO = (LVM_FIRST + 147),
LVM_GETGROUPINFO = (LVM_FIRST + 149),
LVM_REMOVEGROUP = (LVM_FIRST + 150),
LVM_MOVEGROUP = (LVM_FIRST + 151),
LVM_MOVEITEMTOGROUP = (LVM_FIRST + 154),
LVM_SETGROUPMETRICS = (LVM_FIRST + 155),
LVM_GETGROUPMETRICS = (LVM_FIRST + 156),
LVM_ENABLEGROUPVIEW = (LVM_FIRST + 157),
LVM_SORTGROUPS = (LVM_FIRST + 158),
LVM_INSERTGROUPSORTED = (LVM_FIRST + 159),
LVM_REMOVEALLGROUPS = (LVM_FIRST + 160),
LVM_HASGROUP = (LVM_FIRST + 161),
LVM_SETTILEVIEWINFO = (LVM_FIRST + 162),
LVM_GETTILEVIEWINFO = (LVM_FIRST + 163),
LVM_SETTILEINFO = (LVM_FIRST + 164),
LVM_GETTILEINFO = (LVM_FIRST + 165),
LVM_SETINSERTMARK = (LVM_FIRST + 166),
LVM_GETINSERTMARK = (LVM_FIRST + 167),
LVM_INSERTMARKHITTEST = (LVM_FIRST + 168),
LVM_GETINSERTMARKRECT = (LVM_FIRST + 169),
LVM_SETINSERTMARKCOLOR = (LVM_FIRST + 170),
LVM_GETINSERTMARKCOLOR = (LVM_FIRST + 171),
LVM_SETINFOTIP = (LVM_FIRST + 173),
LVM_GETSELECTEDCOLUMN = (LVM_FIRST + 174),
LVM_ISGROUPVIEWENABLED = (LVM_FIRST + 175),
LVM_GETOUTLINECOLOR = (LVM_FIRST + 176),
LVM_SETOUTLINECOLOR = (LVM_FIRST + 177),
LVM_CANCELEDITLABEL = (LVM_FIRST + 179),
LVM_MAPINDEXTOID = (LVM_FIRST + 180),
LVM_MAPIDTOINDEX = (LVM_FIRST + 181),
TVM_INSERTITEMA = (TV_FIRST + 0),
TVM_INSERTITEMW = (TV_FIRST + 50),
TVM_DELETEITEM = (TV_FIRST + 1),
TVM_EXPAND = (TV_FIRST + 2),
TVM_GETITEMRECT = (TV_FIRST + 4),
TVM_GETCOUNT = (TV_FIRST + 5),
TVM_GETINDENT = (TV_FIRST + 6),
TVM_SETINDENT = (TV_FIRST + 7),
TVM_GETIMAGELIST = (TV_FIRST + 8),
TVM_SETIMAGELIST = (TV_FIRST + 9),
TVM_GETNEXTITEM = (TV_FIRST + 10),
TVM_SELECTITEM = (TV_FIRST + 11),
TVM_GETITEMA = (TV_FIRST + 12),
TVM_GETITEMW = (TV_FIRST + 62),
TVM_SETITEMA = (TV_FIRST + 13),
TVM_SETITEMW = (TV_FIRST + 63),
TVM_EDITLABELA = (TV_FIRST + 14),
TVM_EDITLABELW = (TV_FIRST + 65),
TVM_GETEDITCONTROL = (TV_FIRST + 15),
TVM_GETVISIBLECOUNT = (TV_FIRST + 16),
TVM_HITTEST = (TV_FIRST + 17),
TVM_CREATEDRAGIMAGE = (TV_FIRST + 18),
TVM_SORTCHILDREN = (TV_FIRST + 19),
TVM_ENSUREVISIBLE = (TV_FIRST + 20),
TVM_SORTCHILDRENCB = (TV_FIRST + 21),
TVM_ENDEDITLABELNOW = (TV_FIRST + 22),
TVM_GETISEARCHSTRINGA = (TV_FIRST + 23),
TVM_GETISEARCHSTRINGW = (TV_FIRST + 64),
TVM_SETTOOLTIPS = (TV_FIRST + 24),
TVM_GETTOOLTIPS = (TV_FIRST + 25),
TVM_SETINSERTMARK = (TV_FIRST + 26),
TVM_SETUNICODEFORMAT = CCM_SETUNICODEFORMAT,
TVM_GETUNICODEFORMAT = CCM_GETUNICODEFORMAT,
TVM_SETITEMHEIGHT = (TV_FIRST + 27),
TVM_GETITEMHEIGHT = (TV_FIRST + 28),
TVM_SETBKCOLOR = (TV_FIRST + 29),
TVM_SETTEXTCOLOR = (TV_FIRST + 30),
TVM_GETBKCOLOR = (TV_FIRST + 31),
TVM_GETTEXTCOLOR = (TV_FIRST + 32),
TVM_SETSCROLLTIME = (TV_FIRST + 33),
TVM_GETSCROLLTIME = (TV_FIRST + 34),
TVM_SETINSERTMARKCOLOR = (TV_FIRST + 37),
TVM_GETINSERTMARKCOLOR = (TV_FIRST + 38),
TVM_GETITEMSTATE = (TV_FIRST + 39),
TVM_SETLINECOLOR = (TV_FIRST + 40),
TVM_GETLINECOLOR = (TV_FIRST + 41),
TVM_MAPACCIDTOHTREEITEM = (TV_FIRST + 42),
TVM_MAPHTREEITEMTOACCID = (TV_FIRST + 43),
CBEM_INSERTITEMA = (WM_USER + 1),
CBEM_SETIMAGELIST = (WM_USER + 2),
CBEM_GETIMAGELIST = (WM_USER + 3),
CBEM_GETITEMA = (WM_USER + 4),
CBEM_SETITEMA = (WM_USER + 5),
CBEM_DELETEITEM = CB_DELETESTRING,
CBEM_GETCOMBOCONTROL = (WM_USER + 6),
CBEM_GETEDITCONTROL = (WM_USER + 7),
CBEM_SETEXTENDEDSTYLE = (WM_USER + 14),
CBEM_GETEXTENDEDSTYLE = (WM_USER + 9),
CBEM_SETUNICODEFORMAT = CCM_SETUNICODEFORMAT,
CBEM_GETUNICODEFORMAT = CCM_GETUNICODEFORMAT,
CBEM_SETEXSTYLE = (WM_USER + 8),
CBEM_GETEXSTYLE = (WM_USER + 9),
CBEM_HASEDITCHANGED = (WM_USER + 10),
CBEM_INSERTITEMW = (WM_USER + 11),
CBEM_SETITEMW = (WM_USER + 12),
CBEM_GETITEMW = (WM_USER + 13),
TCM_GETIMAGELIST = (TCM_FIRST + 2),
TCM_SETIMAGELIST = (TCM_FIRST + 3),
TCM_GETITEMCOUNT = (TCM_FIRST + 4),
TCM_GETITEMA = (TCM_FIRST + 5),
TCM_GETITEMW = (TCM_FIRST + 60),
TCM_SETITEMA = (TCM_FIRST + 6),
TCM_SETITEMW = (TCM_FIRST + 61),
TCM_INSERTITEMA = (TCM_FIRST + 7),
TCM_INSERTITEMW = (TCM_FIRST + 62),
TCM_DELETEITEM = (TCM_FIRST + 8),
TCM_DELETEALLITEMS = (TCM_FIRST + 9),
TCM_GETITEMRECT = (TCM_FIRST + 10),
TCM_GETCURSEL = (TCM_FIRST + 11),
TCM_SETCURSEL = (TCM_FIRST + 12),
TCM_HITTEST = (TCM_FIRST + 13),
TCM_SETITEMEXTRA = (TCM_FIRST + 14),
TCM_ADJUSTRECT = (TCM_FIRST + 40),
TCM_SETITEMSIZE = (TCM_FIRST + 41),
TCM_REMOVEIMAGE = (TCM_FIRST + 42),
TCM_SETPADDING = (TCM_FIRST + 43),
TCM_GETROWCOUNT = (TCM_FIRST + 44),
TCM_GETTOOLTIPS = (TCM_FIRST + 45),
TCM_SETTOOLTIPS = (TCM_FIRST + 46),
TCM_GETCURFOCUS = (TCM_FIRST + 47),
TCM_SETCURFOCUS = (TCM_FIRST + 48),
TCM_SETMINTABWIDTH = (TCM_FIRST + 49),
TCM_DESELECTALL = (TCM_FIRST + 50),
TCM_HIGHLIGHTITEM = (TCM_FIRST + 51),
TCM_SETEXTENDEDSTYLE = (TCM_FIRST + 52),
TCM_GETEXTENDEDSTYLE = (TCM_FIRST + 53),
TCM_SETUNICODEFORMAT = CCM_SETUNICODEFORMAT,
TCM_GETUNICODEFORMAT = CCM_GETUNICODEFORMAT,
ACM_OPENA = (WM_USER+100),
ACM_OPENW = (WM_USER+103),
ACM_PLAY = (WM_USER+101),
ACM_STOP = (WM_USER+102),
MCM_FIRST = 0x1000,
MCM_GETCURSEL = (MCM_FIRST + 1),
MCM_SETCURSEL = (MCM_FIRST + 2),
MCM_GETMAXSELCOUNT = (MCM_FIRST + 3),
MCM_SETMAXSELCOUNT = (MCM_FIRST + 4),
MCM_GETSELRANGE = (MCM_FIRST + 5),
MCM_SETSELRANGE = (MCM_FIRST + 6),
MCM_GETMONTHRANGE = (MCM_FIRST + 7),
MCM_SETDAYSTATE = (MCM_FIRST + 8),
MCM_GETMINREQRECT = (MCM_FIRST + 9),
MCM_SETCOLOR = (MCM_FIRST + 10),
MCM_GETCOLOR = (MCM_FIRST + 11),
MCM_SETTODAY = (MCM_FIRST + 12),
MCM_GETTODAY = (MCM_FIRST + 13),
MCM_HITTEST = (MCM_FIRST + 14),
MCM_SETFIRSTDAYOFWEEK = (MCM_FIRST + 15),
MCM_GETFIRSTDAYOFWEEK = (MCM_FIRST + 16),
MCM_GETRANGE = (MCM_FIRST + 17),
MCM_SETRANGE = (MCM_FIRST + 18),
MCM_GETMONTHDELTA = (MCM_FIRST + 19),
MCM_SETMONTHDELTA = (MCM_FIRST + 20),
MCM_GETMAXTODAYWIDTH = (MCM_FIRST + 21),
MCM_SETUNICODEFORMAT = CCM_SETUNICODEFORMAT,
MCM_GETUNICODEFORMAT = CCM_GETUNICODEFORMAT,
DTM_FIRST = 0x1000,
DTM_GETSYSTEMTIME = (DTM_FIRST + 1),
DTM_SETSYSTEMTIME = (DTM_FIRST + 2),
DTM_GETRANGE = (DTM_FIRST + 3),
DTM_SETRANGE = (DTM_FIRST + 4),
DTM_SETFORMATA = (DTM_FIRST + 5),
DTM_SETFORMATW = (DTM_FIRST + 50),
DTM_SETMCCOLOR = (DTM_FIRST + 6),
DTM_GETMCCOLOR = (DTM_FIRST + 7),
DTM_GETMONTHCAL = (DTM_FIRST + 8),
DTM_SETMCFONT = (DTM_FIRST + 9),
DTM_GETMCFONT = (DTM_FIRST + 10),
PGM_SETCHILD = (PGM_FIRST + 1),
PGM_RECALCSIZE = (PGM_FIRST + 2),
PGM_FORWARDMOUSE = (PGM_FIRST + 3),
PGM_SETBKCOLOR = (PGM_FIRST + 4),
PGM_GETBKCOLOR = (PGM_FIRST + 5),
PGM_SETBORDER = (PGM_FIRST + 6),
PGM_GETBORDER = (PGM_FIRST + 7),
PGM_SETPOS = (PGM_FIRST + 8),
PGM_GETPOS = (PGM_FIRST + 9),
PGM_SETBUTTONSIZE = (PGM_FIRST + 10),
PGM_GETBUTTONSIZE = (PGM_FIRST + 11),
PGM_GETBUTTONSTATE = (PGM_FIRST + 12),
PGM_GETDROPTARGET = CCM_GETDROPTARGET,
BCM_GETIDEALSIZE = (BCM_FIRST + 0x0001),
BCM_SETIMAGELIST = (BCM_FIRST + 0x0002),
BCM_GETIMAGELIST = (BCM_FIRST + 0x0003),
BCM_SETTEXTMARGIN = (BCM_FIRST + 0x0004),
BCM_GETTEXTMARGIN = (BCM_FIRST + 0x0005),
EM_SETCUEBANNER = (ECM_FIRST + 1),
EM_GETCUEBANNER = (ECM_FIRST + 2),
EM_SHOWBALLOONTIP = (ECM_FIRST + 3),
EM_HIDEBALLOONTIP = (ECM_FIRST + 4),
CB_SETMINVISIBLE = (CBM_FIRST + 1),
CB_GETMINVISIBLE = (CBM_FIRST + 2),
LM_HITTEST = (WM_USER + 0x300),
LM_GETIDEALHEIGHT = (WM_USER + 0x301),
LM_SETITEM = (WM_USER + 0x302),
LM_GETITEM = (WM_USER + 0x303)
}
/// <summary>
/// Grouping of IE-specific messages.
/// </summary>
/// <remarks>
/// Definitions have been scanvenged from the net, but mostly come from PInvoke (www.pinvoke.net).
/// </remarks>
public enum IEMessages : int
{
ID_IE_CONTEXTMENU_VIEWSOURCE = 0x085B
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Glass.Mapper.Pipelines.ConfigurationResolver.Tasks.OnDemandResolver;
using Glass.Mapper.Pipelines.DataMapperResolver;
using Glass.Mapper.Sc.Configuration;
using Glass.Mapper.Sc.Configuration.Attributes;
using Glass.Mapper.Sc.DataMappers;
using Glass.Mapper.Sc.DataMappers.SitecoreQueryParameters;
using NUnit.Framework;
using Sitecore.Data;
using Sitecore.FakeDb;
namespace Glass.Mapper.Sc.FakeDb.DataMappers
{
[TestFixture]
public class SitecoreQueryMapperFixture
{
#region Property - ReadOnly
[Test]
public void ReadOnly_ReturnsTrue()
{
//Assign
var mapper = new SitecoreQueryMapper(null);
//Act
var result = mapper.ReadOnly;
//Assert
Assert.IsTrue(result);
}
#endregion
#region Method - CanHandle
[Test]
public void CanHandle_CorrectConfigIEnumerableMappedClass_ReturnsTrue()
{
//Assign
var mapper = new SitecoreQueryMapper(null);
var config = new SitecoreQueryConfiguration();
config.PropertyInfo = typeof(StubClass).GetProperty("StubMappeds");
var context = Context.Create(Utilities.CreateStandardResolver());
context.Load(new OnDemandLoader<SitecoreTypeConfiguration>(typeof(StubClass)));
//Act
var result = mapper.CanHandle(config, context);
//Assert
Assert.IsTrue(result);
}
[Test]
public void CanHandle_CorrectConfigIEnumerableNotMappedClass_ReturnsTrueOnDemand()
{
//Assign
var mapper = new SitecoreQueryMapper(null);
var config = new SitecoreQueryConfiguration();
config.PropertyInfo = typeof(StubClass).GetProperty("StubNotMappeds");
var context = Context.Create(Utilities.CreateStandardResolver());
context.Load(new OnDemandLoader<SitecoreTypeConfiguration>(typeof(StubClass)));
//Act
var result = mapper.CanHandle(config, context);
//Assert
Assert.IsTrue(result);
}
[Test]
public void CanHandle_CorrectConfigNotMappedClass_ReturnsTrueOnDemand()
{
//Assign
var mapper = new SitecoreQueryMapper(null);
var config = new SitecoreQueryConfiguration();
config.PropertyInfo = typeof(StubClass).GetProperty("StubNotMapped");
var context = Context.Create(Utilities.CreateStandardResolver());
context.Load(new OnDemandLoader<SitecoreTypeConfiguration>(typeof(StubClass)));
//Act
var result = mapper.CanHandle(config, context);
//Assert
Assert.IsTrue(result);
}
[Test]
public void CanHandle_CorrectConfigMappedClass_ReturnsFalse()
{
//Assign
var mapper = new SitecoreQueryMapper(null);
var config = new SitecoreQueryConfiguration();
config.PropertyInfo = typeof(StubClass).GetProperty("StubMapped");
var context = Context.Create(Utilities.CreateStandardResolver());
context.Load(new OnDemandLoader<SitecoreTypeConfiguration>(typeof(StubClass)));
//Act
var result = mapper.CanHandle(config, context);
//Assert
Assert.IsTrue(result);
}
[Test]
public void CanHandle_IncorrectConfigMappedClass_ReturnsFalse()
{
//Assign
var mapper = new SitecoreQueryMapper(null);
var config = new SitecoreFieldConfiguration();
config.PropertyInfo = typeof(StubClass).GetProperty("StubMapped");
var context = Context.Create(Utilities.CreateStandardResolver());
context.Load(new OnDemandLoader<SitecoreTypeConfiguration>(typeof(StubClass)));
//Act
var result = mapper.CanHandle(config, context);
//Assert
Assert.IsFalse(result);
}
#endregion
#region Method - MapToProperty
[Test]
public void MapToProperty_RelativeQuery_ReturnsNoResults()
{
//Assign
using (Db database = new Db
{
new Sitecore.FakeDb.DbItem("Target")
{
new Sitecore.FakeDb.DbItem("Child1"),
new Sitecore.FakeDb.DbItem("Child2")
}
})
{
var config = new SitecoreQueryConfiguration();
config.PropertyInfo = typeof(StubClass).GetProperty("StubMappeds");
config.Query = "../Target/DoesNotExist/*";
config.IsRelative = true;
var context = Context.Create(Utilities.CreateStandardResolver());
context.Load(new OnDemandLoader<SitecoreTypeConfiguration>(typeof(StubMapped)));
var mapper = new SitecoreQueryMapper(null);
mapper.Setup(new DataMapperResolverArgs(context, config));
var source = database.GetItem("/sitecore/content/Target");
var service = new SitecoreService(database.Database, context);
var options = new GetItemOptionsParams();
//Act
var results =
mapper.MapToProperty(new SitecoreDataMappingContext(null, source, service, options)) as
IEnumerable<StubMapped>;
//Assert
Assert.AreEqual(0, results.Count());
}
}
[Test]
public void MapToProperty_RelativeQueryEnforceTemplate_ReturnsNoResults()
{
//Assign
var templateId = ID.NewID;
var childId = ID.NewID;
using (Db database = new Db
{
new Sitecore.FakeDb.DbItem("Target")
{
new Sitecore.FakeDb.DbItem("Child1", childId , templateId),
new Sitecore.FakeDb.DbItem("Child2")
}
})
{
var config = new SitecoreQueryConfiguration();
config.PropertyInfo = typeof(StubClass).GetProperty("StubMappeds");
config.Query = "../Target/*";
config.IsRelative = true;
config.TemplateId = templateId;
config.EnforceTemplate = SitecoreEnforceTemplate.TemplateAndBase;
var context = Context.Create(Utilities.CreateStandardResolver());
context.Load(new OnDemandLoader<SitecoreTypeConfiguration>(typeof(StubMapped)));
var mapper = new SitecoreQueryMapper(null);
mapper.Setup(new DataMapperResolverArgs(context, config));
var source = database.GetItem("/sitecore/content/Target");
var service = new SitecoreService(database.Database, context);
var options = new GetItemOptionsParams();
//Act
var results =
mapper.MapToProperty(new SitecoreDataMappingContext(null, source, service, options)) as
IEnumerable<StubMapped>;
//Assert
Assert.AreEqual(1, results.Count());
}
}
[Test]
public void MapToProperty_RelativeQuerySelf_ReturnsSelf()
{
//Assign
//Assign
using (Db database = new Db
{
new Sitecore.FakeDb.DbItem("Target")
{
new Sitecore.FakeDb.DbItem("Child1"),
new Sitecore.FakeDb.DbItem("Child2")
}
})
{
var config = new SitecoreQueryConfiguration();
config.PropertyInfo = typeof(StubClass).GetProperty("StubMapped");
config.Query = "ancestor-or-self::*";
config.IsRelative = true;
var context = Context.Create(Utilities.CreateStandardResolver());
context.Load(new OnDemandLoader<SitecoreTypeConfiguration>(typeof(StubMapped)));
var mapper = new SitecoreQueryMapper(null);
mapper.Setup(new DataMapperResolverArgs(context, config));
var source = database.GetItem("/sitecore/content/Target");
var service = new SitecoreService(database.Database, context);
var options = new GetItemOptionsParams();
//Act
var result =
mapper.MapToProperty(new SitecoreDataMappingContext(null, source, service, options)) as StubMapped;
//Assert
Assert.AreEqual(source.ID.Guid, result.Id);
}
}
[Test]
public void MapToProperty_RelativeQuery_ReturnsResults()
{
//Assign
using (Db database = new Db
{
new Sitecore.FakeDb.DbItem("Target")
{
new Sitecore.FakeDb.DbItem("Child1"),
new Sitecore.FakeDb.DbItem("Child2")
}
})
{
var config = new SitecoreQueryConfiguration();
config.PropertyInfo = typeof(StubClass).GetProperty("StubMappeds");
config.Query = "../Target/*";
config.IsRelative = true;
var context = Context.Create(Utilities.CreateStandardResolver());
context.Load(new OnDemandLoader<SitecoreTypeConfiguration>(typeof(StubMapped)));
var mapper = new SitecoreQueryMapper(null);
mapper.Setup(new DataMapperResolverArgs(context, config));
var source = database.GetItem("/sitecore/content/Target");
var service = new SitecoreService(database.Database, context);
var result1 = database.GetItem("/sitecore/content/Target/Child1");
var result2 = database.GetItem("/sitecore/content/Target/Child2");
var options = new GetItemOptionsParams();
//Act
var results =
mapper.MapToProperty(new SitecoreDataMappingContext(null, source, service, options)) as
IEnumerable<StubMapped>;
//Assert
Assert.AreEqual(2, results.Count());
Assert.IsTrue(results.Any(x => x.Id == result1.ID.Guid));
Assert.IsTrue(results.Any(x => x.Id == result2.ID.Guid));
}
}
[Test]
public void MapToProperty_AbsoluteQuery_ReturnsResults()
{
//Assign
using (Db database = new Db
{
new Sitecore.FakeDb.DbItem("Target")
{
new Sitecore.FakeDb.DbItem("Child1"),
new Sitecore.FakeDb.DbItem("Child2")
}
})
{
var config = new SitecoreQueryConfiguration();
config.PropertyInfo = typeof(StubClass).GetProperty("StubMappeds");
config.Query = "/sitecore/content/Target/*";
config.IsRelative = false;
var context = Context.Create(Utilities.CreateStandardResolver());
context.Load(new OnDemandLoader<SitecoreTypeConfiguration>(typeof(StubMapped)));
var mapper = new SitecoreQueryMapper(null);
mapper.Setup(new DataMapperResolverArgs(context, config));
var source = database.GetItem("/sitecore/content/Target");
var service = new SitecoreService(database.Database, context);
var result1 = database.GetItem("/sitecore/content/Target/Child1");
var result2 = database.GetItem("/sitecore/content/Target/Child2");
var options = new GetItemOptionsParams();
//Act
var results =
mapper.MapToProperty(new SitecoreDataMappingContext(null, source, service, options)) as
IEnumerable<StubMapped>;
//Assert
Assert.AreEqual(2, results.Count());
Assert.IsTrue(results.Any(x => x.Id == result1.ID.Guid));
Assert.IsTrue(results.Any(x => x.Id == result2.ID.Guid));
}
}
[Test]
public void MapToProperty_AbsoluteQueryMultiLanguages_ReturnsResults()
{
//Assign
var templateId = ID.NewID;
using (Db database = new Db
{
new Sitecore.FakeDb.DbItem("Target")
{
new DbTemplate(templateId)
{
{"title", ""}
},
new Sitecore.FakeDb.DbItem("Child1", new ID(Guid.NewGuid()), templateId) {
Fields =
{
new DbField("title")
{
{"en", "test en"},
{"da", "test"}
}
}
},
new Sitecore.FakeDb.DbItem("Child2", new ID(Guid.NewGuid()), templateId)
{
Fields =
{
new DbField("title")
{
{"en", "test en"},
{"da", "test1"}
}
},
}
}
})
{
var config = new SitecoreQueryConfiguration();
config.PropertyInfo = typeof(StubClass).GetProperty("StubMappeds");
config.Query = "/sitecore/content/Target/Child2";
config.IsRelative = false;
var context = Context.Create(Utilities.CreateStandardResolver());
context.Load(new OnDemandLoader<SitecoreTypeConfiguration>(typeof(StubMapped)));
var mapper = new SitecoreQueryMapper(null);
mapper.Setup(new DataMapperResolverArgs(context, config));
var source = database.GetItem("/sitecore/content/Target/child1", "da");
var service = new SitecoreService(database.Database, context);
var options = new GetItemOptionsParams();
//Act
var results =
mapper.MapToProperty(new SitecoreDataMappingContext(null, source, service, options)) as
IEnumerable<StubMapped>;
//Assert
Assert.AreEqual(1, results.Count());
Assert.AreEqual("test1", results.First().Title);
}
}
[Test]
public void MapToProperty_RelativeQuery_ReturnsSingleResults()
{
//Assign
using (Db database = new Db
{
new Sitecore.FakeDb.DbItem("Target")
{
new Sitecore.FakeDb.DbItem("Child1"),
new Sitecore.FakeDb.DbItem("Child2")
}
})
{
var config = new SitecoreQueryConfiguration();
config.PropertyInfo = typeof(StubClass).GetProperty("StubMapped");
config.Query = "../Target/Child1";
config.IsRelative = true;
var context = Context.Create(Utilities.CreateStandardResolver());
context.Load(new OnDemandLoader<SitecoreTypeConfiguration>(typeof(StubMapped)));
var mapper = new SitecoreQueryMapper(null);
mapper.Setup(new DataMapperResolverArgs(context, config));
var source = database.GetItem("/sitecore/content/Target");
var service = new SitecoreService(database.Database, context);
var result1 = database.GetItem("/sitecore/content/Target/Child1");
var options = new GetItemOptionsParams();
//Act
var result =
mapper.MapToProperty(new SitecoreDataMappingContext(null, source, service, options)) as StubMapped;
//Assert
Assert.AreEqual(result1.ID.Guid, result.Id);
}
}
[Test]
public void MapToProperty_AbsoluteQuery_ReturnsSingleResults()
{
//Assign
using (Db database = new Db
{
new Sitecore.FakeDb.DbItem("Target")
{
new Sitecore.FakeDb.DbItem("Child1"),
new Sitecore.FakeDb.DbItem("Child2")
}
})
{
var config = new SitecoreQueryConfiguration();
config.PropertyInfo = typeof(StubClass).GetProperty("StubMapped");
config.Query = "/sitecore/content/Target/Child1";
config.IsRelative = false;
var context = Context.Create(Utilities.CreateStandardResolver());
context.Load(new OnDemandLoader<SitecoreTypeConfiguration>(typeof(StubMapped)));
var mapper = new SitecoreQueryMapper(null);
mapper.Setup(new DataMapperResolverArgs(context, config));
var source = database.GetItem("/sitecore/content/Target");
var service = new SitecoreService(database.Database, context);
var result1 = database.GetItem("/sitecore/content/Target/Child1");
var options = new GetItemOptionsParams();
//Act
var result =
mapper.MapToProperty(new SitecoreDataMappingContext(null, source, service, options)) as StubMapped;
//Assert
Assert.AreEqual(result1.ID.Guid, result.Id);
}
}
[Test]
public void MapToProperty_RelativeQueryWithQueryContext_ReturnsResults()
{
//Assign
using (Db database = new Db
{
new Sitecore.FakeDb.DbItem("Target")
{
new Sitecore.FakeDb.DbItem("Child1"),
new Sitecore.FakeDb.DbItem("Child2")
}
})
{
var config = new SitecoreQueryConfiguration();
config.PropertyInfo = typeof(StubClass).GetProperty("StubMappeds");
config.Query = "../Target/*";
config.IsRelative = true;
var context = Context.Create(Utilities.CreateStandardResolver());
context.Load(new OnDemandLoader<SitecoreTypeConfiguration>(typeof(StubMapped)));
var mapper = new SitecoreQueryMapper(null);
mapper.Setup(new DataMapperResolverArgs(context, config));
var source = database.GetItem("/sitecore/content/Target");
var service = new SitecoreService(database.Database, context);
var result1 = database.GetItem("/sitecore/content/Target/Child1");
var result2 = database.GetItem("/sitecore/content/Target/Child2");
var options = new GetItemOptionsParams();
//Act
var results =
mapper.MapToProperty(new SitecoreDataMappingContext(null, source, service, options)) as
IEnumerable<StubMapped>;
//Assert
Assert.AreEqual(2, results.Count());
Assert.IsTrue(results.Any(x => x.Id == result1.ID.Guid));
Assert.IsTrue(results.Any(x => x.Id == result2.ID.Guid));
}
}
[Test]
public void MapToProperty_AbsoluteQueryWithQueryContext_ReturnsResults()
{
//Assign
using (Db database = new Db
{
new Sitecore.FakeDb.DbItem("Target")
{
new Sitecore.FakeDb.DbItem("Child1"),
new Sitecore.FakeDb.DbItem("Child2")
}
})
{
var config = new SitecoreQueryConfiguration();
config.PropertyInfo = typeof(StubClass).GetProperty("StubMappeds");
config.Query = "/sitecore/content/Target/*";
config.IsRelative = false;
var context = Context.Create(Utilities.CreateStandardResolver());
context.Load(new OnDemandLoader<SitecoreTypeConfiguration>(typeof(StubMapped)));
var mapper = new SitecoreQueryMapper(null);
mapper.Setup(new DataMapperResolverArgs(context, config));
var source = database.GetItem("/sitecore/content/Target");
var service = new SitecoreService(database.Database, context);
var result1 = database.GetItem("/sitecore/content/Target/Child1");
var result2 = database.GetItem("/sitecore/content/Target/Child2");
var options = new GetItemOptionsParams();
//Act
var results =
mapper.MapToProperty(new SitecoreDataMappingContext(null, source, service, options)) as
IEnumerable<StubMapped>;
//Assert
Assert.AreEqual(2, results.Count());
Assert.IsTrue(results.Any(x => x.Id == result1.ID.Guid));
Assert.IsTrue(results.Any(x => x.Id == result2.ID.Guid));
}
}
[Test]
[Category("LocalOnly")]
public void MapToProperty_AbsoluteQueryWithParameter_ReturnsResults()
{
//Assign
using (Db database = new Db
{
new Sitecore.FakeDb.DbItem("Target")
{
},
new Sitecore.FakeDb.DbItem("Results")
{
new Sitecore.FakeDb.DbItem("Child1"),
new Sitecore.FakeDb.DbItem("Child2")
}
})
{
var config = new SitecoreQueryConfiguration();
config.PropertyInfo = typeof(StubClass).GetProperty("StubMappeds");
config.Query = "{path}/../Results/*";
config.IsRelative = false;
var context = Context.Create(Utilities.CreateStandardResolver());
context.Load(new OnDemandLoader<SitecoreTypeConfiguration>(typeof(StubMapped)));
var mapper = new SitecoreQueryMapper(new[] { new ItemPathParameter() });
mapper.Setup(new DataMapperResolverArgs(context, config));
var source = database.GetItem("/sitecore/content/Target");
var service = new SitecoreService(database.Database, context);
var result1 = database.GetItem("/sitecore/content/Results/Child1");
var result2 = database.GetItem("/sitecore/content/Results/Child2");
var options = new GetItemOptionsParams();
//Act
var results =
mapper.MapToProperty(new SitecoreDataMappingContext(null, source, service, options)) as
IEnumerable<StubMapped>;
//Assert
Assert.AreEqual(2, results.Count());
Assert.IsTrue(results.Any(x => x.Id == result1.ID.Guid));
Assert.IsTrue(results.Any(x => x.Id == result2.ID.Guid));
}
}
#endregion
#region Stubs
[SitecoreType]
public class StubMapped
{
[SitecoreId]
public virtual Guid Id { get; set; }
[SitecoreField]
public virtual string Title { get; set; }
}
public class StubNotMapped { }
public class StubClass
{
public IEnumerable<StubMapped> StubMappeds { get; set; }
public IEnumerable<StubNotMapped> StubNotMappeds { get; set; }
public StubMapped StubMapped { get; set; }
public StubNotMapped StubNotMapped { get; set; }
}
#endregion
}
}
| |
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Collections;
using System.IO;
using log4net.Core;
using log4net.Layout.Pattern;
using log4net.Util;
using log4net.Util.PatternStringConverters;
using AppDomainPatternConverter=log4net.Layout.Pattern.AppDomainPatternConverter;
using DatePatternConverter=log4net.Layout.Pattern.DatePatternConverter;
using IdentityPatternConverter=log4net.Layout.Pattern.IdentityPatternConverter;
using PropertyPatternConverter=log4net.Layout.Pattern.PropertyPatternConverter;
using UserNamePatternConverter=log4net.Layout.Pattern.UserNamePatternConverter;
using UtcDatePatternConverter=log4net.Layout.Pattern.UtcDatePatternConverter;
namespace log4net.Layout
{
/// <summary>
/// A flexible layout configurable with pattern string.
/// </summary>
/// <remarks>
/// <para>
/// The goal of this class is to <see cref="PatternLayout.Format(TextWriter,LoggingEvent)"/> a
/// <see cref="LoggingEvent"/> as a string. The results
/// depend on the <i>conversion pattern</i>.
/// </para>
/// <para>
/// The conversion pattern is closely related to the conversion
/// pattern of the printf function in C. A conversion pattern is
/// composed of literal text and format control expressions called
/// <i>conversion specifiers</i>.
/// </para>
/// <para>
/// <i>You are free to insert any literal text within the conversion
/// pattern.</i>
/// </para>
/// <para>
/// Each conversion specifier starts with a percent sign (%) and is
/// followed by optional <i>format modifiers</i> and a <i>conversion
/// pattern name</i>. The conversion pattern name specifies the type of
/// data, e.g. logger, level, date, thread name. The format
/// modifiers control such things as field width, padding, left and
/// right justification. The following is a simple example.
/// </para>
/// <para>
/// Let the conversion pattern be <b>"%-5level [%thread]: %message%newline"</b> and assume
/// that the log4net environment was set to use a PatternLayout. Then the
/// statements
/// </para>
/// <code lang="C#">
/// ILog log = LogManager.GetLogger(typeof(TestApp));
/// log.Debug("Message 1");
/// log.Warn("Message 2");
/// </code>
/// <para>would yield the output</para>
/// <code>
/// DEBUG [main]: Message 1
/// WARN [main]: Message 2
/// </code>
/// <para>
/// Note that there is no explicit separator between text and
/// conversion specifiers. The pattern parser knows when it has reached
/// the end of a conversion specifier when it reads a conversion
/// character. In the example above the conversion specifier
/// <b>%-5level</b> means the level of the logging event should be left
/// justified to a width of five characters.
/// </para>
/// <para>
/// The recognized conversion pattern names are:
/// </para>
/// <list type="table">
/// <listheader>
/// <term>Conversion Pattern Name</term>
/// <description>Effect</description>
/// </listheader>
/// <item>
/// <term>a</term>
/// <description>Equivalent to <b>appdomain</b></description>
/// </item>
/// <item>
/// <term>appdomain</term>
/// <description>
/// Used to output the friendly name of the AppDomain where the
/// logging event was generated.
/// </description>
/// </item>
/// <item>
/// <term>aspnet-cache</term>
/// <description>
/// <para>
/// Used to output all cache items in the case of <b>%aspnet-cache</b> or just one named item if used as <b>%aspnet-cache{key}</b>
/// </para>
/// <para>
/// This pattern is not available for Compact Framework or Client Profile assemblies.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>aspnet-context</term>
/// <description>
/// <para>
/// Used to output all context items in the case of <b>%aspnet-context</b> or just one named item if used as <b>%aspnet-context{key}</b>
/// </para>
/// <para>
/// This pattern is not available for Compact Framework or Client Profile assemblies.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>aspnet-request</term>
/// <description>
/// <para>
/// Used to output all request parameters in the case of <b>%aspnet-request</b> or just one named param if used as <b>%aspnet-request{key}</b>
/// </para>
/// <para>
/// This pattern is not available for Compact Framework or Client Profile assemblies.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>aspnet-session</term>
/// <description>
/// <para>
/// Used to output all session items in the case of <b>%aspnet-session</b> or just one named item if used as <b>%aspnet-session{key}</b>
/// </para>
/// <para>
/// This pattern is not available for Compact Framework or Client Profile assemblies.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>c</term>
/// <description>Equivalent to <b>logger</b></description>
/// </item>
/// <item>
/// <term>C</term>
/// <description>Equivalent to <b>type</b></description>
/// </item>
/// <item>
/// <term>class</term>
/// <description>Equivalent to <b>type</b></description>
/// </item>
/// <item>
/// <term>d</term>
/// <description>Equivalent to <b>date</b></description>
/// </item>
/// <item>
/// <term>date</term>
/// <description>
/// <para>
/// Used to output the date of the logging event in the local time zone.
/// To output the date in universal time use the <c>%utcdate</c> pattern.
/// The date conversion
/// specifier may be followed by a <i>date format specifier</i> enclosed
/// between braces. For example, <b>%date{HH:mm:ss,fff}</b> or
/// <b>%date{dd MMM yyyy HH:mm:ss,fff}</b>. If no date format specifier is
/// given then ISO8601 format is
/// assumed (<see cref="log4net.DateFormatter.Iso8601DateFormatter"/>).
/// </para>
/// <para>
/// The date format specifier admits the same syntax as the
/// time pattern string of the <see cref="DateTime.ToString(string)"/>.
/// </para>
/// <para>
/// For better results it is recommended to use the log4net date
/// formatters. These can be specified using one of the strings
/// "ABSOLUTE", "DATE" and "ISO8601" for specifying
/// <see cref="log4net.DateFormatter.AbsoluteTimeDateFormatter"/>,
/// <see cref="log4net.DateFormatter.DateTimeDateFormatter"/> and respectively
/// <see cref="log4net.DateFormatter.Iso8601DateFormatter"/>. For example,
/// <b>%date{ISO8601}</b> or <b>%date{ABSOLUTE}</b>.
/// </para>
/// <para>
/// These dedicated date formatters perform significantly
/// better than <see cref="DateTime.ToString(string)"/>.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>exception</term>
/// <description>
/// <para>
/// Used to output the exception passed in with the log message.
/// </para>
/// <para>
/// If an exception object is stored in the logging event
/// it will be rendered into the pattern output with a
/// trailing newline.
/// If there is no exception then nothing will be output
/// and no trailing newline will be appended.
/// It is typical to put a newline before the exception
/// and to have the exception as the last data in the pattern.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>F</term>
/// <description>Equivalent to <b>file</b></description>
/// </item>
/// <item>
/// <term>file</term>
/// <description>
/// <para>
/// Used to output the file name where the logging request was
/// issued.
/// </para>
/// <para>
/// <b>WARNING</b> Generating caller location information is
/// extremely slow. Its use should be avoided unless execution speed
/// is not an issue.
/// </para>
/// <para>
/// See the note below on the availability of caller location information.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>identity</term>
/// <description>
/// <para>
/// Used to output the user name for the currently active user
/// (Principal.Identity.Name).
/// </para>
/// <para>
/// <b>WARNING</b> Generating caller information is
/// extremely slow. Its use should be avoided unless execution speed
/// is not an issue.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>l</term>
/// <description>Equivalent to <b>location</b></description>
/// </item>
/// <item>
/// <term>L</term>
/// <description>Equivalent to <b>line</b></description>
/// </item>
/// <item>
/// <term>location</term>
/// <description>
/// <para>
/// Used to output location information of the caller which generated
/// the logging event.
/// </para>
/// <para>
/// The location information depends on the CLI implementation but
/// usually consists of the fully qualified name of the calling
/// method followed by the callers source the file name and line
/// number between parentheses.
/// </para>
/// <para>
/// The location information can be very useful. However, its
/// generation is <b>extremely</b> slow. Its use should be avoided
/// unless execution speed is not an issue.
/// </para>
/// <para>
/// See the note below on the availability of caller location information.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>level</term>
/// <description>
/// <para>
/// Used to output the level of the logging event.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>line</term>
/// <description>
/// <para>
/// Used to output the line number from where the logging request
/// was issued.
/// </para>
/// <para>
/// <b>WARNING</b> Generating caller location information is
/// extremely slow. Its use should be avoided unless execution speed
/// is not an issue.
/// </para>
/// <para>
/// See the note below on the availability of caller location information.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>logger</term>
/// <description>
/// <para>
/// Used to output the logger of the logging event. The
/// logger conversion specifier can be optionally followed by
/// <i>precision specifier</i>, that is a decimal constant in
/// brackets.
/// </para>
/// <para>
/// If a precision specifier is given, then only the corresponding
/// number of right most components of the logger name will be
/// printed. By default the logger name is printed in full.
/// </para>
/// <para>
/// For example, for the logger name "a.b.c" the pattern
/// <b>%logger{2}</b> will output "b.c".
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>m</term>
/// <description>Equivalent to <b>message</b></description>
/// </item>
/// <item>
/// <term>M</term>
/// <description>Equivalent to <b>method</b></description>
/// </item>
/// <item>
/// <term>message</term>
/// <description>
/// <para>
/// Used to output the application supplied message associated with
/// the logging event.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>mdc</term>
/// <description>
/// <para>
/// The MDC (old name for the ThreadContext.Properties) is now part of the
/// combined event properties. This pattern is supported for compatibility
/// but is equivalent to <b>property</b>.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>method</term>
/// <description>
/// <para>
/// Used to output the method name where the logging request was
/// issued.
/// </para>
/// <para>
/// <b>WARNING</b> Generating caller location information is
/// extremely slow. Its use should be avoided unless execution speed
/// is not an issue.
/// </para>
/// <para>
/// See the note below on the availability of caller location information.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>n</term>
/// <description>Equivalent to <b>newline</b></description>
/// </item>
/// <item>
/// <term>newline</term>
/// <description>
/// <para>
/// Outputs the platform dependent line separator character or
/// characters.
/// </para>
/// <para>
/// This conversion pattern offers the same performance as using
/// non-portable line separator strings such as "\n", or "\r\n".
/// Thus, it is the preferred way of specifying a line separator.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>ndc</term>
/// <description>
/// <para>
/// Used to output the NDC (nested diagnostic context) associated
/// with the thread that generated the logging event.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>p</term>
/// <description>Equivalent to <b>level</b></description>
/// </item>
/// <item>
/// <term>P</term>
/// <description>Equivalent to <b>property</b></description>
/// </item>
/// <item>
/// <term>properties</term>
/// <description>Equivalent to <b>property</b></description>
/// </item>
/// <item>
/// <term>property</term>
/// <description>
/// <para>
/// Used to output the an event specific property. The key to
/// lookup must be specified within braces and directly following the
/// pattern specifier, e.g. <b>%property{user}</b> would include the value
/// from the property that is keyed by the string 'user'. Each property value
/// that is to be included in the log must be specified separately.
/// Properties are added to events by loggers or appenders. By default
/// the <c>log4net:HostName</c> property is set to the name of machine on
/// which the event was originally logged.
/// </para>
/// <para>
/// If no key is specified, e.g. <b>%property</b> then all the keys and their
/// values are printed in a comma separated list.
/// </para>
/// <para>
/// The properties of an event are combined from a number of different
/// contexts. These are listed below in the order in which they are searched.
/// </para>
/// <list type="definition">
/// <item>
/// <term>the event properties</term>
/// <description>
/// The event has <see cref="LoggingEvent.Properties"/> that can be set. These
/// properties are specific to this event only.
/// </description>
/// </item>
/// <item>
/// <term>the thread properties</term>
/// <description>
/// The <see cref="ThreadContext.Properties"/> that are set on the current
/// thread. These properties are shared by all events logged on this thread.
/// </description>
/// </item>
/// <item>
/// <term>the global properties</term>
/// <description>
/// The <see cref="GlobalContext.Properties"/> that are set globally. These
/// properties are shared by all the threads in the AppDomain.
/// </description>
/// </item>
/// </list>
///
/// </description>
/// </item>
/// <item>
/// <term>r</term>
/// <description>Equivalent to <b>timestamp</b></description>
/// </item>
/// <item>
/// <term>stacktrace</term>
/// <description>
/// <para>
/// Used to output the stack trace of the logging event
/// The stack trace level specifier may be enclosed
/// between braces. For example, <b>%stacktrace{level}</b>.
/// If no stack trace level specifier is given then 1 is assumed
/// </para>
/// <para>
/// Output uses the format:
/// type3.MethodCall3 > type2.MethodCall2 > type1.MethodCall1
/// </para>
/// <para>
/// This pattern is not available for Compact Framework assemblies.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>stacktracedetail</term>
/// <description>
/// <para>
/// Used to output the stack trace of the logging event
/// The stack trace level specifier may be enclosed
/// between braces. For example, <b>%stacktracedetail{level}</b>.
/// If no stack trace level specifier is given then 1 is assumed
/// </para>
/// <para>
/// Output uses the format:
/// type3.MethodCall3(type param,...) > type2.MethodCall2(type param,...) > type1.MethodCall1(type param,...)
/// </para>
/// <para>
/// This pattern is not available for Compact Framework assemblies.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>t</term>
/// <description>Equivalent to <b>thread</b></description>
/// </item>
/// <item>
/// <term>timestamp</term>
/// <description>
/// <para>
/// Used to output the number of milliseconds elapsed since the start
/// of the application until the creation of the logging event.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>thread</term>
/// <description>
/// <para>
/// Used to output the name of the thread that generated the
/// logging event. Uses the thread number if no name is available.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>type</term>
/// <description>
/// <para>
/// Used to output the fully qualified type name of the caller
/// issuing the logging request. This conversion specifier
/// can be optionally followed by <i>precision specifier</i>, that
/// is a decimal constant in brackets.
/// </para>
/// <para>
/// If a precision specifier is given, then only the corresponding
/// number of right most components of the class name will be
/// printed. By default the class name is output in fully qualified form.
/// </para>
/// <para>
/// For example, for the class name "log4net.Layout.PatternLayout", the
/// pattern <b>%type{1}</b> will output "PatternLayout".
/// </para>
/// <para>
/// <b>WARNING</b> Generating the caller class information is
/// slow. Thus, its use should be avoided unless execution speed is
/// not an issue.
/// </para>
/// <para>
/// See the note below on the availability of caller location information.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>u</term>
/// <description>Equivalent to <b>identity</b></description>
/// </item>
/// <item>
/// <term>username</term>
/// <description>
/// <para>
/// Used to output the WindowsIdentity for the currently
/// active user.
/// </para>
/// <para>
/// <b>WARNING</b> Generating caller WindowsIdentity information is
/// extremely slow. Its use should be avoided unless execution speed
/// is not an issue.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>utcdate</term>
/// <description>
/// <para>
/// Used to output the date of the logging event in universal time.
/// The date conversion
/// specifier may be followed by a <i>date format specifier</i> enclosed
/// between braces. For example, <b>%utcdate{HH:mm:ss,fff}</b> or
/// <b>%utcdate{dd MMM yyyy HH:mm:ss,fff}</b>. If no date format specifier is
/// given then ISO8601 format is
/// assumed (<see cref="log4net.DateFormatter.Iso8601DateFormatter"/>).
/// </para>
/// <para>
/// The date format specifier admits the same syntax as the
/// time pattern string of the <see cref="DateTime.ToString(string)"/>.
/// </para>
/// <para>
/// For better results it is recommended to use the log4net date
/// formatters. These can be specified using one of the strings
/// "ABSOLUTE", "DATE" and "ISO8601" for specifying
/// <see cref="log4net.DateFormatter.AbsoluteTimeDateFormatter"/>,
/// <see cref="log4net.DateFormatter.DateTimeDateFormatter"/> and respectively
/// <see cref="log4net.DateFormatter.Iso8601DateFormatter"/>. For example,
/// <b>%utcdate{ISO8601}</b> or <b>%utcdate{ABSOLUTE}</b>.
/// </para>
/// <para>
/// These dedicated date formatters perform significantly
/// better than <see cref="DateTime.ToString(string)"/>.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>w</term>
/// <description>Equivalent to <b>username</b></description>
/// </item>
/// <item>
/// <term>x</term>
/// <description>Equivalent to <b>ndc</b></description>
/// </item>
/// <item>
/// <term>X</term>
/// <description>Equivalent to <b>mdc</b></description>
/// </item>
/// <item>
/// <term>%</term>
/// <description>
/// <para>
/// The sequence %% outputs a single percent sign.
/// </para>
/// </description>
/// </item>
/// </list>
/// <para>
/// The single letter patterns are deprecated in favor of the
/// longer more descriptive pattern names.
/// </para>
/// <para>
/// By default the relevant information is output as is. However,
/// with the aid of format modifiers it is possible to change the
/// minimum field width, the maximum field width and justification.
/// </para>
/// <para>
/// The optional format modifier is placed between the percent sign
/// and the conversion pattern name.
/// </para>
/// <para>
/// The first optional format modifier is the <i>left justification
/// flag</i> which is just the minus (-) character. Then comes the
/// optional <i>minimum field width</i> modifier. This is a decimal
/// constant that represents the minimum number of characters to
/// output. If the data item requires fewer characters, it is padded on
/// either the left or the right until the minimum width is
/// reached. The default is to pad on the left (right justify) but you
/// can specify right padding with the left justification flag. The
/// padding character is space. If the data item is larger than the
/// minimum field width, the field is expanded to accommodate the
/// data. The value is never truncated.
/// </para>
/// <para>
/// This behavior can be changed using the <i>maximum field
/// width</i> modifier which is designated by a period followed by a
/// decimal constant. If the data item is longer than the maximum
/// field, then the extra characters are removed from the
/// <i>beginning</i> of the data item and not from the end. For
/// example, it the maximum field width is eight and the data item is
/// ten characters long, then the first two characters of the data item
/// are dropped. This behavior deviates from the printf function in C
/// where truncation is done from the end.
/// </para>
/// <para>
/// Below are various format modifier examples for the logger
/// conversion specifier.
/// </para>
/// <div class="tablediv">
/// <table class="dtTABLE" cellspacing="0">
/// <tr>
/// <th>Format modifier</th>
/// <th>left justify</th>
/// <th>minimum width</th>
/// <th>maximum width</th>
/// <th>comment</th>
/// </tr>
/// <tr>
/// <td align="center">%20logger</td>
/// <td align="center">false</td>
/// <td align="center">20</td>
/// <td align="center">none</td>
/// <td>
/// <para>
/// Left pad with spaces if the logger name is less than 20
/// characters long.
/// </para>
/// </td>
/// </tr>
/// <tr>
/// <td align="center">%-20logger</td>
/// <td align="center">true</td>
/// <td align="center">20</td>
/// <td align="center">none</td>
/// <td>
/// <para>
/// Right pad with spaces if the logger
/// name is less than 20 characters long.
/// </para>
/// </td>
/// </tr>
/// <tr>
/// <td align="center">%.30logger</td>
/// <td align="center">NA</td>
/// <td align="center">none</td>
/// <td align="center">30</td>
/// <td>
/// <para>
/// Truncate from the beginning if the logger
/// name is longer than 30 characters.
/// </para>
/// </td>
/// </tr>
/// <tr>
/// <td align="center"><nobr>%20.30logger</nobr></td>
/// <td align="center">false</td>
/// <td align="center">20</td>
/// <td align="center">30</td>
/// <td>
/// <para>
/// Left pad with spaces if the logger name is shorter than 20
/// characters. However, if logger name is longer than 30 characters,
/// then truncate from the beginning.
/// </para>
/// </td>
/// </tr>
/// <tr>
/// <td align="center">%-20.30logger</td>
/// <td align="center">true</td>
/// <td align="center">20</td>
/// <td align="center">30</td>
/// <td>
/// <para>
/// Right pad with spaces if the logger name is shorter than 20
/// characters. However, if logger name is longer than 30 characters,
/// then truncate from the beginning.
/// </para>
/// </td>
/// </tr>
/// </table>
/// </div>
/// <para>
/// <b>Note about caller location information.</b><br />
/// The following patterns <c>%type %file %line %method %location %class %C %F %L %l %M</c>
/// all generate caller location information.
/// Location information uses the <c>System.Diagnostics.StackTrace</c> class to generate
/// a call stack. The caller's information is then extracted from this stack.
/// </para>
/// <note type="caution">
/// <para>
/// The <c>System.Diagnostics.StackTrace</c> class is not supported on the
/// .NET Compact Framework 1.0 therefore caller location information is not
/// available on that framework.
/// </para>
/// </note>
/// <note type="caution">
/// <para>
/// The <c>System.Diagnostics.StackTrace</c> class has this to say about Release builds:
/// </para>
/// <para>
/// "StackTrace information will be most informative with Debug build configurations.
/// By default, Debug builds include debug symbols, while Release builds do not. The
/// debug symbols contain most of the file, method name, line number, and column
/// information used in constructing StackFrame and StackTrace objects. StackTrace
/// might not report as many method calls as expected, due to code transformations
/// that occur during optimization."
/// </para>
/// <para>
/// This means that in a Release build the caller information may be incomplete or may
/// not exist at all! Therefore caller location information cannot be relied upon in a Release build.
/// </para>
/// </note>
/// <para>
/// Additional pattern converters may be registered with a specific <see cref="PatternLayout"/>
/// instance using the <see cref="AddConverter(string, Type)"/> method.
/// </para>
/// </remarks>
/// <example>
/// This is a more detailed pattern.
/// <code><b>%timestamp [%thread] %level %logger %ndc - %message%newline</b></code>
/// </example>
/// <example>
/// A similar pattern except that the relative time is
/// right padded if less than 6 digits, thread name is right padded if
/// less than 15 characters and truncated if longer and the logger
/// name is left padded if shorter than 30 characters and truncated if
/// longer.
/// <code><b>%-6timestamp [%15.15thread] %-5level %30.30logger %ndc - %message%newline</b></code>
/// </example>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
/// <author>Douglas de la Torre</author>
/// <author>Daniel Cazzulino</author>
public class PatternLayout : LayoutSkeleton
{
#region Constants
/// <summary>
/// Default pattern string for log output.
/// </summary>
/// <remarks>
/// <para>
/// Default pattern string for log output.
/// Currently set to the string <b>"%message%newline"</b>
/// which just prints the application supplied message.
/// </para>
/// </remarks>
public const string DefaultConversionPattern ="%message%newline";
/// <summary>
/// A detailed conversion pattern
/// </summary>
/// <remarks>
/// <para>
/// A conversion pattern which includes Time, Thread, Logger, and Nested Context.
/// Current value is <b>%timestamp [%thread] %level %logger %ndc - %message%newline</b>.
/// </para>
/// </remarks>
public const string DetailConversionPattern = "%timestamp [%thread] %level %logger %ndc - %message%newline";
#endregion
#region Static Fields
/// <summary>
/// Internal map of converter identifiers to converter types.
/// </summary>
/// <remarks>
/// <para>
/// This static map is overridden by the m_converterRegistry instance map
/// </para>
/// </remarks>
private static Hashtable s_globalRulesRegistry;
#endregion Static Fields
#region Member Variables
/// <summary>
/// the pattern
/// </summary>
private string m_pattern;
/// <summary>
/// the head of the pattern converter chain
/// </summary>
private PatternConverter m_head;
/// <summary>
/// patterns defined on this PatternLayout only
/// </summary>
private Hashtable m_instanceRulesRegistry = new Hashtable();
#endregion
#region Static Constructor
/// <summary>
/// Initialize the global registry
/// </summary>
/// <remarks>
/// <para>
/// Defines the builtin global rules.
/// </para>
/// </remarks>
static PatternLayout()
{
s_globalRulesRegistry = new Hashtable(45);
s_globalRulesRegistry.Add("literal", typeof(LiteralPatternConverter));
s_globalRulesRegistry.Add("newline", typeof(NewLinePatternConverter));
s_globalRulesRegistry.Add("n", typeof(NewLinePatternConverter));
// .NET Compact Framework 1.0 has no support for ASP.NET
// SSCLI 1.0 has no support for ASP.NET
#if !NETCF && !SSCLI && !CLIENT_PROFILE
s_globalRulesRegistry.Add("aspnet-cache", typeof(AspNetCachePatternConverter));
s_globalRulesRegistry.Add("aspnet-context", typeof(AspNetContextPatternConverter));
s_globalRulesRegistry.Add("aspnet-request", typeof(AspNetRequestPatternConverter));
s_globalRulesRegistry.Add("aspnet-session", typeof(AspNetSessionPatternConverter));
#endif
s_globalRulesRegistry.Add("c", typeof(LoggerPatternConverter));
s_globalRulesRegistry.Add("logger", typeof(LoggerPatternConverter));
s_globalRulesRegistry.Add("C", typeof(TypeNamePatternConverter));
s_globalRulesRegistry.Add("class", typeof(TypeNamePatternConverter));
s_globalRulesRegistry.Add("type", typeof(TypeNamePatternConverter));
s_globalRulesRegistry.Add("d", typeof(DatePatternConverter));
s_globalRulesRegistry.Add("date", typeof(DatePatternConverter));
s_globalRulesRegistry.Add("exception", typeof(ExceptionPatternConverter));
s_globalRulesRegistry.Add("F", typeof(FileLocationPatternConverter));
s_globalRulesRegistry.Add("file", typeof(FileLocationPatternConverter));
s_globalRulesRegistry.Add("l", typeof(FullLocationPatternConverter));
s_globalRulesRegistry.Add("location", typeof(FullLocationPatternConverter));
s_globalRulesRegistry.Add("L", typeof(LineLocationPatternConverter));
s_globalRulesRegistry.Add("line", typeof(LineLocationPatternConverter));
s_globalRulesRegistry.Add("m", typeof(MessagePatternConverter));
s_globalRulesRegistry.Add("message", typeof(MessagePatternConverter));
s_globalRulesRegistry.Add("M", typeof(MethodLocationPatternConverter));
s_globalRulesRegistry.Add("method", typeof(MethodLocationPatternConverter));
s_globalRulesRegistry.Add("p", typeof(LevelPatternConverter));
s_globalRulesRegistry.Add("level", typeof(LevelPatternConverter));
s_globalRulesRegistry.Add("P", typeof(PropertyPatternConverter));
s_globalRulesRegistry.Add("property", typeof(PropertyPatternConverter));
s_globalRulesRegistry.Add("properties", typeof(PropertyPatternConverter));
s_globalRulesRegistry.Add("r", typeof(RelativeTimePatternConverter));
s_globalRulesRegistry.Add("timestamp", typeof(RelativeTimePatternConverter));
#if !NETCF
s_globalRulesRegistry.Add("stacktrace", typeof(StackTracePatternConverter));
s_globalRulesRegistry.Add("stacktracedetail", typeof(StackTraceDetailPatternConverter));
#endif
s_globalRulesRegistry.Add("t", typeof(ThreadPatternConverter));
s_globalRulesRegistry.Add("thread", typeof(ThreadPatternConverter));
// For backwards compatibility the NDC patterns
s_globalRulesRegistry.Add("x", typeof(NdcPatternConverter));
s_globalRulesRegistry.Add("ndc", typeof(NdcPatternConverter));
// For backwards compatibility the MDC patterns just do a property lookup
s_globalRulesRegistry.Add("X", typeof(PropertyPatternConverter));
s_globalRulesRegistry.Add("mdc", typeof(PropertyPatternConverter));
s_globalRulesRegistry.Add("a", typeof(AppDomainPatternConverter));
s_globalRulesRegistry.Add("appdomain", typeof(AppDomainPatternConverter));
s_globalRulesRegistry.Add("u", typeof(IdentityPatternConverter));
s_globalRulesRegistry.Add("identity", typeof(IdentityPatternConverter));
s_globalRulesRegistry.Add("utcdate", typeof(UtcDatePatternConverter));
s_globalRulesRegistry.Add("utcDate", typeof(UtcDatePatternConverter));
s_globalRulesRegistry.Add("UtcDate", typeof(UtcDatePatternConverter));
s_globalRulesRegistry.Add("w", typeof(UserNamePatternConverter));
s_globalRulesRegistry.Add("username", typeof(UserNamePatternConverter));
}
#endregion Static Constructor
#region Constructors
/// <summary>
/// Constructs a PatternLayout using the DefaultConversionPattern
/// </summary>
/// <remarks>
/// <para>
/// The default pattern just produces the application supplied message.
/// </para>
/// <para>
/// Note to Inheritors: This constructor calls the virtual method
/// <see cref="CreatePatternParser"/>. If you override this method be
/// aware that it will be called before your is called constructor.
/// </para>
/// <para>
/// As per the <see cref="IOptionHandler"/> contract the <see cref="ActivateOptions"/>
/// method must be called after the properties on this object have been
/// configured.
/// </para>
/// </remarks>
public PatternLayout() : this(DefaultConversionPattern)
{
}
/// <summary>
/// Constructs a PatternLayout using the supplied conversion pattern
/// </summary>
/// <param name="pattern">the pattern to use</param>
/// <remarks>
/// <para>
/// Note to Inheritors: This constructor calls the virtual method
/// <see cref="CreatePatternParser"/>. If you override this method be
/// aware that it will be called before your is called constructor.
/// </para>
/// <para>
/// When using this constructor the <see cref="ActivateOptions"/> method
/// need not be called. This may not be the case when using a subclass.
/// </para>
/// </remarks>
public PatternLayout(string pattern)
{
// By default we do not process the exception
IgnoresException = true;
m_pattern = pattern;
if (m_pattern == null)
{
m_pattern = DefaultConversionPattern;
}
ActivateOptions();
}
#endregion
/// <summary>
/// The pattern formatting string
/// </summary>
/// <remarks>
/// <para>
/// The <b>ConversionPattern</b> option. This is the string which
/// controls formatting and consists of a mix of literal content and
/// conversion specifiers.
/// </para>
/// </remarks>
public string ConversionPattern
{
get { return m_pattern; }
set { m_pattern = value; }
}
/// <summary>
/// Create the pattern parser instance
/// </summary>
/// <param name="pattern">the pattern to parse</param>
/// <returns>The <see cref="PatternParser"/> that will format the event</returns>
/// <remarks>
/// <para>
/// Creates the <see cref="PatternParser"/> used to parse the conversion string. Sets the
/// global and instance rules on the <see cref="PatternParser"/>.
/// </para>
/// </remarks>
virtual protected PatternParser CreatePatternParser(string pattern)
{
PatternParser patternParser = new PatternParser(pattern);
// Add all the builtin patterns
foreach(DictionaryEntry entry in s_globalRulesRegistry)
{
ConverterInfo converterInfo = new ConverterInfo();
converterInfo.Name = (string)entry.Key;
converterInfo.Type = (Type)entry.Value;
patternParser.PatternConverters[entry.Key] = converterInfo;
}
// Add the instance patterns
foreach(DictionaryEntry entry in m_instanceRulesRegistry)
{
patternParser.PatternConverters[entry.Key] = entry.Value;
}
return patternParser;
}
#region Implementation of IOptionHandler
/// <summary>
/// Initialize layout options
/// </summary>
/// <remarks>
/// <para>
/// This is part of the <see cref="IOptionHandler"/> delayed object
/// activation scheme. The <see cref="ActivateOptions"/> method must
/// be called on this object after the configuration properties have
/// been set. Until <see cref="ActivateOptions"/> is called this
/// object is in an undefined state and must not be used.
/// </para>
/// <para>
/// If any of the configuration properties are modified then
/// <see cref="ActivateOptions"/> must be called again.
/// </para>
/// </remarks>
override public void ActivateOptions()
{
m_head = CreatePatternParser(m_pattern).Parse();
PatternConverter curConverter = m_head;
while(curConverter != null)
{
PatternLayoutConverter layoutConverter = curConverter as PatternLayoutConverter;
if (layoutConverter != null)
{
if (!layoutConverter.IgnoresException)
{
// Found converter that handles the exception
this.IgnoresException = false;
break;
}
}
curConverter = curConverter.Next;
}
}
#endregion
#region Override implementation of LayoutSkeleton
/// <summary>
/// Produces a formatted string as specified by the conversion pattern.
/// </summary>
/// <param name="loggingEvent">the event being logged</param>
/// <param name="writer">The TextWriter to write the formatted event to</param>
/// <remarks>
/// <para>
/// Parse the <see cref="LoggingEvent"/> using the patter format
/// specified in the <see cref="ConversionPattern"/> property.
/// </para>
/// </remarks>
override public void Format(TextWriter writer, LoggingEvent loggingEvent)
{
if (writer == null)
{
throw new ArgumentNullException("writer");
}
if (loggingEvent == null)
{
throw new ArgumentNullException("loggingEvent");
}
PatternConverter c = m_head;
// loop through the chain of pattern converters
while(c != null)
{
c.Format(writer, loggingEvent);
c = c.Next;
}
}
#endregion
/// <summary>
/// Add a converter to this PatternLayout
/// </summary>
/// <param name="converterInfo">the converter info</param>
/// <remarks>
/// <para>
/// This version of the method is used by the configurator.
/// Programmatic users should use the alternative <see cref="AddConverter(string,Type)"/> method.
/// </para>
/// </remarks>
public void AddConverter(ConverterInfo converterInfo)
{
if (converterInfo == null) throw new ArgumentNullException("converterInfo");
if (!typeof(PatternConverter).IsAssignableFrom(converterInfo.Type))
{
throw new ArgumentException("The converter type specified [" + converterInfo.Type + "] must be a subclass of log4net.Util.PatternConverter", "converterInfo");
}
m_instanceRulesRegistry[converterInfo.Name] = converterInfo;
}
/// <summary>
/// Add a converter to this PatternLayout
/// </summary>
/// <param name="name">the name of the conversion pattern for this converter</param>
/// <param name="type">the type of the converter</param>
/// <remarks>
/// <para>
/// Add a named pattern converter to this instance. This
/// converter will be used in the formatting of the event.
/// This method must be called before <see cref="ActivateOptions"/>.
/// </para>
/// <para>
/// The <paramref name="type"/> specified must extend the
/// <see cref="PatternConverter"/> type.
/// </para>
/// </remarks>
public void AddConverter(string name, Type type)
{
if (name == null) throw new ArgumentNullException("name");
if (type == null) throw new ArgumentNullException("type");
ConverterInfo converterInfo = new ConverterInfo();
converterInfo.Name = name;
converterInfo.Type = type;
AddConverter(converterInfo);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public static class TernaryTests
{
#region Test methods
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryBoolTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
bool[] array2 = new bool[] { true, false };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyBool(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryByteTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
byte[] array2 = new byte[] { 0, 1, byte.MaxValue };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyByte(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryCustomTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
C[] array2 = new C[] { null, new C(), new D(), new D(0), new D(5) };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyCustom(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryCharTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
char[] array2 = new char[] { '\0', '\b', 'A', '\uffff' };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyChar(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryCustom2Test(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
D[] array2 = new D[] { null, new D(), new D(0), new D(5) };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyCustom2(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryDecimalTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
decimal[] array2 = new decimal[] { decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyDecimal(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryDelegateTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
Delegate[] array2 = new Delegate[] { null, (Func<object>)delegate () { return null; }, (Func<int, int>)delegate (int i) { return i + 1; }, (Action<object>)delegate { } };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyDelegate(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryDoubleTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
double[] array2 = new double[] { 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyDouble(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryEnumTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
E[] array2 = new E[] { (E)0, E.A, E.B, (E)int.MaxValue, (E)int.MinValue };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyEnum(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryEnumLongTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
El[] array2 = new El[] { (El)0, El.A, El.B, (El)long.MaxValue, (El)long.MinValue };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyEnumLong(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryFloatTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
float[] array2 = new float[] { 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyFloat(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryFuncOfObjectTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
Func<object>[] array2 = new Func<object>[] { null, (Func<object>)delegate () { return null; } };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyFuncOfObject(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryInterfaceTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
I[] array2 = new I[] { null, new C(), new D(), new D(0), new D(5) };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyInterface(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryIEquatableOfCustomTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
IEquatable<C>[] array2 = new IEquatable<C>[] { null, new C(), new D(), new D(0), new D(5) };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyIEquatableOfCustom(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryIEquatableOfCustom2Test(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
IEquatable<D>[] array2 = new IEquatable<D>[] { null, new D(), new D(0), new D(5) };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyIEquatableOfCustom2(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryIntTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
int[] array2 = new int[] { 0, 1, -1, int.MinValue, int.MaxValue };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyInt(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryLongTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
long[] array2 = new long[] { 0, 1, -1, long.MinValue, long.MaxValue };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyLong(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryObjectTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
object[] array2 = new object[] { null, new object(), new C(), new D(3) };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyObject(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryStructTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
S[] array2 = new S[] { default(S), new S() };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyStruct(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernarySByteTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
sbyte[] array2 = new sbyte[] { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifySByte(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryStructWithStringTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
Sc[] array2 = new Sc[] { default(Sc), new Sc(), new Sc(null) };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyStructWithString(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryStructWithStringAndFieldTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
Scs[] array2 = new Scs[] { default(Scs), new Scs(), new Scs(null, new S()) };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyStructWithStringAndField(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryShortTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
short[] array2 = new short[] { 0, 1, -1, short.MinValue, short.MaxValue };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyShort(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryStructWithTwoValuesTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
Sp[] array2 = new Sp[] { default(Sp), new Sp(), new Sp(5, 5.0) };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyStructWithTwoValues(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryStructWithValueTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
Ss[] array2 = new Ss[] { default(Ss), new Ss(), new Ss(new S()) };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyStructWithValue(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryStringTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
string[] array2 = new string[] { null, "", "a", "foo" };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyString(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryUIntTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
uint[] array2 = new uint[] { 0, 1, uint.MaxValue };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyUInt(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryULongTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
ulong[] array2 = new ulong[] { 0, 1, ulong.MaxValue };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyULong(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryUShortTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
ushort[] array2 = new ushort[] { 0, 1, ushort.MaxValue };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyUShort(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryGenericWithCustomTest(bool useInterpreter)
{
CheckTernaryGenericHelper<C>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryGenericWithEnumTest(bool useInterpreter)
{
CheckTernaryGenericHelper<E>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryGenericWithObjectTest(bool useInterpreter)
{
CheckTernaryGenericHelper<object>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryGenericWithStructTest(bool useInterpreter)
{
CheckTernaryGenericHelper<S>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryGenericWithStructWithStringAndFieldTest(bool useInterpreter)
{
CheckTernaryGenericHelper<Scs>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryGenericWithClassRestrictionWithCustomTest(bool useInterpreter)
{
CheckTernaryGenericWithClassRestrictionHelper<C>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryGenericWithClassRestrictionWithObjectTest(bool useInterpreter)
{
CheckTernaryGenericWithClassRestrictionHelper<object>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryGenericWithSubClassRestrictionWithCustomTest(bool useInterpreter)
{
CheckTernaryGenericWithSubClassRestrictionHelper<C>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryGenericWithClassAndNewRestrictionWithCustomTest(bool useInterpreter)
{
CheckTernaryGenericWithClassAndNewRestrictionHelper<C>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryGenericWithClassAndNewRestrictionWithObjectTest(bool useInterpreter)
{
CheckTernaryGenericWithClassAndNewRestrictionHelper<object>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryGenericWithSubClassAndNewRestrictionWithCustomTest(bool useInterpreter)
{
CheckTernaryGenericWithSubClassAndNewRestrictionHelper<C>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryGenericWithStructRestrictionWithEnumTest(bool useInterpreter)
{
CheckTernaryGenericWithStructRestrictionHelper<E>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryGenericWithStructRestrictionWithStructTest(bool useInterpreter)
{
CheckTernaryGenericWithStructRestrictionHelper<S>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryGenericWithStructRestrictionWithStructWithStringAndFieldTest(bool useInterpreter)
{
CheckTernaryGenericWithStructRestrictionHelper<Scs>(useInterpreter);
}
#endregion
#region Generic helpers
private static void CheckTernaryGenericHelper<T>(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
T[] array2 = new T[] { default(T) };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyGeneric<T>(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
private static void CheckTernaryGenericWithClassRestrictionHelper<Tc>(bool useInterpreter) where Tc : class
{
bool[] array1 = new bool[] { false, true };
Tc[] array2 = new Tc[] { null, default(Tc) };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyGenericWithClassRestriction<Tc>(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
private static void CheckTernaryGenericWithSubClassRestrictionHelper<TC>(bool useInterpreter) where TC : C
{
bool[] array1 = new bool[] { false, true };
TC[] array2 = new TC[] { null, default(TC), (TC)new C() };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyGenericWithSubClassRestriction<TC>(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
private static void CheckTernaryGenericWithClassAndNewRestrictionHelper<Tcn>(bool useInterpreter) where Tcn : class, new()
{
bool[] array1 = new bool[] { false, true };
Tcn[] array2 = new Tcn[] { null, default(Tcn), new Tcn() };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyGenericWithClassAndNewRestriction<Tcn>(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
private static void CheckTernaryGenericWithSubClassAndNewRestrictionHelper<TCn>(bool useInterpreter) where TCn : C, new()
{
bool[] array1 = new bool[] { false, true };
TCn[] array2 = new TCn[] { null, default(TCn), new TCn(), (TCn)new C() };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyGenericWithSubClassAndNewRestriction<TCn>(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
private static void CheckTernaryGenericWithStructRestrictionHelper<Ts>(bool useInterpreter) where Ts : struct
{
bool[] array1 = new bool[] { false, true };
Ts[] array2 = new Ts[] { default(Ts), new Ts() };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyGenericWithStructRestriction<Ts>(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
#endregion
#region Test verifiers
private static void VerifyBool(bool condition, bool a, bool b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(bool)),
Expression.Constant(b, typeof(bool))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(condition ? a : b, f());
}
private static void VerifyByte(bool condition, byte a, byte b, bool useInterpreter)
{
Expression<Func<byte>> e =
Expression.Lambda<Func<byte>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(byte)),
Expression.Constant(b, typeof(byte))),
Enumerable.Empty<ParameterExpression>());
Func<byte> f = e.Compile(useInterpreter);
Assert.Equal(condition ? a : b, f());
}
private static void VerifyCustom(bool condition, C a, C b, bool useInterpreter)
{
Expression<Func<C>> e =
Expression.Lambda<Func<C>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(C)),
Expression.Constant(b, typeof(C))),
Enumerable.Empty<ParameterExpression>());
Func<C> f = e.Compile(useInterpreter);
Assert.Same(condition ? a : b, f());
}
private static void VerifyChar(bool condition, char a, char b, bool useInterpreter)
{
Expression<Func<char>> e =
Expression.Lambda<Func<char>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(char)),
Expression.Constant(b, typeof(char))),
Enumerable.Empty<ParameterExpression>());
Func<char> f = e.Compile(useInterpreter);
Assert.Equal(condition ? a : b, f());
}
private static void VerifyCustom2(bool condition, D a, D b, bool useInterpreter)
{
Expression<Func<D>> e =
Expression.Lambda<Func<D>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(D)),
Expression.Constant(b, typeof(D))),
Enumerable.Empty<ParameterExpression>());
Func<D> f = e.Compile(useInterpreter);
Assert.Same(condition ? a : b, f());
}
private static void VerifyDecimal(bool condition, decimal a, decimal b, bool useInterpreter)
{
Expression<Func<decimal>> e =
Expression.Lambda<Func<decimal>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(decimal)),
Expression.Constant(b, typeof(decimal))),
Enumerable.Empty<ParameterExpression>());
Func<decimal> f = e.Compile(useInterpreter);
Assert.Equal(condition ? a : b, f());
}
private static void VerifyDelegate(bool condition, Delegate a, Delegate b, bool useInterpreter)
{
Expression<Func<Delegate>> e =
Expression.Lambda<Func<Delegate>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(Delegate)),
Expression.Constant(b, typeof(Delegate))),
Enumerable.Empty<ParameterExpression>());
Func<Delegate> f = e.Compile(useInterpreter);
Assert.Same(condition ? a : b, f());
}
private static void VerifyDouble(bool condition, double a, double b, bool useInterpreter)
{
Expression<Func<double>> e =
Expression.Lambda<Func<double>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(double)),
Expression.Constant(b, typeof(double))),
Enumerable.Empty<ParameterExpression>());
Func<double> f = e.Compile(useInterpreter);
Assert.Equal(condition ? a : b, f());
}
private static void VerifyEnum(bool condition, E a, E b, bool useInterpreter)
{
Expression<Func<E>> e =
Expression.Lambda<Func<E>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(E)),
Expression.Constant(b, typeof(E))),
Enumerable.Empty<ParameterExpression>());
Func<E> f = e.Compile(useInterpreter);
Assert.Equal(condition ? a : b, f());
}
private static void VerifyEnumLong(bool condition, El a, El b, bool useInterpreter)
{
Expression<Func<El>> e =
Expression.Lambda<Func<El>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(El)),
Expression.Constant(b, typeof(El))),
Enumerable.Empty<ParameterExpression>());
Func<El> f = e.Compile(useInterpreter);
Assert.Equal(condition ? a : b, f());
}
private static void VerifyFloat(bool condition, float a, float b, bool useInterpreter)
{
Expression<Func<float>> e =
Expression.Lambda<Func<float>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(float)),
Expression.Constant(b, typeof(float))),
Enumerable.Empty<ParameterExpression>());
Func<float> f = e.Compile(useInterpreter);
Assert.Equal(condition ? a : b, f());
}
private static void VerifyFuncOfObject(bool condition, Func<object> a, Func<object> b, bool useInterpreter)
{
Expression<Func<Func<object>>> e =
Expression.Lambda<Func<Func<object>>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(Func<object>)),
Expression.Constant(b, typeof(Func<object>))),
Enumerable.Empty<ParameterExpression>());
Func<Func<object>> f = e.Compile(useInterpreter);
Assert.Same(condition ? a : b, f());
}
private static void VerifyInterface(bool condition, I a, I b, bool useInterpreter)
{
Expression<Func<I>> e =
Expression.Lambda<Func<I>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(I)),
Expression.Constant(b, typeof(I))),
Enumerable.Empty<ParameterExpression>());
Func<I> f = e.Compile(useInterpreter);
Assert.Same(condition ? a : b, f());
}
private static void VerifyIEquatableOfCustom(bool condition, IEquatable<C> a, IEquatable<C> b, bool useInterpreter)
{
Expression<Func<IEquatable<C>>> e =
Expression.Lambda<Func<IEquatable<C>>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(IEquatable<C>)),
Expression.Constant(b, typeof(IEquatable<C>))),
Enumerable.Empty<ParameterExpression>());
Func<IEquatable<C>> f = e.Compile(useInterpreter);
Assert.Same(condition ? a : b, f());
}
private static void VerifyIEquatableOfCustom2(bool condition, IEquatable<D> a, IEquatable<D> b, bool useInterpreter)
{
Expression<Func<IEquatable<D>>> e =
Expression.Lambda<Func<IEquatable<D>>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(IEquatable<D>)),
Expression.Constant(b, typeof(IEquatable<D>))),
Enumerable.Empty<ParameterExpression>());
Func<IEquatable<D>> f = e.Compile(useInterpreter);
Assert.Same(condition ? a : b, f());
}
private static void VerifyInt(bool condition, int a, int b, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(int)),
Expression.Constant(b, typeof(int))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(condition ? a : b, f());
}
private static void VerifyLong(bool condition, long a, long b, bool useInterpreter)
{
Expression<Func<long>> e =
Expression.Lambda<Func<long>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(long)),
Expression.Constant(b, typeof(long))),
Enumerable.Empty<ParameterExpression>());
Func<long> f = e.Compile(useInterpreter);
Assert.Equal(condition ? a : b, f());
}
private static void VerifyObject(bool condition, object a, object b, bool useInterpreter)
{
Expression<Func<object>> e =
Expression.Lambda<Func<object>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(object)),
Expression.Constant(b, typeof(object))),
Enumerable.Empty<ParameterExpression>());
Func<object> f = e.Compile(useInterpreter);
Assert.Same(condition ? a : b, f());
}
private static void VerifyStruct(bool condition, S a, S b, bool useInterpreter)
{
Expression<Func<S>> e =
Expression.Lambda<Func<S>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(S)),
Expression.Constant(b, typeof(S))),
Enumerable.Empty<ParameterExpression>());
Func<S> f = e.Compile(useInterpreter);
Assert.Equal(condition ? a : b, f());
}
private static void VerifySByte(bool condition, sbyte a, sbyte b, bool useInterpreter)
{
Expression<Func<sbyte>> e =
Expression.Lambda<Func<sbyte>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(sbyte)),
Expression.Constant(b, typeof(sbyte))),
Enumerable.Empty<ParameterExpression>());
Func<sbyte> f = e.Compile(useInterpreter);
Assert.Equal(condition ? a : b, f());
}
private static void VerifyStructWithString(bool condition, Sc a, Sc b, bool useInterpreter)
{
Expression<Func<Sc>> e =
Expression.Lambda<Func<Sc>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(Sc)),
Expression.Constant(b, typeof(Sc))),
Enumerable.Empty<ParameterExpression>());
Func<Sc> f = e.Compile(useInterpreter);
Assert.Equal(condition ? a : b, f());
}
private static void VerifyStructWithStringAndField(bool condition, Scs a, Scs b, bool useInterpreter)
{
Expression<Func<Scs>> e =
Expression.Lambda<Func<Scs>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(Scs)),
Expression.Constant(b, typeof(Scs))),
Enumerable.Empty<ParameterExpression>());
Func<Scs> f = e.Compile(useInterpreter);
Assert.Equal(condition ? a : b, f());
}
private static void VerifyShort(bool condition, short a, short b, bool useInterpreter)
{
Expression<Func<short>> e =
Expression.Lambda<Func<short>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(short)),
Expression.Constant(b, typeof(short))),
Enumerable.Empty<ParameterExpression>());
Func<short> f = e.Compile(useInterpreter);
Assert.Equal(condition ? a : b, f());
}
private static void VerifyStructWithTwoValues(bool condition, Sp a, Sp b, bool useInterpreter)
{
Expression<Func<Sp>> e =
Expression.Lambda<Func<Sp>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(Sp)),
Expression.Constant(b, typeof(Sp))),
Enumerable.Empty<ParameterExpression>());
Func<Sp> f = e.Compile(useInterpreter);
Assert.Equal(condition ? a : b, f());
}
private static void VerifyStructWithValue(bool condition, Ss a, Ss b, bool useInterpreter)
{
Expression<Func<Ss>> e =
Expression.Lambda<Func<Ss>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(Ss)),
Expression.Constant(b, typeof(Ss))),
Enumerable.Empty<ParameterExpression>());
Func<Ss> f = e.Compile(useInterpreter);
Assert.Equal(condition ? a : b, f());
}
private static void VerifyString(bool condition, string a, string b, bool useInterpreter)
{
Expression<Func<string>> e =
Expression.Lambda<Func<string>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(string)),
Expression.Constant(b, typeof(string))),
Enumerable.Empty<ParameterExpression>());
Func<string> f = e.Compile(useInterpreter);
Assert.Same(condition ? a : b, f());
}
private static void VerifyUInt(bool condition, uint a, uint b, bool useInterpreter)
{
Expression<Func<uint>> e =
Expression.Lambda<Func<uint>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(uint)),
Expression.Constant(b, typeof(uint))),
Enumerable.Empty<ParameterExpression>());
Func<uint> f = e.Compile(useInterpreter);
Assert.Equal(condition ? a : b, f());
}
private static void VerifyULong(bool condition, ulong a, ulong b, bool useInterpreter)
{
Expression<Func<ulong>> e =
Expression.Lambda<Func<ulong>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(ulong)),
Expression.Constant(b, typeof(ulong))),
Enumerable.Empty<ParameterExpression>());
Func<ulong> f = e.Compile(useInterpreter);
Assert.Equal(condition ? a : b, f());
}
private static void VerifyUShort(bool condition, ushort a, ushort b, bool useInterpreter)
{
Expression<Func<ushort>> e =
Expression.Lambda<Func<ushort>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(ushort)),
Expression.Constant(b, typeof(ushort))),
Enumerable.Empty<ParameterExpression>());
Func<ushort> f = e.Compile(useInterpreter);
Assert.Equal(condition ? a : b, f());
}
private static void VerifyGeneric<T>(bool condition, T a, T b, bool useInterpreter)
{
Expression<Func<T>> e =
Expression.Lambda<Func<T>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(T)),
Expression.Constant(b, typeof(T))),
Enumerable.Empty<ParameterExpression>());
Func<T> f = e.Compile(useInterpreter);
if (default(T) == null)
Assert.Same(condition ? a : b, f());
else
Assert.Equal(condition ? a : b, f());
}
private static void VerifyGenericWithClassRestriction<Tc>(bool condition, Tc a, Tc b, bool useInterpreter)
{
Expression<Func<Tc>> e =
Expression.Lambda<Func<Tc>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(Tc)),
Expression.Constant(b, typeof(Tc))),
Enumerable.Empty<ParameterExpression>());
Func<Tc> f = e.Compile(useInterpreter);
Assert.Same(condition ? a : b, f());
}
private static void VerifyGenericWithSubClassRestriction<TC>(bool condition, TC a, TC b, bool useInterpreter)
{
Expression<Func<TC>> e =
Expression.Lambda<Func<TC>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(TC)),
Expression.Constant(b, typeof(TC))),
Enumerable.Empty<ParameterExpression>());
Func<TC> f = e.Compile(useInterpreter);
Assert.Same(condition ? a : b, f());
}
private static void VerifyGenericWithClassAndNewRestriction<Tcn>(bool condition, Tcn a, Tcn b, bool useInterpreter)
{
Expression<Func<Tcn>> e =
Expression.Lambda<Func<Tcn>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(Tcn)),
Expression.Constant(b, typeof(Tcn))),
Enumerable.Empty<ParameterExpression>());
Func<Tcn> f = e.Compile(useInterpreter);
Assert.Same(condition ? a : b, f());
}
private static void VerifyGenericWithSubClassAndNewRestriction<TCn>(bool condition, TCn a, TCn b, bool useInterpreter)
{
Expression<Func<TCn>> e =
Expression.Lambda<Func<TCn>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(TCn)),
Expression.Constant(b, typeof(TCn))),
Enumerable.Empty<ParameterExpression>());
Func<TCn> f = e.Compile(useInterpreter);
Assert.Same(condition ? a : b, f());
}
private static void VerifyGenericWithStructRestriction<Ts>(bool condition, Ts a, Ts b, bool useInterpreter)
{
Expression<Func<Ts>> e =
Expression.Lambda<Func<Ts>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(Ts)),
Expression.Constant(b, typeof(Ts))),
Enumerable.Empty<ParameterExpression>());
Func<Ts> f = e.Compile(useInterpreter);
Assert.Equal(condition ? a : b, f());
}
#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.Diagnostics;
using Microsoft.CSharp.RuntimeBinder.Errors;
using Microsoft.CSharp.RuntimeBinder.Syntax;
namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
internal enum ACCESSERROR
{
ACCESSERROR_NOACCESS,
ACCESSERROR_NOACCESSTHRU,
ACCESSERROR_NOERROR
};
//
// Semantic check methods on SymbolLoader
//
internal sealed class CSemanticChecker
{
// Generate an error if CType is static.
public void CheckForStaticClass(Symbol symCtx, CType CType, ErrorCode err)
{
if (CType.isStaticClass())
{
throw ReportStaticClassError(symCtx, CType, err);
}
}
public ACCESSERROR CheckAccess2(Symbol symCheck, AggregateType atsCheck, Symbol symWhere, CType typeThru)
{
Debug.Assert(symCheck != null);
Debug.Assert(atsCheck == null || symCheck.parent == atsCheck.getAggregate());
Debug.Assert(typeThru == null ||
typeThru is AggregateType ||
typeThru is TypeParameterType ||
typeThru is ArrayType ||
typeThru is NullableType ||
typeThru is ErrorType);
#if DEBUG
switch (symCheck.getKind())
{
case SYMKIND.SK_MethodSymbol:
case SYMKIND.SK_PropertySymbol:
case SYMKIND.SK_FieldSymbol:
case SYMKIND.SK_EventSymbol:
Debug.Assert(atsCheck != null);
break;
}
#endif // DEBUG
ACCESSERROR error = CheckAccessCore(symCheck, atsCheck, symWhere, typeThru);
if (ACCESSERROR.ACCESSERROR_NOERROR != error)
{
return error;
}
// Check the accessibility of the return CType.
CType CType = symCheck.getType();
if (CType == null)
{
return ACCESSERROR.ACCESSERROR_NOERROR;
}
// For members of AGGSYMs, atsCheck should always be specified!
Debug.Assert(atsCheck != null);
// Substitute on the CType.
if (atsCheck.GetTypeArgsAll().Count > 0)
{
CType = SymbolLoader.GetTypeManager().SubstType(CType, atsCheck);
}
return CheckTypeAccess(CType, symWhere) ? ACCESSERROR.ACCESSERROR_NOERROR : ACCESSERROR.ACCESSERROR_NOACCESS;
}
public bool CheckTypeAccess(CType type, Symbol symWhere)
{
Debug.Assert(type != null);
// Array, Ptr, Nub, etc don't matter.
type = type.GetNakedType(true);
if (!(type is AggregateType ats))
{
Debug.Assert(type is VoidType || type is ErrorType || type is TypeParameterType);
return true;
}
do
{
if (ACCESSERROR.ACCESSERROR_NOERROR != CheckAccessCore(ats.GetOwningAggregate(), ats.outerType, symWhere, null))
{
return false;
}
ats = ats.outerType;
} while(ats != null);
TypeArray typeArgs = ((AggregateType)type).GetTypeArgsAll();
for (int i = 0; i < typeArgs.Count; i++)
{
if (!CheckTypeAccess(typeArgs[i], symWhere))
return false;
}
return true;
}
// Generates an error for static classes
public RuntimeBinderException ReportStaticClassError(Symbol symCtx, CType CType, ErrorCode err) =>
ErrorContext.Error(err, symCtx != null ? new []{CType, new ErrArg(symCtx)} : new ErrArg[]{CType});
public SymbolLoader SymbolLoader { get; } = new SymbolLoader();
/////////////////////////////////////////////////////////////////////////////////
// SymbolLoader forwarders (begin)
//
public ErrorHandling ErrorContext => SymbolLoader.ErrorContext;
public TypeManager GetTypeManager() { return SymbolLoader.GetTypeManager(); }
public BSYMMGR getBSymmgr() { return SymbolLoader.getBSymmgr(); }
public SymFactory GetGlobalSymbolFactory() { return SymbolLoader.GetGlobalSymbolFactory(); }
//protected CompilerPhase GetCompPhase() { return SymbolLoader.CompPhase(); }
//protected void SetCompPhase(CompilerPhase compPhase) { SymbolLoader.compPhase = compPhase; }
public PredefinedTypes getPredefTypes() { return SymbolLoader.GetPredefindTypes(); }
//
// SymbolLoader forwarders (end)
/////////////////////////////////////////////////////////////////////////////////
//
// Utility methods
//
private ACCESSERROR CheckAccessCore(Symbol symCheck, AggregateType atsCheck, Symbol symWhere, CType typeThru)
{
Debug.Assert(symCheck != null);
Debug.Assert(atsCheck == null || symCheck.parent == atsCheck.getAggregate());
Debug.Assert(typeThru == null ||
typeThru is AggregateType ||
typeThru is TypeParameterType ||
typeThru is ArrayType ||
typeThru is NullableType ||
typeThru is ErrorType);
switch (symCheck.GetAccess())
{
default:
throw Error.InternalCompilerError();
//return ACCESSERROR.ACCESSERROR_NOACCESS;
case ACCESS.ACC_UNKNOWN:
return ACCESSERROR.ACCESSERROR_NOACCESS;
case ACCESS.ACC_PUBLIC:
return ACCESSERROR.ACCESSERROR_NOERROR;
case ACCESS.ACC_PRIVATE:
case ACCESS.ACC_PROTECTED:
if (symWhere == null)
{
return ACCESSERROR.ACCESSERROR_NOACCESS;
}
break;
case ACCESS.ACC_INTERNAL:
case ACCESS.ACC_INTERNALPROTECTED: // Check internal, then protected.
if (symWhere == null)
{
return ACCESSERROR.ACCESSERROR_NOACCESS;
}
if (symWhere.SameAssemOrFriend(symCheck))
{
return ACCESSERROR.ACCESSERROR_NOERROR;
}
if (symCheck.GetAccess() == ACCESS.ACC_INTERNAL)
{
return ACCESSERROR.ACCESSERROR_NOACCESS;
}
break;
}
// Find the inner-most enclosing AggregateSymbol.
AggregateSymbol aggWhere = null;
for (Symbol symT = symWhere; symT != null; symT = symT.parent)
{
if (symT is AggregateSymbol aggSym)
{
aggWhere = aggSym;
break;
}
if (symT is AggregateDeclaration aggDec)
{
aggWhere = aggDec.Agg();
break;
}
}
if (aggWhere == null)
{
return ACCESSERROR.ACCESSERROR_NOACCESS;
}
// Should always have atsCheck for private and protected access check.
// We currently don't need it since access doesn't respect instantiation.
// We just use symWhere.parent as AggregateSymbol instead.
AggregateSymbol aggCheck = symCheck.parent as AggregateSymbol;
// First check for private access.
for (AggregateSymbol agg = aggWhere; agg != null; agg = agg.GetOuterAgg())
{
if (agg == aggCheck)
{
return ACCESSERROR.ACCESSERROR_NOERROR;
}
}
if (symCheck.GetAccess() == ACCESS.ACC_PRIVATE)
{
return ACCESSERROR.ACCESSERROR_NOACCESS;
}
// Handle the protected case - which is the only real complicated one.
Debug.Assert(symCheck.GetAccess() == ACCESS.ACC_PROTECTED || symCheck.GetAccess() == ACCESS.ACC_INTERNALPROTECTED);
// Check if symCheck is in aggWhere or a base of aggWhere,
// or in an outer agg of aggWhere or a base of an outer agg of aggWhere.
AggregateType atsThru = null;
if (typeThru != null && !symCheck.isStatic)
{
atsThru = SymbolLoader.GetAggTypeSym(typeThru);
}
// Look for aggCheck among the base classes of aggWhere and outer aggs.
bool found = false;
for (AggregateSymbol agg = aggWhere; agg != null; agg = agg.GetOuterAgg())
{
Debug.Assert(agg != aggCheck); // We checked for this above.
// Look for aggCheck among the base classes of agg.
if (agg.FindBaseAgg(aggCheck))
{
found = true;
// aggCheck is a base class of agg. Check atsThru.
// For non-static protected access to be legal, atsThru must be an instantiation of
// agg or a CType derived from an instantiation of agg. In this case
// all that matters is that agg is in the base AggregateSymbol chain of atsThru. The
// actual AGGTYPESYMs involved don't matter.
if (atsThru == null || atsThru.getAggregate().FindBaseAgg(agg))
{
return ACCESSERROR.ACCESSERROR_NOERROR;
}
}
}
// the CType in which the method is being called has no relationship with the
// CType on which the method is defined surely this is NOACCESS and not NOACCESSTHRU
return found ? ACCESSERROR.ACCESSERROR_NOACCESSTHRU : ACCESSERROR.ACCESSERROR_NOACCESS;
}
public static bool CheckBogus(Symbol sym)
{
return (sym as PropertySymbol)?.Bogus ?? false;
}
public RuntimeBinderException ReportAccessError(SymWithType swtBad, Symbol symWhere, CType typeQual)
{
Debug.Assert(!CheckAccess(swtBad.Sym, swtBad.GetType(), symWhere, typeQual) ||
!CheckTypeAccess(swtBad.GetType(), symWhere));
return CheckAccess2(swtBad.Sym, swtBad.GetType(), symWhere, typeQual)
== ACCESSERROR.ACCESSERROR_NOACCESSTHRU
? ErrorContext.Error(ErrorCode.ERR_BadProtectedAccess, swtBad, typeQual, symWhere)
: ErrorContext.Error(ErrorCode.ERR_BadAccess, swtBad);
}
public bool CheckAccess(Symbol symCheck, AggregateType atsCheck, Symbol symWhere, CType typeThru)
{
return CheckAccess2(symCheck, atsCheck, symWhere, typeThru) == ACCESSERROR.ACCESSERROR_NOERROR;
}
}
}
| |
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
using CorDebugInterop;
using nanoFramework.Tools.Debugger;
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace nanoFramework.Tools.VisualStudio.Extension
{
public abstract class CorDebugValue : ICorDebugHeapValue, ICorDebugValue2
{
protected RuntimeValue m_rtv;
protected CorDebugAppDomain m_appDomain;
public static CorDebugValue CreateValue(RuntimeValue rtv, CorDebugAppDomain appDomain)
{
CorDebugValue val = null;
bool fIsReference;
if (rtv.IsBoxed)
{
val = new CorDebugValueBoxedObject (rtv, appDomain);
fIsReference = true;
}
else if (rtv.IsPrimitive)
{
CorDebugClass c = ClassFromRuntimeValue (rtv, appDomain);
if (c.IsEnum)
{
val = new CorDebugValueObject (rtv, appDomain);
fIsReference = false;
}
else
{
val = new CorDebugValuePrimitive (rtv, appDomain);
fIsReference = false;
}
}
else if (rtv.IsArray)
{
val = new CorDebugValueArray (rtv, appDomain);
fIsReference = true;
}
else if (rtv.CorElementType == CorElementType.ELEMENT_TYPE_STRING)
{
val = new CorDebugValueString (rtv, appDomain);
fIsReference = true;
}
else
{
val = new CorDebugValueObject (rtv, appDomain);
fIsReference = !rtv.IsValueType;
}
if (fIsReference)
{
val = new CorDebugValueReference(val, val.m_rtv, val.m_appDomain);
}
if (rtv.IsReference) //CorElementType.ELEMENT_TYPE_BYREF
{
val = new CorDebugValueReferenceByRef(val, val.m_rtv, val.m_appDomain);
}
return val;
}
public static CorDebugValue[] CreateValues(RuntimeValue[] rtv, CorDebugAppDomain appDomain)
{
CorDebugValue [] values = new CorDebugValue[rtv.Length];
for (int i = 0; i < rtv.Length; i++)
{
values[i] = CorDebugValue.CreateValue(rtv[i], appDomain);
}
return values;
}
public static CorDebugClass ClassFromRuntimeValue(RuntimeValue rtv, CorDebugAppDomain appDomain)
{
RuntimeValue_Reflection rtvf = rtv as RuntimeValue_Reflection;
CorDebugClass cls = null;
object objBuiltInKey = null;
Debug.Assert( !rtv.IsNull );
if (rtvf != null)
{
objBuiltInKey = rtvf.ReflectionType;
}
else if(rtv.DataType == RuntimeDataType.DATATYPE_TRANSPARENT_PROXY)
{
objBuiltInKey = RuntimeDataType.DATATYPE_TRANSPARENT_PROXY;
}
else
{
cls = nanoCLR_TypeSystem.CorDebugClassFromTypeIndex( rtv.Type, appDomain ); ;
}
if(objBuiltInKey != null)
{
CorDebugProcess.BuiltinType builtInType = appDomain.Process.ResolveBuiltInType( objBuiltInKey );
cls = builtInType.GetClass( appDomain );
if(cls == null)
{
cls = new CorDebugClass( builtInType.GetAssembly( appDomain ), builtInType.TokenCLR );
}
}
return cls;
}
public CorDebugValue(RuntimeValue rtv, CorDebugAppDomain appDomain)
{
m_rtv = rtv;
m_appDomain = appDomain;
}
public virtual RuntimeValue RuntimeValue
{
get { return m_rtv; }
set
{
//This should only be used if the underlying RuntimeValue changes, but not the data
//For example, if we ever support compaction. For now, this is only used when the scratch
//pad needs resizing, the RuntimeValues, and there associated heapblock*, will be relocated
Debug.Assert (m_rtv.GetType () == value.GetType ());
Debug.Assert(m_rtv.CorElementType == value.CorElementType || value.IsNull || m_rtv.IsNull);
//other debug checks here...
m_rtv = value;
}
}
public CorDebugAppDomain AppDomain
{
get { return m_appDomain; }
}
protected Engine Engine
{
[System.Diagnostics.DebuggerHidden]
get {return m_appDomain.Engine;}
}
protected CorDebugValue CreateValue(RuntimeValue rtv)
{
return CorDebugValue.CreateValue(rtv, m_appDomain);
}
protected virtual CorElementType ElementTypeProtected
{
get { return m_rtv.CorElementType; }
}
public virtual uint Size
{
get { return 8; }
}
public virtual CorElementType Type
{
get { return this.ElementTypeProtected; }
}
public ICorDebugValue ICorDebugValue
{
get { return (ICorDebugValue)this; }
}
public ICorDebugHeapValue ICorDebugHeapValue
{
get { return (ICorDebugHeapValue)this; }
}
#region ICorDebugValue Members
int ICorDebugValue.GetType( out CorElementType pType )
{
pType = this.Type;
return COM_HResults.S_OK;
}
int ICorDebugValue.GetSize( out uint pSize )
{
pSize = this.Size;
return COM_HResults.S_OK;
}
int ICorDebugValue.GetAddress( out ulong pAddress )
{
pAddress = m_rtv.ReferenceIdDirect;
return COM_HResults.S_OK;
}
int ICorDebugValue.CreateBreakpoint( out ICorDebugValueBreakpoint ppBreakpoint )
{
ppBreakpoint = null;
return COM_HResults.E_NOTIMPL;
}
#endregion
#region ICorDebugHeapValue Members
#region ICorDebugValue
int ICorDebugHeapValue.GetType( out CorElementType pType )
{
return this.ICorDebugValue.GetType( out pType );
}
int ICorDebugHeapValue.GetSize( out uint pSize )
{
return this.ICorDebugValue.GetSize( out pSize );
}
int ICorDebugHeapValue.GetAddress( out ulong pAddress )
{
return this.ICorDebugValue.GetAddress( out pAddress );
}
int ICorDebugHeapValue.CreateBreakpoint( out ICorDebugValueBreakpoint ppBreakpoint )
{
return this.ICorDebugValue.CreateBreakpoint( out ppBreakpoint );
}
#endregion
#region ICorDebugHeapValue
int ICorDebugHeapValue.IsValid( out int pbValid )
{
pbValid = Boolean.TRUE;
return COM_HResults.S_OK;
}
int ICorDebugHeapValue.CreateRelocBreakpoint( out ICorDebugValueBreakpoint ppBreakpoint )
{
ppBreakpoint = null;
return COM_HResults.E_NOTIMPL;
}
#endregion
#endregion
#region ICorDebugValue2 Members
int ICorDebugValue2.GetExactType(out ICorDebugType ppType)
{
ppType = new CorDebugGenericType(RuntimeValue.CorElementType, m_rtv, m_appDomain);
return COM_HResults.S_OK;
}
#endregion
}
public class CorDebugValuePrimitive : CorDebugValue, ICorDebugGenericValue
{
public CorDebugValuePrimitive(RuntimeValue rtv, CorDebugAppDomain appDomain) : base(rtv, appDomain)
{
}
protected virtual object ValueProtected
{
get { return m_rtv.Value; }
set { m_rtv.Value = value; }
}
public override uint Size
{
get
{
object o = this.ValueProtected;
return (uint)Marshal.SizeOf( o );
}
}
public ICorDebugGenericValue ICorDebugGenericValue
{
get {return (ICorDebugGenericValue)this;}
}
#region ICorDebugGenericValue Members
#region ICorDebugValue
int ICorDebugGenericValue.GetType( out CorElementType pType )
{
return this.ICorDebugValue.GetType( out pType );
}
int ICorDebugGenericValue.GetSize( out uint pSize )
{
return this.ICorDebugValue.GetSize( out pSize );
}
int ICorDebugGenericValue.GetAddress( out ulong pAddress )
{
return this.ICorDebugValue.GetAddress( out pAddress );
}
int ICorDebugGenericValue.CreateBreakpoint( out ICorDebugValueBreakpoint ppBreakpoint )
{
return this.ICorDebugValue.CreateBreakpoint( out ppBreakpoint );
}
#endregion
int ICorDebugGenericValue.GetValue( IntPtr pTo )
{
byte[] data = null;
object val = this.ValueProtected;
switch(this.ElementTypeProtected)
{
case CorElementType.ELEMENT_TYPE_BOOLEAN:
data = BitConverter.GetBytes( (bool)val );
break;
case CorElementType.ELEMENT_TYPE_I1:
data = new byte[] { (byte)(sbyte)val };
break;
case CorElementType.ELEMENT_TYPE_U1:
data = new byte[] { (byte)val };
break;
case CorElementType.ELEMENT_TYPE_CHAR:
data = BitConverter.GetBytes( (char)val );
break;
case CorElementType.ELEMENT_TYPE_I2:
data = BitConverter.GetBytes( (short)val );
break;
case CorElementType.ELEMENT_TYPE_U2:
data = BitConverter.GetBytes( (ushort)val );
break;
case CorElementType.ELEMENT_TYPE_I4:
data = BitConverter.GetBytes( (int)val );
break;
case CorElementType.ELEMENT_TYPE_U4:
data = BitConverter.GetBytes( (uint)val );
break;
case CorElementType.ELEMENT_TYPE_R4:
data = BitConverter.GetBytes( (float)val );
break;
case CorElementType.ELEMENT_TYPE_I8:
data = BitConverter.GetBytes( (long)val );
break;
case CorElementType.ELEMENT_TYPE_U8:
data = BitConverter.GetBytes( (ulong)val );
break;
case CorElementType.ELEMENT_TYPE_R8:
data = BitConverter.GetBytes( (double)val );
break;
default:
Debug.Assert( false );
break;
}
Marshal.Copy( data, 0, pTo, data.Length );
return COM_HResults.S_OK;
}
int ICorDebugGenericValue.SetValue( IntPtr pFrom )
{
object val = null;
uint cByte = this.Size;
byte[] data = new byte[cByte];
Marshal.Copy( pFrom, data, 0, (int)cByte );
switch(this.ElementTypeProtected)
{
case CorElementType.ELEMENT_TYPE_BOOLEAN:
val = BitConverter.ToBoolean( data, 0 );
break;
case CorElementType.ELEMENT_TYPE_I1:
val = (sbyte)data[0];
break;
case CorElementType.ELEMENT_TYPE_U1:
val = data[0];
break;
case CorElementType.ELEMENT_TYPE_CHAR:
val = BitConverter.ToChar( data, 0 );
break;
case CorElementType.ELEMENT_TYPE_I2:
val = BitConverter.ToInt16( data, 0 );
break;
case CorElementType.ELEMENT_TYPE_U2:
val = BitConverter.ToUInt16( data, 0 );
break;
case CorElementType.ELEMENT_TYPE_I4:
val = BitConverter.ToInt32( data, 0 );
break;
case CorElementType.ELEMENT_TYPE_U4:
val = BitConverter.ToUInt32( data, 0 );
break;
case CorElementType.ELEMENT_TYPE_R4:
val = BitConverter.ToSingle( data, 0 );
break;
case CorElementType.ELEMENT_TYPE_I8:
val = BitConverter.ToInt64( data, 0 );
break;
case CorElementType.ELEMENT_TYPE_U8:
val = BitConverter.ToUInt64( data, 0 );
break;
case CorElementType.ELEMENT_TYPE_R8:
val = BitConverter.ToDouble( data, 0 );
break;
}
this.ValueProtected = val;
return COM_HResults.S_OK;
}
#endregion
}
public class CorDebugValueBoxedObject : CorDebugValue, ICorDebugBoxValue
{
CorDebugValueObject m_value;
public CorDebugValueBoxedObject(RuntimeValue rtv, CorDebugAppDomain appDomain) : base (rtv, appDomain)
{
m_value = new CorDebugValueObject (rtv, appDomain);
}
public override RuntimeValue RuntimeValue
{
set
{
m_value.RuntimeValue = value;
base.RuntimeValue = value;
}
}
public override CorElementType Type
{
get { return CorElementType.ELEMENT_TYPE_CLASS; }
}
#region ICorDebugBoxValue Members
#region ICorDebugValue
int ICorDebugBoxValue.GetType( out CorElementType pType )
{
return this.ICorDebugValue.GetType( out pType );
}
int ICorDebugBoxValue.GetSize( out uint pSize )
{
return this.ICorDebugValue.GetSize( out pSize );
}
int ICorDebugBoxValue.GetAddress( out ulong pAddress )
{
return this.ICorDebugValue.GetAddress( out pAddress );
}
int ICorDebugBoxValue.CreateBreakpoint( out ICorDebugValueBreakpoint ppBreakpoint )
{
return this.ICorDebugValue.CreateBreakpoint( out ppBreakpoint );
}
#endregion
#region ICorDebugHeapValue
int ICorDebugBoxValue.IsValid( out int pbValid )
{
return this.ICorDebugHeapValue.IsValid( out pbValid );
}
int ICorDebugBoxValue.CreateRelocBreakpoint( out ICorDebugValueBreakpoint ppBreakpoint )
{
return this.ICorDebugValue.CreateBreakpoint( out ppBreakpoint );
}
#endregion
#region ICorDebugBoxValue
int ICorDebugBoxValue.GetObject( out ICorDebugObjectValue ppObject )
{
ppObject = m_value;
return COM_HResults.S_OK;
}
#endregion
#endregion
}
public class CorDebugValueReference : CorDebugValue, ICorDebugHandleValue, ICorDebugValue2
{
private CorDebugValue m_value;
public CorDebugValueReference( CorDebugValue val, RuntimeValue rtv, CorDebugAppDomain appDomain )
: base( rtv, appDomain )
{
m_value = val;
}
public override RuntimeValue RuntimeValue
{
set
{
m_value.RuntimeValue = value;
base.RuntimeValue = value;
}
}
public override CorElementType Type
{
get
{
return m_value.Type;
}
}
public ICorDebugReferenceValue ICorDebugReferenceValue
{
get { return (ICorDebugReferenceValue)this; }
}
#region ICorDebugReferenceValue Members
#region ICorDebugValue2 Members
int ICorDebugValue2.GetExactType(out ICorDebugType ppType)
{
return ((ICorDebugValue2)m_value).GetExactType( out ppType);
}
#endregion
#region ICorDebugValue
int ICorDebugReferenceValue.GetType( out CorElementType pType )
{
return this.ICorDebugValue.GetType( out pType );
}
int ICorDebugReferenceValue.GetSize( out uint pSize )
{
return this.ICorDebugValue.GetSize( out pSize );
}
int ICorDebugReferenceValue.GetAddress( out ulong pAddress )
{
return this.ICorDebugValue.GetAddress( out pAddress );
}
int ICorDebugReferenceValue.CreateBreakpoint( out ICorDebugValueBreakpoint ppBreakpoint )
{
return this.ICorDebugValue.CreateBreakpoint( out ppBreakpoint );
}
#endregion
#region ICorDebugReferenceValue
int ICorDebugReferenceValue.IsNull( out int pbNull )
{
pbNull = Boolean.BoolToInt( m_rtv.IsNull );
return COM_HResults.S_OK;
}
int ICorDebugReferenceValue.GetValue( out ulong pValue )
{
pValue = (ulong)m_rtv.ReferenceIdDirect;
return COM_HResults.S_OK;
}
int ICorDebugReferenceValue.SetValue( ulong value )
{
Debug.Assert( value <= uint.MaxValue );
RuntimeValue rtvNew = m_rtv.Assign((uint)value);
this.RuntimeValue = rtvNew;
return COM_HResults.S_OK;
}
int ICorDebugReferenceValue.Dereference( out ICorDebugValue ppValue )
{
ppValue = m_value;
return COM_HResults.S_OK;
}
int ICorDebugReferenceValue.DereferenceStrong( out ICorDebugValue ppValue )
{
return this.ICorDebugReferenceValue.Dereference( out ppValue );
}
#endregion
#endregion
#region ICorDebugHandleValue Members
#region ICorDebugValue
int ICorDebugHandleValue.GetType( out CorElementType pType )
{
return this.ICorDebugValue.GetType( out pType );
}
int ICorDebugHandleValue.GetSize( out uint pSize )
{
return this.ICorDebugValue.GetSize( out pSize );
}
int ICorDebugHandleValue.GetAddress( out ulong pAddress )
{
return this.ICorDebugValue.GetAddress( out pAddress );
}
int ICorDebugHandleValue.CreateBreakpoint( out ICorDebugValueBreakpoint ppBreakpoint )
{
return this.ICorDebugValue.CreateBreakpoint( out ppBreakpoint );
}
#endregion
#region ICorDebugReferenceValue
int ICorDebugHandleValue.IsNull( out int pbNull )
{
return this.ICorDebugReferenceValue.IsNull( out pbNull );
}
int ICorDebugHandleValue.GetValue( out ulong pValue )
{
return this.ICorDebugReferenceValue.GetValue( out pValue );
}
int ICorDebugHandleValue.SetValue( ulong value )
{
return this.ICorDebugReferenceValue.SetValue( value );
}
int ICorDebugHandleValue.Dereference( out ICorDebugValue ppValue )
{
return this.ICorDebugReferenceValue.Dereference( out ppValue );
}
int ICorDebugHandleValue.DereferenceStrong( out ICorDebugValue ppValue )
{
return this.ICorDebugReferenceValue.DereferenceStrong( out ppValue );
}
#endregion
#region ICorDebugHandleValue
int ICorDebugHandleValue.GetHandleType( out CorDebugHandleType pType )
{
pType = CorDebugHandleType.HANDLE_STRONG;
return COM_HResults.S_OK;
}
int ICorDebugHandleValue.Dispose()
{
return COM_HResults.S_OK;
}
#endregion
#endregion
}
public class CorDebugValueReferenceByRef : CorDebugValueReference
{
public CorDebugValueReferenceByRef(CorDebugValue val, RuntimeValue rtv, CorDebugAppDomain appDomain) : base(val, rtv, appDomain)
{
}
public override CorElementType Type
{
get { return CorElementType.ELEMENT_TYPE_BYREF; }
}
}
public class CorDebugValueArray : CorDebugValue, ICorDebugArrayValue, ICorDebugValue2
{
public CorDebugValueArray(RuntimeValue rtv, CorDebugAppDomain appDomain) : base(rtv, appDomain)
{
}
public static CorElementType typeValue = CorElementType.ELEMENT_TYPE_I4;
public uint Count
{
get { return m_rtv.Length; }
}
public ICorDebugArrayValue ICorDebugArrayValue
{
get { return (ICorDebugArrayValue)this; }
}
#region ICorDebugArrayValue Members
#region ICorDebugValue
int ICorDebugArrayValue.GetType( out CorElementType pType )
{
return this.ICorDebugValue.GetType( out pType );
}
int ICorDebugArrayValue.GetSize( out uint pSize )
{
return this.ICorDebugValue.GetSize( out pSize );
}
int ICorDebugArrayValue.GetAddress( out ulong pAddress )
{
return this.ICorDebugValue.GetAddress( out pAddress );
}
int ICorDebugArrayValue.CreateBreakpoint( out ICorDebugValueBreakpoint ppBreakpoint )
{
return this.ICorDebugValue.CreateBreakpoint( out ppBreakpoint );
}
#endregion
#region ICorDebugValue2 Members
int ICorDebugValue2.GetExactType(out ICorDebugType ppType)
{
ppType = new CorDebugTypeArray( this );
return COM_HResults.S_OK;
}
#endregion
#region ICorDebugHeapValue
int ICorDebugArrayValue.IsValid( out int pbValid )
{
return this.ICorDebugHeapValue.IsValid( out pbValid );
}
int ICorDebugArrayValue.CreateRelocBreakpoint( out ICorDebugValueBreakpoint ppBreakpoint )
{
return this.ICorDebugValue.CreateBreakpoint( out ppBreakpoint );
}
#endregion
#region ICorDebugArrayValue
/* With implementation of ICorDebugValue2.GetExactType this function
* ICorDebugArrayValue.GetElementType is not called.
* It is left to support VS 2005.
* We cannot remove this function since it is part of ICorDebugArrayValue interface.
*/
// FIXME
int ICorDebugArrayValue.GetElementType( out CorElementType pType )
{
if (this.Count != 0)
{
pType = m_rtv.GetElement(0).CorElementType;
}
else
{
pType = CorElementType.ELEMENT_TYPE_CLASS;
}
return COM_HResults.S_OK;
}
int ICorDebugArrayValue.GetRank( out uint pnRank )
{
pnRank = 1;
return COM_HResults.S_OK;
}
int ICorDebugArrayValue.GetCount( out uint pnCount )
{
pnCount = this.Count;
return COM_HResults.S_OK;
}
int ICorDebugArrayValue.GetDimensions( uint cdim, uint[] dims )
{
Debug.Assert( cdim == 1 );
dims[0] = this.Count;
return COM_HResults.S_OK;
}
int ICorDebugArrayValue.HasBaseIndicies( out int pbHasBaseIndicies )
{
pbHasBaseIndicies = Boolean.FALSE;
return COM_HResults.S_OK;
}
int ICorDebugArrayValue.GetBaseIndicies( uint cdim, uint[] indicies )
{
Debug.Assert( cdim == 1 );
indicies[0] = 0;
return COM_HResults.S_OK;
}
int ICorDebugArrayValue.GetElement( uint cdim, uint[] indices, out ICorDebugValue ppValue )
{
//ask for several at once and cache?
Debug.Assert( cdim == 1 );
ppValue = CreateValue(m_rtv.GetElement(indices[0]));
return COM_HResults.S_OK;
}
int ICorDebugArrayValue.GetElementAtPosition( uint nPosition, out ICorDebugValue ppValue )
{
//Cache values?
ppValue = CreateValue(m_rtv.GetElement(nPosition));
return COM_HResults.S_OK;
}
#endregion
#endregion
}
public class CorDebugValueObject : CorDebugValue, ICorDebugObjectValue, ICorDebugGenericValue /*, ICorDebugObjectValue2*/
{
CorDebugClass m_class = null;
CorDebugValuePrimitive m_valuePrimitive = null; //for boxed primitives, or enums
bool m_fIsEnum;
bool m_fIsBoxed;
//Object or CLASS, or VALUETYPE
public CorDebugValueObject(RuntimeValue rtv, CorDebugAppDomain appDomain) : base(rtv, appDomain)
{
if(!rtv.IsNull)
{
m_class = CorDebugValue.ClassFromRuntimeValue(rtv, appDomain);
m_fIsEnum = m_class.IsEnum;
m_fIsBoxed = rtv.IsBoxed;
}
}
private bool IsValuePrimitive()
{
if (m_fIsBoxed || m_fIsEnum)
{
if (m_valuePrimitive == null)
{
if (m_rtv.IsBoxed)
{
RuntimeValue rtv = m_rtv.GetField(1, 0);
Debug.Assert(rtv.IsPrimitive);
//Assert that m_class really points to a primitive
m_valuePrimitive = (CorDebugValuePrimitive)CreateValue(rtv);
}
else
{
Debug.Assert(m_fIsEnum);
m_valuePrimitive = new CorDebugValuePrimitive(m_rtv, m_appDomain);
Debug.Assert(m_rtv.IsPrimitive);
}
}
}
return m_valuePrimitive != null;
}
public override uint Size
{
get
{
if (this.IsValuePrimitive())
{
return m_valuePrimitive.Size;
}
else
{
return 4;
}
}
}
public override CorElementType Type
{
get
{
if(m_fIsEnum)
{
return CorElementType.ELEMENT_TYPE_VALUETYPE;
}
else
{
return base.Type;
}
}
}
#region ICorDebugObjectValue Members
#region ICorDebugValue
int ICorDebugObjectValue.GetType( out CorElementType pType )
{
return this.ICorDebugValue.GetType( out pType );
}
int ICorDebugObjectValue.GetSize( out uint pSize )
{
return this.ICorDebugValue.GetSize( out pSize );
}
int ICorDebugObjectValue.GetAddress( out ulong pAddress )
{
return this.ICorDebugValue.GetAddress( out pAddress );
}
int ICorDebugObjectValue.CreateBreakpoint( out ICorDebugValueBreakpoint ppBreakpoint )
{
return this.ICorDebugValue.CreateBreakpoint( out ppBreakpoint );
}
#endregion
#region ICorDebugObjectValue
int ICorDebugObjectValue.GetClass( out ICorDebugClass ppClass )
{
ppClass = m_class;
return COM_HResults.S_OK;
}
int ICorDebugObjectValue.GetFieldValue( ICorDebugClass pClass, uint fieldDef, out ICorDebugValue ppValue )
{
//cache fields?
RuntimeValue rtv = m_rtv.GetField(0, nanoCLR_TypeSystem.ClassMemberIndexFromCLRToken(fieldDef, ((CorDebugClass)pClass).Assembly));
ppValue = CreateValue( rtv );
return COM_HResults.S_OK;
}
int ICorDebugObjectValue.GetVirtualMethod( uint memberRef, out ICorDebugFunction ppFunction )
{
uint mdVirtual = Engine.GetVirtualMethod(nanoCLR_TypeSystem.ClassMemberIndexFromCLRToken(memberRef, this.m_class.Assembly), this.m_rtv);
ppFunction = nanoCLR_TypeSystem.CorDebugFunctionFromMethodIndex( mdVirtual, this.m_appDomain );
return COM_HResults.S_OK;
}
int ICorDebugObjectValue.GetContext( out ICorDebugContext ppContext )
{
ppContext = null;
return COM_HResults.S_OK;
}
int ICorDebugObjectValue.IsValueClass( out int pbIsValueClass )
{
pbIsValueClass = Boolean.BoolToInt( m_rtv.IsValueType );
return COM_HResults.S_OK;
}
int ICorDebugObjectValue.GetManagedCopy( out object ppObject )
{
ppObject = null;
Debug.Assert( false );
return COM_HResults.S_OK;
}
int ICorDebugObjectValue.SetFromManagedCopy( object pObject )
{
return COM_HResults.S_OK;
}
#endregion
#endregion
#region ICorDebugGenericValue Members
#region ICorDebugValue
int ICorDebugGenericValue.GetType( out CorElementType pType )
{
return this.ICorDebugValue.GetType( out pType );
}
int ICorDebugGenericValue.GetSize( out uint pSize )
{
return this.ICorDebugValue.GetSize( out pSize );
}
int ICorDebugGenericValue.GetAddress( out ulong pAddress )
{
return this.ICorDebugValue.GetAddress( out pAddress );
}
int ICorDebugGenericValue.CreateBreakpoint( out ICorDebugValueBreakpoint ppBreakpoint )
{
return this.ICorDebugValue.CreateBreakpoint( out ppBreakpoint );
}
#endregion
#region ICorDebugGenericValue
int ICorDebugGenericValue.GetValue( IntPtr pTo )
{
int hr = COM_HResults.S_OK;
if (this.IsValuePrimitive())
{
hr = m_valuePrimitive.ICorDebugGenericValue.GetValue(pTo);
}
else
{
ulong addr;
hr = ((ICorDebugGenericValue)this).GetAddress(out addr);
Marshal.WriteInt32(pTo, (int)addr);
}
return hr;
}
int ICorDebugGenericValue.SetValue( IntPtr pFrom )
{
int hr = COM_HResults.S_OK;
if (this.IsValuePrimitive())
{
hr = m_valuePrimitive.ICorDebugGenericValue.SetValue(pFrom);
}
else
{
Debug.Assert(false);
}
return hr;
}
#endregion
#endregion
}
public class CorDebugValueString : CorDebugValue, ICorDebugStringValue
{
public CorDebugValueString( RuntimeValue rtv, CorDebugAppDomain appDomain )
: base( rtv, appDomain )
{
}
private string Value
{
get
{
string ret = m_rtv.Value as string;
return (ret == null) ? "" : ret;
}
}
#region ICorDebugStringValue Members
#region ICorDebugValue
int ICorDebugStringValue.GetType( out CorElementType pType )
{
return this.ICorDebugValue.GetType( out pType );
}
int ICorDebugStringValue.GetSize( out uint pSize )
{
return this.ICorDebugValue.GetSize( out pSize );
}
int ICorDebugStringValue.GetAddress( out ulong pAddress )
{
return this.ICorDebugValue.GetAddress( out pAddress );
}
int ICorDebugStringValue.CreateBreakpoint( out ICorDebugValueBreakpoint ppBreakpoint )
{
return this.ICorDebugValue.CreateBreakpoint( out ppBreakpoint );
}
#endregion
#region ICorDebugHeapValue
int ICorDebugStringValue.IsValid( out int pbValid )
{
return this.ICorDebugHeapValue.IsValid( out pbValid );
}
int ICorDebugStringValue.CreateRelocBreakpoint( out ICorDebugValueBreakpoint ppBreakpoint )
{
return this.ICorDebugHeapValue.CreateRelocBreakpoint( out ppBreakpoint );
}
#endregion
#region ICorDebugStringValue
int ICorDebugStringValue.GetLength( out uint pcchString )
{
pcchString = (uint)Value.Length;
return COM_HResults.S_OK;
}
int ICorDebugStringValue.GetString( uint cchString, IntPtr pcchString, IntPtr szString )
{
Utility.MarshalString( Value, cchString, pcchString, szString, false );
return COM_HResults.S_OK;
}
#endregion
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using hw.DebugFormatter;
using JetBrains.Annotations;
// ReSharper disable CheckNamespace
namespace hw.Helper;
[Serializable]
[PublicAPI]
public sealed class SmbFile
{
/// <summary>
/// Ensure, that all directories are existent when writing to file.
/// Can be modified at any time.
/// </summary>
// ReSharper disable once FieldCanBeMadeReadOnly.Global
[EnableDumpExcept(true)]
public bool AutoCreateDirectories;
readonly string InternalName;
FileSystemInfo FileInfoCache;
public SmbFile() => InternalName = "";
SmbFile(string internalName, bool autoCreateDirectories)
{
InternalName = internalName;
AutoCreateDirectories = autoCreateDirectories;
}
public override string ToString() => FullName;
/// <summary>
/// considers the file as a string. If file exists it should be a text file
/// </summary>
/// <value> the content of the file if existing else null. </value>
[DisableDump]
public string String
{
get
{
if(!File.Exists(InternalName))
return null;
using var reader = File.OpenText(InternalName);
return reader.ReadToEnd();
}
set
{
CheckedEnsureDirectoryOfFileExists();
using var writer = File.CreateText(InternalName);
writer.Write(value);
}
}
public string ModifiedDateString => ModifiedDate.DynamicShortFormat(true);
/// <summary>
/// considers the file as a byte array
/// </summary>
[DisableDump]
public byte[] Bytes
{
get
{
var f = Reader;
var result = new byte[Size];
var actualSize = f.Read(result, 0, (int)Size);
(actualSize == Size).Assert();
f.Close();
return result;
}
set
{
var f = File.OpenWrite(InternalName);
f.Write(value, 0, value.Length);
f.Close();
}
}
[DisableDump]
public FileStream Reader
=> new(InternalName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
/// <summary>
/// Size of file in bytes
/// </summary>
[DisableDump]
public long Size => ((FileInfo)FileSystemInfo).Length;
/// <summary>
/// Gets the full path of the directory or file.
/// </summary>
public string FullName => FileSystemInfo.FullName;
[DisableDump]
public SmbFile Directory => DirectoryName.ToSmbFile();
[DisableDump]
public string DirectoryName => Path.GetDirectoryName(FullName);
[DisableDump]
public string Extension => Path.GetExtension(FullName);
/// <summary>
/// Gets the name of the directory or file without path.
/// </summary>
[DisableDump]
public string Name => FileSystemInfo.Name;
/// <summary>
/// Gets a value indicating whether a file exists.
/// </summary>
public bool Exists => FileSystemInfo.Exists;
/// <summary>
/// Gets a value indicating whether a file exists.
/// </summary>
[DisableDump]
public bool IsMounted
{
get
{
if(!Exists)
return false;
if((FileSystemInfo.Attributes & FileAttributes.ReparsePoint) == 0)
return false;
try
{
((DirectoryInfo)FileSystemInfo).GetFileSystemInfos("dummy");
return true;
}
catch(Exception)
{
return false;
}
}
}
/// <summary>
/// returns true if it is a directory
/// </summary>
public bool IsDirectory => System.IO.Directory.Exists(InternalName);
/// <summary>
/// Content of directory, one line for each file
/// </summary>
[DisableDump]
public string DirectoryString => GetDirectoryString();
[DisableDump]
public SmbFile[] Items => GetItems().Select(f => Create(f.FullName, AutoCreateDirectories)).ToArray();
[EnableDumpExcept(false)]
public bool IsLocked
{
get
{
try
{
File.OpenRead(InternalName).Close();
return false;
}
catch(IOException)
{
return true;
}
//file is not locked
}
}
[DisableDump]
public DateTime ModifiedDate => FileSystemInfo.LastWriteTime;
[DisableDump]
public FileSystemInfo FileSystemInfo
{
get
{
if(FileInfoCache != null)
return FileInfoCache;
FileInfoCache = IsDirectory
? new DirectoryInfo(InternalName)
: new FileInfo(InternalName);
return FileInfoCache;
}
}
/// <summary>
/// Gets the directory of the source file that called this function
/// </summary>
/// <param name="depth"> The depth. </param>
/// <returns> </returns>
public static string SourcePath(int depth = 0)
=> new FileInfo(SourceFileName(depth + 1)).DirectoryName;
/// <summary>
/// Gets the name of the source file that called this function
/// </summary>
/// <param name="depth"> stack depths of the function used. </param>
/// <returns> </returns>
public static string SourceFileName(int depth = 0)
{
var sf = new StackTrace(true).GetFrame(depth + 1);
return sf.GetFileName();
}
/// <summary>
/// Gets list of files that match given path and pattern
/// </summary>
/// <param name="filePattern"></param>
/// <returns></returns>
public static string[] Select(string filePattern)
{
var namePattern = filePattern.Split('\\').Last();
var path = filePattern.Substring(0, filePattern.Length - namePattern.Length - 1);
return System.IO.Directory.GetFiles(path, namePattern);
}
public string SubString(long start, int size)
{
if(!File.Exists(InternalName))
return null;
using var f = Reader;
f.Position = start;
var buffer = new byte[size];
var actualSize = f.Read(buffer, 0, size);
(actualSize == size).Assert();
return Encoding.UTF8.GetString(buffer);
}
public void CheckedEnsureDirectoryOfFileExists()
{
if(AutoCreateDirectories)
EnsureDirectoryOfFileExists();
}
public void EnsureDirectoryOfFileExists()
=> DirectoryName?.ToSmbFile(false).EnsureIsExistentDirectory();
public void EnsureIsExistentDirectory()
{
if(Exists)
IsDirectory.Assert();
else
{
EnsureDirectoryOfFileExists();
System.IO.Directory.CreateDirectory(FullName);
FileInfoCache = null;
}
}
/// <summary>
/// Delete the file
/// </summary>
public void Delete(bool recursive = false)
{
if(IsDirectory)
System.IO.Directory.Delete(InternalName, recursive);
else
File.Delete(InternalName);
}
/// <summary>
/// Move the file
/// </summary>
public void Move(string newName)
{
if(IsDirectory)
System.IO.Directory.Move(InternalName, newName);
else
File.Move(InternalName, newName);
}
public void CopyTo(string destinationPath)
{
if(IsDirectory)
{
destinationPath.ToSmbFile().EnsureIsExistentDirectory();
foreach(var sourceSubFile in Items)
{
var destinationSubPath = destinationPath.PathCombine(sourceSubFile.Name);
sourceSubFile.CopyTo(destinationSubPath);
}
}
else
File.Copy(FullName, destinationPath);
}
public SmbFile[] GuardedItems()
{
try
{
if(IsDirectory)
return Items;
}
catch
{
// ignored
}
return new SmbFile[0];
}
public IEnumerable<SmbFile> RecursiveItems()
{
yield return this;
if(!IsDirectory)
yield break;
FullName.Log();
IEnumerable<string> filePaths = new[] { FullName };
while(true)
{
var newList = new List<string>();
var items =
filePaths.SelectMany(s => s.ToSmbFile(AutoCreateDirectories).GuardedItems())
.ToArray();
foreach(var item in items)
{
yield return item;
if(item.IsDirectory)
newList.Add(item.FullName);
}
if(!newList.Any())
yield break;
filePaths = newList;
}
}
public SmbFile PathCombine(string item) => FullName.PathCombine(item).ToSmbFile();
public bool Contains(SmbFile subFile) => subFile.FullName.StartsWith(FullName, true, null);
public void InitiateExternalProgram()
{
var process = new Process
{
StartInfo = new()
{
WindowStyle = ProcessWindowStyle.Hidden, FileName = FullName
}
};
process.Start();
}
/// <summary>
/// constructs a FileInfo
/// </summary>
/// <param name="name"> the filename </param>
/// <param name="autoCreateDirectories"></param>
internal static SmbFile Create(string name, bool autoCreateDirectories)
=> new(name, autoCreateDirectories);
string GetDirectoryString()
{
var result = "";
foreach(var fi in GetItems())
{
result += fi.Name;
result += "\n";
}
return result;
}
FileSystemInfo[] GetItems()
=> ((DirectoryInfo)FileSystemInfo).GetFileSystemInfos().ToArray();
public string FilePosition
(
TextPart textPart,
FilePositionTag tag
)
=> Tracer.FilePosition(FullName, textPart, tag);
public string FilePosition
(
TextPart textPart,
string tag
)
=> Tracer.FilePosition(FullName, textPart, tag);
}
| |
//-----------------------------------------------------------------------------
//
// <copyright file="ManagedAPIClasses.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// Description: Enums and classes needed for the MSIPC Managed API.
//
//
//
//-----------------------------------------------------------------------------
using System;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Windows.Interop;
namespace Microsoft.InformationProtectionAndControl
{
public class InformationProtectionException : Exception
{
public InformationProtectionException(int hrError, string message)
: base(string.Format("{0} HRESULT: 0x{1:X8}", message, hrError))
{
HResult = hrError;
}
public int ErrorCode
{
get { return HResult; }
}
};
// API Mode values - http://msdn.microsoft.com/en-us/library/windows/desktop/hh535236(v=vs.85).aspx
public enum APIMode : int
{
Client = 1,
Server = 2,
};
// IpcSerializeLicense() flags - http://msdn.microsoft.com/en-us/library/windows/desktop/hh535269(v=vs.85).aspx
[Flags]
public enum SerializeLicenseFlags : int
{
KeyNoPersist = 2,
KeyNoPersistOnDisk = 4,
DeprecatedUnsignedLicenseTemplate = 8,
KeyNoPersistInLicense = 16,
};
// User Id types - http://msdn.microsoft.com/en-us/library/windows/desktop/hh535284(v=vs.85).aspx
public enum UserIdType : uint
{
Email = 1,
IpcUser = 2,
};
// IPC-internal User IDs - http://msdn.microsoft.com/en-us/library/windows/desktop/hh535284(v=vs.85).aspx
public class IpcUserIDs
{
public const string UserIdEveryone = "ANYONE";
public const string UserIdNull = "NULL";
public const string UserIdOwner = "OWNER";
}
// Connection Info - http://msdn.microsoft.com/en-us/library/windows/desktop/hh535274(v=vs.85).aspx
public class ConnectionInfo
{
public ConnectionInfo(Uri extranetUrl, Uri intranetUrl, bool bConfigureForLicenseingOnlyClusters = false)
{
if (extranetUrl == null && intranetUrl == null)
{
throw new ArgumentException("Either extranetUrl or intranetUrl should not be null");
}
m_extranetUrl = extranetUrl;
m_intranetUrl = intranetUrl;
OverrideServiceDiscoveryForLicensing = bConfigureForLicenseingOnlyClusters;
}
/// <summary>
/// This flag only applies to IpcGetTemplateIssuerList and IpcGetTemplateList. When set, this flag configures
/// MSIPC to work correctly with multiple AD RMS licensing-only clusters. When this flag is set, service
/// discovery will use these URLs to locate the appropriate licensing server. When this flag is not set,
/// service discovery will use these URLs to locate the certification cluster and then locate the licensing
/// service off of that certification cluster.
/// </summary>
public bool OverrideServiceDiscoveryForLicensing { get; private set; }
public Uri ExtranetUrl
{
get { return m_extranetUrl; }
}
public Uri IntranetUrl
{
get { return m_intranetUrl; }
}
private Uri m_extranetUrl = null;
private Uri m_intranetUrl = null;
}
// Template Info - http://msdn.microsoft.com/en-us/library/windows/desktop/hh535279(v=vs.85).aspx
public class TemplateInfo
{
public string TemplateId
{
get { return m_templateId; }
set { m_templateId = value; }
}
public CultureInfo CultureInfo
{
get { return m_cultureInfo; }
set { m_cultureInfo = value; }
}
public string Description
{
get { return m_description; }
set { m_description = value; }
}
public string Name
{
get { return m_name; }
set { m_name = value; }
}
public string IssuerDisplayName
{
get { return m_issuerDisplayName; }
set { m_issuerDisplayName = value; }
}
public bool FromTemplate
{
get { return m_fromTemplate; }
set { m_fromTemplate = value; }
}
public TemplateInfo(string templateId, CultureInfo cultureInfo, string templateName, string templateDescription, string issuerDisplayName, bool fromTemplate)
{
m_templateId = templateId;
m_cultureInfo = cultureInfo;
m_name = templateName;
m_description = templateDescription;
m_issuerDisplayName = issuerDisplayName;
m_fromTemplate = fromTemplate;
}
private string m_templateId = null;
private CultureInfo m_cultureInfo = null;
private string m_name = null;
private string m_description = null;
private string m_issuerDisplayName = null;
private bool m_fromTemplate = false;
}
// Template Issuer - http://msdn.microsoft.com/en-us/library/windows/desktop/hh535280(v=vs.85).aspx
public class TemplateIssuer
{
public ConnectionInfo ConnectionInfo
{
get { return m_connectionInfo; }
}
public string DisplayName
{
get { return m_displayName; }
}
public bool AllowFromScratch
{
get { return m_allowFromScratch; }
}
public TemplateIssuer(ConnectionInfo connectionInfo, string displayName, bool allowFromScratch)
{
m_connectionInfo = connectionInfo;
m_displayName = displayName;
m_allowFromScratch = allowFromScratch;
}
private ConnectionInfo m_connectionInfo = null;
private string m_displayName = null;
private bool m_allowFromScratch = false;
}
// Term - http://msdn.microsoft.com/en-us/library/windows/desktop/hh535282(v=vs.85).aspx
public class Term
{
public DateTime From
{
get { return m_from; }
set { m_from = value; }
}
public TimeSpan Duration
{
get { return m_duration; }
set { m_duration = value; }
}
public static bool IsValid(Term validate)
{
DateTime termDisabled = DateTime.FromFileTime(0);
return (validate != null && (validate.From > termDisabled || validate.Duration.Ticks > 0));
}
private DateTime m_from = new DateTime();
private TimeSpan m_duration = new TimeSpan();
}
// Common Rights - http://msdn.microsoft.com/en-us/library/windows/desktop/hh535295(v=vs.85).aspx
public class CommonRights
{
public static string OwnerRight = "OWNER";
public static string ViewRight = "VIEW";
public static string EditRight = "EDIT";
public static string ExtractRight = "EXTRACT";
public static string ExportRight = "EXPORT";
public static string PrintRight = "PRINT";
public static string CommentRight = "COMMENT";
public static string ViewRightsDataRight = "VIEWRIGHTSDATA";
public static string EditRightsDataRight = "EDITRIGHTSDATA";
public static string ForwardRight = "FORWARD";
public static string ReplyRight = "REPLY";
public static string ReplyAllRight = "REPLYALL";
}
// User Rights - http://msdn.microsoft.com/en-us/library/windows/desktop/hh535285(v=vs.85).aspx
public class UserRights
{
public UserRights(UserIdType userIdType, string principalId, Collection<string> rights)
{
if ((userIdType != UserIdType.Email) &&
(userIdType != UserIdType.IpcUser))
{
throw new ArgumentOutOfRangeException("principalIdType");
}
if (principalId == null)
{
throw new ArgumentNullException("principalId");
}
if (principalId.Trim().Length == 0)
{
throw new ArgumentOutOfRangeException("principalId");
}
if (userIdType == UserIdType.IpcUser)
{
if (string.Compare(principalId, IpcUserIDs.UserIdEveryone, StringComparison.InvariantCultureIgnoreCase) != 0 &&
string.Compare(principalId, IpcUserIDs.UserIdNull, StringComparison.InvariantCultureIgnoreCase) != 0 &&
string.Compare(principalId, IpcUserIDs.UserIdOwner, StringComparison.InvariantCultureIgnoreCase) != 0)
{
throw new ArgumentOutOfRangeException("principalId");
}
}
if (rights == null)
{
throw new ArgumentNullException("rights");
}
m_rights = rights;
m_userId = principalId;
m_userIdType = userIdType;
}
public Collection<string> Rights
{
get { return m_rights; }
}
public String UserId
{
get { return m_userId; }
set { m_userId = value; }
}
public UserIdType UserIdType
{
get { return m_userIdType; }
set { m_userIdType = value; }
}
private Collection<string> m_rights = null;
private string m_userId = null;
private UserIdType m_userIdType = UserIdType.Email;
}
// SafeHandle implementation for MSIPC handles - http://msdn.microsoft.com/en-us/library/windows/desktop/hh535288(v=vs.85).aspx
public class SafeInformationProtectionHandle : SafeHandle
{
// Although it is not obvious this constructor is being called by the interop services
// it throws exceptions without it
internal SafeInformationProtectionHandle()
: base(IntPtr.Zero, true)
{
}
internal SafeInformationProtectionHandle(IntPtr handle)
: base(handle, true) // "true" means "owns the handle"
{
}
// base class expects us to override this method with the handle specific release code
protected override bool ReleaseHandle()
{
int hr = 0;
if (!IsInvalid)
{
// we can not use safe handle in the IpcCloseHandle function
// as the SafeHandle implementation marks this instance as an invalid by the time
// ReleaseHandle is called. After that marshalling code doesn't let the current instance
// of the Safe*Handle sub-class to cross managed/unmanaged boundary.
hr = SafeNativeMethods.IpcCloseHandle(this.handle);
#if DEBUG
if (hr > 0)
{
Marshal.ThrowExceptionForHR(hr);
}
#endif
// This member might be called twice(depending on the client app). In order to
// prevent Unmanaged RM SDK from returning an error (Handle is already closed)
// we need to mark our handle as invalid after successful close call
base.SetHandle(IntPtr.Zero);
}
return (hr >= 0);
}
public override bool IsInvalid
{
get
{
return this.handle.Equals(IntPtr.Zero);
}
}
public IntPtr Value
{
get
{
return handle;
}
}
}
// Key Handle - http://msdn.microsoft.com/en-us/library/windows/desktop/hh535288(v=vs.85).aspx
public sealed class SafeInformationProtectionKeyHandle : SafeInformationProtectionHandle
{
// This empty constructor is required to be present for use by interop services
internal SafeInformationProtectionKeyHandle() : base() { }
internal SafeInformationProtectionKeyHandle(IntPtr handle) : base(handle) { }
}
// License Handle - http://msdn.microsoft.com/en-us/library/windows/desktop/hh535288(v=vs.85).aspx
public sealed class SafeInformationProtectionLicenseHandle : SafeInformationProtectionHandle
{
// This empty constructor is required to be present for use by interop services
internal SafeInformationProtectionLicenseHandle() : base() { }
internal SafeInformationProtectionLicenseHandle(IntPtr handle) : base(handle) { }
}
public sealed class SafeInformationProtectionTokenHandle : SafeInformationProtectionHandle
{
internal SafeInformationProtectionTokenHandle() : base() { }
internal SafeInformationProtectionTokenHandle(IntPtr handle) : base(handle) { }
}
public sealed class SafeInformationProtectionFileHandle : SafeInformationProtectionHandle
{
internal SafeInformationProtectionFileHandle() : base() { }
internal SafeInformationProtectionFileHandle(IntPtr handle) : base(handle) { }
}
public class IpcWindow
{
private IpcWindow(IntPtr hWindow)
{
Handle = hWindow;
}
public static IpcWindow Create(object window)
{
if (null == window) { return new IpcWindow(IntPtr.Zero); }
IpcWindow ipcWindow = window as IpcWindow;
if (null != ipcWindow) { return ipcWindow; }
WindowInteropHelper helper = window as WindowInteropHelper;
if (null != helper)
{
return new IpcWindow(helper.Handle);
}
System.Windows.Window wpfWindow = window as System.Windows.Window;
if (null != wpfWindow)
{
return new IpcWindow(new WindowInteropHelper(wpfWindow).Handle);
}
System.Windows.Forms.Form formWindow = window as System.Windows.Forms.Form;
if (null != formWindow)
{
return new IpcWindow(formWindow.Handle);
}
throw new ArgumentException(
"The passed in window must be null or of type: " +
"WindowInteropHelper, System.Windows.Window, or System.Windows.Forms.Form", "window");
}
public IntPtr Handle { get; private set; }
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gaxgrpc = Google.Api.Gax.Grpc;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.BinaryAuthorization.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedSystemPolicyV1ClientTest
{
[xunit::FactAttribute]
public void GetSystemPolicyRequestObject()
{
moq::Mock<SystemPolicyV1.SystemPolicyV1Client> mockGrpcClient = new moq::Mock<SystemPolicyV1.SystemPolicyV1Client>(moq::MockBehavior.Strict);
GetSystemPolicyRequest request = new GetSystemPolicyRequest
{
PolicyName = PolicyName.FromProject("[PROJECT]"),
};
Policy expectedResponse = new Policy
{
PolicyName = PolicyName.FromProject("[PROJECT]"),
AdmissionWhitelistPatterns =
{
new AdmissionWhitelistPattern(),
},
ClusterAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
DefaultAdmissionRule = new AdmissionRule(),
UpdateTime = new wkt::Timestamp(),
Description = "description2cf9da67",
GlobalPolicyEvaluationMode = Policy.Types.GlobalPolicyEvaluationMode.Disable,
KubernetesServiceAccountAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
IstioServiceIdentityAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
KubernetesNamespaceAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
};
mockGrpcClient.Setup(x => x.GetSystemPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SystemPolicyV1Client client = new SystemPolicyV1ClientImpl(mockGrpcClient.Object, null);
Policy response = client.GetSystemPolicy(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetSystemPolicyRequestObjectAsync()
{
moq::Mock<SystemPolicyV1.SystemPolicyV1Client> mockGrpcClient = new moq::Mock<SystemPolicyV1.SystemPolicyV1Client>(moq::MockBehavior.Strict);
GetSystemPolicyRequest request = new GetSystemPolicyRequest
{
PolicyName = PolicyName.FromProject("[PROJECT]"),
};
Policy expectedResponse = new Policy
{
PolicyName = PolicyName.FromProject("[PROJECT]"),
AdmissionWhitelistPatterns =
{
new AdmissionWhitelistPattern(),
},
ClusterAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
DefaultAdmissionRule = new AdmissionRule(),
UpdateTime = new wkt::Timestamp(),
Description = "description2cf9da67",
GlobalPolicyEvaluationMode = Policy.Types.GlobalPolicyEvaluationMode.Disable,
KubernetesServiceAccountAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
IstioServiceIdentityAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
KubernetesNamespaceAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
};
mockGrpcClient.Setup(x => x.GetSystemPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SystemPolicyV1Client client = new SystemPolicyV1ClientImpl(mockGrpcClient.Object, null);
Policy responseCallSettings = await client.GetSystemPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Policy responseCancellationToken = await client.GetSystemPolicyAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetSystemPolicy()
{
moq::Mock<SystemPolicyV1.SystemPolicyV1Client> mockGrpcClient = new moq::Mock<SystemPolicyV1.SystemPolicyV1Client>(moq::MockBehavior.Strict);
GetSystemPolicyRequest request = new GetSystemPolicyRequest
{
PolicyName = PolicyName.FromProject("[PROJECT]"),
};
Policy expectedResponse = new Policy
{
PolicyName = PolicyName.FromProject("[PROJECT]"),
AdmissionWhitelistPatterns =
{
new AdmissionWhitelistPattern(),
},
ClusterAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
DefaultAdmissionRule = new AdmissionRule(),
UpdateTime = new wkt::Timestamp(),
Description = "description2cf9da67",
GlobalPolicyEvaluationMode = Policy.Types.GlobalPolicyEvaluationMode.Disable,
KubernetesServiceAccountAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
IstioServiceIdentityAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
KubernetesNamespaceAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
};
mockGrpcClient.Setup(x => x.GetSystemPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SystemPolicyV1Client client = new SystemPolicyV1ClientImpl(mockGrpcClient.Object, null);
Policy response = client.GetSystemPolicy(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetSystemPolicyAsync()
{
moq::Mock<SystemPolicyV1.SystemPolicyV1Client> mockGrpcClient = new moq::Mock<SystemPolicyV1.SystemPolicyV1Client>(moq::MockBehavior.Strict);
GetSystemPolicyRequest request = new GetSystemPolicyRequest
{
PolicyName = PolicyName.FromProject("[PROJECT]"),
};
Policy expectedResponse = new Policy
{
PolicyName = PolicyName.FromProject("[PROJECT]"),
AdmissionWhitelistPatterns =
{
new AdmissionWhitelistPattern(),
},
ClusterAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
DefaultAdmissionRule = new AdmissionRule(),
UpdateTime = new wkt::Timestamp(),
Description = "description2cf9da67",
GlobalPolicyEvaluationMode = Policy.Types.GlobalPolicyEvaluationMode.Disable,
KubernetesServiceAccountAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
IstioServiceIdentityAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
KubernetesNamespaceAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
};
mockGrpcClient.Setup(x => x.GetSystemPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SystemPolicyV1Client client = new SystemPolicyV1ClientImpl(mockGrpcClient.Object, null);
Policy responseCallSettings = await client.GetSystemPolicyAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Policy responseCancellationToken = await client.GetSystemPolicyAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetSystemPolicyResourceNames()
{
moq::Mock<SystemPolicyV1.SystemPolicyV1Client> mockGrpcClient = new moq::Mock<SystemPolicyV1.SystemPolicyV1Client>(moq::MockBehavior.Strict);
GetSystemPolicyRequest request = new GetSystemPolicyRequest
{
PolicyName = PolicyName.FromProject("[PROJECT]"),
};
Policy expectedResponse = new Policy
{
PolicyName = PolicyName.FromProject("[PROJECT]"),
AdmissionWhitelistPatterns =
{
new AdmissionWhitelistPattern(),
},
ClusterAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
DefaultAdmissionRule = new AdmissionRule(),
UpdateTime = new wkt::Timestamp(),
Description = "description2cf9da67",
GlobalPolicyEvaluationMode = Policy.Types.GlobalPolicyEvaluationMode.Disable,
KubernetesServiceAccountAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
IstioServiceIdentityAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
KubernetesNamespaceAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
};
mockGrpcClient.Setup(x => x.GetSystemPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SystemPolicyV1Client client = new SystemPolicyV1ClientImpl(mockGrpcClient.Object, null);
Policy response = client.GetSystemPolicy(request.PolicyName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetSystemPolicyResourceNamesAsync()
{
moq::Mock<SystemPolicyV1.SystemPolicyV1Client> mockGrpcClient = new moq::Mock<SystemPolicyV1.SystemPolicyV1Client>(moq::MockBehavior.Strict);
GetSystemPolicyRequest request = new GetSystemPolicyRequest
{
PolicyName = PolicyName.FromProject("[PROJECT]"),
};
Policy expectedResponse = new Policy
{
PolicyName = PolicyName.FromProject("[PROJECT]"),
AdmissionWhitelistPatterns =
{
new AdmissionWhitelistPattern(),
},
ClusterAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
DefaultAdmissionRule = new AdmissionRule(),
UpdateTime = new wkt::Timestamp(),
Description = "description2cf9da67",
GlobalPolicyEvaluationMode = Policy.Types.GlobalPolicyEvaluationMode.Disable,
KubernetesServiceAccountAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
IstioServiceIdentityAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
KubernetesNamespaceAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
};
mockGrpcClient.Setup(x => x.GetSystemPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SystemPolicyV1Client client = new SystemPolicyV1ClientImpl(mockGrpcClient.Object, null);
Policy responseCallSettings = await client.GetSystemPolicyAsync(request.PolicyName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Policy responseCancellationToken = await client.GetSystemPolicyAsync(request.PolicyName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Vevo;
using Vevo.Domain;
using Vevo.Domain.DataInterfaces;
using Vevo.Domain.Shipping;
using Vevo.WebUI.Ajax;
using Vevo.WebAppLib;
using Vevo.Base.Domain;
public partial class Admin_MainControls_ShippingZoneGroupList : AdminAdvancedBaseUserControl
{
#region Private
private bool _emptyRow = false;
private bool IsContainingOnlyEmptyRow
{
get { return _emptyRow; }
set { _emptyRow = value; }
}
private GridViewHelper GridHelper
{
get
{
if (ViewState["GridHelper"] == null)
ViewState["GridHelper"] = new GridViewHelper( uxGrid, "ZoneGroupID" );
return (GridViewHelper) ViewState["GridHelper"];
}
}
private void SetUpSearchFilter()
{
IList<TableSchemaItem> list = DataAccessContext.ShippingZoneGroupRepository.GetTableSchemas();
uxSearchFilter.SetUpSchema( list );
}
private void SetFooterRowFocus()
{
Control textBox = uxGrid.FooterRow.FindControl( "uxNameText" );
AjaxUtilities.GetScriptManager( this ).SetFocus( textBox );
}
private void CreateDummyRow( IList<ShippingZoneGroup> list )
{
ShippingZoneGroup zoneGroup = new ShippingZoneGroup();
zoneGroup.ZoneGroupID = "-1";
list.Add( zoneGroup );
}
private void DeleteVisible( bool value )
{
uxDeleteButton.Visible = value;
if (value)
{
if (AdminConfig.CurrentTestMode == AdminConfig.TestMode.Normal)
{
uxDeleteConfirmButton.TargetControlID = "uxDeleteButton";
uxConfirmModalPopup.TargetControlID = "uxDeleteButton";
}
else
{
uxDeleteConfirmButton.TargetControlID = "uxDummyButton";
uxConfirmModalPopup.TargetControlID = "uxDummyButton";
}
}
else
{
uxDeleteConfirmButton.TargetControlID = "uxDummyButton";
uxConfirmModalPopup.TargetControlID = "uxDummyButton";
}
}
private void PopulateControls()
{
if (!MainContext.IsPostBack)
{
RefreshGrid();
}
if (uxGrid.Rows.Count > 0)
{
DeleteVisible( true );
uxPagingControl.Visible = true;
}
else
{
DeleteVisible( false );
uxPagingControl.Visible = false;
}
if (!IsAdminModifiable())
{
uxAddButton.Visible = false;
DeleteVisible( false );
}
}
private void RefreshGrid()
{
int totalItems;
IList<ShippingZoneGroup> list = DataAccessContext.ShippingZoneGroupRepository.SearchShippingZoneGroups(
GridHelper.GetFullSortText(),
uxSearchFilter.SearchFilterObj,
(uxPagingControl.CurrentPage - 1) * uxPagingControl.ItemsPerPages,
(uxPagingControl.CurrentPage * uxPagingControl.ItemsPerPages) - 1,
out totalItems );
if (list == null || list.Count == 0)
{
IsContainingOnlyEmptyRow = true;
list = new List<ShippingZoneGroup>();
CreateDummyRow( list );
}
else
{
IsContainingOnlyEmptyRow = false;
}
uxGrid.DataSource = list;
uxPagingControl.NumberOfPages = (int) Math.Ceiling( (double) totalItems / uxPagingControl.ItemsPerPages );
uxGrid.DataBind();
RefreshDeleteButton();
if (uxGrid.ShowFooter)
{
Control nameText = uxGrid.FooterRow.FindControl( "uxNameText" );
Control addButton = uxGrid.FooterRow.FindControl( "uxAddLinkButton" );
WebUtilities.TieButton( this.Page, nameText, addButton );
}
}
private void RefreshDeleteButton()
{
if (IsContainingOnlyEmptyRow)
uxDeleteButton.Visible = false;
else
uxDeleteButton.Visible = true;
}
private string[] GetCheckedIDs()
{
ArrayList items = new ArrayList();
foreach (GridViewRow row in uxGrid.Rows)
{
CheckBox deleteCheck = (CheckBox) row.FindControl( "uxCheck" );
if (deleteCheck.Checked)
{
string id = uxGrid.DataKeys[row.RowIndex]["ZoneGroupID"].ToString().Trim();
items.Add( id );
}
}
string[] result = new string[items.Count];
items.CopyTo( result );
return result;
}
private bool ContainsShippingOptions( string[] idArray, out string containingID )
{
foreach (string id in idArray)
{
IList<ShippingOption> shippingList = DataAccessContext.ShippingOptionRepository.GetAllByShippingZoneGroupID( Culture.Null, id );
if (shippingList.Count > 0)
{
containingID = id;
return true;
}
}
containingID = "";
return false;
}
private void DeleteItems( string[] checkedIDs )
{
try
{
bool deleted = false;
foreach (string id in checkedIDs)
{
DataAccessContext.ShippingZoneGroupRepository.Delete( id );
deleted = true;
}
uxGrid.EditIndex = -1;
if (deleted)
uxMessage.DisplayMessage( Resources.ShippingZoneMessages.DeleteSuccess );
}
catch (Exception ex)
{
uxMessage.DisplayException( ex );
}
RefreshGrid();
}
#endregion
#region Protected
protected void uxScarchChange( object sender, EventArgs e )
{
RefreshGrid();
}
protected void uxChangePage( object sender, EventArgs e )
{
RefreshGrid();
}
protected void uxGrid_DataBound( object sender, EventArgs e )
{
if (IsContainingOnlyEmptyRow)
{
uxGrid.Rows[0].Visible = false;
}
}
protected void uxDeleteButton_Click( object sender, EventArgs e )
{
string[] checkedIDs = GetCheckedIDs();
string containingID;
if (ContainsShippingOptions( checkedIDs, out containingID ))
{
ShippingZoneGroup zoneGroup = DataAccessContext.ShippingZoneGroupRepository.GetOne( containingID );
uxMessage.DisplayError(
Resources.ShippingZoneMessages.DeleteErrorContainingShippingOptions,
zoneGroup.ZoneName, containingID );
}
else
{
DeleteItems( checkedIDs );
}
}
protected void Page_Load( object sender, EventArgs e )
{
uxSearchFilter.BubbleEvent += new EventHandler( uxScarchChange );
uxPagingControl.BubbleEvent += new EventHandler( uxChangePage );
if (!MainContext.IsPostBack)
SetUpSearchFilter();
}
protected void Page_PreRender( object sender, EventArgs e )
{
PopulateControls();
}
protected void uxAddButton_Click( object sender, EventArgs e )
{
uxGrid.EditIndex = -1;
uxGrid.ShowFooter = true;
uxGrid.ShowHeader = true;
RefreshGrid();
uxAddButton.Visible = false;
SetFooterRowFocus();
}
protected void uxGrid_Sorting( object sender, GridViewSortEventArgs e )
{
GridHelper.SelectSorting( e.SortExpression );
RefreshGrid();
}
protected void uxGrid_RowEditing( object sender, GridViewEditEventArgs e )
{
uxGrid.EditIndex = e.NewEditIndex;
RefreshGrid();
}
protected void uxGrid_CancelingEdit( object sender, GridViewCancelEditEventArgs e )
{
uxGrid.EditIndex = -1;
RefreshGrid();
}
protected void uxGrid_RowCommand( object sender, GridViewCommandEventArgs e )
{
try
{
if (e.CommandName == "Add")
{
string name = ((TextBox) uxGrid.FooterRow.FindControl( "uxNameText" )).Text;
ShippingZoneGroup zoneGroup = new ShippingZoneGroup();
zoneGroup.ZoneName = name;
DataAccessContext.ShippingZoneGroupRepository.Save( zoneGroup );
((TextBox) uxGrid.FooterRow.FindControl( "uxNameText" )).Text = "";
uxMessage.DisplayMessage( Resources.ShippingZoneMessages.AddSuccess );
RefreshGrid();
}
else if (e.CommandName == "Edit")
{
uxGrid.ShowFooter = false;
uxAddButton.Visible = true;
}
}
catch (Exception ex)
{
uxMessage.DisplayException( ex );
}
}
protected void uxGrid_RowUpdating( object sender, GridViewUpdateEventArgs e )
{
try
{
string zoneGroupID = ((Label) uxGrid.Rows[e.RowIndex].FindControl( "uxZoneGroupIDLabel" )).Text;
string name = ((TextBox) uxGrid.Rows[e.RowIndex].FindControl( "uxNameText" )).Text;
if (!String.IsNullOrEmpty( zoneGroupID ))
{
ShippingZoneGroup zoneGroup = new ShippingZoneGroup();
zoneGroup.ZoneName = name;
zoneGroup.ZoneGroupID = zoneGroupID;
DataAccessContext.ShippingZoneGroupRepository.Save( zoneGroup );
}
// End editing
uxGrid.EditIndex = -1;
RefreshGrid();
uxMessage.DisplayMessage( Resources.ShippingZoneMessages.UpdateSuccess );
}
catch (Exception ex)
{
uxMessage.DisplayException( ex );
}
finally
{
// Avoid calling Update() automatically by GridView
e.Cancel = true;
}
}
#endregion
}
| |
// Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD.
// All rights reserved. Licensed under the BSD 3-Clause License; see License.txt.
using System;
using System.ComponentModel;
namespace Moq.Language
{
partial interface IRaise<T>
{
/// <summary>
/// Specifies the event that will be raised when the setup is matched.
/// </summary>
/// <param name="eventExpression">The expression that represents an event attach or detach action.</param>
/// <param name="func">The function that will build the <see cref="EventArgs"/>
/// to pass when raising the event.</param>
/// <typeparam name="T1">The type of the first argument received by the expected invocation.</typeparam>
/// <seealso cref="Raises(Action{T}, EventArgs)"/>
IVerifies Raises<T1>(Action<T> eventExpression, Func<T1, EventArgs> func);
/// <summary>
/// Specifies the event that will be raised when the setup is matched.
/// </summary>
/// <param name="eventExpression">The expression that represents an event attach or detach action.</param>
/// <param name="func">The function that will build the <see cref="EventArgs"/>
/// to pass when raising the event.</param>
/// <typeparam name="T1">The type of the first argument received by the expected invocation.</typeparam>
/// <typeparam name="T2">The type of the second argument received by the expected invocation.</typeparam>
/// <seealso cref="Raises(Action{T}, EventArgs)"/>
IVerifies Raises<T1, T2>(Action<T> eventExpression, Func<T1, T2, EventArgs> func);
/// <summary>
/// Specifies the event that will be raised when the setup is matched.
/// </summary>
/// <param name="eventExpression">The expression that represents an event attach or detach action.</param>
/// <param name="func">The function that will build the <see cref="EventArgs"/>
/// to pass when raising the event.</param>
/// <typeparam name="T1">The type of the first argument received by the expected invocation.</typeparam>
/// <typeparam name="T2">The type of the second argument received by the expected invocation.</typeparam>
/// <typeparam name="T3">The type of the third argument received by the expected invocation.</typeparam>
/// <seealso cref="Raises(Action{T}, EventArgs)"/>
IVerifies Raises<T1, T2, T3>(Action<T> eventExpression, Func<T1, T2, T3, EventArgs> func);
/// <summary>
/// Specifies the event that will be raised when the setup is matched.
/// </summary>
/// <param name="eventExpression">The expression that represents an event attach or detach action.</param>
/// <param name="func">The function that will build the <see cref="EventArgs"/>
/// to pass when raising the event.</param>
/// <typeparam name="T1">The type of the first argument received by the expected invocation.</typeparam>
/// <typeparam name="T2">The type of the second argument received by the expected invocation.</typeparam>
/// <typeparam name="T3">The type of the third argument received by the expected invocation.</typeparam>
/// <typeparam name="T4">The type of the fourth argument received by the expected invocation.</typeparam>
/// <seealso cref="Raises(Action{T}, EventArgs)"/>
IVerifies Raises<T1, T2, T3, T4>(Action<T> eventExpression, Func<T1, T2, T3, T4, EventArgs> func);
/// <summary>
/// Specifies the event that will be raised when the setup is matched.
/// </summary>
/// <param name="eventExpression">The expression that represents an event attach or detach action.</param>
/// <param name="func">The function that will build the <see cref="EventArgs"/>
/// to pass when raising the event.</param>
/// <typeparam name="T1">The type of the first argument received by the expected invocation.</typeparam>
/// <typeparam name="T2">The type of the second argument received by the expected invocation.</typeparam>
/// <typeparam name="T3">The type of the third argument received by the expected invocation.</typeparam>
/// <typeparam name="T4">The type of the fourth argument received by the expected invocation.</typeparam>
/// <typeparam name="T5">The type of the fifth argument received by the expected invocation.</typeparam>
/// <seealso cref="Raises(Action{T}, EventArgs)"/>
IVerifies Raises<T1, T2, T3, T4, T5>(Action<T> eventExpression, Func<T1, T2, T3, T4, T5, EventArgs> func);
/// <summary>
/// Specifies the event that will be raised when the setup is matched.
/// </summary>
/// <param name="eventExpression">The expression that represents an event attach or detach action.</param>
/// <param name="func">The function that will build the <see cref="EventArgs"/>
/// to pass when raising the event.</param>
/// <typeparam name="T1">The type of the first argument received by the expected invocation.</typeparam>
/// <typeparam name="T2">The type of the second argument received by the expected invocation.</typeparam>
/// <typeparam name="T3">The type of the third argument received by the expected invocation.</typeparam>
/// <typeparam name="T4">The type of the fourth argument received by the expected invocation.</typeparam>
/// <typeparam name="T5">The type of the fifth argument received by the expected invocation.</typeparam>
/// <typeparam name="T6">The type of the sixth argument received by the expected invocation.</typeparam>
/// <seealso cref="Raises(Action{T}, EventArgs)"/>
IVerifies Raises<T1, T2, T3, T4, T5, T6>(Action<T> eventExpression, Func<T1, T2, T3, T4, T5, T6, EventArgs> func);
/// <summary>
/// Specifies the event that will be raised when the setup is matched.
/// </summary>
/// <param name="eventExpression">The expression that represents an event attach or detach action.</param>
/// <param name="func">The function that will build the <see cref="EventArgs"/>
/// to pass when raising the event.</param>
/// <typeparam name="T1">The type of the first argument received by the expected invocation.</typeparam>
/// <typeparam name="T2">The type of the second argument received by the expected invocation.</typeparam>
/// <typeparam name="T3">The type of the third argument received by the expected invocation.</typeparam>
/// <typeparam name="T4">The type of the fourth argument received by the expected invocation.</typeparam>
/// <typeparam name="T5">The type of the fifth argument received by the expected invocation.</typeparam>
/// <typeparam name="T6">The type of the sixth argument received by the expected invocation.</typeparam>
/// <typeparam name="T7">The type of the seventh argument received by the expected invocation.</typeparam>
/// <seealso cref="Raises(Action{T}, EventArgs)"/>
IVerifies Raises<T1, T2, T3, T4, T5, T6, T7>(Action<T> eventExpression, Func<T1, T2, T3, T4, T5, T6, T7, EventArgs> func);
/// <summary>
/// Specifies the event that will be raised when the setup is matched.
/// </summary>
/// <param name="eventExpression">The expression that represents an event attach or detach action.</param>
/// <param name="func">The function that will build the <see cref="EventArgs"/>
/// to pass when raising the event.</param>
/// <typeparam name="T1">The type of the first argument received by the expected invocation.</typeparam>
/// <typeparam name="T2">The type of the second argument received by the expected invocation.</typeparam>
/// <typeparam name="T3">The type of the third argument received by the expected invocation.</typeparam>
/// <typeparam name="T4">The type of the fourth argument received by the expected invocation.</typeparam>
/// <typeparam name="T5">The type of the fifth argument received by the expected invocation.</typeparam>
/// <typeparam name="T6">The type of the sixth argument received by the expected invocation.</typeparam>
/// <typeparam name="T7">The type of the seventh argument received by the expected invocation.</typeparam>
/// <typeparam name="T8">The type of the eighth argument received by the expected invocation.</typeparam>
/// <seealso cref="Raises(Action{T}, EventArgs)"/>
IVerifies Raises<T1, T2, T3, T4, T5, T6, T7, T8>(Action<T> eventExpression, Func<T1, T2, T3, T4, T5, T6, T7, T8, EventArgs> func);
/// <summary>
/// Specifies the event that will be raised when the setup is matched.
/// </summary>
/// <param name="eventExpression">The expression that represents an event attach or detach action.</param>
/// <param name="func">The function that will build the <see cref="EventArgs"/>
/// to pass when raising the event.</param>
/// <typeparam name="T1">The type of the first argument received by the expected invocation.</typeparam>
/// <typeparam name="T2">The type of the second argument received by the expected invocation.</typeparam>
/// <typeparam name="T3">The type of the third argument received by the expected invocation.</typeparam>
/// <typeparam name="T4">The type of the fourth argument received by the expected invocation.</typeparam>
/// <typeparam name="T5">The type of the fifth argument received by the expected invocation.</typeparam>
/// <typeparam name="T6">The type of the sixth argument received by the expected invocation.</typeparam>
/// <typeparam name="T7">The type of the seventh argument received by the expected invocation.</typeparam>
/// <typeparam name="T8">The type of the eighth argument received by the expected invocation.</typeparam>
/// <typeparam name="T9">The type of the ninth argument received by the expected invocation.</typeparam>
/// <seealso cref="Raises(Action{T}, EventArgs)"/>
IVerifies Raises<T1, T2, T3, T4, T5, T6, T7, T8, T9>(Action<T> eventExpression, Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, EventArgs> func);
/// <summary>
/// Specifies the event that will be raised when the setup is matched.
/// </summary>
/// <param name="eventExpression">The expression that represents an event attach or detach action.</param>
/// <param name="func">The function that will build the <see cref="EventArgs"/>
/// to pass when raising the event.</param>
/// <typeparam name="T1">The type of the first argument received by the expected invocation.</typeparam>
/// <typeparam name="T2">The type of the second argument received by the expected invocation.</typeparam>
/// <typeparam name="T3">The type of the third argument received by the expected invocation.</typeparam>
/// <typeparam name="T4">The type of the fourth argument received by the expected invocation.</typeparam>
/// <typeparam name="T5">The type of the fifth argument received by the expected invocation.</typeparam>
/// <typeparam name="T6">The type of the sixth argument received by the expected invocation.</typeparam>
/// <typeparam name="T7">The type of the seventh argument received by the expected invocation.</typeparam>
/// <typeparam name="T8">The type of the eighth argument received by the expected invocation.</typeparam>
/// <typeparam name="T9">The type of the ninth argument received by the expected invocation.</typeparam>
/// <typeparam name="T10">The type of the tenth argument received by the expected invocation.</typeparam>
/// <seealso cref="Raises(Action{T}, EventArgs)"/>
IVerifies Raises<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(Action<T> eventExpression, Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, EventArgs> func);
/// <summary>
/// Specifies the event that will be raised when the setup is matched.
/// </summary>
/// <param name="eventExpression">The expression that represents an event attach or detach action.</param>
/// <param name="func">The function that will build the <see cref="EventArgs"/>
/// to pass when raising the event.</param>
/// <typeparam name="T1">The type of the first argument received by the expected invocation.</typeparam>
/// <typeparam name="T2">The type of the second argument received by the expected invocation.</typeparam>
/// <typeparam name="T3">The type of the third argument received by the expected invocation.</typeparam>
/// <typeparam name="T4">The type of the fourth argument received by the expected invocation.</typeparam>
/// <typeparam name="T5">The type of the fifth argument received by the expected invocation.</typeparam>
/// <typeparam name="T6">The type of the sixth argument received by the expected invocation.</typeparam>
/// <typeparam name="T7">The type of the seventh argument received by the expected invocation.</typeparam>
/// <typeparam name="T8">The type of the eighth argument received by the expected invocation.</typeparam>
/// <typeparam name="T9">The type of the ninth argument received by the expected invocation.</typeparam>
/// <typeparam name="T10">The type of the tenth argument received by the expected invocation.</typeparam>
/// <typeparam name="T11">The type of the eleventh argument received by the expected invocation.</typeparam>
/// <seealso cref="Raises(Action{T}, EventArgs)"/>
IVerifies Raises<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(Action<T> eventExpression, Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, EventArgs> func);
/// <summary>
/// Specifies the event that will be raised when the setup is matched.
/// </summary>
/// <param name="eventExpression">The expression that represents an event attach or detach action.</param>
/// <param name="func">The function that will build the <see cref="EventArgs"/>
/// to pass when raising the event.</param>
/// <typeparam name="T1">The type of the first argument received by the expected invocation.</typeparam>
/// <typeparam name="T2">The type of the second argument received by the expected invocation.</typeparam>
/// <typeparam name="T3">The type of the third argument received by the expected invocation.</typeparam>
/// <typeparam name="T4">The type of the fourth argument received by the expected invocation.</typeparam>
/// <typeparam name="T5">The type of the fifth argument received by the expected invocation.</typeparam>
/// <typeparam name="T6">The type of the sixth argument received by the expected invocation.</typeparam>
/// <typeparam name="T7">The type of the seventh argument received by the expected invocation.</typeparam>
/// <typeparam name="T8">The type of the eighth argument received by the expected invocation.</typeparam>
/// <typeparam name="T9">The type of the ninth argument received by the expected invocation.</typeparam>
/// <typeparam name="T10">The type of the tenth argument received by the expected invocation.</typeparam>
/// <typeparam name="T11">The type of the eleventh argument received by the expected invocation.</typeparam>
/// <typeparam name="T12">The type of the twelfth argument received by the expected invocation.</typeparam>
/// <seealso cref="Raises(Action{T}, EventArgs)"/>
IVerifies Raises<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(Action<T> eventExpression, Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, EventArgs> func);
/// <summary>
/// Specifies the event that will be raised when the setup is matched.
/// </summary>
/// <param name="eventExpression">The expression that represents an event attach or detach action.</param>
/// <param name="func">The function that will build the <see cref="EventArgs"/>
/// to pass when raising the event.</param>
/// <typeparam name="T1">The type of the first argument received by the expected invocation.</typeparam>
/// <typeparam name="T2">The type of the second argument received by the expected invocation.</typeparam>
/// <typeparam name="T3">The type of the third argument received by the expected invocation.</typeparam>
/// <typeparam name="T4">The type of the fourth argument received by the expected invocation.</typeparam>
/// <typeparam name="T5">The type of the fifth argument received by the expected invocation.</typeparam>
/// <typeparam name="T6">The type of the sixth argument received by the expected invocation.</typeparam>
/// <typeparam name="T7">The type of the seventh argument received by the expected invocation.</typeparam>
/// <typeparam name="T8">The type of the eighth argument received by the expected invocation.</typeparam>
/// <typeparam name="T9">The type of the ninth argument received by the expected invocation.</typeparam>
/// <typeparam name="T10">The type of the tenth argument received by the expected invocation.</typeparam>
/// <typeparam name="T11">The type of the eleventh argument received by the expected invocation.</typeparam>
/// <typeparam name="T12">The type of the twelfth argument received by the expected invocation.</typeparam>
/// <typeparam name="T13">The type of the thirteenth argument received by the expected invocation.</typeparam>
/// <seealso cref="Raises(Action{T}, EventArgs)"/>
IVerifies Raises<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(Action<T> eventExpression, Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, EventArgs> func);
/// <summary>
/// Specifies the event that will be raised when the setup is matched.
/// </summary>
/// <param name="eventExpression">The expression that represents an event attach or detach action.</param>
/// <param name="func">The function that will build the <see cref="EventArgs"/>
/// to pass when raising the event.</param>
/// <typeparam name="T1">The type of the first argument received by the expected invocation.</typeparam>
/// <typeparam name="T2">The type of the second argument received by the expected invocation.</typeparam>
/// <typeparam name="T3">The type of the third argument received by the expected invocation.</typeparam>
/// <typeparam name="T4">The type of the fourth argument received by the expected invocation.</typeparam>
/// <typeparam name="T5">The type of the fifth argument received by the expected invocation.</typeparam>
/// <typeparam name="T6">The type of the sixth argument received by the expected invocation.</typeparam>
/// <typeparam name="T7">The type of the seventh argument received by the expected invocation.</typeparam>
/// <typeparam name="T8">The type of the eighth argument received by the expected invocation.</typeparam>
/// <typeparam name="T9">The type of the ninth argument received by the expected invocation.</typeparam>
/// <typeparam name="T10">The type of the tenth argument received by the expected invocation.</typeparam>
/// <typeparam name="T11">The type of the eleventh argument received by the expected invocation.</typeparam>
/// <typeparam name="T12">The type of the twelfth argument received by the expected invocation.</typeparam>
/// <typeparam name="T13">The type of the thirteenth argument received by the expected invocation.</typeparam>
/// <typeparam name="T14">The type of the fourteenth argument received by the expected invocation.</typeparam>
/// <seealso cref="Raises(Action{T}, EventArgs)"/>
IVerifies Raises<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14>(Action<T> eventExpression, Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, EventArgs> func);
/// <summary>
/// Specifies the event that will be raised when the setup is matched.
/// </summary>
/// <param name="eventExpression">The expression that represents an event attach or detach action.</param>
/// <param name="func">The function that will build the <see cref="EventArgs"/>
/// to pass when raising the event.</param>
/// <typeparam name="T1">The type of the first argument received by the expected invocation.</typeparam>
/// <typeparam name="T2">The type of the second argument received by the expected invocation.</typeparam>
/// <typeparam name="T3">The type of the third argument received by the expected invocation.</typeparam>
/// <typeparam name="T4">The type of the fourth argument received by the expected invocation.</typeparam>
/// <typeparam name="T5">The type of the fifth argument received by the expected invocation.</typeparam>
/// <typeparam name="T6">The type of the sixth argument received by the expected invocation.</typeparam>
/// <typeparam name="T7">The type of the seventh argument received by the expected invocation.</typeparam>
/// <typeparam name="T8">The type of the eighth argument received by the expected invocation.</typeparam>
/// <typeparam name="T9">The type of the ninth argument received by the expected invocation.</typeparam>
/// <typeparam name="T10">The type of the tenth argument received by the expected invocation.</typeparam>
/// <typeparam name="T11">The type of the eleventh argument received by the expected invocation.</typeparam>
/// <typeparam name="T12">The type of the twelfth argument received by the expected invocation.</typeparam>
/// <typeparam name="T13">The type of the thirteenth argument received by the expected invocation.</typeparam>
/// <typeparam name="T14">The type of the fourteenth argument received by the expected invocation.</typeparam>
/// <typeparam name="T15">The type of the fifteenth argument received by the expected invocation.</typeparam>
/// <seealso cref="Raises(Action{T}, EventArgs)"/>
IVerifies Raises<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15>(Action<T> eventExpression, Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, EventArgs> func);
/// <summary>
/// Specifies the event that will be raised when the setup is matched.
/// </summary>
/// <param name="eventExpression">The expression that represents an event attach or detach action.</param>
/// <param name="func">The function that will build the <see cref="EventArgs"/>
/// to pass when raising the event.</param>
/// <typeparam name="T1">The type of the first argument received by the expected invocation.</typeparam>
/// <typeparam name="T2">The type of the second argument received by the expected invocation.</typeparam>
/// <typeparam name="T3">The type of the third argument received by the expected invocation.</typeparam>
/// <typeparam name="T4">The type of the fourth argument received by the expected invocation.</typeparam>
/// <typeparam name="T5">The type of the fifth argument received by the expected invocation.</typeparam>
/// <typeparam name="T6">The type of the sixth argument received by the expected invocation.</typeparam>
/// <typeparam name="T7">The type of the seventh argument received by the expected invocation.</typeparam>
/// <typeparam name="T8">The type of the eighth argument received by the expected invocation.</typeparam>
/// <typeparam name="T9">The type of the ninth argument received by the expected invocation.</typeparam>
/// <typeparam name="T10">The type of the tenth argument received by the expected invocation.</typeparam>
/// <typeparam name="T11">The type of the eleventh argument received by the expected invocation.</typeparam>
/// <typeparam name="T12">The type of the twelfth argument received by the expected invocation.</typeparam>
/// <typeparam name="T13">The type of the thirteenth argument received by the expected invocation.</typeparam>
/// <typeparam name="T14">The type of the fourteenth argument received by the expected invocation.</typeparam>
/// <typeparam name="T15">The type of the fifteenth argument received by the expected invocation.</typeparam>
/// <typeparam name="T16">The type of the sixteenth argument received by the expected invocation.</typeparam>
/// <seealso cref="Raises(Action{T}, EventArgs)"/>
IVerifies Raises<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16>(Action<T> eventExpression, Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, EventArgs> func);
}
}
| |
using System;
using NBitcoin.BouncyCastle.Crypto.Parameters;
namespace NBitcoin.BouncyCastle.Crypto.Engines
{
/**
* A class that provides a basic International Data Encryption Algorithm (IDEA) engine.
* <p>
* This implementation is based on the "HOWTO: INTERNATIONAL DATA ENCRYPTION ALGORITHM"
* implementation summary by Fauzan Mirza (F.U.Mirza@sheffield.ac.uk). (baring 1 typo at the
* end of the mulinv function!).
* </p>
* <p>
* It can be found at ftp://ftp.funet.fi/pub/crypt/cryptography/symmetric/idea/
* </p>
* <p>
* Note 1: This algorithm is patented in the USA, Japan, and Europe including
* at least Austria, France, Germany, Italy, Netherlands, Spain, Sweden, Switzerland
* and the United Kingdom. Non-commercial use is free, however any commercial
* products are liable for royalties. Please see
* <a href="http://www.mediacrypt.com">www.mediacrypt.com</a> for
* further details. This announcement has been included at the request of
* the patent holders.
* </p>
* <p>
* Note 2: Due to the requests concerning the above, this algorithm is now only
* included in the extended assembly. It is not included in the default distributions.
* </p>
*/
public class IdeaEngine
: IBlockCipher
{
private const int BLOCK_SIZE = 8;
private int[] workingKey;
/**
* standard constructor.
*/
public IdeaEngine()
{
}
/**
* initialise an IDEA cipher.
*
* @param forEncryption whether or not we are for encryption.
* @param parameters the parameters required to set up the cipher.
* @exception ArgumentException if the parameters argument is
* inappropriate.
*/
public void Init(
bool forEncryption,
ICipherParameters parameters)
{
if (!(parameters is KeyParameter))
throw new ArgumentException("invalid parameter passed to IDEA init - " + parameters.GetType().ToString());
workingKey = GenerateWorkingKey(forEncryption,
((KeyParameter)parameters).GetKey());
}
public string AlgorithmName
{
get { return "IDEA"; }
}
public bool IsPartialBlockOkay
{
get { return false; }
}
public int GetBlockSize()
{
return BLOCK_SIZE;
}
public int ProcessBlock(
byte[] input,
int inOff,
byte[] output,
int outOff)
{
if (workingKey == null)
{
throw new InvalidOperationException("IDEA engine not initialised");
}
if ((inOff + BLOCK_SIZE) > input.Length)
{
throw new DataLengthException("input buffer too short");
}
if ((outOff + BLOCK_SIZE) > output.Length)
{
throw new DataLengthException("output buffer too short");
}
IdeaFunc(workingKey, input, inOff, output, outOff);
return BLOCK_SIZE;
}
public void Reset()
{
}
private static readonly int MASK = 0xffff;
private static readonly int BASE = 0x10001;
private int BytesToWord(
byte[] input,
int inOff)
{
return ((input[inOff] << 8) & 0xff00) + (input[inOff + 1] & 0xff);
}
private void WordToBytes(
int word,
byte[] outBytes,
int outOff)
{
outBytes[outOff] = (byte)((uint) word >> 8);
outBytes[outOff + 1] = (byte)word;
}
/**
* return x = x * y where the multiplication is done modulo
* 65537 (0x10001) (as defined in the IDEA specification) and
* a zero input is taken to be 65536 (0x10000).
*
* @param x the x value
* @param y the y value
* @return x = x * y
*/
private int Mul(
int x,
int y)
{
if (x == 0)
{
x = (BASE - y);
}
else if (y == 0)
{
x = (BASE - x);
}
else
{
int p = x * y;
y = p & MASK;
x = (int) ((uint) p >> 16);
x = y - x + ((y < x) ? 1 : 0);
}
return x & MASK;
}
private void IdeaFunc(
int[] workingKey,
byte[] input,
int inOff,
byte[] outBytes,
int outOff)
{
int x0, x1, x2, x3, t0, t1;
int keyOff = 0;
x0 = BytesToWord(input, inOff);
x1 = BytesToWord(input, inOff + 2);
x2 = BytesToWord(input, inOff + 4);
x3 = BytesToWord(input, inOff + 6);
for (int round = 0; round < 8; round++)
{
x0 = Mul(x0, workingKey[keyOff++]);
x1 += workingKey[keyOff++];
x1 &= MASK;
x2 += workingKey[keyOff++];
x2 &= MASK;
x3 = Mul(x3, workingKey[keyOff++]);
t0 = x1;
t1 = x2;
x2 ^= x0;
x1 ^= x3;
x2 = Mul(x2, workingKey[keyOff++]);
x1 += x2;
x1 &= MASK;
x1 = Mul(x1, workingKey[keyOff++]);
x2 += x1;
x2 &= MASK;
x0 ^= x1;
x3 ^= x2;
x1 ^= t1;
x2 ^= t0;
}
WordToBytes(Mul(x0, workingKey[keyOff++]), outBytes, outOff);
WordToBytes(x2 + workingKey[keyOff++], outBytes, outOff + 2); /* NB: Order */
WordToBytes(x1 + workingKey[keyOff++], outBytes, outOff + 4);
WordToBytes(Mul(x3, workingKey[keyOff]), outBytes, outOff + 6);
}
/**
* The following function is used to expand the user key to the encryption
* subkey. The first 16 bytes are the user key, and the rest of the subkey
* is calculated by rotating the previous 16 bytes by 25 bits to the left,
* and so on until the subkey is completed.
*/
private int[] ExpandKey(
byte[] uKey)
{
int[] key = new int[52];
if (uKey.Length < 16)
{
byte[] tmp = new byte[16];
Array.Copy(uKey, 0, tmp, tmp.Length - uKey.Length, uKey.Length);
uKey = tmp;
}
for (int i = 0; i < 8; i++)
{
key[i] = BytesToWord(uKey, i * 2);
}
for (int i = 8; i < 52; i++)
{
if ((i & 7) < 6)
{
key[i] = ((key[i - 7] & 127) << 9 | key[i - 6] >> 7) & MASK;
}
else if ((i & 7) == 6)
{
key[i] = ((key[i - 7] & 127) << 9 | key[i - 14] >> 7) & MASK;
}
else
{
key[i] = ((key[i - 15] & 127) << 9 | key[i - 14] >> 7) & MASK;
}
}
return key;
}
/**
* This function computes multiplicative inverse using Euclid's Greatest
* Common Divisor algorithm. Zero and one are self inverse.
* <p>
* i.e. x * MulInv(x) == 1 (modulo BASE)
* </p>
*/
private int MulInv(
int x)
{
int t0, t1, q, y;
if (x < 2)
{
return x;
}
t0 = 1;
t1 = BASE / x;
y = BASE % x;
while (y != 1)
{
q = x / y;
x = x % y;
t0 = (t0 + (t1 * q)) & MASK;
if (x == 1)
{
return t0;
}
q = y / x;
y = y % x;
t1 = (t1 + (t0 * q)) & MASK;
}
return (1 - t1) & MASK;
}
/**
* Return the additive inverse of x.
* <p>
* i.e. x + AddInv(x) == 0
* </p>
*/
int AddInv(
int x)
{
return (0 - x) & MASK;
}
/**
* The function to invert the encryption subkey to the decryption subkey.
* It also involves the multiplicative inverse and the additive inverse functions.
*/
private int[] InvertKey(
int[] inKey)
{
int t1, t2, t3, t4;
int p = 52; /* We work backwards */
int[] key = new int[52];
int inOff = 0;
t1 = MulInv(inKey[inOff++]);
t2 = AddInv(inKey[inOff++]);
t3 = AddInv(inKey[inOff++]);
t4 = MulInv(inKey[inOff++]);
key[--p] = t4;
key[--p] = t3;
key[--p] = t2;
key[--p] = t1;
for (int round = 1; round < 8; round++)
{
t1 = inKey[inOff++];
t2 = inKey[inOff++];
key[--p] = t2;
key[--p] = t1;
t1 = MulInv(inKey[inOff++]);
t2 = AddInv(inKey[inOff++]);
t3 = AddInv(inKey[inOff++]);
t4 = MulInv(inKey[inOff++]);
key[--p] = t4;
key[--p] = t2; /* NB: Order */
key[--p] = t3;
key[--p] = t1;
}
t1 = inKey[inOff++];
t2 = inKey[inOff++];
key[--p] = t2;
key[--p] = t1;
t1 = MulInv(inKey[inOff++]);
t2 = AddInv(inKey[inOff++]);
t3 = AddInv(inKey[inOff++]);
t4 = MulInv(inKey[inOff]);
key[--p] = t4;
key[--p] = t3;
key[--p] = t2;
key[--p] = t1;
return key;
}
private int[] GenerateWorkingKey(
bool forEncryption,
byte[] userKey)
{
if (forEncryption)
{
return ExpandKey(userKey);
}
else
{
return InvertKey(ExpandKey(userKey));
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void MaxInt16()
{
var test = new SimpleBinaryOpTest__MaxInt16();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__MaxInt16
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(Int16);
private const int Op2ElementCount = VectorSize / sizeof(Int16);
private const int RetElementCount = VectorSize / sizeof(Int16);
private static Int16[] _data1 = new Int16[Op1ElementCount];
private static Int16[] _data2 = new Int16[Op2ElementCount];
private static Vector128<Int16> _clsVar1;
private static Vector128<Int16> _clsVar2;
private Vector128<Int16> _fld1;
private Vector128<Int16> _fld2;
private SimpleBinaryOpTest__DataTable<Int16, Int16, Int16> _dataTable;
static SimpleBinaryOpTest__MaxInt16()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), VectorSize);
}
public SimpleBinaryOpTest__MaxInt16()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
_dataTable = new SimpleBinaryOpTest__DataTable<Int16, Int16, Int16>(_data1, _data2, new Int16[RetElementCount], VectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse2.Max(
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse2.Max(
Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse2.Max(
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Max), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Max), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Max), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse2.Max(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr);
var result = Sse2.Max(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr));
var result = Sse2.Max(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr));
var result = Sse2.Max(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__MaxInt16();
var result = Sse2.Max(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse2.Max(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Int16> left, Vector128<Int16> right, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int16[] left, Int16[] right, Int16[] result, [CallerMemberName] string method = "")
{
if (Math.Max(left[0], right[0]) != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (Math.Max(left[i], right[i]) != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.Max)}<Int16>(Vector128<Int16>, Vector128<Int16>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
#if UNITY_EDITOR
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using TNRD.Automatron.Drawers;
using TNRD.Automatron.Editor;
using TNRD.Automatron.Editor.Core;
using TNRD.Automatron.Editor.Serialization;
using TNRD.Automatron.Editor.Utilities;
using TNRD.Automatron.Editor.Windows;
using UnityEditor;
using UnityEngine;
namespace TNRD.Automatron {
public class AutomatronEditor : ExtendedWindow {
#region Automation Loading
private static Dictionary<string, Type> automations = new Dictionary<string, Type>();
[InitializeOnLoadMethod]
private static void LoadAutomations() {
var mush = from assembly in AppDomain.CurrentDomain.GetAssemblies()
from type in assembly.GetTypes()
let attributes = type.GetCustomAttributes( typeof( AutomationAttribute ), true )
where attributes != null && attributes.Length > 0
select new { AutomationType = type, Attributes = attributes.Cast<AutomationAttribute>() };
mush = mush.OrderBy( m => m.Attributes.ElementAt( 0 ).Name );
foreach ( var item in mush ) {
var name = item.Attributes.ElementAt( 0 ).Name;
if ( !automations.ContainsKey( name ) ) {
automations.Add( name, item.AutomationType );
} else {
Debug.Log( "Double for " + name );
}
}
}
#endregion
#region Drawer Loading
private static Dictionary<Type, Type> drawers = new Dictionary<Type, Type>();
[InitializeOnLoadMethod]
private static void LoadDrawers() {
var mush = from assembly in AppDomain.CurrentDomain.GetAssemblies()
from type in assembly.GetTypes()
let attributes = type.GetCustomAttributes( typeof( CustomDrawerAttribute ), true )
where attributes != null && attributes.Length > 0
select new { DrawerType = type, Attributes = attributes.Cast<CustomDrawerAttribute>() };
foreach ( var item in mush ) {
var type = item.Attributes.ElementAt( 0 ).Type;
if ( !drawers.ContainsKey( type ) ) {
drawers.Add( type, item.DrawerType );
}
}
}
public static Type GetDrawerType( Type fieldType ) {
if ( drawers.ContainsKey( fieldType ) ) {
return drawers[fieldType];
} else {
return typeof( HelpDrawer );
}
}
#endregion
#region Type Loading
[InitializeOnLoadMethod]
private static void LoadTypes() {
Globals.Types = GetAssemblyTypes(
"Assembly-CSharp",
"Assembly-CSharp-Editor",
"UnityEngine",
"UnityEditor" );
}
private static List<Type> GetAssemblyTypes( params string[] names ) {
var list = new List<Type>();
foreach ( var item in names ) {
try {
var assembly = Assembly.Load( item );
list.AddRange( assembly.GetTypes()
.Where( t => t.IsPublic )
.Where( t => !t.Name.StartsWith( "<" ) && !t.Name.StartsWith( "$" ) ) );
} catch ( System.IO.FileNotFoundException ) {
// this library doesn't exist (yet)
continue;
}
}
return list;
}
#endregion
public string Name;
public string Path;
private InternalQueueStart entryPoint;
[RequireSerialization]
public string EntryId;
private GUIContent executeContent;
private GUIContent stopContent;
private GUIContent trashContent;
private GUIContent resetContent;
private EditorCoroutine executionRoutine = null;
private EditorCoroutine lookAtRoutine = null;
[IgnoreSerialization]
private AutomationTemplator templator;
[RequireSerialization]
private Vector2 camera;
private bool spacePan = false;
private bool mousePan = false;
public void NewAutomatron( string path, string name ) {
Name = name;
Path = path;
entryPoint = new InternalQueueStart() {
Position = WindowRect.center
};
AddControl( entryPoint );
EntryId = entryPoint.ID;
Globals.Camera = new Vector2();
Save();
}
public void LoadAutomatron( string path ) {
var a = AutomatronSerializer.Load( path );
if ( a == null ) {
return;
}
Globals.Camera = a.Camera;
Name = a.Name;
Path = a.Path;
foreach ( var item in a.Automations ) {
var type = Globals.Types.Where( t => t.FullName == item.Type ).FirstOrDefault();
if ( type == null ) {
type = Type.GetType( item.Type );
}
if ( type == null ) continue;
var pos = item.Position;
var instance = (Automation)Activator.CreateInstance( type );
instance.Position = pos;
AddControl( instance );
instance.ID = item.ID;
instance.LoadFields();
foreach ( var f in item.Fields ) {
var fid = instance.GetField( f.ID );
if ( fid != null ) {
fid.SetValue( f.Value );
}
}
if ( item.ID == a.EntryID ) {
entryPoint = (InternalQueueStart)instance;
EntryId = entryPoint.ID;
}
}
var automations = GetControls<Automation>();
foreach ( var item in a.Lines ) {
if ( item.LineType == ELineType.FieldLine ) {
var left = automations.Where( auto => auto.HasField( item.IdLeft ) ).FirstOrDefault();
var right = automations.Where( auto => auto.HasField( item.IdRight ) ).FirstOrDefault();
if ( left == null || right == null ) continue;
var line = new FieldLine( left.GetField( item.IdLeft ), right.GetField( item.IdRight ) );
AddControl( line );
} else {
var left = automations.Where( auto => auto.ID == item.IdLeft ).FirstOrDefault();
var right = automations.Where( auto => auto.ID == item.IdRight ).FirstOrDefault();
if ( left == null || right == null ) continue;
BezierLine line = null;
switch ( item.LineType ) {
case ELineType.AutomationLine:
line = new AutomationLine( left, right );
break;
case ELineType.ConditionalLine:
line = new ConditionalLine( (ConditionalAutomation)left, right );
break;
case ELineType.LoopableLine:
line = new LoopableLine( (LoopableAutomation)left, right );
break;
}
if ( line != null ) {
AddControl( line );
line.ID = item.ID;
}
}
}
var id = GetControlID();
if ( id < a.ControlID ) {
var amount = a.ControlID - id;
for ( int i = 0; i < amount; i++ ) {
GetControlID();
}
}
if ( entryPoint == null ) {
entryPoint = new InternalQueueStart() {
Position = WindowRect.center
};
AddControl( entryPoint );
EntryId = entryPoint.ID;
}
}
protected override void OnInitialize() {
WindowStyle = EWindowStyle.NoToolbarLight;
WindowSettings.IsFullscreen = true;
CreateIcons();
Globals.IsError = false;
Globals.IsExecuting = false;
Globals.LastError = null;
Globals.TempAutomationLine = null;
Globals.TempFieldLine = null;
templator = new AutomationTemplator( this );
}
protected override void OnBeforeSerialize() {
EntryId = entryPoint.ID;
if ( lookAtRoutine != null ) {
lookAtRoutine.Stop();
}
camera = Globals.Camera;
}
protected override void OnAfterSerialized() {
var entries = GetControls<InternalQueueStart>();
foreach ( var item in entries ) {
if ( item.ID == EntryId ) {
entryPoint = item;
break;
}
}
WindowSettings.IsFullscreen = true;
Globals.Camera = camera;
CreateIcons();
templator = new AutomationTemplator( this );
}
protected override void OnGUI() {
EditorGUILayout.BeginHorizontal( EditorStyles.toolbar );
EditorGUI.BeginDisabledGroup( Globals.IsExecuting );
if ( GUILayout.Button( "File", EditorStyles.toolbarDropDown ) ) {
var gm = GenericMenuBuilder.CreateMenu();
gm.AddItem( "New Automatron", false, () => {
AddWindow( new AutomatronMenu( 1 ) );
Remove();
} );
gm.AddItem( "Open Automatron", false, () => {
AddWindow( new AutomatronMenu() );
Remove();
} );
gm.AddSeparator();
gm.AddItem( "Save Automatron", false, () => {
AutomatronSerializer.Save( this );
ShowNotification( "Automatron saved" );
} );
gm.AddItem( "Save Automatron As...", false, () => {
ShowPopup( new InputBox(
"Save Automatron As...",
"Please insert a new name for the Automatron",
( EDialogResult result, string input ) => {
if ( result == EDialogResult.OK && !string.IsNullOrEmpty( input ) ) {
Name = input;
Save();
ShowNotification( string.Format( "Automatron saved as '{0}'", input ) );
}
} ) );
} );
gm.AddSeparator();
gm.AddItem( "Create.../Automation", false, () => {
ShowPopup( new InputBox(
"Create Automation",
"Please insert the name for your Automation",
( EDialogResult result, string input ) => {
if ( result == EDialogResult.OK && !string.IsNullOrEmpty( input ) ) {
templator.CreateAutomation( input );
}
} ) );
} );
gm.AddItem( "Create.../Conditional Automation", false, () => {
ShowPopup( new InputBox(
"Create Conditional Automation",
"Please insert the name for your Automation",
( EDialogResult result, string input ) => {
if ( result == EDialogResult.OK && !string.IsNullOrEmpty( input ) ) {
templator.CreateConditionalAutomation( input );
}
} ) );
} );
gm.AddItem( "Create.../Loopable Automation", false, () => {
ShowPopup( new InputBox(
"Create Loopable Automation",
"Please insert the name for your Automation",
( EDialogResult result, string input ) => {
if ( result == EDialogResult.OK && !string.IsNullOrEmpty( input ) ) {
templator.CreateLoopableAutomation( input );
}
} ) );
} );
gm.AddSeparator( "Create.../" );
gm.AddItem( "Create.../Generator", false, () => {
Generation.Generator.CreateMe();
} );
gm.AddSeparator();
gm.AddItem( "Settings", false, () => {
PreferencesWindow.Show( "Automatron" );
} );
gm.AddSeparator();
gm.AddItem( "Exit", false, () => {
Editor.Close();
} );
gm.ShowAsContext();
}
if ( GUILayout.Button( "Automations", EditorStyles.toolbarDropDown ) ) {
ShowAutomationPopup();
}
EditorGUI.EndDisabledGroup();
// Spacer
GUILayout.Button( "", EditorStyles.toolbarButton );
if ( Globals.IsExecuting ) {
if ( GUILayout.Button( stopContent, EditorStyles.toolbarButton ) ) {
executionRoutine.Stop();
executionRoutine = null;
Globals.IsExecuting = false;
}
} else {
if ( GUILayout.Button( executeContent, EditorStyles.toolbarButton ) ) {
ExecuteAutomations();
}
}
EditorGUI.BeginDisabledGroup( Globals.IsExecuting );
if ( GUILayout.Button( resetContent, EditorStyles.toolbarButton ) ) {
var list = GetControls<Automation>();
foreach ( var item in list ) {
item.Reset();
item.ResetFields();
}
}
if ( GUILayout.Button( trashContent, EditorStyles.toolbarButton ) ) {
ShowPopup( new MessageBox( "Caution!", "You're about to empty this Automatron...\nAre you sure you want to do this?", EMessageBoxButtons.YesNo, ( EDialogResult result ) => {
if ( result == EDialogResult.Yes ) {
var controls = GetControls<ExtendedControl>();
for ( int i = controls.Count - 1; i >= 0; i-- ) {
var item = controls[i];
if ( item != entryPoint ) {
item.Remove();
}
}
entryPoint.Reset();
Globals.Camera = new Vector2();
entryPoint.Position = WindowRect.center;
}
} ) );
}
EditorGUI.EndDisabledGroup();
GUILayout.FlexibleSpace();
if ( GUILayout.Button( "Help", EditorStyles.toolbarDropDown ) ) {
GenericMenuBuilder.CreateMenu()
.AddItem( "Documentation", false, OpenDocumentation )
.AddItem( "Reference", false, OpenReference )
.ShowAsContext();
}
EditorGUILayout.EndHorizontal();
if ( Input.KeyReleased( KeyCode.F1 ) ) {
OpenDocumentation();
} else if ( Input.KeyReleased( KeyCode.F2 ) ) {
OpenReference();
}
if ( Event.current.keyCode == KeyCode.Space ) {
if ( Event.current.type == EventType.KeyDown ) {
spacePan = true;
Event.current.Use();
} else if ( Event.current.type == EventType.KeyUp ) {
spacePan = false;
Event.current.Use();
}
}
if ( Input.ButtonPressed( EMouseButton.Middle ) ) {
mousePan = true;
} else if ( Input.ButtonDown( EMouseButton.Middle ) ) {
Globals.Camera += Input.DragDelta;
} else if ( Input.ButtonReleased( EMouseButton.Middle ) || Input.ButtonUp( EMouseButton.Middle ) ) {
mousePan = false;
}
if ( spacePan || mousePan ) {
EditorGUIUtility.AddCursorRect( new Rect( 0, 0, Size.x, Size.y ), MouseCursor.Pan );
if ( !mousePan && ( Input.ButtonDown( EMouseButton.Left ) || Input.ButtonDown( EMouseButton.Right ) ) ) {
Globals.Camera += Input.DragDelta;
}
} else if ( Input.ButtonReleased( EMouseButton.Right ) ) {
ShowAutomationPopup();
Input.Use();
}
if ( AutomatronSettings.AutoSave ) {
if ( Input.ButtonReleased( EMouseButton.Left ) ) {
Save();
Input.Use();
}
}
Repaint();
}
private void OpenDocumentation() {
Application.OpenURL( "http://tnrd.net/automatron" );
}
private void OpenReference() {
Application.OpenURL( "http://tnrd.net/automatron/reference" );
}
private void CreateIcons() {
// Secretly reusing the foldOut
executeContent = new GUIContent( Assets["foldOut"], "Execute the automation sequence" );
stopContent = new GUIContent( Assets["stop"], "Stop the active automation sequence" );
resetContent = new GUIContent( Assets["reset"], "Reset the values and progress of the automations" );
trashContent = new GUIContent( Assets["trash"], "Remove all the automations" );
}
private void ShowAutomationPopup() {
if ( Globals.IsExecuting ) return;
var items = new List<AutomationPopup.TreeItem>();
foreach ( var item in automations ) {
items.Add( new AutomationPopup.TreeItem<Vector2, Type>( item.Key, Input.MousePosition, item.Value, CreateAutomation ) );
}
AutomationPopup.ShowAsContext( items.ToArray() );
}
private void CreateAutomation( Vector2 mpos, Type type ) {
var instance = (Automation)Activator.CreateInstance( type );
instance.Position = mpos - Globals.Camera;
AddControl( instance );
if ( AutomatronSettings.FocusNewAutomation ) {
LookAtAutomationSmooth( instance );
}
}
private void ExecuteAutomations() {
executionRoutine = EditorCoroutine.Start( ExecuteAutomationsAsync() );
}
private IEnumerator ExecuteAutomationsAsync() {
AutomatronLogger.Start( Name );
var autos = GetControls<Automation>();
foreach ( var item in autos ) {
item.Reset();
}
Globals.LastError = null;
Globals.LastAutomation = null;
Globals.IsError = false;
Globals.IsExecuting = true;
var errors = GetControls<AutomationError>();
foreach ( var item in errors ) {
item.Remove();
}
yield return null;
var entries = new List<QueueStart>() {
entryPoint
};
var entryPoints = GetControls<QueueStart>();
foreach ( var item in entryPoints ) {
if ( !entries.Contains( item ) ) {
entries.Add( item );
}
}
foreach ( var item in entries ) {
var automations = item.GetNextAutomations();
var loops = new List<LoopableAutomation>();
while ( true ) {
if ( automations == null || automations.Count == 0 ) break;
foreach ( var auto in automations ) {
AutomatronLogger.Log( string.Format( "Start {0}", auto.Name ) );
auto.GetDependencies();
if ( Globals.IsError ) break;
yield return null;
if ( auto is LoopableAutomation ) {
var l = (LoopableAutomation)auto;
if ( !loops.Contains( l ) ) {
try {
auto.PreExecute();
} catch ( Exception ex ) {
SetErrorInfo( ex, auto, ErrorType.PreExecute );
break;
}
loops.Add( l );
} else {
l.MoveNext();
}
l.ResetLoop();
} else {
try {
auto.PreExecute();
} catch ( Exception ex ) {
SetErrorInfo( ex, auto, ErrorType.PreExecute );
break;
}
}
if ( AutomatronSettings.FocusActiveAutomation ) {
LookAtAutomationSmooth( auto );
}
IEnumerator routine = null;
try {
routine = auto.Execute();
} catch ( Exception ex ) {
SetErrorInfo( ex, auto, ErrorType.Execute );
break;
}
while ( true ) {
var moveNext = false;
try {
moveNext = routine.MoveNext();
} catch ( Exception ex ) {
SetErrorInfo( ex, auto, ErrorType.Execute );
break;
}
if ( !moveNext ) break;
yield return routine.Current;
}
if ( Globals.IsError ) break;
if ( !( auto is LoopableAutomation ) ) {
try {
auto.PostExecute();
} catch ( Exception ex ) {
SetErrorInfo( ex, auto, ErrorType.PostExecute );
break;
}
auto.Progress = 1;
}
auto.HasRun = true;
AutomatronLogger.Log( string.Format( "End {0}", auto.Name ) );
}
if ( Globals.IsError ) break;
automations = automations[automations.Count - 1].GetNextAutomations();
if ( automations.Count > 0 && loops.Count > 0 ) {
var l = loops[loops.Count - 1];
if ( l.IsDone() ) {
try {
l.PostExecute();
} catch ( Exception ex ) {
SetErrorInfo( ex, l, ErrorType.PostExecute );
break;
}
l.Progress = 1;
loops.Remove( l );
}
} else {
while ( automations.Count == 0 && loops.Count > 0 ) {
var l = loops[loops.Count - 1];
if ( l.IsDone() ) {
try {
l.PostExecute();
} catch ( Exception ex ) {
SetErrorInfo( ex, l, ErrorType.PostExecute );
break;
}
l.Progress = 1;
automations = l.GetNextAutomations();
loops.Remove( l );
} else {
l.GetAutomations( ref automations, false );
}
yield return null;
}
}
yield return null;
}
if ( Globals.IsError ) break;
yield return null;
}
if ( Globals.IsError ) {
LookAtAutomationSmooth( Globals.LastAutomation );
AddControl( new AutomationError( Globals.LastError ) );
} else {
ShowNotification( "Automatron executed" );
}
Globals.IsExecuting = false;
if ( AutomatronSettings.AutoLog ) {
AutomatronLogger.Save();
}
yield break;
}
private void SetErrorInfo( Exception ex, Automation auto, ErrorType type ) {
Globals.LastError = ex;
Globals.LastAutomation = auto;
Globals.IsError = true;
auto.ErrorType = type;
AutomatronLogger.Log( string.Format( "{0} caused an exception: {1}\n{2}", auto.Name, ex.Message, ex ) );
}
private void CreateAutomation( object data ) {
var mpos = (Vector2)( data as object[] )[0] - Globals.Camera;
var type = (Type)( data as object[] )[1];
var instance = (Automation)Activator.CreateInstance( type );
instance.Position = mpos;
AddControl( instance );
}
public void LookAtAutomation( Automation auto ) {
var rect = auto.Rectangle;
Globals.Camera -= rect.position - new Vector2( Size.x / 2, Size.y / 2 ) + ( rect.size / 2 );
}
public void LookAtAutomationSmooth( Automation auto ) {
if ( lookAtRoutine != null ) {
lookAtRoutine.Stop();
lookAtRoutine = null;
}
var rect = auto.Rectangle;
var npos = rect.position - new Vector2( Size.x / 2, Size.y / 2 ) + ( rect.size / 2 );
lookAtRoutine = EditorCoroutine.Start( LookAtAutomationSmoothAsync( npos ) );
}
private IEnumerator LookAtAutomationSmoothAsync( Vector2 pos ) {
var dest = Globals.Camera - pos;
var timer = 0f;
var tween = new TinyTween.Vector2Tween();
tween.Start( Globals.Camera, dest, 1, TinyTween.ScaleFuncs.CubicEaseOut );
while ( timer < 1 ) {
timer += ExtendedEditor.DeltaTime;
tween.Update( timer );
if ( tween.CurrentValue == dest )
break;
Globals.Camera = tween.CurrentValue;
yield return null;
}
Globals.Camera = dest;
yield break;
}
public void Save() {
AutomatronSerializer.Save( this );
}
}
}
#endif
| |
/*
* Copyright (C) 2011 Mitsuaki Kuwahara
* Released under the MIT License.
*/
using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
using System.Reflection;
using System.IO;
using Nana.Infr;
namespace UnitTest.Infr
{
[TestFixture]
public class Experiment
{
//[Test]
public void No0001()
{
Assembly mscorlib = Assembly.Load("mscorlib.dll");
string yen = Path.DirectorySeparatorChar.ToString();
string sysPath = Path.GetDirectoryName(mscorlib.Location) + yen;
string cscRspPath = sysPath + "csc.rsp";
if (!File.Exists(cscRspPath)) throw new Exception("No csc.rsp file. Checked path=" + cscRspPath);
List<string> refList = new List<string>();
string ln2;
foreach (string ln in File.ReadAllLines(cscRspPath))
{
ln2 = ln.Trim();
if (string.IsNullOrEmpty(ln2) || ln2.StartsWith("#")) continue;
if (ln2.StartsWith("/r:")) {
ln2 = ln2.Substring(3);
ln2 = ln2.Substring(0, ln2.Length - 4);
refList.Add(ln2);
//refList.Add(ln2.Substring(3));
}
}
Console.WriteLine("== ref list ==");
refList.Add("mscorlib");
refList.Sort();
List<Assembly> refasm = new List<Assembly>();
foreach (string s in refList)
{
Console.WriteLine(s + ".dll");
Assembly a = Assembly.LoadFile(sysPath + s + ".dll");
refasm.Add(a);
}
Console.WriteLine("== ref asm ==");
foreach (Assembly a in refasm)
{
Console.WriteLine(a.GetName());
}
//return;
Type[] ts;
List<string> tmps = new List<string>();
foreach (Assembly a in refasm)
{
tmps.Clear();
Console.WriteLine("== "+ a.GetName() + " ==");
ts = a.GetExportedTypes();
Console.WriteLine("-- ExportedTypes[" + ts.Length.ToString("D4") + "] --");
foreach (Type t in ts)
{
tmps.Add(t.FullName);
//Console.WriteLine(t.Name);
}
tmps.Sort();
foreach (string s in tmps)
{
Console.WriteLine(s);
}
tmps.Clear();
ts = a.GetTypes();
Console.WriteLine("-- Types[" + ts.Length.ToString("D4") + "] --");
foreach (Type t in ts)
{
tmps.Add(t.FullName);
//Console.WriteLine(t.Name);
}
tmps.Sort();
foreach (string s in tmps)
{
Console.WriteLine(s);
}
}
}
//[Test]
public void No0002()
{
DateTime begin, end;
begin = DateTime.Now;
Assembly mscorlib = Assembly.Load("mscorlib.dll");
string yen = Path.DirectorySeparatorChar.ToString();
string sysPath = Path.GetDirectoryName(mscorlib.Location) + yen;
string cscRspPath = sysPath + "csc.rsp";
if (!File.Exists(cscRspPath)) throw new Exception("No csc.rsp file. Checked path=" + cscRspPath);
List<string> refList = new List<string>();
string ln2;
foreach (string ln in File.ReadAllLines(cscRspPath))
{
ln2 = ln.Trim();
if (string.IsNullOrEmpty(ln2) || ln2.StartsWith("#")) continue;
if (ln2.StartsWith("/r:"))
{
ln2 = ln2.Substring(3);
ln2 = ln2.Substring(0, ln2.Length - 4);
refList.Add(ln2);
//refList.Add(ln2.Substring(3));
}
}
//Console.WriteLine("== ref list ==");
refList.Add("mscorlib");
refList.Sort();
List<Assembly> refasm = new List<Assembly>();
foreach (string s in refList)
{
//Console.WriteLine(s + ".dll");
Assembly a = Assembly.LoadFile(sysPath + s + ".dll");
refasm.Add(a);
}
//Console.WriteLine("== ref asm ==");
foreach (Assembly a in refasm)
{
//Console.WriteLine(a.GetName());
}
//return;
Type[] ts;
List<string> tmps = new List<string>();
foreach (Assembly a in refasm)
{
tmps.Clear();
//Console.WriteLine("== " + a.GetName() + " ==");
ts = a.GetExportedTypes();
//Console.WriteLine("-- ExportedTypes[" + ts.Length.ToString("D4") + "] --");
foreach (Type t in ts)
{
tmps.Add(t.FullName);
//Console.WriteLine(t.Name);
}
tmps.Sort();
foreach (string s in tmps)
{
//Console.WriteLine(s);
}
tmps.Clear();
ts = a.GetTypes();
//Console.WriteLine("-- Types[" + ts.Length.ToString("D4") + "] --");
foreach (Type t in ts)
{
tmps.Add(t.FullName);
//Console.WriteLine(t.Name);
}
tmps.Sort();
foreach (string s in tmps)
{
//Console.WriteLine(s);
}
}
end = DateTime.Now;
TimeSpan times = end - begin;
Console.WriteLine(begin);
Console.WriteLine(end);
Console.WriteLine(times);
}
//[Test]
public void E0003_ReadWindowsForms()
{
Assembly mscorlib = Assembly.Load("mscorlib.dll");
string yen = Path.DirectorySeparatorChar.ToString();
string sysPath = Path.GetDirectoryName(mscorlib.Location) + yen;
string s;
s = @"System.Windows.Forms.dll";
Assembly a = Assembly.LoadFile(sysPath + s);
string fn = @"System.Windows.Forms.Form";
Type t;
t = a.GetType(fn);
string rsl;
rsl = t.FullName;
}
[Test]
public void E004_LoadTypeInThisAssembly()
{
TypeLoader tl = new TypeLoader();
string path;
path = Assembly.GetExecutingAssembly().Location;
tl.InAssembly.LoadFrameworkClassLibrarie(path);
Type t = tl.GetTypeByName("UnitTest.Infr.UTA", new string[0]);
Console.WriteLine(t.ToString());
Console.WriteLine(MethodBase.GetCurrentMethod().Name);
//Assembly.GetExecutingAssembly().
}
}
public class UTA
{
}
}
| |
// 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.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Tests.Common;
using System.Text;
using System.Xml;
using Infrastructure.Common;
using Xunit;
public static class BasicHttpBindingTest
{
[WcfFact]
public static void Default_Ctor_Initializes_Properties()
{
var binding = new BasicHttpBinding();
Assert.Equal<string>("BasicHttpBinding", binding.Name);
Assert.Equal<string>("http://tempuri.org/", binding.Namespace);
Assert.Equal<string>("http", binding.Scheme);
Assert.Equal<Encoding>(Encoding.GetEncoding("utf-8"), binding.TextEncoding);
Assert.Equal<string>(Encoding.GetEncoding("utf-8").WebName, binding.TextEncoding.WebName);
Assert.False(binding.AllowCookies);
Assert.Equal<TimeSpan>(TimeSpan.FromMinutes(1), binding.CloseTimeout);
Assert.Equal<TimeSpan>(TimeSpan.FromMinutes(1), binding.OpenTimeout);
Assert.Equal<TimeSpan>(TimeSpan.FromMinutes(10), binding.ReceiveTimeout);
Assert.Equal<TimeSpan>(TimeSpan.FromMinutes(1), binding.SendTimeout);
Assert.Equal<EnvelopeVersion>(EnvelopeVersion.Soap11, binding.EnvelopeVersion);
Assert.Equal<MessageVersion>(MessageVersion.Soap11, binding.MessageVersion);
Assert.Equal<long>(524288, binding.MaxBufferPoolSize);
Assert.Equal<long>(65536, binding.MaxBufferSize);
Assert.Equal<long>(65536, binding.MaxReceivedMessageSize);
Assert.Equal<TransferMode>(TransferMode.Buffered, binding.TransferMode);
Assert.True(TestHelpers.XmlDictionaryReaderQuotasAreEqual(binding.ReaderQuotas, new XmlDictionaryReaderQuotas()), "XmlDictionaryReaderQuotas");
}
[WcfFact]
public static void Ctor_With_BasicHttpSecurityMode_Transport_Initializes_Properties()
{
var binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
Assert.Equal<string>("BasicHttpBinding", binding.Name);
Assert.Equal<string>("http://tempuri.org/", binding.Namespace);
Assert.Equal<string>("https", binding.Scheme);
Assert.Equal<Encoding>(Encoding.GetEncoding("utf-8"), binding.TextEncoding);
Assert.Equal<string>(Encoding.GetEncoding("utf-8").WebName, binding.TextEncoding.WebName);
Assert.False(binding.AllowCookies);
Assert.Equal<TimeSpan>(TimeSpan.FromMinutes(1), binding.CloseTimeout);
Assert.Equal<TimeSpan>(TimeSpan.FromMinutes(1), binding.OpenTimeout);
Assert.Equal<TimeSpan>(TimeSpan.FromMinutes(10), binding.ReceiveTimeout);
Assert.Equal<TimeSpan>(TimeSpan.FromMinutes(1), binding.SendTimeout);
Assert.Equal<EnvelopeVersion>(EnvelopeVersion.Soap11, binding.EnvelopeVersion);
Assert.Equal<MessageVersion>(MessageVersion.Soap11, binding.MessageVersion);
Assert.Equal<long>(524288, binding.MaxBufferPoolSize);
Assert.Equal<long>(65536, binding.MaxBufferSize);
Assert.Equal<long>(65536, binding.MaxReceivedMessageSize);
Assert.Equal<TransferMode>(TransferMode.Buffered, binding.TransferMode);
Assert.True(TestHelpers.XmlDictionaryReaderQuotasAreEqual(binding.ReaderQuotas, new XmlDictionaryReaderQuotas()), "XmlDictionaryReaderQuotas");
}
[WcfFact]
public static void Ctor_With_BasicHttpSecurityMode_TransportCredentialOnly_Initializes_Properties()
{
var binding = new BasicHttpBinding(BasicHttpSecurityMode.TransportCredentialOnly);
Assert.Equal<string>("BasicHttpBinding", binding.Name);
Assert.Equal<string>("http://tempuri.org/", binding.Namespace);
Assert.Equal<string>("http", binding.Scheme);
Assert.Equal<Encoding>(Encoding.GetEncoding("utf-8"), binding.TextEncoding);
Assert.Equal<string>(Encoding.GetEncoding("utf-8").WebName, binding.TextEncoding.WebName);
Assert.False(binding.AllowCookies);
Assert.Equal<TimeSpan>(TimeSpan.FromMinutes(1), binding.CloseTimeout);
Assert.Equal<TimeSpan>(TimeSpan.FromMinutes(1), binding.OpenTimeout);
Assert.Equal<TimeSpan>(TimeSpan.FromMinutes(10), binding.ReceiveTimeout);
Assert.Equal<TimeSpan>(TimeSpan.FromMinutes(1), binding.SendTimeout);
Assert.Equal<EnvelopeVersion>(EnvelopeVersion.Soap11, binding.EnvelopeVersion);
Assert.Equal<MessageVersion>(MessageVersion.Soap11, binding.MessageVersion);
Assert.Equal<long>(524288, binding.MaxBufferPoolSize);
Assert.Equal<long>(65536, binding.MaxBufferSize);
Assert.Equal<long>(65536, binding.MaxReceivedMessageSize);
Assert.Equal<TransferMode>(TransferMode.Buffered, binding.TransferMode);
Assert.True(TestHelpers.XmlDictionaryReaderQuotasAreEqual(binding.ReaderQuotas, new XmlDictionaryReaderQuotas()), "XmlDictionaryReaderQuotas");
}
[WcfTheory]
[InlineData(true)]
[InlineData(false)]
public static void AllowCookies_Property_Sets(bool value)
{
var binding = new BasicHttpBinding();
binding.AllowCookies = value;
Assert.Equal<bool>(value, binding.AllowCookies);
}
[WcfTheory]
[InlineData(0)]
[InlineData(1)]
[InlineData(int.MaxValue)]
public static void MaxBufferPoolSize_Property_Sets(long value)
{
var binding = new BasicHttpBinding();
binding.MaxBufferPoolSize = value;
Assert.Equal<long>(value, binding.MaxBufferPoolSize);
}
[WcfTheory]
[InlineData(-1)]
[InlineData(int.MinValue)]
public static void MaxBufferPoolSize_Property_Set_Invalid_Value_Throws(long value)
{
var binding = new BasicHttpBinding();
Assert.Throws<ArgumentOutOfRangeException>(() => binding.MaxBufferPoolSize = value);
}
[WcfTheory]
[InlineData(1)]
[InlineData(int.MaxValue)]
public static void MaxBufferSize_Property_Sets(int value)
{
var binding = new BasicHttpBinding();
binding.MaxBufferSize = value;
Assert.Equal<long>(value, binding.MaxBufferSize);
}
[WcfTheory]
[InlineData(0)]
[InlineData(-1)]
[InlineData(int.MinValue)]
public static void MaxBufferSize_Property_Set_Invalid_Value_Throws(int value)
{
var binding = new BasicHttpBinding();
Assert.Throws<ArgumentOutOfRangeException>(() => binding.MaxBufferSize = value);
}
[WcfTheory]
[InlineData(1)]
[InlineData(int.MaxValue)]
public static void MaxReceivedMessageSize_Property_Sets(long value)
{
var binding = new BasicHttpBinding();
binding.MaxReceivedMessageSize = value;
Assert.Equal<long>(value, binding.MaxReceivedMessageSize);
}
[WcfTheory]
[InlineData(0)]
[InlineData(-1)]
[InlineData(int.MinValue)]
public static void MaxReceivedMessageSize_Property_Set_Invalid_Value_Throws(int value)
{
var binding = new BasicHttpBinding();
Assert.Throws<ArgumentOutOfRangeException>(() => binding.MaxReceivedMessageSize = value);
}
[WcfTheory]
[InlineData("testName")]
public static void Name_Property_Sets(string value)
{
var binding = new BasicHttpBinding();
binding.Name = value;
Assert.Equal<string>(value, binding.Name);
}
[WcfTheory]
[InlineData(new object[] { null } )] // Work-around issue #1449 with this syntax
[InlineData("")]
public static void Name_Property_Set_Invalid_Value_Throws(string value)
{
var binding = new BasicHttpBinding();
Assert.Throws<ArgumentException>(() => binding.Name = value);
}
[WcfTheory]
[InlineData("")]
[InlineData("http://hello")]
[InlineData("testNamespace")]
public static void Namespace_Property_Sets(string value)
{
var binding = new BasicHttpBinding();
binding.Namespace = value;
Assert.Equal<string>(value, binding.Namespace);
}
[WcfTheory]
[InlineData(new object[] { null } )] // Work-around issue #1449 with this syntax
public static void Namespace_Property_Set_Invalid_Value_Throws(string value)
{
var binding = new BasicHttpBinding();
Assert.Throws<ArgumentNullException>(() => binding.Namespace = value);
}
[WcfFact]
public static void ReaderQuotas_Property_Sets()
{
var binding = new BasicHttpBinding();
XmlDictionaryReaderQuotas maxQuota = XmlDictionaryReaderQuotas.Max;
XmlDictionaryReaderQuotas defaultQuota = new XmlDictionaryReaderQuotas();
Assert.True(TestHelpers.XmlDictionaryReaderQuotasAreEqual(binding.ReaderQuotas, defaultQuota));
maxQuota.CopyTo(binding.ReaderQuotas);
Assert.True(TestHelpers.XmlDictionaryReaderQuotasAreEqual(binding.ReaderQuotas, maxQuota), "Setting Max ReaderQuota failed");
}
[WcfFact]
public static void ReaderQuotas_Property_Set_Null_Throws()
{
var binding = new BasicHttpBinding();
Assert.Throws<ArgumentNullException>(() => binding.ReaderQuotas = null);
}
[WcfTheory]
[MemberData("ValidTimeOuts", MemberType = typeof(TestData))]
public static void CloseTimeout_Property_Sets(TimeSpan timeSpan)
{
BasicHttpBinding binding = new BasicHttpBinding();
binding.CloseTimeout = timeSpan;
Assert.Equal<TimeSpan>(timeSpan, binding.CloseTimeout);
}
[WcfTheory]
[MemberData("InvalidTimeOuts", MemberType = typeof(TestData))]
public static void CloseTimeout_Property_Set_Invalid_Value_Throws(TimeSpan timeSpan)
{
BasicHttpBinding binding = new BasicHttpBinding();
Assert.Throws<ArgumentOutOfRangeException>(() => binding.CloseTimeout = timeSpan);
}
[WcfTheory]
[MemberData("ValidTimeOuts", MemberType = typeof(TestData))]
public static void OpenTimeout_Property_Sets(TimeSpan timeSpan)
{
BasicHttpBinding binding = new BasicHttpBinding();
binding.OpenTimeout = timeSpan;
Assert.Equal<TimeSpan>(timeSpan, binding.OpenTimeout);
}
[WcfTheory]
[MemberData("InvalidTimeOuts", MemberType = typeof(TestData))]
public static void OpenTimeout_Property_Set_Invalid_Value_Throws(TimeSpan timeSpan)
{
BasicHttpBinding binding = new BasicHttpBinding();
Assert.Throws<ArgumentOutOfRangeException>(() => binding.OpenTimeout = timeSpan);
}
[WcfTheory]
[MemberData("ValidTimeOuts", MemberType = typeof(TestData))]
public static void SendTimeout_Property_Sets(TimeSpan timeSpan)
{
BasicHttpBinding binding = new BasicHttpBinding();
binding.SendTimeout = timeSpan;
Assert.Equal<TimeSpan>(timeSpan, binding.SendTimeout);
}
[WcfTheory]
[MemberData("InvalidTimeOuts", MemberType = typeof(TestData))]
public static void SendTimeout_Property_Set_Invalid_Value_Throws(TimeSpan timeSpan)
{
BasicHttpBinding binding = new BasicHttpBinding();
Assert.Throws<ArgumentOutOfRangeException>(() => binding.SendTimeout = timeSpan);
}
[WcfTheory]
[MemberData("ValidTimeOuts", MemberType = typeof(TestData))]
public static void ReceiveTimeout_Property_Sets(TimeSpan timeSpan)
{
BasicHttpBinding binding = new BasicHttpBinding();
binding.ReceiveTimeout = timeSpan;
Assert.Equal<TimeSpan>(timeSpan, binding.ReceiveTimeout);
}
[WcfTheory]
[MemberData("InvalidTimeOuts", MemberType = typeof(TestData))]
public static void ReceiveTimeout_Property_Set_Invalid_Value_Throws(TimeSpan timeSpan)
{
BasicHttpBinding binding = new BasicHttpBinding();
Assert.Throws<ArgumentOutOfRangeException>(() => binding.SendTimeout = timeSpan);
}
[WcfTheory]
[MemberData("ValidEncodings", MemberType = typeof(TestData))]
public static void TextEncoding_Property_Sets(Encoding encoding)
{
var binding = new BasicHttpBinding();
binding.TextEncoding = encoding;
Assert.Equal<Encoding>(encoding, binding.TextEncoding);
}
[WcfTheory]
[MemberData("InvalidEncodings", MemberType = typeof(TestData))]
public static void TextEncoding_Property_Set_Invalid_Value_Throws(Encoding encoding)
{
var binding = new BasicHttpBinding();
Assert.Throws<ArgumentException>(() => binding.TextEncoding = encoding);
}
[WcfTheory]
[InlineData(TransferMode.Buffered)]
[InlineData(TransferMode.Streamed)]
[InlineData(TransferMode.StreamedRequest)]
[InlineData(TransferMode.StreamedResponse)]
public static void TransferMode_Property_Sets(TransferMode transferMode)
{
var binding = new BasicHttpBinding();
binding.TransferMode = transferMode;
Assert.Equal<TransferMode>(transferMode, binding.TransferMode);
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Elem{
public float temperature, moisture, height;
public int available; //0 je validna vrednost
public Position p; //koordinate u matrici
public string toString(){
return p.ToString();
}
}
public class Coords{
public Position north, west, east, south;
public Coords(){
north = new Position ();
south = new Position ();
east = new Position ();
west = new Position ();
}
}
public class Heads{
public Coords c;
public List<Elem> elems;
public Heads(){
c = new Coords();
elems = new List<Elem> ();
}
}
public class Position{
public int x, y;
public Position ()
{
}
public Position(int x, int y){
this.x=x;
this.y=y;
}
public static bool operator ==(Position x, Position y){
if (x.x==y.x && x.y==y.y) return true;
else return false;
}
public static bool operator !=(Position x, Position y){
if (x.x==y.x && x.y==y.y) return false;
else return true;
}
public static bool operator >(Position x, Position y){
if (x.x>y.x) return true;
else if (x.x<y.x) return false;
else if (x.y>y.y) return true;
else return false;
}
public static bool operator <(Position x, Position y){
return !(x>y);
}
public string ToString(){
return x+" "+y+"\n";
}
public int CompareTo(Position p){
if (this>p) return 1;
else if (this<p) return -1;
else return 0;
}
}
public class Field {
public static int size, tile=16;
public static Elem[,] mat;
public static List<Heads> cc = new List<Heads> ();
static float angleLimit = 20;
public static void start(Terrain t, int tSize, Vector2 terrainSize, int terrainHeight, GameObject object1,GameObject object2,GameObject object3,float waterLimit){
float[,] newMat = new float[tSize, tSize];
for (int i=0; i< tSize; i++)
for (int j=0; j<tSize; j++) {
Vector2 point = TerrainGenerator.getTerrainFromHeightMap (new Vector2 (i, j), tSize, terrainSize);
newMat [j,i] = Terrain.activeTerrain.SampleHeight (new Vector3 (point.x, 0 , point.y)) / terrainHeight;
}
mat = new Elem[(tSize+tile-1)/tile+2,(tSize+tile-1)/tile+2];
size = (tSize+tile-1)/tile+2;
// newMat = t.terrainData.GetHeights (0, 0, tSize, tSize);
//newMat=htmap;
shift (newMat);
fill ();
check (t,waterLimit);
connectedComponents();
/* printH();
printA();
printB(newMat);*/
//(new City ()).arrange (g);
Debug.Log ("ovde");
(new CityPicker ()).setFlags (cc,object1,object2,object3);
Debug.Log (cc.Count);
}
static int count(){
int k=0;
for (int i=0;i<size; i++)
for (int j=0;j<size;j++)
if (mat[i,j].available==-1) k++;
return k;
}
static void check(Terrain t,float waterLimit){
for (int i=1; i<size-1; i++)
for (int j=1; j<size-1; j++) {
if (mat[i,j].height<=waterLimit) mat[i,j].available=-1;
else if (mat[i,j].available==1) continue;
else{/*
if (Mathf.Atan(Mathf.Abs(mat[i,j].height-mat[i-1,j-1].height))>angleLimit) {
mat[i,j].available=mat[i-1,j-1].available=1;
}
if (Mathf.Atan(Mathf.Abs(mat[i,j].height-mat[i-1,j].height))>angleLimit) {
mat[i,j].available=mat[i-1,j].available=1;
}
if (Mathf.Atan(Mathf.Abs(mat[i,j].height-mat[i-1,j+1].height))>angleLimit) {
mat[i,j].available=mat[i-1,j+1].available=1;
}
if (Mathf.Atan(Mathf.Abs(mat[i,j].height-mat[i,j-1].height))>angleLimit) {
mat[i,j].available=mat[i,j-1].available=1;
}
if (Mathf.Atan(Mathf.Abs(mat[i,j].height-mat[i,j+1].height))>angleLimit) {
mat[i,j].available=mat[i,j+1].available=1;
}
if (Mathf.Atan(Mathf.Abs(mat[i,j].height-mat[i+1,j-1].height))>angleLimit) {
mat[i,j].available=mat[i+1,j-1].available=1;
}
if (Mathf.Atan(Mathf.Abs(mat[i,j].height-mat[i+1,j].height))>angleLimit) {
mat[i,j].available=mat[i+1,j].available=1;
}
if (Mathf.Atan(Mathf.Abs(mat[i,j].height-mat[i+1,j+1].height))>angleLimit) {
mat[i,j].available=mat[i+1,j+1].available=1;
}*/
if ((mat[i,j].height-mat[i-1,j-1].height)*512>angleLimit) {
// Debug.Log ((mat[i,j].height-mat[i-1,j-1].height)*512);
mat[i,j].available=mat[i-1,j-1].available=1;
}
if ((mat[i,j].height-mat[i-1,j].height)*512>angleLimit) {
mat[i,j].available=mat[i-1,j].available=1;
}
if ((mat[i,j].height-mat[i-1,j+1].height)*512>angleLimit) {
mat[i,j].available=mat[i-1,j+1].available=1;
}
if ((mat[i,j].height-mat[i,j-1].height)*512>angleLimit) {
mat[i,j].available=mat[i,j-1].available=1;
}
if ((mat[i,j].height-mat[i,j+1].height)*512>angleLimit) {
mat[i,j].available=mat[i,j+1].available=1;
}
if ((mat[i,j].height-mat[i+1,j-1].height)*512>angleLimit) {
mat[i,j].available=mat[i+1,j-1].available=1;
}
if ((mat[i,j].height-mat[i+1,j].height)*512>angleLimit) {
mat[i,j].available=mat[i+1,j].available=1;
}
if ((mat[i,j].height-mat[i+1,j+1].height)*512>angleLimit) {
mat[i,j].available=mat[i+1,j+1].available=1;
}
}
}
}
static void fill(){
for (int i=0; i<size; i++) {
mat[0,i] = new Elem();
mat[size-1, i] = new Elem();
mat [0, i].height = -1;
mat [size - 1, i].height = -1;
mat [0, i].available = 1;
mat [size - 1, i].available = 1;
mat [0, i].p = new Position(0,i);
mat [size - 1, i].p = new Position(size-1, i);
}
for (int i=0; i<size; i++) {
mat[i,0] = new Elem();
mat[i,size-1] = new Elem();
mat [i, 0].height = -1;
mat [i, size - 1].height = -1;
mat [i, 0].available = 1;
mat [i, size - 1].available = 1;
mat[i,0].p = new Position(i,0);
mat[i,size-1].p = new Position(i, size-1);
}
}
static void shift(float[,] newMat){
int size = (int)Mathf.Sqrt(newMat.Length);
int size1 = (int)Mathf.Sqrt(mat.Length)-2;
for (int i=0; i<size1; i++)
for (int j=0; j<size1; j++) {
mat [i+1, j+1] = new Elem();
int k=0;
int t=tile*i;
while (k<tile && k+t<size){
int n=0;
int t1=tile*j;
while (n<tile && n+t1<size){
mat[i+1,j+1].height+=newMat[k+t, n+t1];
n++;
}
k++;
}
mat [i+1,j+1].height/=tile*tile;
mat [i+1, j+1].p = new Position(i+1, j+1);
}
}
static void connectedComponents(){
int i, j, k=1;
int n=0;
while (k<=mat.Length-4*size+4) {
if (mat[i = (((k-1)/(size-2))+1), j = (((k-1)%(size-2))+1)].available==0){
Heads h = new Heads();
cc.Add (h);
cc[n].elems = bfs(i, j, n);
n++;
}
k++;
}
}
static List<Elem> bfs(int i, int j, int n){
Queue<Elem> q = new Queue<Elem> ();
List<Elem> l = new List<Elem> ();
Elem p;
q.Enqueue (mat [i, j]);
while (q.Count!=0) {
p = q.Dequeue();
i=p.p.x;
j=p.p.y;
if (cc[n].c.north.x == 0 && cc[n].c.north.y == 0)
{
cc[n].c.north = p.p;
cc[n].c.south = p.p;
cc[n].c.east = p.p;
cc[n].c.west = p.p;
}
else
{
if ( p.p.x < cc[n].c.north.x)
cc[n].c.north = p.p;
else if (p.p.x > cc[n].c.south.x)
cc[n].c.south = p.p;
if (p.p.y < cc[n].c.west.y)
cc[n].c.west = p.p;
else if (p.p.y > cc[n].c.east.y)
cc[n].c.east = p.p;
}
l.Add (p);
if (mat[i-1,j].available==0) q.Enqueue(mat[i-1,j]);
if (mat[i+1,j].available==0) q.Enqueue(mat[i+1,j]);
if (mat[i,j-1].available==0) q.Enqueue(mat[i,j-1]);
if (mat[i,j+1].available==0) q.Enqueue(mat[i,j+1]);
p.available=2;
}
return l;
}
static void printH(){
string s = "";
for (int i=0; i<size; i++){
s+="\n";
for (int j=0; j<size; j++)
s+=(mat[i,j].height*512) +" ";
}
Debug.Log (s);
}
static void printA(){
string s = "";
for (int i=0; i<size; i++){
s+="AAA\n";
for (int j=0; j<size; j++)
s+=mat[i,j].available +" ";
}
Debug.Log (s);
}
static void printB(float [,] mat){
string s = "";
for (int i=0; i<size; i++){
s+="BBB\n";
for (int j=0; j<size; j++)
s+=mat[i,j] +" ";
}
Debug.Log (s);
}
}
/*SORTIRANJE LISTE
*
* List<Elem> l = new List<Elem>();
for (int i=0;i<3;i++)
for (int j=2;j>=0;j--){
Elem e = new Elem();
e.p = new Position(i,j);
l.Add (e);
}
l.Sort(
delegate(Elem e1, Elem e2){
return e1.p.CompareTo(e2.p);
}
);
Debug.Log (l[0].p.x);
Debug.Log(l[0].p.y);*/
/*TEST POVEZANIH KOMPONENTI
*
*
* mat = new Elem[5,5];
string s = "2222220112211122100222222";
size=5;
for (int i=0;i<size;i++)
for (int j=0;j<size;j++){
mat[i,j] = new Elem();
mat[i,j].p = new Position(i,j);
mat[i,j].available = s[i*5+j]-'0';
}
*/
| |
using System;
using System.Collections;
using ChainUtils.BouncyCastle.Asn1;
using ChainUtils.BouncyCastle.Asn1.CryptoPro;
using ChainUtils.BouncyCastle.Asn1.Kisa;
using ChainUtils.BouncyCastle.Asn1.Nist;
using ChainUtils.BouncyCastle.Asn1.Ntt;
using ChainUtils.BouncyCastle.Asn1.Oiw;
using ChainUtils.BouncyCastle.Asn1.Pkcs;
using ChainUtils.BouncyCastle.Crypto;
using ChainUtils.BouncyCastle.Crypto.Agreement;
using ChainUtils.BouncyCastle.Crypto.Digests;
using ChainUtils.BouncyCastle.Crypto.Encodings;
using ChainUtils.BouncyCastle.Crypto.Engines;
using ChainUtils.BouncyCastle.Crypto.Generators;
using ChainUtils.BouncyCastle.Crypto.Macs;
using ChainUtils.BouncyCastle.Crypto.Modes;
using ChainUtils.BouncyCastle.Crypto.Paddings;
using ChainUtils.BouncyCastle.Utilities;
namespace ChainUtils.BouncyCastle.Security
{
/// <remarks>
/// Cipher Utility class contains methods that can not be specifically grouped into other classes.
/// </remarks>
public sealed class CipherUtilities
{
private enum CipherAlgorithm {
AES,
ARC4,
BLOWFISH,
CAMELLIA,
CAST5,
CAST6,
DES,
DESEDE,
ELGAMAL,
GOST28147,
HC128,
HC256,
IDEA,
NOEKEON,
PBEWITHSHAAND128BITRC4,
PBEWITHSHAAND40BITRC4,
RC2,
RC5,
RC5_64,
RC6,
RIJNDAEL,
RSA,
SALSA20,
SEED,
SERPENT,
SKIPJACK,
TEA,
TWOFISH,
VMPC,
VMPC_KSA3,
XTEA,
};
private enum CipherMode { ECB, NONE, CBC, CFB, CTR, CTS, EAX, GCM, GOFB, OCB, OFB, OPENPGPCFB, SIC };
private enum CipherPadding
{
NOPADDING,
RAW,
ISO10126PADDING,
ISO10126D2PADDING,
ISO10126_2PADDING,
ISO7816_4PADDING,
ISO9797_1PADDING,
ISO9796_1,
ISO9796_1PADDING,
OAEP,
OAEPPADDING,
OAEPWITHMD5ANDMGF1PADDING,
OAEPWITHSHA1ANDMGF1PADDING,
OAEPWITHSHA_1ANDMGF1PADDING,
OAEPWITHSHA224ANDMGF1PADDING,
OAEPWITHSHA_224ANDMGF1PADDING,
OAEPWITHSHA256ANDMGF1PADDING,
OAEPWITHSHA_256ANDMGF1PADDING,
OAEPWITHSHA384ANDMGF1PADDING,
OAEPWITHSHA_384ANDMGF1PADDING,
OAEPWITHSHA512ANDMGF1PADDING,
OAEPWITHSHA_512ANDMGF1PADDING,
PKCS1,
PKCS1PADDING,
PKCS5,
PKCS5PADDING,
PKCS7,
PKCS7PADDING,
TBCPADDING,
WITHCTS,
X923PADDING,
ZEROBYTEPADDING,
};
private static readonly IDictionary algorithms = Platform.CreateHashtable();
private static readonly IDictionary oids = Platform.CreateHashtable();
static CipherUtilities()
{
// Signal to obfuscation tools not to change enum constants
((CipherAlgorithm)Enums.GetArbitraryValue(typeof(CipherAlgorithm))).ToString();
((CipherMode)Enums.GetArbitraryValue(typeof(CipherMode))).ToString();
((CipherPadding)Enums.GetArbitraryValue(typeof(CipherPadding))).ToString();
// TODO Flesh out the list of aliases
algorithms[NistObjectIdentifiers.IdAes128Ecb.Id] = "AES/ECB/PKCS7PADDING";
algorithms[NistObjectIdentifiers.IdAes192Ecb.Id] = "AES/ECB/PKCS7PADDING";
algorithms[NistObjectIdentifiers.IdAes256Ecb.Id] = "AES/ECB/PKCS7PADDING";
algorithms["AES//PKCS7"] = "AES/ECB/PKCS7PADDING";
algorithms["AES//PKCS7PADDING"] = "AES/ECB/PKCS7PADDING";
algorithms["AES//PKCS5"] = "AES/ECB/PKCS7PADDING";
algorithms["AES//PKCS5PADDING"] = "AES/ECB/PKCS7PADDING";
algorithms[NistObjectIdentifiers.IdAes128Cbc.Id] = "AES/CBC/PKCS7PADDING";
algorithms[NistObjectIdentifiers.IdAes192Cbc.Id] = "AES/CBC/PKCS7PADDING";
algorithms[NistObjectIdentifiers.IdAes256Cbc.Id] = "AES/CBC/PKCS7PADDING";
algorithms[NistObjectIdentifiers.IdAes128Ofb.Id] = "AES/OFB/NOPADDING";
algorithms[NistObjectIdentifiers.IdAes192Ofb.Id] = "AES/OFB/NOPADDING";
algorithms[NistObjectIdentifiers.IdAes256Ofb.Id] = "AES/OFB/NOPADDING";
algorithms[NistObjectIdentifiers.IdAes128Cfb.Id] = "AES/CFB/NOPADDING";
algorithms[NistObjectIdentifiers.IdAes192Cfb.Id] = "AES/CFB/NOPADDING";
algorithms[NistObjectIdentifiers.IdAes256Cfb.Id] = "AES/CFB/NOPADDING";
algorithms["RSA/ECB/PKCS1"] = "RSA//PKCS1PADDING";
algorithms["RSA/ECB/PKCS1PADDING"] = "RSA//PKCS1PADDING";
algorithms[PkcsObjectIdentifiers.RsaEncryption.Id] = "RSA//PKCS1PADDING";
algorithms[PkcsObjectIdentifiers.IdRsaesOaep.Id] = "RSA//OAEPPADDING";
algorithms[OiwObjectIdentifiers.DesCbc.Id] = "DES/CBC";
algorithms[OiwObjectIdentifiers.DesCfb.Id] = "DES/CFB";
algorithms[OiwObjectIdentifiers.DesEcb.Id] = "DES/ECB";
algorithms[OiwObjectIdentifiers.DesOfb.Id] = "DES/OFB";
algorithms[OiwObjectIdentifiers.DesEde.Id] = "DESEDE";
algorithms["TDEA"] = "DESEDE";
algorithms[PkcsObjectIdentifiers.DesEde3Cbc.Id] = "DESEDE/CBC";
algorithms[PkcsObjectIdentifiers.RC2Cbc.Id] = "RC2/CBC";
algorithms["1.3.6.1.4.1.188.7.1.1.2"] = "IDEA/CBC";
algorithms["1.2.840.113533.7.66.10"] = "CAST5/CBC";
algorithms["RC4"] = "ARC4";
algorithms["ARCFOUR"] = "ARC4";
algorithms["1.2.840.113549.3.4"] = "ARC4";
algorithms["PBEWITHSHA1AND128BITRC4"] = "PBEWITHSHAAND128BITRC4";
algorithms[PkcsObjectIdentifiers.PbeWithShaAnd128BitRC4.Id] = "PBEWITHSHAAND128BITRC4";
algorithms["PBEWITHSHA1AND40BITRC4"] = "PBEWITHSHAAND40BITRC4";
algorithms[PkcsObjectIdentifiers.PbeWithShaAnd40BitRC4.Id] = "PBEWITHSHAAND40BITRC4";
algorithms["PBEWITHSHA1ANDDES"] = "PBEWITHSHA1ANDDES-CBC";
algorithms[PkcsObjectIdentifiers.PbeWithSha1AndDesCbc.Id] = "PBEWITHSHA1ANDDES-CBC";
algorithms["PBEWITHSHA1ANDRC2"] = "PBEWITHSHA1ANDRC2-CBC";
algorithms[PkcsObjectIdentifiers.PbeWithSha1AndRC2Cbc.Id] = "PBEWITHSHA1ANDRC2-CBC";
algorithms["PBEWITHSHA1AND3-KEYTRIPLEDES-CBC"] = "PBEWITHSHAAND3-KEYTRIPLEDES-CBC";
algorithms["PBEWITHSHAAND3KEYTRIPLEDES"] = "PBEWITHSHAAND3-KEYTRIPLEDES-CBC";
algorithms[PkcsObjectIdentifiers.PbeWithShaAnd3KeyTripleDesCbc.Id] = "PBEWITHSHAAND3-KEYTRIPLEDES-CBC";
algorithms["PBEWITHSHA1ANDDESEDE"] = "PBEWITHSHAAND3-KEYTRIPLEDES-CBC";
algorithms["PBEWITHSHA1AND2-KEYTRIPLEDES-CBC"] = "PBEWITHSHAAND2-KEYTRIPLEDES-CBC";
algorithms[PkcsObjectIdentifiers.PbeWithShaAnd2KeyTripleDesCbc.Id] = "PBEWITHSHAAND2-KEYTRIPLEDES-CBC";
algorithms["PBEWITHSHA1AND128BITRC2-CBC"] = "PBEWITHSHAAND128BITRC2-CBC";
algorithms[PkcsObjectIdentifiers.PbeWithShaAnd128BitRC2Cbc.Id] = "PBEWITHSHAAND128BITRC2-CBC";
algorithms["PBEWITHSHA1AND40BITRC2-CBC"] = "PBEWITHSHAAND40BITRC2-CBC";
algorithms[PkcsObjectIdentifiers.PbewithShaAnd40BitRC2Cbc.Id] = "PBEWITHSHAAND40BITRC2-CBC";
algorithms["PBEWITHSHA1AND128BITAES-CBC-BC"] = "PBEWITHSHAAND128BITAES-CBC-BC";
algorithms["PBEWITHSHA-1AND128BITAES-CBC-BC"] = "PBEWITHSHAAND128BITAES-CBC-BC";
algorithms["PBEWITHSHA1AND192BITAES-CBC-BC"] = "PBEWITHSHAAND192BITAES-CBC-BC";
algorithms["PBEWITHSHA-1AND192BITAES-CBC-BC"] = "PBEWITHSHAAND192BITAES-CBC-BC";
algorithms["PBEWITHSHA1AND256BITAES-CBC-BC"] = "PBEWITHSHAAND256BITAES-CBC-BC";
algorithms["PBEWITHSHA-1AND256BITAES-CBC-BC"] = "PBEWITHSHAAND256BITAES-CBC-BC";
algorithms["PBEWITHSHA-256AND128BITAES-CBC-BC"] = "PBEWITHSHA256AND128BITAES-CBC-BC";
algorithms["PBEWITHSHA-256AND192BITAES-CBC-BC"] = "PBEWITHSHA256AND192BITAES-CBC-BC";
algorithms["PBEWITHSHA-256AND256BITAES-CBC-BC"] = "PBEWITHSHA256AND256BITAES-CBC-BC";
algorithms["GOST"] = "GOST28147";
algorithms["GOST-28147"] = "GOST28147";
algorithms[CryptoProObjectIdentifiers.GostR28147Cbc.Id] = "GOST28147/CBC/PKCS7PADDING";
algorithms["RC5-32"] = "RC5";
algorithms[NttObjectIdentifiers.IdCamellia128Cbc.Id] = "CAMELLIA/CBC/PKCS7PADDING";
algorithms[NttObjectIdentifiers.IdCamellia192Cbc.Id] = "CAMELLIA/CBC/PKCS7PADDING";
algorithms[NttObjectIdentifiers.IdCamellia256Cbc.Id] = "CAMELLIA/CBC/PKCS7PADDING";
algorithms[KisaObjectIdentifiers.IdSeedCbc.Id] = "SEED/CBC/PKCS7PADDING";
algorithms["1.3.6.1.4.1.3029.1.2"] = "BLOWFISH/CBC";
}
private CipherUtilities()
{
}
/// <summary>
/// Returns a ObjectIdentifier for a give encoding.
/// </summary>
/// <param name="mechanism">A string representation of the encoding.</param>
/// <returns>A DerObjectIdentifier, null if the Oid is not available.</returns>
// TODO Don't really want to support this
public static DerObjectIdentifier GetObjectIdentifier(
string mechanism)
{
if (mechanism == null)
throw new ArgumentNullException("mechanism");
mechanism = Platform.ToUpperInvariant(mechanism);
var aliased = (string) algorithms[mechanism];
if (aliased != null)
mechanism = aliased;
return (DerObjectIdentifier) oids[mechanism];
}
public static ICollection Algorithms
{
get { return oids.Keys; }
}
public static IBufferedCipher GetCipher(
DerObjectIdentifier oid)
{
return GetCipher(oid.Id);
}
public static IBufferedCipher GetCipher(
string algorithm)
{
if (algorithm == null)
throw new ArgumentNullException("algorithm");
algorithm = Platform.ToUpperInvariant(algorithm);
{
var aliased = (string) algorithms[algorithm];
if (aliased != null)
algorithm = aliased;
}
IBasicAgreement iesAgreement = null;
if (algorithm == "IES")
{
iesAgreement = new DHBasicAgreement();
}
else if (algorithm == "ECIES")
{
iesAgreement = new ECDHBasicAgreement();
}
if (iesAgreement != null)
{
return new BufferedIesCipher(
new IesEngine(
iesAgreement,
new Kdf2BytesGenerator(
new Sha1Digest()),
new HMac(
new Sha1Digest())));
}
if (algorithm.StartsWith("PBE"))
{
if (algorithm.EndsWith("-CBC"))
{
if (algorithm == "PBEWITHSHA1ANDDES-CBC")
{
return new PaddedBufferedBlockCipher(
new CbcBlockCipher(new DesEngine()));
}
else if (algorithm == "PBEWITHSHA1ANDRC2-CBC")
{
return new PaddedBufferedBlockCipher(
new CbcBlockCipher(new RC2Engine()));
}
else if (Strings.IsOneOf(algorithm,
"PBEWITHSHAAND2-KEYTRIPLEDES-CBC", "PBEWITHSHAAND3-KEYTRIPLEDES-CBC"))
{
return new PaddedBufferedBlockCipher(
new CbcBlockCipher(new DesEdeEngine()));
}
else if (Strings.IsOneOf(algorithm,
"PBEWITHSHAAND128BITRC2-CBC", "PBEWITHSHAAND40BITRC2-CBC"))
{
return new PaddedBufferedBlockCipher(
new CbcBlockCipher(new RC2Engine()));
}
}
else if (algorithm.EndsWith("-BC") || algorithm.EndsWith("-OPENSSL"))
{
if (Strings.IsOneOf(algorithm,
"PBEWITHSHAAND128BITAES-CBC-BC",
"PBEWITHSHAAND192BITAES-CBC-BC",
"PBEWITHSHAAND256BITAES-CBC-BC",
"PBEWITHSHA256AND128BITAES-CBC-BC",
"PBEWITHSHA256AND192BITAES-CBC-BC",
"PBEWITHSHA256AND256BITAES-CBC-BC",
"PBEWITHMD5AND128BITAES-CBC-OPENSSL",
"PBEWITHMD5AND192BITAES-CBC-OPENSSL",
"PBEWITHMD5AND256BITAES-CBC-OPENSSL"))
{
return new PaddedBufferedBlockCipher(
new CbcBlockCipher(new AesFastEngine()));
}
}
}
var parts = algorithm.Split('/');
IBlockCipher blockCipher = null;
IAsymmetricBlockCipher asymBlockCipher = null;
IStreamCipher streamCipher = null;
var algorithmName = parts[0];
{
var aliased = (string)algorithms[algorithmName];
if (aliased != null)
algorithmName = aliased;
}
CipherAlgorithm cipherAlgorithm;
try
{
cipherAlgorithm = (CipherAlgorithm)Enums.GetEnumValue(typeof(CipherAlgorithm), algorithmName);
}
catch (ArgumentException)
{
throw new SecurityUtilityException("Cipher " + algorithm + " not recognised.");
}
switch (cipherAlgorithm)
{
case CipherAlgorithm.AES:
blockCipher = new AesFastEngine();
break;
case CipherAlgorithm.ARC4:
streamCipher = new RC4Engine();
break;
case CipherAlgorithm.BLOWFISH:
blockCipher = new BlowfishEngine();
break;
case CipherAlgorithm.CAMELLIA:
blockCipher = new CamelliaEngine();
break;
case CipherAlgorithm.CAST5:
blockCipher = new Cast5Engine();
break;
case CipherAlgorithm.CAST6:
blockCipher = new Cast6Engine();
break;
case CipherAlgorithm.DES:
blockCipher = new DesEngine();
break;
case CipherAlgorithm.DESEDE:
blockCipher = new DesEdeEngine();
break;
case CipherAlgorithm.ELGAMAL:
asymBlockCipher = new ElGamalEngine();
break;
case CipherAlgorithm.GOST28147:
blockCipher = new Gost28147Engine();
break;
case CipherAlgorithm.HC128:
streamCipher = new HC128Engine();
break;
case CipherAlgorithm.HC256:
streamCipher = new HC256Engine();
break;
case CipherAlgorithm.IDEA:
blockCipher = new IdeaEngine();
break;
case CipherAlgorithm.NOEKEON:
blockCipher = new NoekeonEngine();
break;
case CipherAlgorithm.PBEWITHSHAAND128BITRC4:
case CipherAlgorithm.PBEWITHSHAAND40BITRC4:
streamCipher = new RC4Engine();
break;
case CipherAlgorithm.RC2:
blockCipher = new RC2Engine();
break;
case CipherAlgorithm.RC5:
blockCipher = new RC532Engine();
break;
case CipherAlgorithm.RC5_64:
blockCipher = new RC564Engine();
break;
case CipherAlgorithm.RC6:
blockCipher = new RC6Engine();
break;
case CipherAlgorithm.RIJNDAEL:
blockCipher = new RijndaelEngine();
break;
case CipherAlgorithm.RSA:
asymBlockCipher = new RsaBlindedEngine();
break;
case CipherAlgorithm.SALSA20:
streamCipher = new Salsa20Engine();
break;
case CipherAlgorithm.SEED:
blockCipher = new SeedEngine();
break;
case CipherAlgorithm.SERPENT:
blockCipher = new SerpentEngine();
break;
case CipherAlgorithm.SKIPJACK:
blockCipher = new SkipjackEngine();
break;
case CipherAlgorithm.TEA:
blockCipher = new TeaEngine();
break;
case CipherAlgorithm.TWOFISH:
blockCipher = new TwofishEngine();
break;
case CipherAlgorithm.VMPC:
streamCipher = new VmpcEngine();
break;
case CipherAlgorithm.VMPC_KSA3:
streamCipher = new VmpcKsa3Engine();
break;
case CipherAlgorithm.XTEA:
blockCipher = new XteaEngine();
break;
default:
throw new SecurityUtilityException("Cipher " + algorithm + " not recognised.");
}
if (streamCipher != null)
{
if (parts.Length > 1)
throw new ArgumentException("Modes and paddings not used for stream ciphers");
return new BufferedStreamCipher(streamCipher);
}
var cts = false;
var padded = true;
IBlockCipherPadding padding = null;
IAeadBlockCipher aeadBlockCipher = null;
if (parts.Length > 2)
{
if (streamCipher != null)
throw new ArgumentException("Paddings not used for stream ciphers");
var paddingName = parts[2];
CipherPadding cipherPadding;
if (paddingName == "")
{
cipherPadding = CipherPadding.RAW;
}
else if (paddingName == "X9.23PADDING")
{
cipherPadding = CipherPadding.X923PADDING;
}
else
{
try
{
cipherPadding = (CipherPadding)Enums.GetEnumValue(typeof(CipherPadding), paddingName);
}
catch (ArgumentException)
{
throw new SecurityUtilityException("Cipher " + algorithm + " not recognised.");
}
}
switch (cipherPadding)
{
case CipherPadding.NOPADDING:
padded = false;
break;
case CipherPadding.RAW:
break;
case CipherPadding.ISO10126PADDING:
case CipherPadding.ISO10126D2PADDING:
case CipherPadding.ISO10126_2PADDING:
padding = new ISO10126d2Padding();
break;
case CipherPadding.ISO7816_4PADDING:
case CipherPadding.ISO9797_1PADDING:
padding = new ISO7816d4Padding();
break;
case CipherPadding.ISO9796_1:
case CipherPadding.ISO9796_1PADDING:
asymBlockCipher = new ISO9796d1Encoding(asymBlockCipher);
break;
case CipherPadding.OAEP:
case CipherPadding.OAEPPADDING:
asymBlockCipher = new OaepEncoding(asymBlockCipher);
break;
case CipherPadding.OAEPWITHMD5ANDMGF1PADDING:
asymBlockCipher = new OaepEncoding(asymBlockCipher, new MD5Digest());
break;
case CipherPadding.OAEPWITHSHA1ANDMGF1PADDING:
case CipherPadding.OAEPWITHSHA_1ANDMGF1PADDING:
asymBlockCipher = new OaepEncoding(asymBlockCipher, new Sha1Digest());
break;
case CipherPadding.OAEPWITHSHA224ANDMGF1PADDING:
case CipherPadding.OAEPWITHSHA_224ANDMGF1PADDING:
asymBlockCipher = new OaepEncoding(asymBlockCipher, new Sha224Digest());
break;
case CipherPadding.OAEPWITHSHA256ANDMGF1PADDING:
case CipherPadding.OAEPWITHSHA_256ANDMGF1PADDING:
asymBlockCipher = new OaepEncoding(asymBlockCipher, new Sha256Digest());
break;
case CipherPadding.OAEPWITHSHA384ANDMGF1PADDING:
case CipherPadding.OAEPWITHSHA_384ANDMGF1PADDING:
asymBlockCipher = new OaepEncoding(asymBlockCipher, new Sha384Digest());
break;
case CipherPadding.OAEPWITHSHA512ANDMGF1PADDING:
case CipherPadding.OAEPWITHSHA_512ANDMGF1PADDING:
asymBlockCipher = new OaepEncoding(asymBlockCipher, new Sha512Digest());
break;
case CipherPadding.PKCS1:
case CipherPadding.PKCS1PADDING:
asymBlockCipher = new Pkcs1Encoding(asymBlockCipher);
break;
case CipherPadding.PKCS5:
case CipherPadding.PKCS5PADDING:
case CipherPadding.PKCS7:
case CipherPadding.PKCS7PADDING:
padding = new Pkcs7Padding();
break;
case CipherPadding.TBCPADDING:
padding = new TbcPadding();
break;
case CipherPadding.WITHCTS:
cts = true;
break;
case CipherPadding.X923PADDING:
padding = new X923Padding();
break;
case CipherPadding.ZEROBYTEPADDING:
padding = new ZeroBytePadding();
break;
default:
throw new SecurityUtilityException("Cipher " + algorithm + " not recognised.");
}
}
var mode = "";
if (parts.Length > 1)
{
mode = parts[1];
var di = GetDigitIndex(mode);
var modeName = di >= 0 ? mode.Substring(0, di) : mode;
try
{
var cipherMode = modeName == ""
? CipherMode.NONE
: (CipherMode)Enums.GetEnumValue(typeof(CipherMode), modeName);
switch (cipherMode)
{
case CipherMode.ECB:
case CipherMode.NONE:
break;
case CipherMode.CBC:
blockCipher = new CbcBlockCipher(blockCipher);
break;
case CipherMode.CFB:
{
var bits = (di < 0)
? 8 * blockCipher.GetBlockSize()
: int.Parse(mode.Substring(di));
blockCipher = new CfbBlockCipher(blockCipher, bits);
break;
}
case CipherMode.CTR:
blockCipher = new SicBlockCipher(blockCipher);
break;
case CipherMode.CTS:
cts = true;
blockCipher = new CbcBlockCipher(blockCipher);
break;
case CipherMode.EAX:
aeadBlockCipher = new EaxBlockCipher(blockCipher);
break;
case CipherMode.GCM:
aeadBlockCipher = new GcmBlockCipher(blockCipher);
break;
case CipherMode.GOFB:
blockCipher = new GOfbBlockCipher(blockCipher);
break;
case CipherMode.OCB:
aeadBlockCipher = new OcbBlockCipher(blockCipher, CreateBlockCipher(cipherAlgorithm));
break;
case CipherMode.OFB:
{
var bits = (di < 0)
? 8 * blockCipher.GetBlockSize()
: int.Parse(mode.Substring(di));
blockCipher = new OfbBlockCipher(blockCipher, bits);
break;
}
case CipherMode.OPENPGPCFB:
blockCipher = new OpenPgpCfbBlockCipher(blockCipher);
break;
case CipherMode.SIC:
if (blockCipher.GetBlockSize() < 16)
{
throw new ArgumentException("Warning: SIC-Mode can become a twotime-pad if the blocksize of the cipher is too small. Use a cipher with a block size of at least 128 bits (e.g. AES)");
}
blockCipher = new SicBlockCipher(blockCipher);
break;
default:
throw new SecurityUtilityException("Cipher " + algorithm + " not recognised.");
}
}
catch (ArgumentException)
{
throw new SecurityUtilityException("Cipher " + algorithm + " not recognised.");
}
}
if (aeadBlockCipher != null)
{
if (cts)
throw new SecurityUtilityException("CTS mode not valid for AEAD ciphers.");
if (padded && parts.Length > 2 && parts[2] != "")
throw new SecurityUtilityException("Bad padding specified for AEAD cipher.");
return new BufferedAeadBlockCipher(aeadBlockCipher);
}
if (blockCipher != null)
{
if (cts)
{
return new CtsBlockCipher(blockCipher);
}
if (padding != null)
{
return new PaddedBufferedBlockCipher(blockCipher, padding);
}
if (!padded || blockCipher.IsPartialBlockOkay)
{
return new BufferedBlockCipher(blockCipher);
}
return new PaddedBufferedBlockCipher(blockCipher);
}
if (asymBlockCipher != null)
{
return new BufferedAsymmetricBlockCipher(asymBlockCipher);
}
throw new SecurityUtilityException("Cipher " + algorithm + " not recognised.");
}
public static string GetAlgorithmName(
DerObjectIdentifier oid)
{
return (string) algorithms[oid.Id];
}
private static int GetDigitIndex(
string s)
{
for (var i = 0; i < s.Length; ++i)
{
if (char.IsDigit(s[i]))
return i;
}
return -1;
}
private static IBlockCipher CreateBlockCipher(CipherAlgorithm cipherAlgorithm)
{
switch (cipherAlgorithm)
{
case CipherAlgorithm.AES: return new AesFastEngine();
case CipherAlgorithm.BLOWFISH: return new BlowfishEngine();
case CipherAlgorithm.CAMELLIA: return new CamelliaEngine();
case CipherAlgorithm.CAST5: return new Cast5Engine();
case CipherAlgorithm.CAST6: return new Cast6Engine();
case CipherAlgorithm.DES: return new DesEngine();
case CipherAlgorithm.DESEDE: return new DesEdeEngine();
case CipherAlgorithm.GOST28147: return new Gost28147Engine();
case CipherAlgorithm.IDEA: return new IdeaEngine();
case CipherAlgorithm.NOEKEON: return new NoekeonEngine();
case CipherAlgorithm.RC2: return new RC2Engine();
case CipherAlgorithm.RC5: return new RC532Engine();
case CipherAlgorithm.RC5_64: return new RC564Engine();
case CipherAlgorithm.RC6: return new RC6Engine();
case CipherAlgorithm.RIJNDAEL: return new RijndaelEngine();
case CipherAlgorithm.SEED: return new SeedEngine();
case CipherAlgorithm.SERPENT: return new SerpentEngine();
case CipherAlgorithm.SKIPJACK: return new SkipjackEngine();
case CipherAlgorithm.TEA: return new TeaEngine();
case CipherAlgorithm.TWOFISH: return new TwofishEngine();
case CipherAlgorithm.XTEA: return new XteaEngine();
default:
throw new SecurityUtilityException("Cipher " + cipherAlgorithm + " not recognised or not a block cipher");
}
}
}
}
| |
// Copyright (c) Alexandre Mutel. All rights reserved.
// Licensed under the BSD-Clause 2 license.
// See license.txt file in the project root for full license information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
namespace Scriban.Syntax
{
[ScriptSyntax("literal", "<value>")]
#if SCRIBAN_PUBLIC
public
#else
internal
#endif
partial class ScriptLiteral : ScriptExpression, IScriptTerminal
{
public ScriptLiteral()
{
}
public ScriptLiteral(object value)
{
Value = value;
}
public ScriptTrivias Trivias { get; set; }
public object Value { get; set; }
public ScriptLiteralStringQuoteType StringQuoteType { get; set; }
public override object Evaluate(TemplateContext context)
{
return Value;
}
public bool IsPositiveInteger()
{
if (Value == null)
{
return false;
}
var type = Value.GetType();
if (type == typeof(int))
{
return ((int)Value) >= 0;
}
else if (type == typeof(byte))
{
return true;
}
else if (type == typeof(sbyte))
{
return ((sbyte)Value) >= 0;
}
else if (type == typeof(short))
{
return ((short)Value) >= 0;
}
else if (type == typeof(ushort))
{
return true;
}
else if (type == typeof(uint))
{
return true;
}
else if (type == typeof(long))
{
return (long)Value > 0;
}
else if (type == typeof(ulong))
{
return true;
}
return false;
}
public override void PrintTo(ScriptPrinter printer)
{
if (Value == null)
{
printer.Write("null");
return;
}
var type = Value.GetType();
if (type == typeof(string))
{
printer.Write(ToLiteral(StringQuoteType, (string) Value));
}
else if (type == typeof(bool))
{
printer.Write(((bool) Value) ? "true" : "false");
}
else if (type == typeof(int))
{
printer.Write(((int) Value).ToString(CultureInfo.InvariantCulture));
}
else if (type == typeof(double))
{
printer.Write(AppendDecimalPoint(((double)Value).ToString("R", CultureInfo.InvariantCulture), true));
}
else if (type == typeof(float))
{
printer.Write(AppendDecimalPoint(((float)Value).ToString("R", CultureInfo.InvariantCulture), true));
printer.Write("f");
}
else if (type == typeof(decimal))
{
printer.Write(AppendDecimalPoint(((decimal)Value).ToString(CultureInfo.InvariantCulture), true));
printer.Write("m");
}
else if (type == typeof(byte))
{
printer.Write(((byte) Value).ToString(CultureInfo.InvariantCulture));
}
else if (type == typeof(sbyte))
{
printer.Write(((sbyte) Value).ToString(CultureInfo.InvariantCulture));
}
else if (type == typeof(short))
{
printer.Write(((short) Value).ToString(CultureInfo.InvariantCulture));
}
else if (type == typeof(ushort))
{
printer.Write(((ushort) Value).ToString(CultureInfo.InvariantCulture));
}
else if (type == typeof(uint))
{
printer.Write(((uint) Value).ToString(CultureInfo.InvariantCulture));
}
else if (type == typeof(long))
{
printer.Write(((long) Value).ToString(CultureInfo.InvariantCulture));
}
else if (type == typeof(ulong))
{
printer.Write(((uint) Value).ToString(CultureInfo.InvariantCulture));
}
else if (type == typeof(char))
{
printer.Write(ToLiteral(ScriptLiteralStringQuoteType.SimpleQuote, Value.ToString()));
}
else
{
printer.Write(Value.ToString());
}
}
private static string ToLiteral(ScriptLiteralStringQuoteType quoteType, string input)
{
char quote;
switch (quoteType)
{
case ScriptLiteralStringQuoteType.DoubleQuote:
quote = '"';
break;
case ScriptLiteralStringQuoteType.SimpleQuote:
quote = '\'';
break;
case ScriptLiteralStringQuoteType.Verbatim:
quote = '`';
break;
default:
throw new ArgumentOutOfRangeException(nameof(quoteType));
}
var literal = new StringBuilder(input.Length + 2);
literal.Append(quote);
if (quoteType == ScriptLiteralStringQuoteType.Verbatim)
{
literal.Append(input.Replace("`", "``"));
}
else
{
foreach (var c in input)
{
switch (c)
{
case '\\': literal.Append(@"\\"); break;
case '\0': literal.Append(@"\0"); break;
case '\a': literal.Append(@"\a"); break;
case '\b': literal.Append(@"\b"); break;
case '\f': literal.Append(@"\f"); break;
case '\n': literal.Append(@"\n"); break;
case '\r': literal.Append(@"\r"); break;
case '\t': literal.Append(@"\t"); break;
case '\v': literal.Append(@"\v"); break;
default:
if (c == quote)
{
literal.Append('\\').Append(c);
}
else if (char.IsControl(c))
{
literal.Append(@"\u");
literal.Append(((ushort)c).ToString("x4"));
}
else
{
literal.Append(c);
}
break;
}
}
}
literal.Append(quote);
return literal.ToString();
}
// Code from SharpYaml
private static string AppendDecimalPoint(string text, bool hasNaN)
{
for (var i = 0; i < text.Length; i++)
{
var c = text[i];
// Do not append a decimal point if floating point type value
// - is in exponential form, or
// - already has a decimal point
if (c == 'e' || c == 'E' || c == '.')
{
return text;
}
}
// Special cases for floating point type supporting NaN and Infinity
if (hasNaN && (string.Equals(text, "NaN") || text.Contains("Infinity")))
return text;
return text + ".0";
}
}
#if SCRIBAN_PUBLIC
public
#else
internal
#endif
enum ScriptLiteralStringQuoteType
{
DoubleQuote,
SimpleQuote,
Verbatim
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the opsworks-2013-02-18.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.OpsWorks.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.OpsWorks.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for Stack Object
/// </summary>
public class StackUnmarshaller : IUnmarshaller<Stack, XmlUnmarshallerContext>, IUnmarshaller<Stack, JsonUnmarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
Stack IUnmarshaller<Stack, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context)
{
throw new NotImplementedException();
}
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public Stack Unmarshall(JsonUnmarshallerContext context)
{
context.Read();
if (context.CurrentTokenType == JsonToken.Null)
return null;
Stack unmarshalledObject = new Stack();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("AgentVersion", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.AgentVersion = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("Arn", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.Arn = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("Attributes", targetDepth))
{
var unmarshaller = new DictionaryUnmarshaller<string, string, StringUnmarshaller, StringUnmarshaller>(StringUnmarshaller.Instance, StringUnmarshaller.Instance);
unmarshalledObject.Attributes = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("ChefConfiguration", targetDepth))
{
var unmarshaller = ChefConfigurationUnmarshaller.Instance;
unmarshalledObject.ChefConfiguration = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("ConfigurationManager", targetDepth))
{
var unmarshaller = StackConfigurationManagerUnmarshaller.Instance;
unmarshalledObject.ConfigurationManager = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("CreatedAt", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.CreatedAt = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("CustomCookbooksSource", targetDepth))
{
var unmarshaller = SourceUnmarshaller.Instance;
unmarshalledObject.CustomCookbooksSource = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("CustomJson", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.CustomJson = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("DefaultAvailabilityZone", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.DefaultAvailabilityZone = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("DefaultInstanceProfileArn", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.DefaultInstanceProfileArn = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("DefaultOs", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.DefaultOs = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("DefaultRootDeviceType", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.DefaultRootDeviceType = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("DefaultSshKeyName", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.DefaultSshKeyName = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("DefaultSubnetId", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.DefaultSubnetId = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("HostnameTheme", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.HostnameTheme = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("Name", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.Name = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("Region", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.Region = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("ServiceRoleArn", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.ServiceRoleArn = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("StackId", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.StackId = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("UseCustomCookbooks", targetDepth))
{
var unmarshaller = BoolUnmarshaller.Instance;
unmarshalledObject.UseCustomCookbooks = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("UseOpsworksSecurityGroups", targetDepth))
{
var unmarshaller = BoolUnmarshaller.Instance;
unmarshalledObject.UseOpsworksSecurityGroups = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("VpcId", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.VpcId = unmarshaller.Unmarshall(context);
continue;
}
}
return unmarshalledObject;
}
private static StackUnmarshaller _instance = new StackUnmarshaller();
/// <summary>
/// Gets the singleton.
/// </summary>
public static StackUnmarshaller Instance
{
get
{
return _instance;
}
}
}
}
| |
// 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.Linq;
using Xunit;
public static class GuidTests
{
private static readonly Guid _testGuid = new Guid("a8a110d5-fc49-43c5-bf46-802db8f843ff");
[Fact]
public static void Testctor()
{
// Void Guid..ctor(Byte[])
var g1 = new Guid(_testGuid.ToByteArray());
Assert.Equal(_testGuid, g1);
// Void Guid..ctor(Int32, Int16, Int16, Byte, Byte, Byte, Byte, Byte, Byte, Byte, Byte)
var g2 = new Guid(unchecked((int)0xa8a110d5), unchecked((short)0xfc49), (short)0x43c5, 0xbf, 0x46, 0x80, 0x2d, 0xb8, 0xf8, 0x43, 0xff);
Assert.Equal(_testGuid, g2);
// Void Guid..ctor(Int32, Int16, Int16, Byte[])
var g3 = new Guid(unchecked((int)0xa8a110d5), unchecked((short)0xfc49), (short)0x43c5, new byte[] { 0xbf, 0x46, 0x80, 0x2d, 0xb8, 0xf8, 0x43, 0xff });
Assert.Equal(_testGuid, g3);
// Void Guid..ctor(String)
var g4 = new Guid("a8a110d5-fc49-43c5-bf46-802db8f843ff");
Assert.Equal(_testGuid, g4);
}
[Fact]
public static void TestEquals()
{
// Boolean Guid.Equals(Guid)
Assert.True(_testGuid.Equals(_testGuid));
Assert.False(_testGuid.Equals(Guid.Empty));
Assert.False(Guid.Empty.Equals(_testGuid));
// Boolean Guid.Equals(Object)
Assert.False(_testGuid.Equals(null));
Assert.False(_testGuid.Equals("a8a110d5-fc49-43c5-bf46-802db8f843ff"));
// Boolean Guid.op_Equality(Guid, Guid)
Assert.True(_testGuid == new Guid("a8a110d5-fc49-43c5-bf46-802db8f843ff"));
Assert.True(Guid.Empty == new Guid(0, 0, 0, new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 }));
// Boolean Guid.op_Inequality(Guid, Guid)
Assert.True(_testGuid != Guid.Empty);
Assert.True(Guid.Empty != _testGuid);
}
[Fact]
public static void TestCompareTo()
{
// Int32 Guid.CompareTo(Guid)
Assert.True(_testGuid.CompareTo(new Guid("98a110d5-fc49-43c5-bf46-802db8f843ff")) > 0);
Assert.True(_testGuid.CompareTo(new Guid("a8a110d5-fc49-43c5-bf46-802db8f843ff")) == 0);
Assert.True(_testGuid.CompareTo(new Guid("e8a110d5-fc49-43c5-bf46-802db8f843ff")) < 0);
// Int32 Guid.System.IComparable.CompareTo(Object)
IComparable icomp = _testGuid;
Assert.True(icomp.CompareTo(new Guid("98a110d5-fc49-43c5-bf46-802db8f843ff")) > 0);
Assert.True(icomp.CompareTo(new Guid("a8a110d5-fc49-43c5-bf46-802db8f843ff")) == 0);
Assert.True(icomp.CompareTo(new Guid("e8a110d5-fc49-43c5-bf46-802db8f843ff")) < 0);
Assert.True(icomp.CompareTo(null) > 0);
Assert.Throws<ArgumentException>(() => icomp.CompareTo("a8a110d5-fc49-43c5-bf46-802db8f843ff"));
}
[Fact]
public static void TestToByteArray()
{
// Byte[] Guid.ToByteArray()
var bytes1 = new byte[] { 0xd5, 0x10, 0xa1, 0xa8, 0x49, 0xfc, 0xc5, 0x43, 0xbf, 0x46, 0x80, 0x2d, 0xb8, 0xf8, 0x43, 0xff };
var bytes2 = _testGuid.ToByteArray();
Assert.Equal(bytes1.Length, bytes2.Length);
for (int i = 0; i < bytes1.Length; i++)
Assert.Equal(bytes1[i], bytes2[i]);
}
[Fact]
public static void TestEmpty()
{
// Guid Guid.Empty
Assert.Equal(Guid.Empty, new Guid(0, 0, 0, new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 }));
}
[Fact]
public static void TestNewGuid()
{
// Guid Guid.NewGuid()
var g = Guid.NewGuid();
Assert.NotEqual(Guid.Empty, g);
var g2 = Guid.NewGuid();
Assert.NotEqual(g, g2);
}
[Fact]
public static void TestParse()
{
// Guid Guid.Parse(String)
// Guid Guid.ParseExact(String, String)
Assert.Equal(_testGuid, Guid.Parse("a8a110d5-fc49-43c5-bf46-802db8f843ff"));
Assert.Equal(_testGuid, Guid.Parse("a8a110d5fc4943c5bf46802db8f843ff"));
Assert.Equal(_testGuid, Guid.Parse("a8a110d5-fc49-43c5-bf46-802db8f843ff"));
Assert.Equal(_testGuid, Guid.Parse("{a8a110d5-fc49-43c5-bf46-802db8f843ff}"));
Assert.Equal(_testGuid, Guid.Parse("(a8a110d5-fc49-43c5-bf46-802db8f843ff)"));
Assert.Equal(_testGuid, Guid.Parse("{0xa8a110d5,0xfc49,0x43c5,{0xbf,0x46,0x80,0x2d,0xb8,0xf8,0x43,0xff}}"));
Assert.Equal(_testGuid, Guid.ParseExact("a8a110d5fc4943c5bf46802db8f843ff", "N"));
Assert.Equal(_testGuid, Guid.ParseExact("a8a110d5-fc49-43c5-bf46-802db8f843ff", "D"));
Assert.Equal(_testGuid, Guid.ParseExact("{a8a110d5-fc49-43c5-bf46-802db8f843ff}", "B"));
Assert.Equal(_testGuid, Guid.ParseExact("(a8a110d5-fc49-43c5-bf46-802db8f843ff)", "P"));
Assert.Equal(_testGuid, Guid.ParseExact("{0xa8a110d5,0xfc49,0x43c5,{0xbf,0x46,0x80,0x2d,0xb8,0xf8,0x43,0xff}}", "X"));
}
[Fact]
public static void TestTryParse()
{
// Boolean Guid.TryParse(String, Guid)
// Boolean Guid.TryParseExact(String, String, Guid)
Guid g;
Assert.True(Guid.TryParse("a8a110d5-fc49-43c5-bf46-802db8f843ff", out g));
Assert.Equal(_testGuid, g);
Assert.True(Guid.TryParse("a8a110d5fc4943c5bf46802db8f843ff", out g));
Assert.Equal(_testGuid, g);
Assert.True(Guid.TryParse("a8a110d5-fc49-43c5-bf46-802db8f843ff", out g));
Assert.Equal(_testGuid, g);
Assert.True(Guid.TryParse("{a8a110d5-fc49-43c5-bf46-802db8f843ff}", out g));
Assert.Equal(_testGuid, g);
Assert.True(Guid.TryParse("(a8a110d5-fc49-43c5-bf46-802db8f843ff)", out g));
Assert.Equal(_testGuid, g);
Assert.True(Guid.TryParse("{0xa8a110d5,0xfc49,0x43c5,{0xbf,0x46,0x80,0x2d,0xb8,0xf8,0x43,0xff}}", out g));
Assert.Equal(_testGuid, g);
Assert.True(Guid.TryParseExact("a8a110d5fc4943c5bf46802db8f843ff", "N", out g));
Assert.Equal(_testGuid, g);
Assert.True(Guid.TryParseExact("a8a110d5-fc49-43c5-bf46-802db8f843ff", "D", out g));
Assert.Equal(_testGuid, g);
Assert.True(Guid.TryParseExact("{a8a110d5-fc49-43c5-bf46-802db8f843ff}", "B", out g));
Assert.Equal(_testGuid, g);
Assert.True(Guid.TryParseExact("(a8a110d5-fc49-43c5-bf46-802db8f843ff)", "P", out g));
Assert.Equal(_testGuid, g);
Assert.True(Guid.TryParseExact("{0xa8a110d5,0xfc49,0x43c5,{0xbf,0x46,0x80,0x2d,0xb8,0xf8,0x43,0xff}}", "X", out g));
Assert.Equal(_testGuid, g);
Assert.False(Guid.TryParse("a8a110d5fc4943c5bf46802db8f843f", out g)); // One two few digits
Assert.False(Guid.TryParseExact("a8a110d5-fc49-43c5-bf46-802db8f843ff", "N", out g)); // Contains '-' when "N" doesn't support those
}
[Fact]
public static void TestGetHashCode()
{
// Int32 Guid.GetHashCode()
Assert.NotEqual(_testGuid.GetHashCode(), Guid.Empty.GetHashCode());
}
[Fact]
public static void TestToString()
{
// String Guid.ToString()
// String Guid.ToString(String)
// String Guid.System.IFormattable.ToString(String, IFormatProvider) // The IFormatProvider is ignored so don't need to test
Assert.Equal(_testGuid.ToString(), "a8a110d5-fc49-43c5-bf46-802db8f843ff");
Assert.Equal(_testGuid.ToString("N"), "a8a110d5fc4943c5bf46802db8f843ff");
Assert.Equal(_testGuid.ToString("D"), "a8a110d5-fc49-43c5-bf46-802db8f843ff");
Assert.Equal(_testGuid.ToString("B"), "{a8a110d5-fc49-43c5-bf46-802db8f843ff}");
Assert.Equal(_testGuid.ToString("P"), "(a8a110d5-fc49-43c5-bf46-802db8f843ff)");
Assert.Equal(_testGuid.ToString("X"), "{0xa8a110d5,0xfc49,0x43c5,{0xbf,0x46,0x80,0x2d,0xb8,0xf8,0x43,0xff}}");
}
[Fact]
public static void TestRandomness()
{
const int Iterations = 100;
const int GuidSize = 16;
byte[] random = new byte[GuidSize * Iterations];
for (int i = 0; i < Iterations; i++)
{
// Get a new Guid
Guid g = Guid.NewGuid();
byte[] bytes = g.ToByteArray();
// Make sure it's different from all of the previously created ones
for (int j = 0; j < i; j++)
{
Assert.False(bytes.SequenceEqual(new ArraySegment<byte>(random, j * GuidSize, GuidSize)));
}
// Copy it to our randomness array
Array.Copy(bytes, 0, random, i * GuidSize, GuidSize);
}
// Verify the randomness of the data in the array. Guid has some small bias in it
// due to several bits fixed based on the format, but that bias is small enough and
// the variability allowed by VerifyRandomDistribution large enough that we don't do
// anything special for it.
RandomDataGenerator.VerifyRandomDistribution(random);
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics.Contracts;
using System.Runtime.Serialization;
using System.Threading;
namespace System.Globalization
{
// Gregorian Calendars use Era Info
[Serializable]
internal class EraInfo
{
internal int era; // The value of the era.
internal long ticks; // The time in ticks when the era starts
internal int yearOffset; // The offset to Gregorian year when the era starts.
// Gregorian Year = Era Year + yearOffset
// Era Year = Gregorian Year - yearOffset
internal int minEraYear; // Min year value in this era. Generally, this value is 1, but this may
// be affected by the DateTime.MinValue;
internal int maxEraYear; // Max year value in this era. (== the year length of the era + 1)
internal String eraName; // The era name
internal String abbrevEraName; // Abbreviated Era Name
internal String englishEraName; // English era name
internal EraInfo(int era, int startYear, int startMonth, int startDay, int yearOffset, int minEraYear, int maxEraYear)
{
this.era = era;
this.yearOffset = yearOffset;
this.minEraYear = minEraYear;
this.maxEraYear = maxEraYear;
this.ticks = new DateTime(startYear, startMonth, startDay).Ticks;
}
internal EraInfo(int era, int startYear, int startMonth, int startDay, int yearOffset, int minEraYear, int maxEraYear,
String eraName, String abbrevEraName, String englishEraName)
{
this.era = era;
this.yearOffset = yearOffset;
this.minEraYear = minEraYear;
this.maxEraYear = maxEraYear;
this.ticks = new DateTime(startYear, startMonth, startDay).Ticks;
this.eraName = eraName;
this.abbrevEraName = abbrevEraName;
this.englishEraName = englishEraName;
}
}
// This calendar recognizes two era values:
// 0 CurrentEra (AD)
// 1 BeforeCurrentEra (BC)
internal class GregorianCalendarHelper
{
// 1 tick = 100ns = 10E-7 second
// Number of ticks per time unit
internal const long TicksPerMillisecond = 10000;
internal const long TicksPerSecond = TicksPerMillisecond * 1000;
internal const long TicksPerMinute = TicksPerSecond * 60;
internal const long TicksPerHour = TicksPerMinute * 60;
internal const long TicksPerDay = TicksPerHour * 24;
// Number of milliseconds per time unit
internal const int MillisPerSecond = 1000;
internal const int MillisPerMinute = MillisPerSecond * 60;
internal const int MillisPerHour = MillisPerMinute * 60;
internal const int MillisPerDay = MillisPerHour * 24;
// Number of days in a non-leap year
internal const int DaysPerYear = 365;
// Number of days in 4 years
internal const int DaysPer4Years = DaysPerYear * 4 + 1;
// Number of days in 100 years
internal const int DaysPer100Years = DaysPer4Years * 25 - 1;
// Number of days in 400 years
internal const int DaysPer400Years = DaysPer100Years * 4 + 1;
// Number of days from 1/1/0001 to 1/1/10000
internal const int DaysTo10000 = DaysPer400Years * 25 - 366;
internal const long MaxMillis = (long)DaysTo10000 * MillisPerDay;
internal const int DatePartYear = 0;
internal const int DatePartDayOfYear = 1;
internal const int DatePartMonth = 2;
internal const int DatePartDay = 3;
//
// This is the max Gregorian year can be represented by DateTime class. The limitation
// is derived from DateTime class.
//
internal int MaxYear
{
get
{
return (m_maxYear);
}
}
internal static readonly int[] DaysToMonth365 =
{
0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365
};
internal static readonly int[] DaysToMonth366 =
{
0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366
};
internal int m_maxYear = 9999;
internal int m_minYear;
internal Calendar m_Cal;
internal EraInfo[] m_EraInfo;
internal int[] m_eras = null;
// Construct an instance of gregorian calendar.
internal GregorianCalendarHelper(Calendar cal, EraInfo[] eraInfo)
{
m_Cal = cal;
m_EraInfo = eraInfo;
m_maxYear = m_EraInfo[0].maxEraYear;
m_minYear = m_EraInfo[0].minEraYear; ;
}
/*=================================GetGregorianYear==========================
**Action: Get the Gregorian year value for the specified year in an era.
**Returns: The Gregorian year value.
**Arguments:
** year the year value in Japanese calendar
** era the Japanese emperor era value.
**Exceptions:
** ArgumentOutOfRangeException if year value is invalid or era value is invalid.
============================================================================*/
internal int GetGregorianYear(int year, int era)
{
if (year < 0)
{
throw new ArgumentOutOfRangeException(nameof(year),
SR.ArgumentOutOfRange_NeedNonNegNum);
}
Contract.EndContractBlock();
if (era == Calendar.CurrentEra)
{
era = m_Cal.CurrentEraValue;
}
for (int i = 0; i < m_EraInfo.Length; i++)
{
if (era == m_EraInfo[i].era)
{
if (year < m_EraInfo[i].minEraYear || year > m_EraInfo[i].maxEraYear)
{
throw new ArgumentOutOfRangeException(
nameof(year),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
m_EraInfo[i].minEraYear,
m_EraInfo[i].maxEraYear));
}
return (m_EraInfo[i].yearOffset + year);
}
}
throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue);
}
internal bool IsValidYear(int year, int era)
{
if (year < 0)
{
return false;
}
if (era == Calendar.CurrentEra)
{
era = m_Cal.CurrentEraValue;
}
for (int i = 0; i < m_EraInfo.Length; i++)
{
if (era == m_EraInfo[i].era)
{
if (year < m_EraInfo[i].minEraYear || year > m_EraInfo[i].maxEraYear)
{
return false;
}
return true;
}
}
return false;
}
// Returns a given date part of this DateTime. This method is used
// to compute the year, day-of-year, month, or day part.
internal virtual int GetDatePart(long ticks, int part)
{
CheckTicksRange(ticks);
// n = number of days since 1/1/0001
int n = (int)(ticks / TicksPerDay);
// y400 = number of whole 400-year periods since 1/1/0001
int y400 = n / DaysPer400Years;
// n = day number within 400-year period
n -= y400 * DaysPer400Years;
// y100 = number of whole 100-year periods within 400-year period
int y100 = n / DaysPer100Years;
// Last 100-year period has an extra day, so decrement result if 4
if (y100 == 4) y100 = 3;
// n = day number within 100-year period
n -= y100 * DaysPer100Years;
// y4 = number of whole 4-year periods within 100-year period
int y4 = n / DaysPer4Years;
// n = day number within 4-year period
n -= y4 * DaysPer4Years;
// y1 = number of whole years within 4-year period
int y1 = n / DaysPerYear;
// Last year has an extra day, so decrement result if 4
if (y1 == 4) y1 = 3;
// If year was requested, compute and return it
if (part == DatePartYear)
{
return (y400 * 400 + y100 * 100 + y4 * 4 + y1 + 1);
}
// n = day number within year
n -= y1 * DaysPerYear;
// If day-of-year was requested, return it
if (part == DatePartDayOfYear)
{
return (n + 1);
}
// Leap year calculation looks different from IsLeapYear since y1, y4,
// and y100 are relative to year 1, not year 0
bool leapYear = (y1 == 3 && (y4 != 24 || y100 == 3));
int[] days = leapYear ? DaysToMonth366 : DaysToMonth365;
// All months have less than 32 days, so n >> 5 is a good conservative
// estimate for the month
int m = (n >> 5) + 1;
// m = 1-based month number
while (n >= days[m]) m++;
// If month was requested, return it
if (part == DatePartMonth) return (m);
// Return 1-based day-of-month
return (n - days[m - 1] + 1);
}
/*=================================GetAbsoluteDate==========================
**Action: Gets the absolute date for the given Gregorian date. The absolute date means
** the number of days from January 1st, 1 A.D.
**Returns: the absolute date
**Arguments:
** year the Gregorian year
** month the Gregorian month
** day the day
**Exceptions:
** ArgumentOutOfRangException if year, month, day value is valid.
**Note:
** This is an internal method used by DateToTicks() and the calculations of Hijri and Hebrew calendars.
** Number of Days in Prior Years (both common and leap years) +
** Number of Days in Prior Months of Current Year +
** Number of Days in Current Month
**
============================================================================*/
internal static long GetAbsoluteDate(int year, int month, int day)
{
if (year >= 1 && year <= 9999 && month >= 1 && month <= 12)
{
int[] days = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0))) ? DaysToMonth366 : DaysToMonth365;
if (day >= 1 && (day <= days[month] - days[month - 1]))
{
int y = year - 1;
int absoluteDate = y * 365 + y / 4 - y / 100 + y / 400 + days[month - 1] + day - 1;
return (absoluteDate);
}
}
throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadYearMonthDay);
}
// Returns the tick count corresponding to the given year, month, and day.
// Will check the if the parameters are valid.
internal static long DateToTicks(int year, int month, int day)
{
return (GetAbsoluteDate(year, month, day) * TicksPerDay);
}
// Return the tick count corresponding to the given hour, minute, second.
// Will check the if the parameters are valid.
internal static long TimeToTicks(int hour, int minute, int second, int millisecond)
{
//TimeSpan.TimeToTicks is a family access function which does no error checking, so
//we need to put some error checking out here.
if (hour >= 0 && hour < 24 && minute >= 0 && minute < 60 && second >= 0 && second < 60)
{
if (millisecond < 0 || millisecond >= MillisPerSecond)
{
throw new ArgumentOutOfRangeException(
nameof(millisecond),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
0,
MillisPerSecond - 1));
}
return (InternalGlobalizationHelper.TimeToTicks(hour, minute, second) + millisecond * TicksPerMillisecond); ;
}
throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadHourMinuteSecond);
}
internal void CheckTicksRange(long ticks)
{
if (ticks < m_Cal.MinSupportedDateTime.Ticks || ticks > m_Cal.MaxSupportedDateTime.Ticks)
{
throw new ArgumentOutOfRangeException(
"time",
String.Format(
CultureInfo.InvariantCulture,
SR.ArgumentOutOfRange_CalendarRange,
m_Cal.MinSupportedDateTime,
m_Cal.MaxSupportedDateTime));
}
Contract.EndContractBlock();
}
// Returns the DateTime resulting from adding the given number of
// months to the specified DateTime. The result is computed by incrementing
// (or decrementing) the year and month parts of the specified DateTime by
// value months, and, if required, adjusting the day part of the
// resulting date downwards to the last day of the resulting month in the
// resulting year. The time-of-day part of the result is the same as the
// time-of-day part of the specified DateTime.
//
// In more precise terms, considering the specified DateTime to be of the
// form y / m / d + t, where y is the
// year, m is the month, d is the day, and t is the
// time-of-day, the result is y1 / m1 / d1 + t,
// where y1 and m1 are computed by adding value months
// to y and m, and d1 is the largest value less than
// or equal to d that denotes a valid day in month m1 of year
// y1.
//
public DateTime AddMonths(DateTime time, int months)
{
if (months < -120000 || months > 120000)
{
throw new ArgumentOutOfRangeException(
nameof(months),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
-120000,
120000));
}
Contract.EndContractBlock();
CheckTicksRange(time.Ticks);
int y = GetDatePart(time.Ticks, DatePartYear);
int m = GetDatePart(time.Ticks, DatePartMonth);
int d = GetDatePart(time.Ticks, DatePartDay);
int i = m - 1 + months;
if (i >= 0)
{
m = i % 12 + 1;
y = y + i / 12;
}
else
{
m = 12 + (i + 1) % 12;
y = y + (i - 11) / 12;
}
int[] daysArray = (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)) ? DaysToMonth366 : DaysToMonth365;
int days = (daysArray[m] - daysArray[m - 1]);
if (d > days)
{
d = days;
}
long ticks = DateToTicks(y, m, d) + (time.Ticks % TicksPerDay);
Calendar.CheckAddResult(ticks, m_Cal.MinSupportedDateTime, m_Cal.MaxSupportedDateTime);
return (new DateTime(ticks));
}
// Returns the DateTime resulting from adding the given number of
// years to the specified DateTime. The result is computed by incrementing
// (or decrementing) the year part of the specified DateTime by value
// years. If the month and day of the specified DateTime is 2/29, and if the
// resulting year is not a leap year, the month and day of the resulting
// DateTime becomes 2/28. Otherwise, the month, day, and time-of-day
// parts of the result are the same as those of the specified DateTime.
//
public DateTime AddYears(DateTime time, int years)
{
return (AddMonths(time, years * 12));
}
// Returns the day-of-month part of the specified DateTime. The returned
// value is an integer between 1 and 31.
//
public int GetDayOfMonth(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartDay));
}
// Returns the day-of-week part of the specified DateTime. The returned value
// is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates
// Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates
// Thursday, 5 indicates Friday, and 6 indicates Saturday.
//
public DayOfWeek GetDayOfWeek(DateTime time)
{
CheckTicksRange(time.Ticks);
return ((DayOfWeek)((time.Ticks / TicksPerDay + 1) % 7));
}
// Returns the day-of-year part of the specified DateTime. The returned value
// is an integer between 1 and 366.
//
public int GetDayOfYear(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartDayOfYear));
}
// Returns the number of days in the month given by the year and
// month arguments.
//
[Pure]
public int GetDaysInMonth(int year, int month, int era)
{
//
// Convert year/era value to Gregorain year value.
//
year = GetGregorianYear(year, era);
if (month < 1 || month > 12)
{
throw new ArgumentOutOfRangeException(nameof(month), SR.ArgumentOutOfRange_Month);
}
int[] days = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? DaysToMonth366 : DaysToMonth365);
return (days[month] - days[month - 1]);
}
// Returns the number of days in the year given by the year argument for the current era.
//
public int GetDaysInYear(int year, int era)
{
//
// Convert year/era value to Gregorain year value.
//
year = GetGregorianYear(year, era);
return ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? 366 : 365);
}
// Returns the era for the specified DateTime value.
public int GetEra(DateTime time)
{
long ticks = time.Ticks;
// The assumption here is that m_EraInfo is listed in reverse order.
for (int i = 0; i < m_EraInfo.Length; i++)
{
if (ticks >= m_EraInfo[i].ticks)
{
return (m_EraInfo[i].era);
}
}
throw new ArgumentOutOfRangeException(nameof(time), SR.ArgumentOutOfRange_Era);
}
public int[] Eras
{
get
{
if (m_eras == null)
{
m_eras = new int[m_EraInfo.Length];
for (int i = 0; i < m_EraInfo.Length; i++)
{
m_eras[i] = m_EraInfo[i].era;
}
}
return ((int[])m_eras.Clone());
}
}
// Returns the month part of the specified DateTime. The returned value is an
// integer between 1 and 12.
//
public int GetMonth(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartMonth));
}
// Returns the number of months in the specified year and era.
public int GetMonthsInYear(int year, int era)
{
year = GetGregorianYear(year, era);
return (12);
}
// Returns the year part of the specified DateTime. The returned value is an
// integer between 1 and 9999.
//
public int GetYear(DateTime time)
{
long ticks = time.Ticks;
int year = GetDatePart(ticks, DatePartYear);
for (int i = 0; i < m_EraInfo.Length; i++)
{
if (ticks >= m_EraInfo[i].ticks)
{
return (year - m_EraInfo[i].yearOffset);
}
}
throw new ArgumentException(SR.Argument_NoEra);
}
// Returns the year that match the specified Gregorian year. The returned value is an
// integer between 1 and 9999.
//
public int GetYear(int year, DateTime time)
{
long ticks = time.Ticks;
for (int i = 0; i < m_EraInfo.Length; i++)
{
// while calculating dates with JapaneseLuniSolarCalendar, we can run into cases right after the start of the era
// and still belong to the month which is started in previous era. Calculating equivalent calendar date will cause
// using the new era info which will have the year offset equal to the year we are calculating year = m_EraInfo[i].yearOffset
// which will end up with zero as calendar year.
// We should use the previous era info instead to get the right year number. Example of such date is Feb 2nd 1989
if (ticks >= m_EraInfo[i].ticks && year > m_EraInfo[i].yearOffset)
{
return (year - m_EraInfo[i].yearOffset);
}
}
throw new ArgumentException(SR.Argument_NoEra);
}
// Checks whether a given day in the specified era is a leap day. This method returns true if
// the date is a leap day, or false if not.
//
public bool IsLeapDay(int year, int month, int day, int era)
{
// year/month/era checking is done in GetDaysInMonth()
if (day < 1 || day > GetDaysInMonth(year, month, era))
{
throw new ArgumentOutOfRangeException(
nameof(day),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
1,
GetDaysInMonth(year, month, era)));
}
Contract.EndContractBlock();
if (!IsLeapYear(year, era))
{
return (false);
}
if (month == 2 && day == 29)
{
return (true);
}
return (false);
}
// Returns the leap month in a calendar year of the specified era. This method returns 0
// if this calendar does not have leap month, or this year is not a leap year.
//
public int GetLeapMonth(int year, int era)
{
year = GetGregorianYear(year, era);
return (0);
}
// Checks whether a given month in the specified era is a leap month. This method returns true if
// month is a leap month, or false if not.
//
public bool IsLeapMonth(int year, int month, int era)
{
year = GetGregorianYear(year, era);
if (month < 1 || month > 12)
{
throw new ArgumentOutOfRangeException(
nameof(month),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
1,
12));
}
return (false);
}
// Checks whether a given year in the specified era is a leap year. This method returns true if
// year is a leap year, or false if not.
//
public bool IsLeapYear(int year, int era)
{
year = GetGregorianYear(year, era);
return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
}
// Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid.
//
public DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era)
{
year = GetGregorianYear(year, era);
long ticks = DateToTicks(year, month, day) + TimeToTicks(hour, minute, second, millisecond);
CheckTicksRange(ticks);
return (new DateTime(ticks));
}
public virtual int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek)
{
CheckTicksRange(time.Ticks);
// Use GregorianCalendar to get around the problem that the implmentation in Calendar.GetWeekOfYear()
// can call GetYear() that exceeds the supported range of the Gregorian-based calendars.
return (GregorianCalendar.GetDefaultInstance().GetWeekOfYear(time, rule, firstDayOfWeek));
}
public int ToFourDigitYear(int year, int twoDigitYearMax)
{
if (year < 0)
{
throw new ArgumentOutOfRangeException(nameof(year),
SR.ArgumentOutOfRange_NeedPosNum);
}
Contract.EndContractBlock();
if (year < 100)
{
int y = year % 100;
return ((twoDigitYearMax / 100 - (y > twoDigitYearMax % 100 ? 1 : 0)) * 100 + y);
}
if (year < m_minYear || year > m_maxYear)
{
throw new ArgumentOutOfRangeException(
nameof(year),
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range, m_minYear, m_maxYear));
}
// If the year value is above 100, just return the year value. Don't have to do
// the TwoDigitYearMax comparison.
return (year);
}
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* 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 OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.CoreModules.ServiceConnectors.Interregion
{
public class LocalInterregionComms : IRegionModule, IInterregionCommsOut, IInterregionCommsIn
{
private bool m_enabled = false;
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private List<Scene> m_sceneList = new List<Scene>();
#region Events
public event ChildAgentUpdateReceived OnChildAgentUpdate;
#endregion /* Events */
#region IRegionModule
public void Initialize(Scene scene, IConfigSource config)
{
if (m_sceneList.Count == 0)
{
IConfig startupConfig = config.Configs["Communications"];
if ((startupConfig != null) && (startupConfig.GetString("InterregionComms", "RESTComms") == "LocalComms"))
{
m_log.Debug("[LOCAL COMMS]: Enabling InterregionComms LocalComms module");
m_enabled = true;
}
}
if (!m_enabled)
return;
Init(scene);
}
public void PostInitialize()
{
}
public void Close()
{
}
public string Name
{
get { return "LocalInterregionCommsModule"; }
}
public bool IsSharedModule
{
get { return true; }
}
/// <summary>
/// Can be called from other modules.
/// </summary>
/// <param name="scene"></param>
public void Init(Scene scene)
{
if (!m_sceneList.Contains(scene))
{
lock (m_sceneList)
{
m_sceneList.Add(scene);
if (m_enabled)
scene.RegisterModuleInterface<IInterregionCommsOut>(this);
scene.RegisterModuleInterface<IInterregionCommsIn>(this);
}
}
}
#endregion /* IRegionModule */
#region IInterregionComms
/**
* Agent-related communications
*/
public bool SendCreateChildAgent(ulong regionHandle, AgentCircuitData aCircuit, bool authorize, out string reason)
{
foreach (Scene s in m_sceneList)
{
if (s.RegionInfo.RegionHandle == regionHandle)
{
// If this is intended as a root agent entry into the region, check whether it's authorized (e.g. not banned).
if (authorize && !s.AuthorizeUserInRegion(aCircuit.AgentID, aCircuit.FirstName, aCircuit.LastName, aCircuit.ClientVersion, out reason))
return false;
// m_log.DebugFormat("[LOCAL COMMS]: Found region {0} to send SendCreateChildAgent", regionHandle);
return s.NewUserConnection(aCircuit, out reason);
}
}
// m_log.DebugFormat("[LOCAL COMMS]: Did not find region {0} for SendCreateChildAgent", regionHandle);
reason = "Did not find region.";
return false;
}
public bool SendChildAgentUpdate(ulong regionHandle, AgentData cAgentData)
{
foreach (Scene s in m_sceneList)
{
if (s.RegionInfo.RegionHandle == regionHandle)
{
//m_log.DebugFormat(
// "[LOCAL COMMS]: Found region {0} {1} to send ChildAgentUpdate",
// s.RegionInfo.RegionName, regionHandle);
s.IncomingChildAgentDataUpdate(cAgentData);
return true;
}
}
// m_log.DebugFormat("[LOCAL COMMS]: Did not find region {0} for ChildAgentUpdate", regionHandle);
return false;
}
public bool SendChildAgentUpdate(ulong regionHandle, AgentPosition cAgentData)
{
foreach (Scene s in m_sceneList)
{
if (s.RegionInfo.RegionHandle == regionHandle)
{
//m_log.Debug("[LOCAL COMMS]: Found region to send ChildAgentUpdate");
s.IncomingChildAgentDataUpdate(cAgentData);
return true;
}
}
//m_log.Debug("[LOCAL COMMS]: region not found for ChildAgentUpdate");
return false;
}
public bool SendRetrieveRootAgent(ulong regionHandle, UUID id, out IAgentData agent)
{
agent = null;
foreach (Scene s in m_sceneList)
{
if (s.RegionInfo.RegionHandle == regionHandle)
{
//m_log.Debug("[LOCAL COMMS]: Found region to send ChildAgentUpdate");
return s.IncomingRetrieveRootAgent(id, out agent);
}
}
//m_log.Debug("[LOCAL COMMS]: region not found for ChildAgentUpdate");
return false;
}
public bool SendReleaseAgent(ulong regionHandle, UUID id, string uri)
{
//uint x, y;
//Utils.LongToUInts(regionHandle, out x, out y);
//x = x / Constants.RegionSize;
//y = y / Constants.RegionSize;
//m_log.Debug("\n >>> Local SendReleaseAgent " + x + "-" + y);
foreach (Scene s in m_sceneList)
{
if (s.RegionInfo.RegionHandle == regionHandle)
{
//m_log.Debug("[LOCAL COMMS]: Found region to SendReleaseAgent");
return s.IncomingReleaseAgent(id);
}
}
//m_log.Debug("[LOCAL COMMS]: region not found in SendReleaseAgent");
return false;
}
public bool SendCloseAgent(ulong regionHandle, UUID id)
{
//uint x, y;
//Utils.LongToUInts(regionHandle, out x, out y);
//x = x / Constants.RegionSize;
//y = y / Constants.RegionSize;
//m_log.Debug("\n >>> Local SendCloseAgent " + x + "-" + y);
foreach (Scene s in m_sceneList)
{
if (s.RegionInfo.RegionHandle == regionHandle)
{
//m_log.Debug("[LOCAL COMMS]: Found region to SendCloseAgent");
return s.IncomingCloseAgent(id);
}
}
//m_log.Debug("[LOCAL COMMS]: region not found in SendCloseAgent");
return false;
}
/**
* Object-related communications
*/
public bool SendCreateObject(ulong regionHandle, SceneObjectGroup sog, List<UUID> avatars, bool isLocalCall, Vector3 posInOtherRegion,
bool isAttachment)
{
foreach (Scene s in m_sceneList)
{
if (s.RegionInfo.RegionHandle == regionHandle)
{
//m_log.Debug("[LOCAL COMMS]: Found region to SendCreateObject");
if (isLocalCall)
{
if (!isAttachment)
{
sog.OffsetForNewRegion(posInOtherRegion);
}
// We need to make a local copy of the object
ISceneObject sogClone = sog.CloneForNewScene();
sogClone.SetState(sog.GetStateSnapshot(true), s.RegionInfo.RegionID);
return s.IncomingCreateObject(sogClone, avatars);
}
else
{
// Use the object as it came through the wire
return s.IncomingCreateObject(sog, avatars);
}
}
}
return false;
}
public bool SendCreateObject(ulong regionHandle, UUID userID, UUID itemID)
{
foreach (Scene s in m_sceneList)
{
if (s.RegionInfo.RegionHandle == regionHandle)
{
return s.IncomingCreateObject(userID, itemID);
}
}
return false;
}
public bool SendDeleteObject(ulong regionHandle, UUID objectID, long nonceID)
{
foreach (Scene s in m_sceneList)
{
if (s.RegionInfo.RegionHandle == regionHandle)
{
SceneObjectPart part = s.GetSceneObjectPart(objectID);
SceneObjectGroup sog = (part == null) ? null : part.ParentGroup;
if (sog != null)
{
m_log.InfoFormat("[LOCAL COMMS]: Crossing abort - deleting object {0} named '{1}'.", sog.UUID, sog.Name);
s.DeleteSceneObject(sog, false, true, false);
return true;
}
}
}
return false;
}
public bool SendUpdateEstateInfo(UUID regionID)
{
foreach (Scene s in m_sceneList)
{
if (s.RegionInfo.RegionID == regionID)
{
// m_log.DebugFormat("[LOCAL COMMS]: Found region {0} to send SendUpdateEstateInfo", regionHandle);
EstateSettings es = s.StorageManager.EstateDataStore.LoadEstateSettings(s.RegionInfo.RegionID);
if (es == null)
return false;
// Don't replace the existing estate settings unless we were able to successfully fully load them.
s.RegionInfo.EstateSettings = es;
return true;
}
}
return false;
}
#endregion /* IInterregionComms */
#region Misc
public UUID GetRegionID(ulong regionhandle)
{
foreach (Scene s in m_sceneList)
{
if (s.RegionInfo.RegionHandle == regionhandle)
return s.RegionInfo.RegionID;
}
// ? weird. should not happen
return m_sceneList[0].RegionInfo.RegionID;
}
public bool IsLocalRegion(ulong regionhandle)
{
foreach (Scene s in m_sceneList)
if (s.RegionInfo.RegionHandle == regionhandle)
return true;
return false;
}
public SimpleRegionInfo GetRegion(ulong regionhandle)
{
foreach (Scene s in m_sceneList)
if (s.RegionInfo.RegionHandle == regionhandle)
return s.RegionInfo;
return null;
}
#endregion
public ChildAgentUpdate2Response SendChildAgentUpdate2(SimpleRegionInfo regionInfo, AgentData data)
{
foreach (Scene s in m_sceneList)
{
if (s.RegionInfo.RegionHandle == regionInfo.RegionHandle)
{
return s.IncomingChildAgentDataUpdate2(data);
}
}
return ChildAgentUpdate2Response.Error;
}
public System.Threading.Tasks.Task<Tuple<bool, string>> SendCreateRemoteChildAgentAsync(SimpleRegionInfo regionInfo, AgentCircuitData aCircuit)
{
throw new NotImplementedException();
}
internal bool SendWaitScenePresence(ulong regionHandle, UUID agentId, int maxSpWait)
{
foreach (Scene s in m_sceneList)
{
if (s.RegionInfo.RegionHandle == regionHandle)
{
if (s.IncomingWaitScenePresence(agentId, maxSpWait))
{
return true;
}
}
}
return false;
}
public System.Threading.Tasks.Task<bool> SendCloseAgentAsync(SimpleRegionInfo regionInfo, UUID id)
{
throw new NotImplementedException();
}
}
}
| |
//
// 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.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Common;
using Microsoft.WindowsAzure.Common.Internals;
using Microsoft.WindowsAzure.Management;
using Microsoft.WindowsAzure.Management.Models;
namespace Microsoft.WindowsAzure.Management
{
/// <summary>
/// Operation for listing subscription operations and details. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/gg715315.aspx for
/// more information)
/// </summary>
internal partial class SubscriptionOperations : IServiceOperations<ManagementClient>, ISubscriptionOperations
{
/// <summary>
/// Initializes a new instance of the SubscriptionOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal SubscriptionOperations(ManagementClient client)
{
this._client = client;
}
private ManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.WindowsAzure.Management.ManagementClient.
/// </summary>
public ManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// The Get Subscription operation returns account and resource
/// allocation information on the specified subscription. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/hh403995.aspx
/// for more information)
/// </summary>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The Get Subscription operation response.
/// </returns>
public async Task<SubscriptionGetResponse> GetAsync(CancellationToken cancellationToken)
{
// Validate
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
Tracing.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = this.Client.BaseUri + "/" + this.Client.Credentials.SubscriptionId;
// 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-version", "2013-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.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), CloudExceptionType.Xml);
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
SubscriptionGetResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new SubscriptionGetResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement subscriptionElement = responseDoc.Element(XName.Get("Subscription", "http://schemas.microsoft.com/windowsazure"));
if (subscriptionElement != null)
{
XElement subscriptionIDElement = subscriptionElement.Element(XName.Get("SubscriptionID", "http://schemas.microsoft.com/windowsazure"));
if (subscriptionIDElement != null)
{
string subscriptionIDInstance = subscriptionIDElement.Value;
result.SubscriptionID = subscriptionIDInstance;
}
XElement subscriptionNameElement = subscriptionElement.Element(XName.Get("SubscriptionName", "http://schemas.microsoft.com/windowsazure"));
if (subscriptionNameElement != null)
{
string subscriptionNameInstance = subscriptionNameElement.Value;
result.SubscriptionName = subscriptionNameInstance;
}
XElement subscriptionStatusElement = subscriptionElement.Element(XName.Get("SubscriptionStatus", "http://schemas.microsoft.com/windowsazure"));
if (subscriptionStatusElement != null)
{
SubscriptionStatus subscriptionStatusInstance = (SubscriptionStatus)Enum.Parse(typeof(SubscriptionStatus), subscriptionStatusElement.Value, false);
result.SubscriptionStatus = subscriptionStatusInstance;
}
XElement accountAdminLiveEmailIdElement = subscriptionElement.Element(XName.Get("AccountAdminLiveEmailId", "http://schemas.microsoft.com/windowsazure"));
if (accountAdminLiveEmailIdElement != null)
{
string accountAdminLiveEmailIdInstance = accountAdminLiveEmailIdElement.Value;
result.AccountAdminLiveEmailId = accountAdminLiveEmailIdInstance;
}
XElement serviceAdminLiveEmailIdElement = subscriptionElement.Element(XName.Get("ServiceAdminLiveEmailId", "http://schemas.microsoft.com/windowsazure"));
if (serviceAdminLiveEmailIdElement != null)
{
string serviceAdminLiveEmailIdInstance = serviceAdminLiveEmailIdElement.Value;
result.ServiceAdminLiveEmailId = serviceAdminLiveEmailIdInstance;
}
XElement maxCoreCountElement = subscriptionElement.Element(XName.Get("MaxCoreCount", "http://schemas.microsoft.com/windowsazure"));
if (maxCoreCountElement != null)
{
int maxCoreCountInstance = int.Parse(maxCoreCountElement.Value, CultureInfo.InvariantCulture);
result.MaximumCoreCount = maxCoreCountInstance;
}
XElement maxStorageAccountsElement = subscriptionElement.Element(XName.Get("MaxStorageAccounts", "http://schemas.microsoft.com/windowsazure"));
if (maxStorageAccountsElement != null)
{
int maxStorageAccountsInstance = int.Parse(maxStorageAccountsElement.Value, CultureInfo.InvariantCulture);
result.MaximumStorageAccounts = maxStorageAccountsInstance;
}
XElement maxHostedServicesElement = subscriptionElement.Element(XName.Get("MaxHostedServices", "http://schemas.microsoft.com/windowsazure"));
if (maxHostedServicesElement != null)
{
int maxHostedServicesInstance = int.Parse(maxHostedServicesElement.Value, CultureInfo.InvariantCulture);
result.MaximumHostedServices = maxHostedServicesInstance;
}
XElement currentCoreCountElement = subscriptionElement.Element(XName.Get("CurrentCoreCount", "http://schemas.microsoft.com/windowsazure"));
if (currentCoreCountElement != null)
{
int currentCoreCountInstance = int.Parse(currentCoreCountElement.Value, CultureInfo.InvariantCulture);
result.CurrentCoreCount = currentCoreCountInstance;
}
XElement currentStorageAccountsElement = subscriptionElement.Element(XName.Get("CurrentStorageAccounts", "http://schemas.microsoft.com/windowsazure"));
if (currentStorageAccountsElement != null)
{
int currentStorageAccountsInstance = int.Parse(currentStorageAccountsElement.Value, CultureInfo.InvariantCulture);
result.CurrentStorageAccounts = currentStorageAccountsInstance;
}
XElement currentHostedServicesElement = subscriptionElement.Element(XName.Get("CurrentHostedServices", "http://schemas.microsoft.com/windowsazure"));
if (currentHostedServicesElement != null)
{
int currentHostedServicesInstance = int.Parse(currentHostedServicesElement.Value, CultureInfo.InvariantCulture);
result.CurrentHostedServices = currentHostedServicesInstance;
}
XElement maxVirtualNetworkSitesElement = subscriptionElement.Element(XName.Get("MaxVirtualNetworkSites", "http://schemas.microsoft.com/windowsazure"));
if (maxVirtualNetworkSitesElement != null)
{
int maxVirtualNetworkSitesInstance = int.Parse(maxVirtualNetworkSitesElement.Value, CultureInfo.InvariantCulture);
result.MaximumVirtualNetworkSites = maxVirtualNetworkSitesInstance;
}
XElement currentVirtualNetworkSitesElement = subscriptionElement.Element(XName.Get("CurrentVirtualNetworkSites", "http://schemas.microsoft.com/windowsazure"));
if (currentVirtualNetworkSitesElement != null)
{
int currentVirtualNetworkSitesInstance = int.Parse(currentVirtualNetworkSitesElement.Value, CultureInfo.InvariantCulture);
result.CurrentVirtualNetworkSites = currentVirtualNetworkSitesInstance;
}
XElement maxLocalNetworkSitesElement = subscriptionElement.Element(XName.Get("MaxLocalNetworkSites", "http://schemas.microsoft.com/windowsazure"));
if (maxLocalNetworkSitesElement != null)
{
int maxLocalNetworkSitesInstance = int.Parse(maxLocalNetworkSitesElement.Value, CultureInfo.InvariantCulture);
result.MaximumLocalNetworkSites = maxLocalNetworkSitesInstance;
}
XElement maxDnsServersElement = subscriptionElement.Element(XName.Get("MaxDnsServers", "http://schemas.microsoft.com/windowsazure"));
if (maxDnsServersElement != null)
{
int maxDnsServersInstance = int.Parse(maxDnsServersElement.Value, CultureInfo.InvariantCulture);
result.MaximumDnsServers = maxDnsServersInstance;
}
XElement currentLocalNetworkSitesElement = subscriptionElement.Element(XName.Get("CurrentLocalNetworkSites", "http://schemas.microsoft.com/windowsazure"));
if (currentLocalNetworkSitesElement != null)
{
int currentLocalNetworkSitesInstance = int.Parse(currentLocalNetworkSitesElement.Value, CultureInfo.InvariantCulture);
result.CurrentLocalNetworkSites = currentLocalNetworkSitesInstance;
}
XElement currentDnsServersElement = subscriptionElement.Element(XName.Get("CurrentDnsServers", "http://schemas.microsoft.com/windowsazure"));
if (currentDnsServersElement != null)
{
int currentDnsServersInstance = int.Parse(currentDnsServersElement.Value, CultureInfo.InvariantCulture);
result.CurrentDnsServers = currentDnsServersInstance;
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The List Subscription Operations operation returns a list of
/// create, update, and delete operations that were performed on a
/// subscription during the specified timeframe. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/gg715318.aspx
/// for more information)
/// </summary>
/// <param name='parameters'>
/// Parameters supplied to the List Subscription Operations operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The List Subscription Operations operation response.
/// </returns>
public async Task<SubscriptionListOperationsResponse> ListOperationsAsync(SubscriptionListOperationsParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("parameters", parameters);
Tracing.Enter(invocationId, this, "ListOperationsAsync", tracingParameters);
}
// Construct URL
string url = this.Client.BaseUri + "/" + this.Client.Credentials.SubscriptionId + "/operations?";
url = url + "&StartTime=" + Uri.EscapeUriString(string.Format(CultureInfo.InvariantCulture, "{0:O}", parameters.StartTime.ToUniversalTime()));
url = url + "&EndTime=" + Uri.EscapeUriString(string.Format(CultureInfo.InvariantCulture, "{0:O}", parameters.EndTime.ToUniversalTime()));
if (parameters.ObjectIdFilter != null)
{
url = url + "&ObjectIdFilter=" + Uri.EscapeUriString(parameters.ObjectIdFilter);
}
if (parameters.OperationStatus != null)
{
url = url + "&OperationResultFilter=" + Uri.EscapeUriString(parameters.OperationStatus.Value.ToString());
}
if (parameters.ContinuationToken != null)
{
url = url + "&ContinuationToken=" + Uri.EscapeUriString(parameters.ContinuationToken);
}
// 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-version", "2013-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.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), CloudExceptionType.Xml);
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
SubscriptionListOperationsResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new SubscriptionListOperationsResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement subscriptionOperationCollectionElement = responseDoc.Element(XName.Get("SubscriptionOperationCollection", "http://schemas.microsoft.com/windowsazure"));
if (subscriptionOperationCollectionElement != null)
{
XElement continuationTokenElement = subscriptionOperationCollectionElement.Element(XName.Get("ContinuationToken", "http://schemas.microsoft.com/windowsazure"));
if (continuationTokenElement != null)
{
string continuationTokenInstance = continuationTokenElement.Value;
result.ContinuationToken = continuationTokenInstance;
}
XElement subscriptionOperationsSequenceElement = subscriptionOperationCollectionElement.Element(XName.Get("SubscriptionOperations", "http://schemas.microsoft.com/windowsazure"));
if (subscriptionOperationsSequenceElement != null)
{
foreach (XElement subscriptionOperationsElement in subscriptionOperationsSequenceElement.Elements(XName.Get("SubscriptionOperation", "http://schemas.microsoft.com/windowsazure")))
{
SubscriptionListOperationsResponse.SubscriptionOperation subscriptionOperationInstance = new SubscriptionListOperationsResponse.SubscriptionOperation();
result.SubscriptionOperations.Add(subscriptionOperationInstance);
XElement operationIdElement = subscriptionOperationsElement.Element(XName.Get("OperationId", "http://schemas.microsoft.com/windowsazure"));
if (operationIdElement != null)
{
string operationIdInstance = operationIdElement.Value;
subscriptionOperationInstance.OperationId = operationIdInstance;
}
XElement operationObjectIdElement = subscriptionOperationsElement.Element(XName.Get("OperationObjectId", "http://schemas.microsoft.com/windowsazure"));
if (operationObjectIdElement != null)
{
string operationObjectIdInstance = operationObjectIdElement.Value;
subscriptionOperationInstance.OperationObjectId = operationObjectIdInstance;
}
XElement operationNameElement = subscriptionOperationsElement.Element(XName.Get("OperationName", "http://schemas.microsoft.com/windowsazure"));
if (operationNameElement != null)
{
string operationNameInstance = operationNameElement.Value;
subscriptionOperationInstance.OperationName = operationNameInstance;
}
XElement operationParametersSequenceElement = subscriptionOperationsElement.Element(XName.Get("OperationParameters", "http://schemas.microsoft.com/windowsazure"));
if (operationParametersSequenceElement != null)
{
foreach (XElement operationParametersElement in operationParametersSequenceElement.Elements(XName.Get("OperationParameter", "http://schemas.microsoft.com/windowsazure")))
{
string operationParametersKey = operationParametersElement.Element(XName.Get("Name", "http://schemas.datacontract.org/2004/07/Microsoft.WindowsAzure.ServiceManagement")).Value;
string operationParametersValue = operationParametersElement.Element(XName.Get("Value", "http://schemas.datacontract.org/2004/07/Microsoft.WindowsAzure.ServiceManagement")).Value;
subscriptionOperationInstance.OperationParameters.Add(operationParametersKey, operationParametersValue);
}
}
XElement operationCallerElement = subscriptionOperationsElement.Element(XName.Get("OperationCaller", "http://schemas.microsoft.com/windowsazure"));
if (operationCallerElement != null)
{
SubscriptionListOperationsResponse.OperationCallerDetails operationCallerInstance = new SubscriptionListOperationsResponse.OperationCallerDetails();
subscriptionOperationInstance.OperationCaller = operationCallerInstance;
XElement usedServiceManagementApiElement = operationCallerElement.Element(XName.Get("UsedServiceManagementApi", "http://schemas.microsoft.com/windowsazure"));
if (usedServiceManagementApiElement != null)
{
bool usedServiceManagementApiInstance = bool.Parse(usedServiceManagementApiElement.Value);
operationCallerInstance.UsedServiceManagementApi = usedServiceManagementApiInstance;
}
XElement userEmailAddressElement = operationCallerElement.Element(XName.Get("UserEmailAddress", "http://schemas.microsoft.com/windowsazure"));
if (userEmailAddressElement != null)
{
string userEmailAddressInstance = userEmailAddressElement.Value;
operationCallerInstance.UserEmailAddress = userEmailAddressInstance;
}
XElement subscriptionCertificateThumbprintElement = operationCallerElement.Element(XName.Get("SubscriptionCertificateThumbprint", "http://schemas.microsoft.com/windowsazure"));
if (subscriptionCertificateThumbprintElement != null)
{
string subscriptionCertificateThumbprintInstance = subscriptionCertificateThumbprintElement.Value;
operationCallerInstance.SubscriptionCertificateThumbprint = subscriptionCertificateThumbprintInstance;
}
XElement clientIPElement = operationCallerElement.Element(XName.Get("ClientIP", "http://schemas.microsoft.com/windowsazure"));
if (clientIPElement != null)
{
string clientIPInstance = clientIPElement.Value;
operationCallerInstance.ClientIPAddress = clientIPInstance;
}
}
XElement operationStatusElement = subscriptionOperationsElement.Element(XName.Get("OperationStatus", "http://schemas.microsoft.com/windowsazure"));
if (operationStatusElement != null)
{
string operationStatusInstance = operationStatusElement.Value;
subscriptionOperationInstance.OperationStatus = operationStatusInstance;
}
XElement operationStartedTimeElement = subscriptionOperationsElement.Element(XName.Get("OperationStartedTime", "http://schemas.microsoft.com/windowsazure"));
if (operationStartedTimeElement != null)
{
DateTime operationStartedTimeInstance = DateTime.Parse(operationStartedTimeElement.Value, CultureInfo.InvariantCulture);
subscriptionOperationInstance.OperationStartedTime = operationStartedTimeInstance;
}
XElement operationCompletedTimeElement = subscriptionOperationsElement.Element(XName.Get("OperationCompletedTime", "http://schemas.microsoft.com/windowsazure"));
if (operationCompletedTimeElement != null)
{
DateTime operationCompletedTimeInstance = DateTime.Parse(operationCompletedTimeElement.Value, CultureInfo.InvariantCulture);
subscriptionOperationInstance.OperationCompletedTime = operationCompletedTimeInstance;
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Register a resource with your subscription.
/// </summary>
/// <param name='resourceName'>
/// Name of the resource to register.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<OperationResponse> RegisterResourceAsync(string resourceName, CancellationToken cancellationToken)
{
// Validate
if (resourceName == null)
{
throw new ArgumentNullException("resourceName");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceName", resourceName);
Tracing.Enter(invocationId, this, "RegisterResourceAsync", tracingParameters);
}
// Construct URL
string url = this.Client.BaseUri + "/" + this.Client.Credentials.SubscriptionId + "/services?service=" + resourceName + "&action=register";
// 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-version", "2013-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false), CloudExceptionType.Xml);
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
OperationResponse result = null;
result = new OperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Unregister a resource with your subscription.
/// </summary>
/// <param name='resourceName'>
/// Name of the resource to unregister.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<OperationResponse> UnregisterResourceAsync(string resourceName, CancellationToken cancellationToken)
{
// Validate
if (resourceName == null)
{
throw new ArgumentNullException("resourceName");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceName", resourceName);
Tracing.Enter(invocationId, this, "UnregisterResourceAsync", tracingParameters);
}
// Construct URL
string url = this.Client.BaseUri + "/" + this.Client.Credentials.SubscriptionId + "/services?service=" + resourceName + "&action=unregister";
// 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-version", "2013-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false), CloudExceptionType.Xml);
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
OperationResponse result = null;
result = new OperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gagr = Google.Api.Gax.ResourceNames;
using gcav = Google.Cloud.ArtifactRegistry.V1;
using sys = System;
namespace Google.Cloud.ArtifactRegistry.V1
{
/// <summary>Resource name for the <c>Repository</c> resource.</summary>
public sealed partial class RepositoryName : gax::IResourceName, sys::IEquatable<RepositoryName>
{
/// <summary>The possible contents of <see cref="RepositoryName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>projects/{project}/locations/{location}/repositories/{repository}</c>.
/// </summary>
ProjectLocationRepository = 1,
}
private static gax::PathTemplate s_projectLocationRepository = new gax::PathTemplate("projects/{project}/locations/{location}/repositories/{repository}");
/// <summary>Creates a <see cref="RepositoryName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="RepositoryName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static RepositoryName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new RepositoryName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="RepositoryName"/> with the pattern
/// <c>projects/{project}/locations/{location}/repositories/{repository}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="repositoryId">The <c>Repository</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="RepositoryName"/> constructed from the provided ids.</returns>
public static RepositoryName FromProjectLocationRepository(string projectId, string locationId, string repositoryId) =>
new RepositoryName(ResourceNameType.ProjectLocationRepository, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), repositoryId: gax::GaxPreconditions.CheckNotNullOrEmpty(repositoryId, nameof(repositoryId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="RepositoryName"/> with pattern
/// <c>projects/{project}/locations/{location}/repositories/{repository}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="repositoryId">The <c>Repository</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="RepositoryName"/> with pattern
/// <c>projects/{project}/locations/{location}/repositories/{repository}</c>.
/// </returns>
public static string Format(string projectId, string locationId, string repositoryId) =>
FormatProjectLocationRepository(projectId, locationId, repositoryId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="RepositoryName"/> with pattern
/// <c>projects/{project}/locations/{location}/repositories/{repository}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="repositoryId">The <c>Repository</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="RepositoryName"/> with pattern
/// <c>projects/{project}/locations/{location}/repositories/{repository}</c>.
/// </returns>
public static string FormatProjectLocationRepository(string projectId, string locationId, string repositoryId) =>
s_projectLocationRepository.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(repositoryId, nameof(repositoryId)));
/// <summary>Parses the given resource name string into a new <see cref="RepositoryName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/locations/{location}/repositories/{repository}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="repositoryName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="RepositoryName"/> if successful.</returns>
public static RepositoryName Parse(string repositoryName) => Parse(repositoryName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="RepositoryName"/> instance; optionally allowing
/// an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/locations/{location}/repositories/{repository}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="repositoryName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="RepositoryName"/> if successful.</returns>
public static RepositoryName Parse(string repositoryName, bool allowUnparsed) =>
TryParse(repositoryName, allowUnparsed, out RepositoryName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="RepositoryName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/locations/{location}/repositories/{repository}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="repositoryName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="RepositoryName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string repositoryName, out RepositoryName result) =>
TryParse(repositoryName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="RepositoryName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/locations/{location}/repositories/{repository}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="repositoryName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="RepositoryName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string repositoryName, bool allowUnparsed, out RepositoryName result)
{
gax::GaxPreconditions.CheckNotNull(repositoryName, nameof(repositoryName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationRepository.TryParseName(repositoryName, out resourceName))
{
result = FromProjectLocationRepository(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(repositoryName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private RepositoryName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string locationId = null, string projectId = null, string repositoryId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
LocationId = locationId;
ProjectId = projectId;
RepositoryId = repositoryId;
}
/// <summary>
/// Constructs a new instance of a <see cref="RepositoryName"/> class from the component parts of pattern
/// <c>projects/{project}/locations/{location}/repositories/{repository}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="repositoryId">The <c>Repository</c> ID. Must not be <c>null</c> or empty.</param>
public RepositoryName(string projectId, string locationId, string repositoryId) : this(ResourceNameType.ProjectLocationRepository, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), repositoryId: gax::GaxPreconditions.CheckNotNullOrEmpty(repositoryId, nameof(repositoryId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The <c>Repository</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string RepositoryId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectLocationRepository: return s_projectLocationRepository.Expand(ProjectId, LocationId, RepositoryId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as RepositoryName);
/// <inheritdoc/>
public bool Equals(RepositoryName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(RepositoryName a, RepositoryName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(RepositoryName a, RepositoryName b) => !(a == b);
}
public partial class Repository
{
/// <summary>
/// <see cref="gcav::RepositoryName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcav::RepositoryName RepositoryName
{
get => string.IsNullOrEmpty(Name) ? null : gcav::RepositoryName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class ListRepositoriesRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class GetRepositoryRequest
{
/// <summary>
/// <see cref="gcav::RepositoryName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcav::RepositoryName RepositoryName
{
get => string.IsNullOrEmpty(Name) ? null : gcav::RepositoryName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
using System;
using System.Collections;
using System.Collections.Specialized;
namespace System.Collections.Specialized.Tests
{
public class CtorNvcTests
{
[Fact]
public void Test01()
{
NameValueCollection nvc;
NameValueCollection nvc1; // argument NameValueCollection
// simple string values
string[] values =
{
"",
" ",
"a",
"aa",
"tExt",
" SPaces",
"1",
"$%^#",
"2222222222222222222222222",
System.DateTime.Today.ToString(),
Int32.MaxValue.ToString()
};
// names(keys) for simple string values
string[] names =
{
"zero",
"oNe",
" ",
"",
"aA",
"1",
System.DateTime.Today.ToString(),
"$%^#",
Int32.MaxValue.ToString(),
" spaces",
"2222222222222222222222222"
};
// [] NameValueCollection is constructed as expected
//-----------------------------------------------------------------
nvc1 = new NameValueCollection();
//
// [] create from another empty collection
//
nvc = new NameValueCollection(nvc1);
if (nvc == null)
{
Assert.False(true, "Error, collection is null");
}
if (nvc.Count != 0)
{
Assert.False(true, string.Format("Error, Count = {0} ", nvc.Count));
}
if (nvc.Get("key") != null)
{
Assert.False(true, "Error, Get(some_key) returned non-null after default ctor");
}
string[] keys = nvc.AllKeys;
if (keys.Length != 0)
{
Assert.False(true, string.Format("Error, AllKeys contains {0} keys after default ctor", keys.Length));
}
//
// Item(some_key) should return null
//
if (nvc["key"] != null)
{
Assert.False(true, "Error, Item(some_key) returned non-null after default ctor");
}
//
// Add(string, string)
//
nvc.Add("Name", "Value");
if (nvc.Count != 1)
{
Assert.False(true, string.Format("Error, Count returned {0} instead of 1", nvc.Count));
}
if (String.Compare(nvc["Name"], "Value") != 0)
{
Assert.False(true, "Error, Item() returned unexpected value");
}
//
// Clear()
//
nvc.Clear();
if (nvc.Count != 0)
{
Assert.False(true, string.Format("Error, Count returned {0} instead of 0 after Clear()", nvc.Count));
}
if (nvc["Name"] != null)
{
Assert.False(true, "Error, Item() returned non-null value after Clear()");
}
//
// [] create from filled collection
//
int len = values.Length;
for (int i = 0; i < len; i++)
{
nvc1.Add(names[i], values[i]);
}
if (nvc1.Count != len)
{
Assert.False(true, string.Format("Error, Count = {0} after instead of {1}", nvc.Count, len));
}
nvc = new NameValueCollection(nvc1);
if (nvc.Count != nvc1.Count)
{
Assert.False(true, string.Format("Error, Count = {0} instead of {1}", nvc.Count, nvc1.Count));
}
string[] keys1 = nvc1.AllKeys;
keys = nvc.AllKeys;
if (keys1.Length != keys.Length)
{
Assert.False(true, string.Format("Error, new collection Keys.Length is {0} instead of {1}", keys.Length, keys1.Length));
}
else
{
for (int i = 0; i < keys1.Length; i++)
{
if (Array.IndexOf(keys, keys1[i]) < 0)
{
Assert.False(true, string.Format("Error, no key \"{1}\" in AllKeys", i, keys1[i]));
}
}
}
for (int i = 0; i < keys.Length; i++)
{
string[] val = nvc.GetValues(keys[i]);
if ((val.Length != 1) || String.Compare(val[0], (nvc1.GetValues(keys[i]))[0]) != 0)
{
Assert.False(true, string.Format("Error, unexpected value at key \"{1}\"", i, keys1[i]));
}
}
//
// [] change argument collection
//
string toChange = keys1[0];
string init = nvc1[toChange];
//
// Change element
//
nvc1[toChange] = "new Value";
if (String.Compare(nvc1[toChange], "new Value") != 0)
{
Assert.False(true, "Error, failed to change element");
}
if (String.Compare(nvc[toChange], init) != 0)
{
Assert.False(true, "Error, changed element in new collection");
}
//
// Remove element
//
nvc1.Remove(toChange);
if (nvc1.Count != len - 1)
{
Assert.False(true, "Error, failed to remove element");
}
if (nvc.Count != len)
{
Assert.False(true, "Error, collection changed after argument change - removed element");
}
keys = nvc.AllKeys;
if (Array.IndexOf(keys, toChange) < 0)
{
Assert.False(true, "Error, collection changed after argument change - no key");
}
//
// [] invalid parameter
//
Assert.Throws<ArgumentNullException>(() => { nvc = new NameValueCollection((NameValueCollection)null); });
}
}
}
| |
using UnityEngine;
namespace NG.AssertDebug
{
/// <summary>
/// Replacement class that "extends" UnityEngine.Assertions.
/// Is not executed if not running in the editor and not a debug build.
/// </summary>
public class Assert
{
private static bool ShouldExecute()
{
#pragma warning disable 0162
if (AssertDebugConfig.instance.masterDisable || AssertDebugConfig.instance.assertDisable)
return false;
#if UNITY_EDITOR
RegisterLogCallBack();
return true;
#endif
if (!UnityEngine.Debug.isDebugBuild && AssertDebugConfig.instance.runInDebugBuildOnly)
return false;
RegisterLogCallBack();
return true;
#pragma warning restore
}
private static bool isCallbackRegistered = false;
private static void RegisterLogCallBack()
{
if (isCallbackRegistered)
return;
isCallbackRegistered = true;
HandleLog handleLog = GameObject.FindObjectOfType<HandleLog>();
if (handleLog == null)
{
GameObject go = new GameObject("HandleLog");
Object.DontDestroyOnLoad(go);
handleLog = go.AddComponent<HandleLog>();
}
}
#region AreEqual
public delegate void AreEqualDelegate();
public static AreEqualDelegate AreEqualCallback;
/// <summary>
/// Asserts that two values are equal and disables the referenced MonoBehaviour.
/// </summary>
/// <param name="monoBehaviour">The class instance that will be disabled on failure</param>
/// <returns>true if values are equal</returns>
public static bool AreEqual<T>(T expected, T actual, MonoBehaviour monoBehaviour)
{
if (!ShouldExecute())
return true;
if (!Equals(expected, actual))
{
UnityEngine.Assertions.Assert.AreEqual(expected, actual);
if (monoBehaviour != null)
monoBehaviour.enabled = false;
if (AreEqualCallback != null)
AreEqualCallback();
FailureHandler.HandleFailure(typeof(Assert));
return false;
}
return true;
}
public static bool AreEqual<T>(T expected, T actual)
{
return AreEqual(expected, actual, null);
}
#endregion
#region AreApproximatelyEqual
public delegate void AreApproximatelyEqualDelegate();
public static AreApproximatelyEqualDelegate AreApproximatelyEqualCallback;
public static bool AreApproximatelyEqual(float expected, float actual, float? tolerance, MonoBehaviour monoBehaviour)
{
if (!ShouldExecute())
return true;
bool pass = true;
if (tolerance != null)
{
tolerance = Mathf.Abs((float)tolerance);
float difference = Mathf.Abs(expected - actual);
if (difference > tolerance)
{
UnityEngine.Assertions.Assert.AreApproximatelyEqual(expected, actual, (float)tolerance);
pass = false;
}
}
else
{
if (!Mathf.Approximately(expected, actual))
{
UnityEngine.Assertions.Assert.AreApproximatelyEqual(expected, actual);
pass = false;
}
}
if (!pass)
{
if (monoBehaviour != null)
monoBehaviour.enabled = false;
if (AreApproximatelyEqualCallback != null)
AreApproximatelyEqualCallback();
FailureHandler.HandleFailure(typeof(Assert));
return false;
}
return pass;
}
public static bool AreApproximatelyEqual(float expected, float actual, float tolerance)
{
return AreApproximatelyEqual(expected, actual, tolerance, null);
}
public static bool AreApproximatelyEqual(float expected, float actual, MonoBehaviour monoBehaviour)
{
return AreApproximatelyEqual(expected, actual, null, monoBehaviour);
}
public static bool AreApproximatelyEqual(float expected, float actual)
{
return AreApproximatelyEqual(expected, actual, null, null);
}
#endregion
#region AreNotApproximatelyEqual
public delegate void AreNotApproximatelyEqualDelegate();
public static AreNotApproximatelyEqualDelegate AreNotApproximatelyEqualCallback;
public static bool AreNotApproximatelyEqual(float expected, float actual, float? tolerance, MonoBehaviour monoBehaviour)
{
if (!ShouldExecute())
return true;
bool pass = true;
if (tolerance != null)
{
tolerance = Mathf.Abs((float)tolerance);
float difference = Mathf.Abs(expected - actual);
if (difference < tolerance)
{
UnityEngine.Assertions.Assert.AreNotApproximatelyEqual(expected, actual, (float)tolerance);
pass = false;
}
}
else
{
if (Mathf.Approximately(expected, actual))
{
UnityEngine.Assertions.Assert.AreNotApproximatelyEqual(expected, actual);
pass = false;
}
}
if (!pass)
{
if (monoBehaviour != null)
monoBehaviour.enabled = false;
if (AreNotApproximatelyEqualCallback != null)
AreNotApproximatelyEqualCallback();
FailureHandler.HandleFailure(typeof(Assert));
return false;
}
return pass;
}
public static bool AreNotApproximatelyEqual(float expected, float actual, float tolerance)
{
return AreNotApproximatelyEqual(expected, actual, tolerance, null);
}
public static bool AreNotApproximatelyEqual(float expected, float actual, MonoBehaviour monoBehaviour)
{
return AreNotApproximatelyEqual(expected, actual, null, monoBehaviour);
}
public static bool AreNotApproximatelyEqual(float expected, float actual)
{
return AreNotApproximatelyEqual(expected, actual, null, null);
}
#endregion
#region AreNotEqual
public delegate void AreNotEqualDelegate();
public static AreNotEqualDelegate AreNotEqualCallback;
public static bool AreNotEqual<T>(T expected, T actual, MonoBehaviour monoBehaviour)
{
if (!ShouldExecute())
return true;
if (Equals(expected, actual))
{
UnityEngine.Assertions.Assert.AreNotEqual(expected, actual);
if (monoBehaviour != null)
monoBehaviour.enabled = false;
if (AreNotEqualCallback != null)
AreNotEqualCallback();
FailureHandler.HandleFailure(typeof(Assert));
return false;
}
return true;
}
public static bool AreNotEqual<T>(T expected, T actual)
{
return AreNotEqual(expected, actual, null);
}
#endregion
#region IsFalse
public delegate void IsFalseDelegate();
public static IsFalseDelegate IsFalseCallback;
public static bool IsFalse(bool condition, MonoBehaviour monoBehaviour)
{
if (!ShouldExecute())
return true;
if (condition)
{
UnityEngine.Assertions.Assert.IsFalse(condition);
if (monoBehaviour != null)
monoBehaviour.enabled = false;
if (IsFalseCallback != null)
IsFalseCallback();
FailureHandler.HandleFailure(typeof(Assert));
return false;
}
return true;
}
public static bool IsFalse(bool condition)
{
return IsFalse(condition, null);
}
#endregion
#region IsTrue
public delegate void IsTrueDelegate();
public static IsTrueDelegate IsTrueCallback;
public static bool IsTrue(bool condition, MonoBehaviour monoBehaviour)
{
if (!ShouldExecute())
return true;
if (!condition)
{
UnityEngine.Assertions.Assert.IsTrue(condition);
if (monoBehaviour != null)
monoBehaviour.enabled = false;
if (IsTrueCallback != null)
IsTrueCallback();
FailureHandler.HandleFailure(typeof(Assert));
return false;
}
return true;
}
public static bool IsTrue(bool condition)
{
return IsTrue(condition, null);
}
#endregion
#region IsNotNull
public delegate void IsNotNullDelegate();
public static IsNotNullDelegate IsNotNullCallback;
public static bool IsNotNull(object value, MonoBehaviour monoBehaviour)
{
if (!ShouldExecute())
return true;
if (value == null)
{
UnityEngine.Assertions.Assert.IsNotNull(value);
if (monoBehaviour != null)
monoBehaviour.enabled = false;
if (IsNotNullCallback != null)
IsNotNullCallback();
FailureHandler.HandleFailure(typeof(Assert));
return false;
}
return true;
}
public static bool IsNotNull(object value)
{
return IsNotNull(value, null);
}
#endregion
#region IsNull
public delegate void IsNullDelegate();
public static IsNotNullDelegate IsNullCallback;
public static bool IsNull(object value, MonoBehaviour monoBehaviour)
{
if (!ShouldExecute())
return true;
if (value != null)
{
UnityEngine.Assertions.Assert.IsNull(value);
if (monoBehaviour != null)
monoBehaviour.enabled = false;
if (IsNotNullCallback != null)
IsNotNullCallback();
FailureHandler.HandleFailure(typeof(Assert));
return false;
}
return true;
}
public static bool IsNull(object value)
{
return IsNull(value, null);
}
#endregion
}
}
| |
using System;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Xml.Linq;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Locator;
using Nuke.Common;
using Nuke.Common.Execution;
using Nuke.Common.Git;
using Nuke.Common.IO;
using Nuke.Common.ProjectModel;
using Nuke.Common.Tooling;
using Nuke.Common.Tools.DotNet;
using Nuke.Common.Tools.MSBuild;
using Nuke.Common.Tools.Npm;
using Nuke.Common.Tools.VSTest;
using Nuke.Common.Utilities.Collections;
using static Nuke.Common.IO.FileSystemTasks;
using static Nuke.Common.Logger;
using static Nuke.Common.Tooling.ProcessTasks;
using static Nuke.Common.Tools.Chocolatey.ChocolateyTasks;
using static Nuke.Common.Tools.DotNet.DotNetTasks;
using static Nuke.Common.Tools.MSBuild.MSBuildTasks;
using static Nuke.Common.Tools.Npm.NpmTasks;
using static Nuke.Common.Tools.VSTest.VSTestTasks;
using Project = Nuke.Common.ProjectModel.Project;
[CheckBuildProjectConfigurations]
partial class Build : NukeBuild
{
public Build()
{
var msBuildExtensionPath = Environment.GetEnvironmentVariable("MSBuildExtensionsPath");
var msBuildExePath = Environment.GetEnvironmentVariable("MSBUILD_EXE_PATH");
var msBuildSdkPath = Environment.GetEnvironmentVariable("MSBuildSDKsPath");
MSBuildLocator.RegisterDefaults();
TriggerAssemblyResolution();
Environment.SetEnvironmentVariable("MSBuildExtensionsPath", msBuildExtensionPath);
Environment.SetEnvironmentVariable("MSBUILD_EXE_PATH", msBuildExePath);
Environment.SetEnvironmentVariable("MSBuildSDKsPath", msBuildSdkPath);
}
static void TriggerAssemblyResolution() => _ = new ProjectCollection();
/// Support plugins are available for:
/// - JetBrains ReSharper https://nuke.build/resharper
/// - JetBrains Rider https://nuke.build/rider
/// - Microsoft VisualStudio https://nuke.build/visualstudio
/// - Microsoft VSCode https://nuke.build/vscode
public static int Main() => Execute<Build>(x => x.Compile);
[Parameter("Configuration to build - Default is 'Debug' (local) or 'Release' (server)")]
readonly Configuration Configuration = IsLocalBuild ? Configuration.Debug : Configuration.Release;
[Solution] readonly Solution Solution;
[GitRepository] readonly GitRepository GitRepository;
AbsolutePath SourceDirectory => RootDirectory / "src";
AbsolutePath ArtifactsDirectory => RootDirectory / "artifacts";
AbsolutePath NSwagStudioBinaries => SourceDirectory / "NSwagStudio" / "bin" / Configuration;
AbsolutePath NSwagNpmBinaries => SourceDirectory / "NSwag.Npm";
static bool IsRunningOnWindows => RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
bool IsTaggedBuild;
string VersionPrefix;
string VersionSuffix;
string DetermineVersionPrefix()
{
var versionPrefix = GitRepository.Tags.SingleOrDefault(x => x.StartsWith("v"))?[1..];
if (!string.IsNullOrWhiteSpace(versionPrefix))
{
IsTaggedBuild = true;
Info($"Tag version {versionPrefix} from Git found, using it as version prefix");
}
else
{
var propsDocument = XDocument.Parse(TextTasks.ReadAllText(SourceDirectory / "Directory.Build.props"));
versionPrefix = propsDocument.Element("Project").Element("PropertyGroup").Element("VersionPrefix").Value;
Info($"Version prefix {versionPrefix} read from Directory.Build.props");
}
return versionPrefix;
}
protected override void OnBuildInitialized()
{
VersionPrefix = DetermineVersionPrefix();
VersionSuffix = !IsTaggedBuild
? $"preview-{DateTime.UtcNow:yyyyMMdd-HHmm}"
: "";
if (IsLocalBuild)
{
VersionSuffix = $"dev-{DateTime.UtcNow:yyyyMMdd-HHmm}";
}
using var _ = Block("BUILD SETUP");
Info("Configuration:\t" + Configuration);
Info("Version prefix:\t" + VersionPrefix);
Info("Version suffix:\t" + VersionSuffix);
Info("Tagged build:\t" + IsTaggedBuild);
}
Target Clean => _ => _
.Before(Restore)
.Executes(() =>
{
SourceDirectory.GlobDirectories("**/bin", "**/obj").ForEach(DeleteDirectory);
EnsureCleanDirectory(ArtifactsDirectory);
});
Target InstallDependencies => _ => _
.Before(Restore, Compile)
.Executes(() =>
{
Chocolatey("install wixtoolset -y");
NpmInstall(x => x
.EnableGlobal()
.AddPackages("dotnettools")
);
});
// logic from 00_Install.bat
Target Restore => _ => _
.Executes(() =>
{
NpmInstall(x => x
.SetProcessWorkingDirectory(SourceDirectory / "NSwag.Npm")
);
NpmInstall(x => x
.SetProcessWorkingDirectory(SourceDirectory / "NSwag.Integration.TypeScriptWeb")
);
MSBuild(x => x
.SetTargetPath(Solution)
.SetTargets("Restore")
.SetMaxCpuCount(Environment.ProcessorCount)
.SetNodeReuse(IsLocalBuild)
.SetVerbosity(MSBuildVerbosity.Minimal)
);
DotNetRestore(x => x
.SetProjectFile(Solution)
.SetVerbosity(DotNetVerbosity.Minimal)
);
});
// logic from 01_Build.bat
Target Compile => _ => _
.DependsOn(Restore)
.Executes(() =>
{
EnsureCleanDirectory(SourceDirectory / "NSwag.Npm" / "bin" / "binaries");
Info("Build and copy full .NET command line with configuration " + Configuration);
MSBuild(x => x
.SetTargetPath(Solution)
.SetTargets("Rebuild")
.SetAssemblyVersion(VersionPrefix)
.SetFileVersion(VersionPrefix)
.SetInformationalVersion(VersionPrefix)
.SetConfiguration(Configuration)
.SetMaxCpuCount(Environment.ProcessorCount)
.SetNodeReuse(IsLocalBuild)
.SetVerbosity(MSBuildVerbosity.Minimal)
.SetProperty("Deterministic", IsServerBuild)
.SetProperty("ContinuousIntegrationBuild", IsServerBuild)
);
});
// logic from 02_RunUnitTests.bat
Target UnitTest => _ => _
.After(Compile)
.Executes(() =>
{
var webApiTest = Solution.GetProject("NSwag.Generation.WebApi.Tests");
VSTest(x => x
.SetTestAssemblies(webApiTest.Directory / "bin" / Configuration / "NSwag.Generation.WebApi.Tests.dll")
);
/*
VSTest(x => x
.SetLogger(logger)
.SetTestAssemblies(SourceDirectory / "NSwag.Tests" / "bin" / Configuration / "NSwag.Tests.dll")
);
*/
// project name + target framework pairs
var dotNetTestTargets = new (string ProjectName, string Framework)[]
{
("NSwag.CodeGeneration.Tests", null),
("NSwag.CodeGeneration.CSharp.Tests", null),
("NSwag.CodeGeneration.TypeScript.Tests", null),
("NSwag.Generation.AspNetCore.Tests", null),
("NSwag.Core.Tests", null),
("NSwag.Core.Yaml.Tests", null),
("NSwag.AssemblyLoader.Tests", null)
};
foreach (var (project, targetFramework) in dotNetTestTargets)
{
DotNetTest(x => x
.SetProjectFile(Solution.GetProject(project))
.SetFramework(targetFramework)
.SetConfiguration(Configuration)
);
}
});
// logic from 03_RunIntegrationTests.bat
Target IntegrationTest => _ => _
.After(Compile)
.DependsOn(Samples)
.Executes(() =>
{
var nswagCommand = NSwagStudioBinaries / "nswag.cmd";
// project name + runtime pairs
var dotnetTargets = new[]
{
("NSwag.Sample.NETCore21", "NetCore21"),
("NSwag.Sample.NETCore31", "NetCore31"),
("NSwag.Sample.NET50", "Net50"),
("NSwag.Sample.NET60", "Net60"),
("NSwag.Sample.NET60Minimal", "Net60")
};
foreach (var (projectName, runtime) in dotnetTargets)
{
var project = Solution.GetProject(projectName);
DotNetBuild(x => BuildDefaults(x)
.SetProcessWorkingDirectory(project.Directory)
.SetProperty("CopyLocalLockFileAssemblies", true)
);
var process = StartProcess(nswagCommand, $"run /runtime:{runtime}", workingDirectory: project.Directory);
process.WaitForExit();
}
// project name + runtime pairs
var msbuildTargets = new[]
{
("NSwag.Sample.NetGlobalAsax", "Winx64"),
("NSwag.Integration.WebAPI", "Winx64")
};
foreach (var (projectName, runtime) in msbuildTargets)
{
var project = Solution.GetProject(projectName);
MSBuild(x => x
.SetProcessWorkingDirectory(project.Directory)
.SetNodeReuse(IsLocalBuild)
);
var process = StartProcess(nswagCommand, $"run /runtime:{runtime}", workingDirectory: project.Directory);
process.WaitForExit();
}
});
Target Test => _ => _
.DependsOn(UnitTest, IntegrationTest);
// logic from runs.ps1
Target Samples => _ => _
.After(Compile)
.Executes(() =>
{
var studioProject = Solution.GetProject("NSwagStudio");
void NSwagRun(
Project project,
string configurationFile,
string runtime,
Configuration configuration,
bool build)
{
var nswagConfigurationFile = project.Directory / $"{configurationFile}.nswag";
var nswagSwaggerFile = project.Directory / $"{configurationFile}_swagger.json";
DeleteFile(nswagSwaggerFile);
if (build)
{
DotNetBuild(x => BuildDefaults(x)
.SetConfiguration(configuration)
.SetProjectFile(project)
);
}
else
{
DotNetRestore(x => x
.SetProjectFile(project)
);
}
var cliPath = studioProject.Directory / "bin" / Configuration / runtime / "dotnet-nswag.dll";
DotNet($"{cliPath} run {nswagConfigurationFile} /variables:configuration=" + configuration);
if (!File.Exists(nswagSwaggerFile))
{
throw new Exception($"Output ${nswagSwaggerFile} not generated for {nswagConfigurationFile}.");
}
}
var samplesPath = RootDirectory / "samples";
var sampleSolution = ProjectModelTasks.ParseSolution(samplesPath / "Samples.sln");
NSwagRun(sampleSolution.GetProject("Sample.AspNetCore21"), "nswag_assembly", "NetCore21", Configuration.Release, true);
NSwagRun(sampleSolution.GetProject("Sample.AspNetCore21"), "nswag_project", "NetCore21", Configuration.Release, false);
NSwagRun(sampleSolution.GetProject("Sample.AspNetCore21"), "nswag_reflection", "NetCore21", Configuration.Release, true);
NSwagRun(sampleSolution.GetProject("Sample.AspNetCore21"), "nswag_assembly", "NetCore21", Configuration.Debug, true);
NSwagRun(sampleSolution.GetProject("Sample.AspNetCore21"), "nswag_project", "NetCore21", Configuration.Debug, false);
NSwagRun(sampleSolution.GetProject("Sample.AspNetCore21"), "nswag_reflection", "NetCore21", Configuration.Debug, true);
});
DotNetBuildSettings BuildDefaults(DotNetBuildSettings s)
{
return s
.SetAssemblyVersion(VersionPrefix)
.SetFileVersion(VersionPrefix)
.SetInformationalVersion(VersionPrefix)
.SetConfiguration(Configuration)
.SetDeterministic(IsServerBuild)
.SetContinuousIntegrationBuild(IsServerBuild);
}
}
| |
/*
* Copyright (c) 2012 Calvin Rien
*
* Based on the JSON parser by Patrick van Bergen
* http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html
*
* Simplified it so that it doesn't throw exceptions
* and can be used in Unity iPhone with maximum code stripping.
*
* 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 System.IO;
using System.Text;
namespace UnityORM{//MiniJSON {
// Get from http://forum.unity3d.com/threads/35484-MiniJSON-script-for-parsing-JSON-data
// and modifed.
//
// Example usage:
//
// using UnityEngine;
// using System.Collections;
// using System.Collections.Generic;
// using MiniJSON;
//
// public class MiniJSONTest : MonoBehaviour {
// void Start () {
// var jsonString = "{ \"array\": [1.44,2,3], " +
// "\"object\": {\"key1\":\"value1\", \"key2\":256}, " +
// "\"string\": \"The quick brown fox \\\"jumps\\\" over the lazy dog \", " +
// "\"unicode\": \"\\u3041 Men\u00fa sesi\u00f3n\", " +
// "\"int\": 65536, " +
// "\"float\": 3.1415926, " +
// "\"bool\": true, " +
// "\"null\": null }";
//
// var dict = Json.Deserialize(jsonString) as Dictionary<string,object>;
//
// Debug.Log("deserialized: " + dict.GetType());
// Debug.Log("dict['array'][0]: " + ((List<object>) dict["array"])[0]);
// Debug.Log("dict['string']: " + (string) dict["string"]);
// Debug.Log("dict['float']: " + (double) dict["float"]); // floats come out as doubles
// Debug.Log("dict['int']: " + (long) dict["int"]); // ints come out as longs
// Debug.Log("dict['unicode']: " + (string) dict["unicode"]);
//
// var str = Json.Serialize(dict);
//
// Debug.Log("serialized: " + str);
// }
// }
/// <summary>
/// This class encodes and decodes JSON strings.
/// Spec. details, see http://www.json.org/
///
/// JSON uses Arrays and Objects. These correspond here to the datatypes IList and IDictionary.
/// All numbers are parsed to doubles.
/// </summary>
public static class Json {
/// <summary>
/// Parses the string json into a value
/// </summary>
/// <param name="json">A JSON string.</param>
/// <returns>An List<object>, a Dictionary<string, object>, a double, an integer,a string, null, true, or false</returns>
public static object Deserialize(string json) {
// save the string for debug information
if (json == null) {
return null;
}
return Parser.Parse(json);
}
sealed class Parser : IDisposable {
const string WHITE_SPACE = " \t\n\r";
const string WORD_BREAK = " \t\n\r{}[],:\"";
enum TOKEN {
NONE,
CURLY_OPEN,
CURLY_CLOSE,
SQUARED_OPEN,
SQUARED_CLOSE,
COLON,
COMMA,
STRING,
NUMBER,
TRUE,
FALSE,
NULL
};
StringReader json;
Parser(string jsonString) {
json = new StringReader(jsonString);
}
public static object Parse(string jsonString) {
using (var instance = new Parser(jsonString)) {
return instance.ParseValue();
}
}
public void Dispose() {
json.Dispose();
json = null;
}
Dictionary<string, object> ParseObject() {
Dictionary<string, object> table = new Dictionary<string, object>();
// ditch opening brace
json.Read();
// {
while (true) {
switch (NextToken) {
case TOKEN.NONE:
return null;
case TOKEN.COMMA:
continue;
case TOKEN.CURLY_CLOSE:
return table;
default:
// name
string name = ParseString();
if (name == null) {
return null;
}
// :
if (NextToken != TOKEN.COLON) {
return null;
}
// ditch the colon
json.Read();
// value
table[name] = ParseValue();
break;
}
}
}
List<object> ParseArray() {
List<object> array = new List<object>();
// ditch opening bracket
json.Read();
// [
var parsing = true;
while (parsing) {
TOKEN nextToken = NextToken;
switch (nextToken) {
case TOKEN.NONE:
return null;
case TOKEN.COMMA:
continue;
case TOKEN.SQUARED_CLOSE:
parsing = false;
break;
default:
object value = ParseByToken(nextToken);
array.Add(value);
break;
}
}
return array;
}
object ParseValue() {
TOKEN nextToken = NextToken;
return ParseByToken(nextToken);
}
object ParseByToken(TOKEN token) {
switch (token) {
case TOKEN.STRING:
return ParseString();
case TOKEN.NUMBER:
return ParseNumber();
case TOKEN.CURLY_OPEN:
return ParseObject();
case TOKEN.SQUARED_OPEN:
return ParseArray();
case TOKEN.TRUE:
return true;
case TOKEN.FALSE:
return false;
case TOKEN.NULL:
return null;
default:
return null;
}
}
string ParseString() {
StringBuilder s = new StringBuilder();
char c;
// ditch opening quote
json.Read();
bool parsing = true;
while (parsing) {
if (json.Peek() == -1) {
parsing = false;
break;
}
c = NextChar;
switch (c) {
case '"':
parsing = false;
break;
case '\\':
if (json.Peek() == -1) {
parsing = false;
break;
}
c = NextChar;
switch (c) {
case '"':
case '\\':
case '/':
s.Append(c);
break;
case 'b':
s.Append('\b');
break;
case 'f':
s.Append('\f');
break;
case 'n':
s.Append('\n');
break;
case 'r':
s.Append('\r');
break;
case 't':
s.Append('\t');
break;
case 'u':
var hex = new StringBuilder();
for (int i=0; i< 4; i++) {
hex.Append(NextChar);
}
s.Append((char) Convert.ToInt32(hex.ToString(), 16));
break;
}
break;
default:
s.Append(c);
break;
}
}
return s.ToString();
}
object ParseNumber() {
string number = NextWord;
if (number.IndexOf('.') == -1) {
long parsedInt;
Int64.TryParse(number, out parsedInt);
return parsedInt;
}
double parsedDouble;
Double.TryParse(number, out parsedDouble);
return parsedDouble;
}
void EatWhitespace() {
while (WHITE_SPACE.IndexOf(PeekChar) != -1) {
json.Read();
if (json.Peek() == -1) {
break;
}
}
}
char PeekChar {
get {
return Convert.ToChar(json.Peek());
}
}
char NextChar {
get {
return Convert.ToChar(json.Read());
}
}
string NextWord {
get {
StringBuilder word = new StringBuilder();
while (WORD_BREAK.IndexOf(PeekChar) == -1) {
word.Append(NextChar);
if (json.Peek() == -1) {
break;
}
}
return word.ToString();
}
}
TOKEN NextToken {
get {
EatWhitespace();
if (json.Peek() == -1) {
return TOKEN.NONE;
}
char c = PeekChar;
switch (c) {
case '{':
return TOKEN.CURLY_OPEN;
case '}':
json.Read();
return TOKEN.CURLY_CLOSE;
case '[':
return TOKEN.SQUARED_OPEN;
case ']':
json.Read();
return TOKEN.SQUARED_CLOSE;
case ',':
json.Read();
return TOKEN.COMMA;
case '"':
return TOKEN.STRING;
case ':':
return TOKEN.COLON;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '-':
return TOKEN.NUMBER;
}
string word = NextWord;
switch (word) {
case "false":
return TOKEN.FALSE;
case "true":
return TOKEN.TRUE;
case "null":
return TOKEN.NULL;
}
return TOKEN.NONE;
}
}
}
/// <summary>
/// Converts a IDictionary / IList object or a simple type (string, int, etc.) into a JSON string
/// </summary>
/// <param name="json">A Dictionary<string, object> / List<object></param>
/// <returns>A JSON encoded string, or null if object 'json' is not serializable</returns>
public static string Serialize(object obj) {
return Serializer.Serialize(obj);
}
sealed class Serializer {
StringBuilder builder;
Serializer() {
builder = new StringBuilder();
}
public static string Serialize(object obj) {
var instance = new Serializer();
instance.SerializeValue(obj);
return instance.builder.ToString();
}
void SerializeValue(object value) {
IList asList;
IDictionary asDict;
string asStr;
if (value == null) {
builder.Append("null");
}
else if ((asStr = value as string) != null) {
SerializeString(asStr);
}
else if (value is bool) {
builder.Append(value.ToString().ToLower());
}
else if ((asList = value as IList) != null) {
SerializeArray(asList);
}
else if ((asDict = value as IDictionary) != null) {
SerializeObject(asDict);
}
else if (value is char) {
SerializeString(value.ToString());
}
else {
SerializeOther(value);
}
}
void SerializeObject(IDictionary obj) {
bool first = true;
builder.Append('{');
foreach (object e in obj.Keys) {
if (!first) {
builder.Append(',');
}
SerializeString(e.ToString());
builder.Append(':');
SerializeValue(obj[e]);
first = false;
}
builder.Append('}');
}
void SerializeArray(IList anArray) {
builder.Append('[');
bool first = true;
foreach (object obj in anArray) {
if (!first) {
builder.Append(',');
}
SerializeValue(obj);
first = false;
}
builder.Append(']');
}
void SerializeString(string str) {
builder.Append('\"');
char[] charArray = str.ToCharArray();
foreach (var c in charArray) {
switch (c) {
case '"':
builder.Append("\\\"");
break;
case '\\':
builder.Append("\\\\");
break;
case '\b':
builder.Append("\\b");
break;
case '\f':
builder.Append("\\f");
break;
case '\n':
builder.Append("\\n");
break;
case '\r':
builder.Append("\\r");
break;
case '\t':
builder.Append("\\t");
break;
default:
int codepoint = Convert.ToInt32(c);
if ((codepoint >= 32) && (codepoint <= 126)) {
builder.Append(c);
}
else {
builder.Append("\\u" + Convert.ToString(codepoint, 16).PadLeft(4, '0'));
}
break;
}
}
builder.Append('\"');
}
void SerializeOther(object value) {
if (value is float
|| value is int
|| value is uint
|| value is long
|| value is double
|| value is sbyte
|| value is byte
|| value is short
|| value is ushort
|| value is ulong
|| value is decimal) {
builder.Append(value.ToString());
}
else {
SerializeString(value.ToString());
}
}
}
}
}
| |
#region Copyright
/*Copyright (C) 2015 Konstantin Udilovich
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Windows.Controls;
using Dynamo.Controls;
using Dynamo.Models;
using Dynamo.Wpf;
using ProtoCore.AST.AssociativeAST;
using Kodestruct.Common.CalculationLogger;
using Kodestruct.Dynamo.Common;
using Kodestruct.Loads.ASCE7.Entities;
using Kodestruct.Dynamo.Common.Infra.TreeItems;
using System.Xml;
using System.Windows.Input;
using System.Windows;
using Kodestruct.Dynamo.UI.Common.TreeItems;
using GalaSoft.MvvmLight.Command;
using KodestructDynamoUI.Views.Loads.ASCE7;
using Dynamo.Nodes;
using Dynamo.Graph;
using Dynamo.Graph.Nodes;
namespace Kodestruct.Loads.ASCE7.Gravity.Live
{
/// <summary>
///Occupancy or use for selection of uniformly distributed loads - ASCE7-10
/// </summary>
[NodeName("Live Load occupancy selection")]
[NodeCategory("Kodestruct.Loads.ASCE7.Gravity.Live")]
[NodeDescription("Occupancy or use for selection of uniformly distributed loads")]
[IsDesignScriptCompatible]
public class LiveLoadOccupancySelection : UiNodeBase
{
public LiveLoadOccupancySelection()
{
ReportEntry="";
LiveLoadOccupancyId = "Office";
LiveLoadOccupancyDescription = "Office space";
//OutPortData.Add(new PortData("ReportEntry", "Calculation log entries (for reporting)"));
OutPortData.Add(new PortData("LiveLoadOccupancyId", "description of space for calculation of live loads"));
RegisterAllPorts();
//PropertyChanged += NodePropertyChanged;
}
/// <summary>
/// Gets the type of this class, to be used in base class for reflection
/// </summary>
protected override Type GetModelType()
{
return GetType();
}
#region properties
#region OutputProperties
#region LiveLoadOccupancyIdProperty
/// <summary>
/// LiveLoadOccupancyId property
/// </summary>
/// <value>description of space for calculation of live loads</value>
public string _LiveLoadOccupancyId;
public string LiveLoadOccupancyId
{
get { return _LiveLoadOccupancyId; }
set
{
_LiveLoadOccupancyId = value;
RaisePropertyChanged("LiveLoadOccupancyId");
OnNodeModified(true);
}
}
#endregion
#region LiveLoadOccupancyDescription Property
private string liveLoadOccupancyDescription;
public string LiveLoadOccupancyDescription
{
get { return liveLoadOccupancyDescription; }
set
{
liveLoadOccupancyDescription = value;
RaisePropertyChanged("LiveLoadOccupancyDescription");
}
}
#endregion
#region ReportEntryProperty
/// <summary>
/// log property
/// </summary>
/// <value>Calculation entries that can be converted into a report.</value>
public string reportEntry;
public string ReportEntry
{
get { return reportEntry; }
set
{
reportEntry = value;
RaisePropertyChanged("ReportEntry");
OnNodeModified(true);
}
}
#endregion
#endregion
#endregion
#region Serialization
/// <summary>
///Saves property values to be retained when opening the node
/// </summary>
protected override void SerializeCore(XmlElement nodeElement, SaveContext context)
{
base.SerializeCore(nodeElement, context);
nodeElement.SetAttribute("LiveLoadOccupancyId", LiveLoadOccupancyId);
}
/// <summary>
///Retrieves property values when opening the node
/// </summary>
protected override void DeserializeCore(XmlElement nodeElement, SaveContext context)
{
base.DeserializeCore(nodeElement, context);
var attrib = nodeElement.Attributes["LiveLoadOccupancyId"];
if (attrib == null)
return;
LiveLoadOccupancyId = attrib.Value;
SetOcupancyDescription();
}
public void UpdateSelectionEvents()
{
if (TreeViewControl != null)
{
TreeViewControl.SelectedItemChanged += OnTreeViewSelectionChanged;
}
}
private void OnTreeViewSelectionChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
OnSelectedItemChanged(e.NewValue);
}
private void SetOcupancyDescription()
{
Uri uri = new Uri("pack://application:,,,/KodestructDynamoUI;component/Views/Loads/ASCE7/Live/LiveLoadOccupancyIdTreeData.xml");
XmlTreeHelper treeHelper = new XmlTreeHelper();
treeHelper.ExamineXmlTreeFile(uri, new EvaluateXmlNodeDelegate(FindOccupancyDescription));
}
private void FindOccupancyDescription(XmlNode node)
{
if (null != node.Attributes["Id"])
{
if (node.Attributes["Id"].Value== LiveLoadOccupancyId)
{
LiveLoadOccupancyDescription = node.Attributes["Description"].Value;
}
}
}
#endregion
#region treeView elements
public TreeView TreeViewControl { get; set; }
public void DisplayComponentUI(XTreeItem selectedComponent)
{
//TODO: Add partition allowance here
}
private XTreeItem selectedItem;
public XTreeItem SelectedItem
{
get { return selectedItem; }
set
{
selectedItem = value;
}
}
private void OnSelectedItemChanged(object i)
{
XmlElement item = i as XmlElement;
XTreeItem xtreeItem = new XTreeItem()
{
Header = item.GetAttribute("Header"),
Description = item.GetAttribute("Description"),
Id = item.GetAttribute("Id"),
ResourcePath = item.GetAttribute("ResourcePath"),
Tag = item.GetAttribute("Tag"),
TemplateName = item.GetAttribute("TemplateName")
};
if (item != null)
{
string id =xtreeItem.Id;
if (id != "X")
{
LiveLoadOccupancyId = xtreeItem.Id;
LiveLoadOccupancyDescription = xtreeItem.Description;
SelectedItem = xtreeItem;
DisplayComponentUI(xtreeItem);
}
}
}
#endregion
//Additional UI is a user control which is based on the user selection
// can remove this property
#region Additional UI
private UserControl additionalUI;
public UserControl AdditionalUI
{
get { return additionalUI; }
set
{
additionalUI = value;
RaisePropertyChanged("AdditionalUI");
}
}
#endregion
/// <summary>
///Customization of WPF view in Dynamo UI
/// </summary>
public class LiveLoadOccupancyIdViewCustomization : UiNodeBaseViewCustomization,
INodeViewCustomization<LiveLoadOccupancySelection>
{
public void CustomizeView(LiveLoadOccupancySelection model, NodeView nodeView)
{
base.CustomizeView(model, nodeView);
LiveLoadOccupancyIdView control = new LiveLoadOccupancyIdView();
control.DataContext = model;
//remove this part if control does not contain tree
TreeView tv = control.FindName("selectionTree") as TreeView;
if (tv!=null)
{
model.TreeViewControl = tv;
model.UpdateSelectionEvents();
}
nodeView.inputGrid.Children.Add(control);
base.CustomizeView(model, nodeView);
}
}
}
}
| |
/*******************************************************************************
* Copyright 2008-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* *****************************************************************************
* __ _ _ ___
* ( )( \/\/ )/ __)
* /__\ \ / \__ \
* (_)(_) \/\/ (___/
*
* AWS SDK for .NET
* API Version: 2006-03-01
*
*/
using System;
using System.Xml.Serialization;
namespace Amazon.S3.Model
{
/// <summary>
/// The parameters to fetch an object from a bucket.
/// </summary>
/// <remarks>
/// For more information about the optional parameters, refer to:
/// <see href="http://docs.amazonwebservices.com/AmazonS3/latest/RESTObjectGET.html"/>
/// <br />Required Parameters: BucketName, Key
/// <br />Optional Parameters: VersionId, ModifiedSinceDate, UnmodifiedSinceDate, ETagToMatch, ETagToNotMatch, ByteRange
/// </remarks>
public class GetObjectRequest : S3Request
{
#region Private Members
string bucketName;
string key;
string versionId;
DateTime? modifiedSinceDate;
DateTime? unmodifiedSinceDate;
string etagToMatch;
string etagToNotMatch;
Tuple<long, long> byteRange;
ResponseHeaderOverrides _responseHeaders;
#endregion
#region BucketName
/// <summary>
/// The name of the bucket containing the object.
/// </summary>
[XmlElementAttribute(ElementName = "BucketName")]
public string BucketName
{
get { return this.bucketName; }
set { this.bucketName = value; }
}
/// <summary>
/// Sets the name of the bucket containing the object.
/// </summary>
/// <param name="bucketName">The bucket name</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public GetObjectRequest WithBucketName(string bucketName)
{
this.bucketName = bucketName;
return this;
}
/// <summary>
/// Checks if BucketName property is set.
/// </summary>
/// <returns>true if BucketName property is set.</returns>
internal bool IsSetBucketName()
{
return !System.String.IsNullOrEmpty(this.bucketName);
}
#endregion
#region Key
/// <summary>
/// The key of the object to be fetched.
/// </summary>
[XmlElementAttribute(ElementName = "Key")]
public string Key
{
get { return this.key; }
set { this.key = value; }
}
/// <summary>
/// Sets the key of the object to be fetched.
/// </summary>
/// <param name="key">The object key</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public GetObjectRequest WithKey(string key)
{
this.key = key;
return this;
}
/// <summary>
/// Checks if Key property is set.
/// </summary>
/// <returns>true if Key property is set.</returns>
internal bool IsSetKey()
{
return !System.String.IsNullOrEmpty(this.key);
}
#endregion
#region VersionId
/// <summary>
/// Version of the object to fetch. If not set, the latest version of
/// the object is returned.
/// </summary>
[XmlElementAttribute(ElementName = "VersionId")]
public string VersionId
{
get { return this.versionId; }
set { this.versionId = value; }
}
/// <summary>
/// Sets the version of the object to fetch. If not set, the latest version of
/// the object is returned.
/// </summary>
/// <param name="versionId">Object version id</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public GetObjectRequest WithVersionId(string versionId)
{
this.versionId = versionId;
return this;
}
/// <summary>
/// Checks if VersionId property is set.
/// </summary>
/// <returns>true if VersionId property is set.</returns>
internal bool IsSetVersionId()
{
return !System.String.IsNullOrEmpty(this.versionId);
}
#endregion
#region ModifiedSinceDate
/// <summary>
/// Returns the object only if it has been modified since the specified time,
/// otherwise returns a PreconditionFailed.
/// </summary>
[XmlElementAttribute(ElementName = "ModifiedSinceDate")]
public DateTime ModifiedSinceDate
{
get { return this.modifiedSinceDate.GetValueOrDefault(); }
set { this.modifiedSinceDate = value; }
}
/// <summary>
/// Returns the object only if it has been modified since the specified time,
/// otherwise returns a PreconditionFailed.
/// </summary>
/// <remarks>
/// When this is set the S3 object is returned only if it has been modified since the specified time, otherwise
/// returns a 304 (not modified).
/// </remarks>
/// <param name="modifiedSinceDate">Date and time to test</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public GetObjectRequest WithModifiedSinceDate(DateTime modifiedSinceDate)
{
this.modifiedSinceDate = modifiedSinceDate;
return this;
}
/// <summary>
/// Checks if ModifiedSinceDate property is set.
/// </summary>
/// <returns>true if ModifiedSinceDate property is set.</returns>
internal bool IsSetModifiedSinceDate()
{
return modifiedSinceDate.HasValue;
}
#endregion
#region UnmodifiedSinceDate
/// <summary>
/// Returns the object only if it has not been modified since the specified time,
/// otherwise returns a PreconditionFailed.
/// </summary>
[XmlElementAttribute(ElementName = "UnmodifiedSinceDate")]
public DateTime UnmodifiedSinceDate
{
get { return this.unmodifiedSinceDate.GetValueOrDefault(); }
set { this.unmodifiedSinceDate = value; }
}
/// <summary>
/// Returns the object only if it has been modified since the specified time,
/// otherwise returns a PreconditionFailed.
/// </summary>
/// <remarks>
/// When this is set the S3 object is returned only if it has not been modified since the specified time, otherwise
/// return a 412 (precondition failed).
/// </remarks>
/// <param name="unmodifiedSinceDate">The date and time to test</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public GetObjectRequest WithUnmodifiedSinceDate(DateTime unmodifiedSinceDate)
{
this.unmodifiedSinceDate = unmodifiedSinceDate;
return this;
}
/// <summary>
/// Checks if UnmodifiedSinceDate property is set.
/// </summary>
/// <returns>true if UnmodifiedSinceDate property is set.</returns>
internal bool IsSetUnmodifiedSinceDate()
{
return unmodifiedSinceDate.HasValue;
}
#endregion
#region ETagToMatch
/// <summary>
/// ETag to be matched as a pre-condition for returning the object,
/// otherwise a PreconditionFailed signal is returned.
/// </summary>
[XmlElementAttribute(ElementName = "ETagToMatch")]
public string ETagToMatch
{
get { return this.etagToMatch; }
set { this.etagToMatch = value; }
}
/// <summary>
/// Sets an ETag to be matched as a pre-condition for returning the object,
/// otherwise a PreconditionFailed signal is returned.
/// </summary>
/// <remarks>
/// When this is set the S3 object is returned only if its entity tag (ETag) is the same as the one specified,
/// otherwise return a 412 (precondition failed).
/// </remarks>
/// <param name="etagToMatch">The ETag to match</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public GetObjectRequest WithETagToMatch(string etagToMatch)
{
this.etagToMatch = etagToMatch;
return this;
}
/// <summary>
/// Checks if ETagToMatch property is set.
/// </summary>
/// <returns>true if ETagToMatch property is set.</returns>
internal bool IsSetETagToMatch()
{
return !System.String.IsNullOrEmpty(this.etagToMatch);
}
#endregion
#region ETagToNotMatch
/// <summary>
/// ETag that should not be matched as a pre-condition for returning the object,
/// otherwise a PreconditionFailed signal is returned.
/// </summary>
[XmlElementAttribute(ElementName = "ETagToNotMatch")]
public string ETagToNotMatch
{
get { return this.etagToNotMatch; }
set { this.etagToNotMatch = value; }
}
/// <summary>
/// Sets an ETag that should not be matched as a pre-condition for returning the object,
/// otherwise a PreconditionFailed signal is returned.
/// </summary>
/// <remarks>
/// When this is set the S3 object is returned only if
/// its entity tag (ETag) is different from the one
/// specified, otherwise return a 304 (not modified).
/// </remarks>
/// <param name="etagToNotMatch">The ETag to test</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public GetObjectRequest WithETagToNotMatch(string etagToNotMatch)
{
this.etagToNotMatch = etagToNotMatch;
return this;
}
/// <summary>
/// Checks if ETagToNotMatch property is set.
/// </summary>
/// <returns>true if ETagToNotMatch property is set.</returns>
internal bool IsSetETagToNotMatch()
{
return !System.String.IsNullOrEmpty(this.etagToNotMatch);
}
#endregion
#region ByteRange
/// <summary>
/// Byte range of the object to return. When this is set the request downloads the specified range of an object.
/// </summary>
[XmlElementAttribute(ElementName = "ByteRange")]
public Tuple<long, long> ByteRangeLong
{
get { return this.byteRange; }
set { this.byteRange = value; }
}
/// <summary>
/// Sets a byte range of the object to return. When this is set the request downloads the specified range of an object.
/// </summary>
/// <param name="startIndex">The index to start at</param>
/// <param name="endIndex">The index to end at</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public GetObjectRequest WithByteRangeLong(long startIndex, long endIndex)
{
if (startIndex > endIndex)
{
throw new ArgumentException("The Start Index of the range needs to be greater than the End Index");
}
if (startIndex < 0)
{
throw new ArgumentException("The Start Index of the range needs to be >= 0");
}
if (endIndex < 0)
{
throw new ArgumentException("The End Index of the range needs to be >= 0");
}
this.byteRange = new Tuple<long, long>(startIndex, endIndex);
return this;
}
/// <summary>
/// Returns the byte range to retrieve, if set.
/// </summary>
public Tuple<int, int> ByteRange
{
get
{
if (this.byteRange == null)
{
return null;
}
return new Tuple<int, int>((int)this.byteRange.First, (int)this.byteRange.Second);
}
}
/// <summary>
/// Sets a byte range of the object to return. When this is set the request downloads the specified range of an object.
/// </summary>
/// <param name="startIndex">The index to start at</param>
/// <param name="endIndex">The index to end at</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public GetObjectRequest WithByteRange(int startIndex, int endIndex)
{
if (startIndex > endIndex)
{
throw new ArgumentException("The Start Index of the range needs to be greater than the End Index");
}
if (startIndex < 0)
{
throw new ArgumentException("The Start Index of the range needs to be >= 0");
}
if (endIndex < 0)
{
throw new ArgumentException("The End Index of the range needs to be >= 0");
}
this.byteRange = new Tuple<long, long>(startIndex, endIndex);
return this;
}
/// <summary>
/// Checks if ByteRange property is set.
/// </summary>
/// <returns>true if ByteRange property is set.</returns>
internal bool IsSetByteRange()
{
return this.ByteRangeLong != null;
}
#endregion
#region Timeout
/// <summary>
/// Overrides the default HttpWebRequest timeout value.
/// </summary>
/// <remarks>
/// <para>
/// The value of this property (in milliseconds) is assigned to the Timeout property of the HTTPWebRequest object used
/// for S3 GET Object requests.
/// </para>
/// <para>
/// Please specify a timeout value only if you are certain that the file will not be retrieved within the default intervals
/// specified for an HttpWebRequest.
/// </para>
/// <para>
/// A value less than or equal to 0 will be silently ignored
/// </para>
/// </remarks>
/// <param name="timeout">Timeout property</param>
/// <returns>this instance</returns>
/// <seealso cref="P:System.Net.HttpWebRequest.ReadWriteTimeout"/>
/// <seealso cref="P:System.Net.HttpWebRequest.Timeout"/>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
new public GetObjectRequest WithTimeout(int timeout)
{
Timeout = timeout;
return this;
}
#endregion
#region ReadWriteTimeout
/// <summary>
/// Overrides the default HttpWebRequest ReadWriteTimeout value.
/// </summary>
/// <remarks>
/// <para>
/// The value of this property (in milliseconds) is assigned to the
/// ReadWriteTimeout property of the HTTPWebRequest object
/// used for S3 GET Object requests.
/// </para>
/// <para>
/// A value less than or equal to 0 will be silently ignored
/// </para>
/// </remarks>
/// <param name="readWriteTimeout">ReadWriteTimeout property</param>
/// <returns>this instance</returns>
/// <seealso cref="P:System.Net.HttpWebRequest.ReadWriteTimeout"/>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
new public GetObjectRequest WithReadWriteTimeout(int readWriteTimeout)
{
ReadWriteTimeout = readWriteTimeout;
return this;
}
#endregion
#region Response Headers
/// <summary>
/// A set of response headers that should be returned with the object.
/// </summary>
public ResponseHeaderOverrides ResponseHeaderOverrides
{
get
{
if (this._responseHeaders == null)
{
this._responseHeaders = new ResponseHeaderOverrides();
}
return this._responseHeaders;
}
set
{
this._responseHeaders = value;
}
}
/// <summary>
/// A set of response headers that should be returned with the object.
/// </summary>
/// <param name="responseHeaderOverrides">Response headers to return</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public GetObjectRequest WithResponseHeaderOverrides(ResponseHeaderOverrides responseHeaderOverrides)
{
this.ResponseHeaderOverrides = responseHeaderOverrides;
return this;
}
#endregion
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.