context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
public class tk2dSystemUtility
{
static string GetObjectGUID(Object obj) { return AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(obj)); }
// Make this asset loadable at runtime, using the guid and the given name
// The guid MUST match the GUID of the object.
// The name is arbitrary and should be unique to make all assets findable using name,
// but doesn't have to be. Name can be an empty string, but not null.
public static bool MakeLoadableAsset(Object obj, string name)
{
string guid = GetObjectGUID(obj);
// Check if it already is Loadable
bool isLoadable = IsLoadableAsset(obj);
if (isLoadable)
{
// Update name if it is different
foreach (tk2dResourceTocEntry t in tk2dSystem.inst.Editor__Toc)
{
if (t.assetGUID == guid)
{
t.assetName = name;
break;
}
}
tk2dUtil.SetDirty(tk2dSystem.inst);
// Already loadable
return true;
}
// Create resource object
string resourcePath = GetOrCreateResourcesDir() + "/" + "tk2d_" + guid + ".asset";
tk2dResource resource = ScriptableObject.CreateInstance<tk2dResource>();
resource.objectReference = obj;
AssetDatabase.CreateAsset(resource, resourcePath);
AssetDatabase.SaveAssets();
// Add index entry
tk2dResourceTocEntry tocEntry = new tk2dResourceTocEntry();
tocEntry.resourceGUID = AssetDatabase.AssetPathToGUID(resourcePath);
tocEntry.assetName = (name.Length == 0)?obj.name:name;
tocEntry.assetGUID = guid;
List<tk2dResourceTocEntry> toc = new List<tk2dResourceTocEntry>(tk2dSystem.inst.Editor__Toc);
toc.Add(tocEntry);
tk2dSystem.inst.Editor__Toc = toc.ToArray();
tk2dUtil.SetDirty(tk2dSystem.inst);
AssetDatabase.SaveAssets();
return true;
}
// Deletes the asset from the global asset dictionary
// and removes the associated the asset from the build
public static bool UnmakeLoadableAsset(Object obj)
{
string guid = GetObjectGUID(obj);
List<tk2dResourceTocEntry> toc = new List<tk2dResourceTocEntry>(tk2dSystem.inst.Editor__Toc);
foreach (tk2dResourceTocEntry entry in toc)
{
if (entry.assetGUID == guid)
{
// Delete the corresponding resource object
string resourceObjectPath = AssetDatabase.GUIDToAssetPath(entry.resourceGUID);
AssetDatabase.DeleteAsset(resourceObjectPath);
// remove from TOC
toc.Remove(entry);
break;
}
}
if (tk2dSystem.inst.Editor__Toc.Length == toc.Count)
{
Debug.LogError("tk2dSystem.UnmakeLoadableAsset - Unable to delete asset");
return false;
}
else
{
tk2dSystem.inst.Editor__Toc = toc.ToArray();
tk2dUtil.SetDirty(tk2dSystem.inst);
AssetDatabase.SaveAssets();
return true;
}
}
// Update asset name
public static void UpdateAssetName(Object obj, string name)
{
MakeLoadableAsset(obj, name);
}
// This will return false if the system hasn't been initialized, without initializing it.
public static bool IsLoadableAsset(Object obj)
{
string resourcesDir = GetResourcesDir();
if (resourcesDir.Length == 0) // tk2dSystem hasn't been initialized yet
return false;
string guid = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(obj));
string resourcePath = GetResourcesDir() + "/tk2d_" + guid + ".asset";
return System.IO.File.Exists(resourcePath);
}
// Returns the path to the global resources directory
// It is /Assets/TK2DSYSTEM/Resources by default, but can be moved anywhere
// When the tk2dSystem object exists, the path to the object will be returned
public static string GetOrCreateResourcesDir()
{
tk2dSystem inst = tk2dSystem.inst;
string assetPath = AssetDatabase.GetAssetPath(inst);
if (assetPath.Length > 0)
{
// This has already been serialized, just return path as is
return System.IO.Path.GetDirectoryName(assetPath).Replace('\\', '/'); // already serialized
}
else
{
// Create the system asset
const string resPath = "Assets/Resources";
if (!System.IO.Directory.Exists(resPath)) System.IO.Directory.CreateDirectory(resPath);
const string basePath = resPath + "/tk2d";
if (!System.IO.Directory.Exists(basePath)) System.IO.Directory.CreateDirectory(basePath);
assetPath = basePath + "/" + tk2dSystem.assetFileName;
AssetDatabase.CreateAsset(inst, assetPath);
return basePath;
}
}
// Returns the path to the global resources directory
// Will not create if it doesn't exists
static string GetResourcesDir()
{
tk2dSystem inst = tk2dSystem.inst_NoCreate;
if (inst == null)
return "";
else return GetOrCreateResourcesDir(); // this already exists, so this function will follow the correct path
}
// Call when platform has changed
public static void PlatformChanged()
{
List<tk2dSpriteCollectionData> changedSpriteCollections = new List<tk2dSpriteCollectionData>();
tk2dSpriteCollectionData[] allSpriteCollections = Resources.FindObjectsOfTypeAll(typeof(tk2dSpriteCollectionData)) as tk2dSpriteCollectionData[];
foreach (tk2dSpriteCollectionData scd in allSpriteCollections)
{
if (scd.hasPlatformData)
{
scd.ResetPlatformData();
changedSpriteCollections.Add(scd);
}
}
allSpriteCollections = null;
tk2dFontData[] allFontDatas = Resources.FindObjectsOfTypeAll(typeof(tk2dFontData)) as tk2dFontData[];
foreach (tk2dFontData fd in allFontDatas)
{
if (fd.hasPlatformData)
{
fd.ResetPlatformData();
}
}
allFontDatas = null;
if (changedSpriteCollections.Count == 0)
return; // nothing worth changing has changed
// Scan all loaded sprite assets and rebuild them
foreach (var assembly in System.AppDomain.CurrentDomain.GetAssemblies())
{
try
{
System.Type[] types = assembly.GetTypes();
foreach (var type in types)
{
if (type.GetInterface("tk2dRuntime.ISpriteCollectionForceBuild") != null)
{
Object[] objects = Resources.FindObjectsOfTypeAll(type);
foreach (var spriteCollectionData in changedSpriteCollections)
{
foreach (var o in objects)
{
if (tk2dEditorUtility.IsPrefab(o))
continue;
tk2dRuntime.ISpriteCollectionForceBuild isc = o as tk2dRuntime.ISpriteCollectionForceBuild;
if (isc.UsesSpriteCollection(spriteCollectionData))
isc.ForceBuild();
}
}
}
}
}
catch { }
}
}
public static void RebuildResources()
{
// Delete all existing resources
string systemFileName = tk2dSystem.assetFileName.ToLower();
string tk2dIndexDir = "Assets/Resources/tk2d";
if (System.IO.Directory.Exists(tk2dIndexDir))
{
string[] files = System.IO.Directory.GetFiles(tk2dIndexDir);
foreach (string file in files)
{
string filename = System.IO.Path.GetFileName(file).ToLower();
if (filename.IndexOf(systemFileName) != -1) continue; // don't delete system object
if (filename.IndexOf("tk2d_") == -1)
{
Debug.LogError(string.Format("Unknown file '{0}' in tk2d resources directory, ignoring.", filename));
continue;
}
AssetDatabase.DeleteAsset(file);
}
}
// Delete all referenced resources, in the event they've been moved out of the directory
if (tk2dSystem.inst_NoCreate != null)
{
tk2dSystem sys = tk2dSystem.inst;
tk2dResourceTocEntry[] toc = sys.Editor__Toc;
for (int i = 0; i < toc.Length; ++i)
{
string path = AssetDatabase.GUIDToAssetPath(toc[i].resourceGUID);
if (path.Length > 0)
AssetDatabase.DeleteAsset(path);
}
sys.Editor__Toc = new tk2dResourceTocEntry[0]; // clear index
tk2dUtil.SetDirty(sys);
AssetDatabase.SaveAssets();
}
AssetDatabase.Refresh();
// Need to create new index?
tk2dSpriteCollectionIndex[] spriteCollectionIndex = tk2dEditorUtility.GetExistingIndex().GetSpriteCollectionIndex();
tk2dGenericIndexItem[] fontIndex = tk2dEditorUtility.GetExistingIndex().GetFonts();
int numLoadableAssets = 0;
foreach (tk2dGenericIndexItem font in fontIndex) { if (font.managed || font.loadable) numLoadableAssets++; }
foreach (tk2dSpriteCollectionIndex sc in spriteCollectionIndex) { if (sc.managedSpriteCollection || sc.loadable) numLoadableAssets++; }
// Need an index
if (numLoadableAssets > 0)
{
// If it already existed, the index would have been cleared by now
tk2dSystem sys = tk2dSystem.inst;
foreach (tk2dGenericIndexItem font in fontIndex)
{
if (font.managed || font.loadable) AddFontFromIndex(font);
tk2dEditorUtility.CollectAndUnloadUnusedAssets();
}
foreach (tk2dSpriteCollectionIndex sc in spriteCollectionIndex)
{
if (sc.managedSpriteCollection || sc.loadable) AddSpriteCollectionFromIndex(sc);
tk2dEditorUtility.CollectAndUnloadUnusedAssets();
}
Debug.Log(string.Format("Rebuilt {0} resources for tk2dSystem", sys.Editor__Toc.Length));
}
tk2dEditorUtility.CollectAndUnloadUnusedAssets();
}
static void AddSpriteCollectionFromIndex(tk2dSpriteCollectionIndex indexEntry)
{
string path = AssetDatabase.GUIDToAssetPath( indexEntry.spriteCollectionDataGUID );
tk2dSpriteCollectionData data = AssetDatabase.LoadAssetAtPath(path, typeof(tk2dSpriteCollectionData)) as tk2dSpriteCollectionData;
if (data == null)
{
Debug.LogError(string.Format("Unable to load sprite collection '{0}' at path '{1}'", indexEntry.name, path));
return;
}
MakeLoadableAsset(data, indexEntry.managedSpriteCollection ? " " : data.assetName);
data = null;
}
static void AddFontFromIndex(tk2dGenericIndexItem indexEntry)
{
string path = AssetDatabase.GUIDToAssetPath( indexEntry.dataGUID );
tk2dFontData data = AssetDatabase.LoadAssetAtPath(path, typeof(tk2dFontData)) as tk2dFontData;
if (data == null)
{
Debug.LogError(string.Format("Unable to load font data '{0}' at path '{1}'", indexEntry.AssetName, path));
return;
}
MakeLoadableAsset(data, ""); // can't make it directly loadable, hence no asset name
data = null;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
using System.Text;
using System.Xml.Schema;
using System.Collections;
using System.Diagnostics;
using System.Globalization;
using System.Security.Policy;
using System.Collections.Generic;
using System.Runtime.Versioning;
using System.Threading.Tasks;
namespace System.Xml
{
internal sealed partial class XmlValidatingReaderImpl : XmlReader, IXmlLineInfo, IXmlNamespaceResolver
{
// Returns the text value of the current node.
public override Task<string> GetValueAsync()
{
return _coreReader.GetValueAsync();
}
// Reads and validated next node from the input data
public override async Task<bool> ReadAsync()
{
switch (_parsingFunction)
{
case ParsingFunction.Read:
if (await _coreReader.ReadAsync().ConfigureAwait(false))
{
ProcessCoreReaderEvent();
return true;
}
else
{
_validator.CompleteValidation();
return false;
}
case ParsingFunction.ParseDtdFromContext:
_parsingFunction = ParsingFunction.Read;
await ParseDtdFromParserContextAsync().ConfigureAwait(false);
goto case ParsingFunction.Read;
case ParsingFunction.Error:
case ParsingFunction.ReaderClosed:
return false;
case ParsingFunction.Init:
_parsingFunction = ParsingFunction.Read; // this changes the value returned by ReadState
if (_coreReader.ReadState == ReadState.Interactive)
{
ProcessCoreReaderEvent();
return true;
}
else
{
goto case ParsingFunction.Read;
}
case ParsingFunction.ResolveEntityInternally:
_parsingFunction = ParsingFunction.Read;
await ResolveEntityInternallyAsync().ConfigureAwait(false);
goto case ParsingFunction.Read;
case ParsingFunction.InReadBinaryContent:
_parsingFunction = ParsingFunction.Read;
await _readBinaryHelper.FinishAsync().ConfigureAwait(false);
goto case ParsingFunction.Read;
default:
Debug.Assert(false);
return false;
}
}
public override async Task<int> ReadContentAsBase64Async(byte[] buffer, int index, int count)
{
if (ReadState != ReadState.Interactive)
{
return 0;
}
// init ReadChunkHelper if called the first time
if (_parsingFunction != ParsingFunction.InReadBinaryContent)
{
_readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, _outerReader);
}
// set parsingFunction to Read state in order to have a normal Read() behavior when called from readBinaryHelper
_parsingFunction = ParsingFunction.Read;
// call to the helper
int readCount = await _readBinaryHelper.ReadContentAsBase64Async(buffer, index, count).ConfigureAwait(false);
// setup parsingFunction
_parsingFunction = ParsingFunction.InReadBinaryContent;
return readCount;
}
public override async Task<int> ReadContentAsBinHexAsync(byte[] buffer, int index, int count)
{
if (ReadState != ReadState.Interactive)
{
return 0;
}
// init ReadChunkHelper when called first time
if (_parsingFunction != ParsingFunction.InReadBinaryContent)
{
_readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, _outerReader);
}
// set parsingFunction to Read state in order to have a normal Read() behavior when called from readBinaryHelper
_parsingFunction = ParsingFunction.Read;
// call to the helper
int readCount = await _readBinaryHelper.ReadContentAsBinHexAsync(buffer, index, count).ConfigureAwait(false);
// setup parsingFunction
_parsingFunction = ParsingFunction.InReadBinaryContent;
return readCount;
}
public override async Task<int> ReadElementContentAsBase64Async(byte[] buffer, int index, int count)
{
if (ReadState != ReadState.Interactive)
{
return 0;
}
// init ReadChunkHelper if called the first time
if (_parsingFunction != ParsingFunction.InReadBinaryContent)
{
_readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, _outerReader);
}
// set parsingFunction to Read state in order to have a normal Read() behavior when called from readBinaryHelper
_parsingFunction = ParsingFunction.Read;
// call to the helper
int readCount = await _readBinaryHelper.ReadElementContentAsBase64Async(buffer, index, count).ConfigureAwait(false);
// setup parsingFunction
_parsingFunction = ParsingFunction.InReadBinaryContent;
return readCount;
}
public override async Task<int> ReadElementContentAsBinHexAsync(byte[] buffer, int index, int count)
{
if (ReadState != ReadState.Interactive)
{
return 0;
}
// init ReadChunkHelper when called first time
if (_parsingFunction != ParsingFunction.InReadBinaryContent)
{
_readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, _outerReader);
}
// set parsingFunction to Read state in order to have a normal Read() behavior when called from readBinaryHelper
_parsingFunction = ParsingFunction.Read;
// call to the helper
int readCount = await _readBinaryHelper.ReadElementContentAsBinHexAsync(buffer, index, count).ConfigureAwait(false);
// setup parsingFunction
_parsingFunction = ParsingFunction.InReadBinaryContent;
return readCount;
}
internal async Task MoveOffEntityReferenceAsync()
{
if (_outerReader.NodeType == XmlNodeType.EntityReference && _parsingFunction != ParsingFunction.ResolveEntityInternally)
{
if (!await _outerReader.ReadAsync().ConfigureAwait(false))
{
throw new InvalidOperationException(SR.Xml_InvalidOperation);
}
}
}
// Returns typed value of the current node (based on the type specified by schema)
public async Task<object> ReadTypedValueAsync()
{
if (_validationType == ValidationType.None)
{
return null;
}
switch (_outerReader.NodeType)
{
case XmlNodeType.Attribute:
return _coreReaderImpl.InternalTypedValue;
case XmlNodeType.Element:
if (SchemaType == null)
{
return null;
}
XmlSchemaDatatype dtype = (SchemaType is XmlSchemaDatatype) ? (XmlSchemaDatatype)SchemaType : ((XmlSchemaType)SchemaType).Datatype;
if (dtype != null)
{
if (!_outerReader.IsEmptyElement)
{
for (;;)
{
if (!await _outerReader.ReadAsync().ConfigureAwait(false))
{
throw new InvalidOperationException(SR.Xml_InvalidOperation);
}
XmlNodeType type = _outerReader.NodeType;
if (type != XmlNodeType.CDATA && type != XmlNodeType.Text &&
type != XmlNodeType.Whitespace && type != XmlNodeType.SignificantWhitespace &&
type != XmlNodeType.Comment && type != XmlNodeType.ProcessingInstruction)
{
break;
}
}
if (_outerReader.NodeType != XmlNodeType.EndElement)
{
throw new XmlException(SR.Xml_InvalidNodeType, _outerReader.NodeType.ToString());
}
}
return _coreReaderImpl.InternalTypedValue;
}
return null;
case XmlNodeType.EndElement:
return null;
default:
if (_coreReaderImpl.V1Compat)
{ //If v1 XmlValidatingReader return null
return null;
}
else
{
return await GetValueAsync().ConfigureAwait(false);
}
}
}
//
// Private implementation methods
//
private async Task ParseDtdFromParserContextAsync()
{
Debug.Assert(_parserContext != null);
Debug.Assert(_coreReaderImpl.DtdInfo == null);
if (_parserContext.DocTypeName == null || _parserContext.DocTypeName.Length == 0)
{
return;
}
IDtdParser dtdParser = DtdParser.Create();
XmlTextReaderImpl.DtdParserProxy proxy = new XmlTextReaderImpl.DtdParserProxy(_coreReaderImpl);
IDtdInfo dtdInfo = await dtdParser.ParseFreeFloatingDtdAsync(_parserContext.BaseURI, _parserContext.DocTypeName, _parserContext.PublicId, _parserContext.SystemId, _parserContext.InternalSubset, proxy).ConfigureAwait(false);
_coreReaderImpl.SetDtdInfo(dtdInfo);
ValidateDtd();
}
private async Task ResolveEntityInternallyAsync()
{
Debug.Assert(_coreReader.NodeType == XmlNodeType.EntityReference);
int initialDepth = _coreReader.Depth;
_outerReader.ResolveEntity();
while (await _outerReader.ReadAsync().ConfigureAwait(false) && _coreReader.Depth > initialDepth) ;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Reflection;
using System.Threading;
using Nwc.XmlRpc;
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Services.Interfaces;
/***************************************************************************
* Simian Data Map
* ===============
*
* OwnerID -> Type -> Key
* -----------------------
*
* UserID -> Group -> ActiveGroup
* + GroupID
*
* UserID -> GroupSessionDropped -> GroupID
* UserID -> GroupSessionInvited -> GroupID
*
* UserID -> GroupMember -> GroupID
* + SelectedRoleID [UUID]
* + AcceptNotices [bool]
* + ListInProfile [bool]
* + Contribution [int]
*
* UserID -> GroupRole[GroupID] -> RoleID
*
*
* GroupID -> Group -> GroupName
* + Charter
* + ShowInList
* + InsigniaID
* + MembershipFee
* + OpenEnrollment
* + AllowPublish
* + MaturePublish
* + FounderID
* + EveryonePowers
* + OwnerRoleID
* + OwnersPowers
*
* GroupID -> GroupRole -> RoleID
* + Name
* + Description
* + Title
* + Powers
*
* GroupID -> GroupMemberInvite -> InviteID
* + AgentID
* + RoleID
*
* GroupID -> GroupNotice -> NoticeID
* + TimeStamp [uint]
* + FromName [string]
* + Subject [string]
* + Message [string]
* + BinaryBucket [byte[]]
*
* */
namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "SimianGroupsServicesConnectorModule")]
public class SimianGroupsServicesConnectorModule : ISharedRegionModule, IGroupsServicesConnector
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public const GroupPowers m_DefaultEveryonePowers = GroupPowers.AllowSetHome |
GroupPowers.Accountable |
GroupPowers.JoinChat |
GroupPowers.AllowVoiceChat |
GroupPowers.ReceiveNotices |
GroupPowers.StartProposal |
GroupPowers.VoteOnProposal;
// Would this be cleaner as (GroupPowers)ulong.MaxValue;
public const GroupPowers m_DefaultOwnerPowers = GroupPowers.Accountable
| GroupPowers.AllowEditLand
| GroupPowers.AllowFly
| GroupPowers.AllowLandmark
| GroupPowers.AllowRez
| GroupPowers.AllowSetHome
| GroupPowers.AllowVoiceChat
| GroupPowers.AssignMember
| GroupPowers.AssignMemberLimited
| GroupPowers.ChangeActions
| GroupPowers.ChangeIdentity
| GroupPowers.ChangeMedia
| GroupPowers.ChangeOptions
| GroupPowers.CreateRole
| GroupPowers.DeedObject
| GroupPowers.DeleteRole
| GroupPowers.Eject
| GroupPowers.FindPlaces
| GroupPowers.Invite
| GroupPowers.JoinChat
| GroupPowers.LandChangeIdentity
| GroupPowers.LandDeed
| GroupPowers.LandDivideJoin
| GroupPowers.LandEdit
| GroupPowers.LandEjectAndFreeze
| GroupPowers.LandGardening
| GroupPowers.LandManageAllowed
| GroupPowers.LandManageBanned
| GroupPowers.LandManagePasses
| GroupPowers.LandOptions
| GroupPowers.LandRelease
| GroupPowers.LandSetSale
| GroupPowers.ModerateChat
| GroupPowers.ObjectManipulate
| GroupPowers.ObjectSetForSale
| GroupPowers.ReceiveNotices
| GroupPowers.RemoveMember
| GroupPowers.ReturnGroupOwned
| GroupPowers.ReturnGroupSet
| GroupPowers.ReturnNonGroup
| GroupPowers.RoleProperties
| GroupPowers.SendNotices
| GroupPowers.SetLandingPoint
| GroupPowers.StartProposal
| GroupPowers.VoteOnProposal;
private bool m_connectorEnabled = false;
private string m_groupsServerURI = string.Empty;
private bool m_debugEnabled = false;
private Dictionary<string, bool> m_pendingRequests = new Dictionary<string,bool>();
private ExpiringCache<string, OSDMap> m_memoryCache;
private int m_cacheTimeout = 30;
// private IUserAccountService m_accountService = null;
#region Region Module interfaceBase Members
public string Name
{
get { return "SimianGroupsServicesConnector"; }
}
// this module is not intended to be replaced, but there should only be 1 of them.
public Type ReplaceableInterface
{
get { return null; }
}
public void Initialise(IConfigSource config)
{
IConfig groupsConfig = config.Configs["Groups"];
if (groupsConfig == null)
{
// Do not run this module by default.
return;
}
else
{
// if groups aren't enabled, we're not needed.
// if we're not specified as the connector to use, then we're not wanted
if ((groupsConfig.GetBoolean("Enabled", false) == false)
|| (groupsConfig.GetString("ServicesConnectorModule", "XmlRpcGroupsServicesConnector") != Name))
{
m_connectorEnabled = false;
return;
}
m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR]: Initializing {0}", this.Name);
m_groupsServerURI = groupsConfig.GetString("GroupsServerURI", string.Empty);
if ((m_groupsServerURI == null) ||
(m_groupsServerURI == string.Empty))
{
m_log.ErrorFormat("Please specify a valid Simian Server for GroupsServerURI in OpenSim.ini, [Groups]");
m_connectorEnabled = false;
return;
}
m_cacheTimeout = groupsConfig.GetInt("GroupsCacheTimeout", 30);
if (m_cacheTimeout == 0)
{
m_log.WarnFormat("[SIMIAN-GROUPS-CONNECTOR] Groups Cache Disabled.");
}
else
{
m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] Groups Cache Timeout set to {0}.", m_cacheTimeout);
}
m_memoryCache = new ExpiringCache<string,OSDMap>();
// If we got all the config options we need, lets start'er'up
m_connectorEnabled = true;
m_debugEnabled = groupsConfig.GetBoolean("DebugEnabled", true);
}
}
public void Close()
{
m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR]: Closing {0}", this.Name);
}
public void AddRegion(OpenSim.Region.Framework.Scenes.Scene scene)
{
if (m_connectorEnabled)
{
scene.RegisterModuleInterface<IGroupsServicesConnector>(this);
}
}
public void RemoveRegion(OpenSim.Region.Framework.Scenes.Scene scene)
{
if (scene.RequestModuleInterface<IGroupsServicesConnector>() == this)
{
scene.UnregisterModuleInterface<IGroupsServicesConnector>(this);
}
}
public void RegionLoaded(OpenSim.Region.Framework.Scenes.Scene scene)
{
// TODO: May want to consider listenning for Agent Connections so we can pre-cache group info
// scene.EventManager.OnNewClient += OnNewClient;
}
#endregion
#region ISharedRegionModule Members
public void PostInitialise()
{
// NoOp
}
#endregion
#region IGroupsServicesConnector Members
/// <summary>
/// Create a Group, including Everyone and Owners Role, place FounderID in both groups, select Owner as selected role, and newly created group as agent's active role.
/// </summary>
public UUID CreateGroup(UUID requestingAgentID, string name, string charter, bool showInList, UUID insigniaID,
int membershipFee, bool openEnrollment, bool allowPublish,
bool maturePublish, UUID founderID)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
UUID GroupID = UUID.Random();
UUID OwnerRoleID = UUID.Random();
OSDMap GroupInfoMap = new OSDMap();
GroupInfoMap["Charter"] = OSD.FromString(charter);
GroupInfoMap["ShowInList"] = OSD.FromBoolean(showInList);
GroupInfoMap["InsigniaID"] = OSD.FromUUID(insigniaID);
GroupInfoMap["MembershipFee"] = OSD.FromInteger(0);
GroupInfoMap["OpenEnrollment"] = OSD.FromBoolean(openEnrollment);
GroupInfoMap["AllowPublish"] = OSD.FromBoolean(allowPublish);
GroupInfoMap["MaturePublish"] = OSD.FromBoolean(maturePublish);
GroupInfoMap["FounderID"] = OSD.FromUUID(founderID);
GroupInfoMap["EveryonePowers"] = OSD.FromULong((ulong)m_DefaultEveryonePowers);
GroupInfoMap["OwnerRoleID"] = OSD.FromUUID(OwnerRoleID);
GroupInfoMap["OwnersPowers"] = OSD.FromULong((ulong)m_DefaultOwnerPowers);
if (SimianAddGeneric(GroupID, "Group", name, GroupInfoMap))
{
AddGroupRole(requestingAgentID, GroupID, UUID.Zero, "Everyone", "Members of " + name, "Member of " + name, (ulong)m_DefaultEveryonePowers);
AddGroupRole(requestingAgentID, GroupID, OwnerRoleID, "Owners", "Owners of " + name, "Owner of " + name, (ulong)m_DefaultOwnerPowers);
AddAgentToGroup(requestingAgentID, requestingAgentID, GroupID, OwnerRoleID);
return GroupID;
}
else
{
return UUID.Zero;
}
}
public void UpdateGroup(UUID requestingAgentID, UUID groupID, string charter, bool showInList,
UUID insigniaID, int membershipFee, bool openEnrollment,
bool allowPublish, bool maturePublish)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
// TODO: Check to make sure requestingAgentID has permission to update group
string GroupName;
OSDMap GroupInfoMap;
if (SimianGetFirstGenericEntry(groupID, "GroupInfo", out GroupName, out GroupInfoMap))
{
GroupInfoMap["Charter"] = OSD.FromString(charter);
GroupInfoMap["ShowInList"] = OSD.FromBoolean(showInList);
GroupInfoMap["InsigniaID"] = OSD.FromUUID(insigniaID);
GroupInfoMap["MembershipFee"] = OSD.FromInteger(0);
GroupInfoMap["OpenEnrollment"] = OSD.FromBoolean(openEnrollment);
GroupInfoMap["AllowPublish"] = OSD.FromBoolean(allowPublish);
GroupInfoMap["MaturePublish"] = OSD.FromBoolean(maturePublish);
SimianAddGeneric(groupID, "Group", GroupName, GroupInfoMap);
}
}
public void AddGroupRole(UUID requestingAgentID, UUID groupID, UUID roleID, string name, string description,
string title, ulong powers)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
OSDMap GroupRoleInfo = new OSDMap();
GroupRoleInfo["Name"] = OSD.FromString(name);
GroupRoleInfo["Description"] = OSD.FromString(description);
GroupRoleInfo["Title"] = OSD.FromString(title);
GroupRoleInfo["Powers"] = OSD.FromULong((ulong)powers);
// TODO: Add security, make sure that requestingAgentID has permision to add roles
SimianAddGeneric(groupID, "GroupRole", roleID.ToString(), GroupRoleInfo);
}
public void RemoveGroupRole(UUID requestingAgentID, UUID groupID, UUID roleID)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
// TODO: Add security
// Can't delete the Everyone Role
if (roleID != UUID.Zero)
{
// Remove all GroupRole Members from Role
Dictionary<UUID, OSDMap> GroupRoleMembers;
string GroupRoleMemberType = "GroupRole" + groupID.ToString();
if (SimianGetGenericEntries(GroupRoleMemberType, roleID.ToString(), out GroupRoleMembers))
{
foreach (UUID UserID in GroupRoleMembers.Keys)
{
EnsureRoleNotSelectedByMember(groupID, roleID, UserID);
SimianRemoveGenericEntry(UserID, GroupRoleMemberType, roleID.ToString());
}
}
// Remove role
SimianRemoveGenericEntry(groupID, "GroupRole", roleID.ToString());
}
}
public void UpdateGroupRole(UUID requestingAgentID, UUID groupID, UUID roleID, string name, string description,
string title, ulong powers)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
// TODO: Security, check that requestingAgentID is allowed to update group roles
OSDMap GroupRoleInfo;
if (SimianGetGenericEntry(groupID, "GroupRole", roleID.ToString(), out GroupRoleInfo))
{
if (name != null)
{
GroupRoleInfo["Name"] = OSD.FromString(name);
}
if (description != null)
{
GroupRoleInfo["Description"] = OSD.FromString(description);
}
if (title != null)
{
GroupRoleInfo["Title"] = OSD.FromString(title);
}
GroupRoleInfo["Powers"] = OSD.FromULong((ulong)powers);
}
SimianAddGeneric(groupID, "GroupRole", roleID.ToString(), GroupRoleInfo);
}
public GroupRecord GetGroupRecord(UUID requestingAgentID, UUID groupID, string groupName)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
OSDMap GroupInfoMap = null;
if (groupID != UUID.Zero)
{
if (!SimianGetFirstGenericEntry(groupID, "Group", out groupName, out GroupInfoMap))
{
return null;
}
}
else if ((groupName != null) && (groupName != string.Empty))
{
if (!SimianGetFirstGenericEntry("Group", groupName, out groupID, out GroupInfoMap))
{
return null;
}
}
GroupRecord GroupInfo = new GroupRecord();
GroupInfo.GroupID = groupID;
GroupInfo.GroupName = groupName;
GroupInfo.Charter = GroupInfoMap["Charter"].AsString();
GroupInfo.ShowInList = GroupInfoMap["ShowInList"].AsBoolean();
GroupInfo.GroupPicture = GroupInfoMap["InsigniaID"].AsUUID();
GroupInfo.MembershipFee = GroupInfoMap["MembershipFee"].AsInteger();
GroupInfo.OpenEnrollment = GroupInfoMap["OpenEnrollment"].AsBoolean();
GroupInfo.AllowPublish = GroupInfoMap["AllowPublish"].AsBoolean();
GroupInfo.MaturePublish = GroupInfoMap["MaturePublish"].AsBoolean();
GroupInfo.FounderID = GroupInfoMap["FounderID"].AsUUID();
GroupInfo.OwnerRoleID = GroupInfoMap["OwnerRoleID"].AsUUID();
return GroupInfo;
}
public GroupProfileData GetMemberGroupProfile(UUID requestingAgentID, UUID groupID, UUID memberID)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
OSDMap groupProfile;
string groupName;
if (!SimianGetFirstGenericEntry(groupID, "Group", out groupName, out groupProfile))
{
// GroupProfileData is not nullable
return new GroupProfileData();
}
GroupProfileData MemberGroupProfile = new GroupProfileData();
MemberGroupProfile.GroupID = groupID;
MemberGroupProfile.Name = groupName;
if (groupProfile["Charter"] != null)
{
MemberGroupProfile.Charter = groupProfile["Charter"].AsString();
}
MemberGroupProfile.ShowInList = groupProfile["ShowInList"].AsString() == "1";
MemberGroupProfile.InsigniaID = groupProfile["InsigniaID"].AsUUID();
MemberGroupProfile.MembershipFee = groupProfile["MembershipFee"].AsInteger();
MemberGroupProfile.OpenEnrollment = groupProfile["OpenEnrollment"].AsBoolean();
MemberGroupProfile.AllowPublish = groupProfile["AllowPublish"].AsBoolean();
MemberGroupProfile.MaturePublish = groupProfile["MaturePublish"].AsBoolean();
MemberGroupProfile.FounderID = groupProfile["FounderID"].AsUUID();;
MemberGroupProfile.OwnerRole = groupProfile["OwnerRoleID"].AsUUID();
Dictionary<UUID, OSDMap> Members;
if (SimianGetGenericEntries("GroupMember",groupID.ToString(), out Members))
{
MemberGroupProfile.GroupMembershipCount = Members.Count;
}
Dictionary<string, OSDMap> Roles;
if (SimianGetGenericEntries(groupID, "GroupRole", out Roles))
{
MemberGroupProfile.GroupRolesCount = Roles.Count;
}
// TODO: Get Group Money balance from somewhere
// group.Money = 0;
GroupMembershipData MemberInfo = GetAgentGroupMembership(requestingAgentID, memberID, groupID);
MemberGroupProfile.MemberTitle = MemberInfo.GroupTitle;
MemberGroupProfile.PowersMask = MemberInfo.GroupPowers;
return MemberGroupProfile;
}
public void SetAgentActiveGroup(UUID requestingAgentID, UUID agentID, UUID groupID)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
OSDMap ActiveGroup = new OSDMap();
ActiveGroup.Add("GroupID", OSD.FromUUID(groupID));
SimianAddGeneric(agentID, "Group", "ActiveGroup", ActiveGroup);
}
public void SetAgentActiveGroupRole(UUID requestingAgentID, UUID agentID, UUID groupID, UUID roleID)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
OSDMap GroupMemberInfo;
if (!SimianGetGenericEntry(agentID, "GroupMember", groupID.ToString(), out GroupMemberInfo))
{
GroupMemberInfo = new OSDMap();
}
GroupMemberInfo["SelectedRoleID"] = OSD.FromUUID(roleID);
SimianAddGeneric(agentID, "GroupMember", groupID.ToString(), GroupMemberInfo);
}
public void SetAgentGroupInfo(UUID requestingAgentID, UUID agentID, UUID groupID, bool acceptNotices, bool listInProfile)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
OSDMap GroupMemberInfo;
if (!SimianGetGenericEntry(agentID, "GroupMember", groupID.ToString(), out GroupMemberInfo))
{
GroupMemberInfo = new OSDMap();
}
GroupMemberInfo["AcceptNotices"] = OSD.FromBoolean(acceptNotices);
GroupMemberInfo["ListInProfile"] = OSD.FromBoolean(listInProfile);
GroupMemberInfo["Contribution"] = OSD.FromInteger(0);
GroupMemberInfo["SelectedRole"] = OSD.FromUUID(UUID.Zero);
SimianAddGeneric(agentID, "GroupMember", groupID.ToString(), GroupMemberInfo);
}
public void AddAgentToGroupInvite(UUID requestingAgentID, UUID inviteID, UUID groupID, UUID roleID, UUID agentID)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
OSDMap Invite = new OSDMap();
Invite["AgentID"] = OSD.FromUUID(agentID);
Invite["RoleID"] = OSD.FromUUID(roleID);
SimianAddGeneric(groupID, "GroupMemberInvite", inviteID.ToString(), Invite);
}
public GroupInviteInfo GetAgentToGroupInvite(UUID requestingAgentID, UUID inviteID)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
OSDMap GroupMemberInvite;
UUID GroupID;
if (!SimianGetFirstGenericEntry("GroupMemberInvite", inviteID.ToString(), out GroupID, out GroupMemberInvite))
{
return null;
}
GroupInviteInfo inviteInfo = new GroupInviteInfo();
inviteInfo.InviteID = inviteID;
inviteInfo.GroupID = GroupID;
inviteInfo.AgentID = GroupMemberInvite["AgentID"].AsUUID();
inviteInfo.RoleID = GroupMemberInvite["RoleID"].AsUUID();
return inviteInfo;
}
public void RemoveAgentToGroupInvite(UUID requestingAgentID, UUID inviteID)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
GroupInviteInfo invite = GetAgentToGroupInvite(requestingAgentID, inviteID);
SimianRemoveGenericEntry(invite.GroupID, "GroupMemberInvite", inviteID.ToString());
}
public void AddAgentToGroup(UUID requestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
// Setup Agent/Group information
SetAgentGroupInfo(requestingAgentID, AgentID, GroupID, true, true);
// Add agent to Everyone Group
AddAgentToGroupRole(requestingAgentID, AgentID, GroupID, UUID.Zero);
// Add agent to Specified Role
AddAgentToGroupRole(requestingAgentID, AgentID, GroupID, RoleID);
// Set selected role in this group to specified role
SetAgentActiveGroupRole(requestingAgentID, AgentID, GroupID, RoleID);
}
public void RemoveAgentFromGroup(UUID requestingAgentID, UUID agentID, UUID groupID)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
// If current active group is the group the agent is being removed from, change their group to UUID.Zero
GroupMembershipData memberActiveMembership = GetAgentActiveMembership(requestingAgentID, agentID);
if (memberActiveMembership.GroupID == groupID)
{
SetAgentActiveGroup(agentID, agentID, UUID.Zero);
}
// Remove Group Member information for this group
SimianRemoveGenericEntry(agentID, "GroupMember", groupID.ToString());
// By using a Simian Generics Type consisting of a prefix and a groupID,
// combined with RoleID as key allows us to get a list of roles a particular member
// of a group is assigned to.
string GroupRoleMemberType = "GroupRole" + groupID.ToString();
// Take Agent out of all other group roles
Dictionary<string, OSDMap> GroupRoles;
if (SimianGetGenericEntries(agentID, GroupRoleMemberType, out GroupRoles))
{
foreach (string roleID in GroupRoles.Keys)
{
SimianRemoveGenericEntry(agentID, GroupRoleMemberType, roleID);
}
}
}
public void AddAgentToGroupRole(UUID requestingAgentID, UUID agentID, UUID groupID, UUID roleID)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
SimianAddGeneric(agentID, "GroupRole" + groupID.ToString(), roleID.ToString(), new OSDMap());
}
public void RemoveAgentFromGroupRole(UUID requestingAgentID, UUID agentID, UUID groupID, UUID roleID)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
// Cannot remove members from the Everyone Role
if (roleID != UUID.Zero)
{
EnsureRoleNotSelectedByMember(groupID, roleID, agentID);
string GroupRoleMemberType = "GroupRole" + groupID.ToString();
SimianRemoveGenericEntry(agentID, GroupRoleMemberType, roleID.ToString());
}
}
public List<DirGroupsReplyData> FindGroups(UUID requestingAgentID, string search)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
List<DirGroupsReplyData> findings = new List<DirGroupsReplyData>();
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetGenerics" },
{ "Type", "Group" },
{ "Key", search },
{ "Fuzzy", "1" }
};
OSDMap response = CachedPostRequest(requestArgs);
if (response["Success"].AsBoolean() && response["Entries"] is OSDArray)
{
OSDArray entryArray = (OSDArray)response["Entries"];
foreach (OSDMap entryMap in entryArray)
{
DirGroupsReplyData data = new DirGroupsReplyData();
data.groupID = entryMap["OwnerID"].AsUUID();
data.groupName = entryMap["Key"].AsString();
// TODO: is there a better way to do this?
Dictionary<UUID, OSDMap> Members;
if (SimianGetGenericEntries("GroupMember", data.groupID.ToString(), out Members))
{
data.members = Members.Count;
}
else
{
data.members = 0;
}
// TODO: sort results?
// data.searchOrder = order;
findings.Add(data);
}
}
return findings;
}
public GroupMembershipData GetAgentGroupMembership(UUID requestingAgentID, UUID agentID, UUID groupID)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
GroupMembershipData data = null;
// bool foundData = false;
OSDMap UserGroupMemberInfo;
if (SimianGetGenericEntry(agentID, "GroupMember", groupID.ToString(), out UserGroupMemberInfo))
{
data = new GroupMembershipData();
data.AcceptNotices = UserGroupMemberInfo["AcceptNotices"].AsBoolean();
data.Contribution = UserGroupMemberInfo["Contribution"].AsInteger();
data.ListInProfile = UserGroupMemberInfo["ListInProfile"].AsBoolean();
data.ActiveRole = UserGroupMemberInfo["SelectedRoleID"].AsUUID();
///////////////////////////////
// Agent Specific Information:
//
OSDMap UserActiveGroup;
if (SimianGetGenericEntry(agentID, "Group", "ActiveGroup", out UserActiveGroup))
{
data.Active = UserActiveGroup["GroupID"].AsUUID().Equals(groupID);
}
///////////////////////////////
// Role Specific Information:
//
OSDMap GroupRoleInfo;
if (SimianGetGenericEntry(groupID, "GroupRole", data.ActiveRole.ToString(), out GroupRoleInfo))
{
data.GroupTitle = GroupRoleInfo["Title"].AsString();
data.GroupPowers = GroupRoleInfo["Powers"].AsULong();
}
///////////////////////////////
// Group Specific Information:
//
OSDMap GroupInfo;
string GroupName;
if (SimianGetFirstGenericEntry(groupID, "Group", out GroupName, out GroupInfo))
{
data.GroupID = groupID;
data.AllowPublish = GroupInfo["AllowPublish"].AsBoolean();
data.Charter = GroupInfo["Charter"].AsString();
data.FounderID = GroupInfo["FounderID"].AsUUID();
data.GroupName = GroupName;
data.GroupPicture = GroupInfo["InsigniaID"].AsUUID();
data.MaturePublish = GroupInfo["MaturePublish"].AsBoolean();
data.MembershipFee = GroupInfo["MembershipFee"].AsInteger();
data.OpenEnrollment = GroupInfo["OpenEnrollment"].AsBoolean();
data.ShowInList = GroupInfo["ShowInList"].AsBoolean();
}
}
return data;
}
public GroupMembershipData GetAgentActiveMembership(UUID requestingAgentID, UUID agentID)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
UUID GroupID = UUID.Zero;
OSDMap UserActiveGroup;
if (SimianGetGenericEntry(agentID, "Group", "ActiveGroup", out UserActiveGroup))
{
GroupID = UserActiveGroup["GroupID"].AsUUID();
}
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] Active GroupID : {0}", GroupID.ToString());
return GetAgentGroupMembership(requestingAgentID, agentID, GroupID);
}
public List<GroupMembershipData> GetAgentGroupMemberships(UUID requestingAgentID, UUID agentID)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
List<GroupMembershipData> memberships = new List<GroupMembershipData>();
Dictionary<string,OSDMap> GroupMemberShips;
if (SimianGetGenericEntries(agentID, "GroupMember", out GroupMemberShips))
{
foreach (string key in GroupMemberShips.Keys)
{
memberships.Add(GetAgentGroupMembership(requestingAgentID, agentID, UUID.Parse(key)));
}
}
return memberships;
}
public List<GroupRolesData> GetAgentGroupRoles(UUID requestingAgentID, UUID agentID, UUID groupID)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
List<GroupRolesData> Roles = new List<GroupRolesData>();
Dictionary<string, OSDMap> GroupRoles;
if (SimianGetGenericEntries(groupID, "GroupRole", out GroupRoles))
{
Dictionary<string, OSDMap> MemberRoles;
if (SimianGetGenericEntries(agentID, "GroupRole" + groupID.ToString(), out MemberRoles))
{
foreach (KeyValuePair<string, OSDMap> kvp in MemberRoles)
{
GroupRolesData data = new GroupRolesData();
data.RoleID = UUID.Parse(kvp.Key);
data.Name = GroupRoles[kvp.Key]["Name"].AsString();
data.Description = GroupRoles[kvp.Key]["Description"].AsString();
data.Title = GroupRoles[kvp.Key]["Title"].AsString();
data.Powers = GroupRoles[kvp.Key]["Powers"].AsULong();
Roles.Add(data);
}
}
}
return Roles;
}
public List<GroupRolesData> GetGroupRoles(UUID requestingAgentID, UUID groupID)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
List<GroupRolesData> Roles = new List<GroupRolesData>();
Dictionary<string, OSDMap> GroupRoles;
if (SimianGetGenericEntries(groupID, "GroupRole", out GroupRoles))
{
foreach (KeyValuePair<string, OSDMap> role in GroupRoles)
{
GroupRolesData data = new GroupRolesData();
data.RoleID = UUID.Parse(role.Key);
data.Name = role.Value["Name"].AsString();
data.Description = role.Value["Description"].AsString();
data.Title = role.Value["Title"].AsString();
data.Powers = role.Value["Powers"].AsULong();
Dictionary<UUID, OSDMap> GroupRoleMembers;
if (SimianGetGenericEntries("GroupRole" + groupID.ToString(), role.Key, out GroupRoleMembers))
{
data.Members = GroupRoleMembers.Count;
}
else
{
data.Members = 0;
}
Roles.Add(data);
}
}
return Roles;
}
public List<GroupMembersData> GetGroupMembers(UUID requestingAgentID, UUID GroupID)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
List<GroupMembersData> members = new List<GroupMembersData>();
OSDMap GroupInfo;
string GroupName;
UUID GroupOwnerRoleID = UUID.Zero;
if (!SimianGetFirstGenericEntry(GroupID, "Group", out GroupName, out GroupInfo))
{
return members;
}
GroupOwnerRoleID = GroupInfo["OwnerRoleID"].AsUUID();
// Locally cache group roles, since we'll be needing this data for each member
Dictionary<string,OSDMap> GroupRoles;
SimianGetGenericEntries(GroupID, "GroupRole", out GroupRoles);
// Locally cache list of group owners
Dictionary<UUID, OSDMap> GroupOwners;
SimianGetGenericEntries("GroupRole" + GroupID.ToString(), GroupOwnerRoleID.ToString(), out GroupOwners);
Dictionary<UUID, OSDMap> GroupMembers;
if (SimianGetGenericEntries("GroupMember", GroupID.ToString(), out GroupMembers))
{
foreach (KeyValuePair<UUID, OSDMap> member in GroupMembers)
{
GroupMembersData data = new GroupMembersData();
data.AgentID = member.Key;
UUID SelectedRoleID = member.Value["SelectedRoleID"].AsUUID();
data.AcceptNotices = member.Value["AcceptNotices"].AsBoolean();
data.ListInProfile = member.Value["ListInProfile"].AsBoolean();
data.Contribution = member.Value["Contribution"].AsInteger();
data.IsOwner = GroupOwners.ContainsKey(member.Key);
OSDMap GroupRoleInfo = GroupRoles[SelectedRoleID.ToString()];
data.Title = GroupRoleInfo["Title"].AsString();
data.AgentPowers = GroupRoleInfo["Powers"].AsULong();
members.Add(data);
}
}
return members;
}
public List<GroupRoleMembersData> GetGroupRoleMembers(UUID requestingAgentID, UUID groupID)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
List<GroupRoleMembersData> members = new List<GroupRoleMembersData>();
Dictionary<string, OSDMap> GroupRoles;
if (SimianGetGenericEntries(groupID, "GroupRole", out GroupRoles))
{
foreach (KeyValuePair<string, OSDMap> Role in GroupRoles)
{
Dictionary<UUID, OSDMap> GroupRoleMembers;
if (SimianGetGenericEntries("GroupRole"+groupID.ToString(), Role.Key, out GroupRoleMembers))
{
foreach (KeyValuePair<UUID, OSDMap> GroupRoleMember in GroupRoleMembers)
{
GroupRoleMembersData data = new GroupRoleMembersData();
data.MemberID = GroupRoleMember.Key;
data.RoleID = UUID.Parse(Role.Key);
members.Add(data);
}
}
}
}
return members;
}
public List<GroupNoticeData> GetGroupNotices(UUID requestingAgentID, UUID GroupID)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
List<GroupNoticeData> values = new List<GroupNoticeData>();
Dictionary<string, OSDMap> Notices;
if (SimianGetGenericEntries(GroupID, "GroupNotice", out Notices))
{
foreach (KeyValuePair<string, OSDMap> Notice in Notices)
{
GroupNoticeData data = new GroupNoticeData();
data.NoticeID = UUID.Parse(Notice.Key);
data.Timestamp = Notice.Value["TimeStamp"].AsUInteger();
data.FromName = Notice.Value["FromName"].AsString();
data.Subject = Notice.Value["Subject"].AsString();
data.HasAttachment = Notice.Value["BinaryBucket"].AsBinary().Length > 0;
//TODO: Figure out how to get this
data.AssetType = 0;
values.Add(data);
}
}
return values;
}
public GroupNoticeInfo GetGroupNotice(UUID requestingAgentID, UUID noticeID)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
OSDMap GroupNotice;
UUID GroupID;
if (SimianGetFirstGenericEntry("GroupNotice", noticeID.ToString(), out GroupID, out GroupNotice))
{
GroupNoticeInfo data = new GroupNoticeInfo();
data.GroupID = GroupID;
data.Message = GroupNotice["Message"].AsString();
data.BinaryBucket = GroupNotice["BinaryBucket"].AsBinary();
data.noticeData.NoticeID = noticeID;
data.noticeData.Timestamp = GroupNotice["TimeStamp"].AsUInteger();
data.noticeData.FromName = GroupNotice["FromName"].AsString();
data.noticeData.Subject = GroupNotice["Subject"].AsString();
data.noticeData.HasAttachment = data.BinaryBucket.Length > 0;
data.noticeData.AssetType = 0;
if (data.Message == null)
{
data.Message = string.Empty;
}
return data;
}
return null;
}
public void AddGroupNotice(UUID requestingAgentID, UUID groupID, UUID noticeID, string fromName, string subject, string message, byte[] binaryBucket)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
OSDMap Notice = new OSDMap();
Notice["TimeStamp"] = OSD.FromUInteger((uint)Util.UnixTimeSinceEpoch());
Notice["FromName"] = OSD.FromString(fromName);
Notice["Subject"] = OSD.FromString(subject);
Notice["Message"] = OSD.FromString(message);
Notice["BinaryBucket"] = OSD.FromBinary(binaryBucket);
SimianAddGeneric(groupID, "GroupNotice", noticeID.ToString(), Notice);
}
#endregion
#region GroupSessionTracking
public void ResetAgentGroupChatSessions(UUID agentID)
{
Dictionary<string, OSDMap> agentSessions;
if (SimianGetGenericEntries(agentID, "GroupSessionDropped", out agentSessions))
{
foreach (string GroupID in agentSessions.Keys)
{
SimianRemoveGenericEntry(agentID, "GroupSessionDropped", GroupID);
}
}
if (SimianGetGenericEntries(agentID, "GroupSessionInvited", out agentSessions))
{
foreach (string GroupID in agentSessions.Keys)
{
SimianRemoveGenericEntry(agentID, "GroupSessionInvited", GroupID);
}
}
}
public bool hasAgentDroppedGroupChatSession(UUID agentID, UUID groupID)
{
OSDMap session;
return SimianGetGenericEntry(agentID, "GroupSessionDropped", groupID.ToString(), out session);
}
public void AgentDroppedFromGroupChatSession(UUID agentID, UUID groupID)
{
SimianAddGeneric(agentID, "GroupSessionDropped", groupID.ToString(), new OSDMap());
}
public void AgentInvitedToGroupChatSession(UUID agentID, UUID groupID)
{
SimianAddGeneric(agentID, "GroupSessionInvited", groupID.ToString(), new OSDMap());
}
public bool hasAgentBeenInvitedToGroupChatSession(UUID agentID, UUID groupID)
{
OSDMap session;
return SimianGetGenericEntry(agentID, "GroupSessionDropped", groupID.ToString(), out session);
}
#endregion
private void EnsureRoleNotSelectedByMember(UUID groupID, UUID roleID, UUID userID)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
// If member's SelectedRole is roleID, change their selected role to Everyone
// before removing them from the role
OSDMap UserGroupInfo;
if (SimianGetGenericEntry(userID, "GroupMember", groupID.ToString(), out UserGroupInfo))
{
if (UserGroupInfo["SelectedRoleID"].AsUUID() == roleID)
{
UserGroupInfo["SelectedRoleID"] = OSD.FromUUID(UUID.Zero);
}
SimianAddGeneric(userID, "GroupMember", groupID.ToString(), UserGroupInfo);
}
}
#region Simian Util Methods
private bool SimianAddGeneric(UUID ownerID, string type, string key, OSDMap map)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called ({1},{2},{3})", System.Reflection.MethodBase.GetCurrentMethod().Name, ownerID, type, key);
string value = OSDParser.SerializeJsonString(map);
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] value: {0}", value);
NameValueCollection RequestArgs = new NameValueCollection
{
{ "RequestMethod", "AddGeneric" },
{ "OwnerID", ownerID.ToString() },
{ "Type", type },
{ "Key", key },
{ "Value", value}
};
OSDMap Response = CachedPostRequest(RequestArgs);
if (Response["Success"].AsBoolean())
{
return true;
}
else
{
m_log.WarnFormat("[SIMIAN GROUPS CONNECTOR]: Error {0}, {1}, {2}, {3}", ownerID, type, key, Response["Message"]);
return false;
}
}
/// <summary>
/// Returns the first of possibly many entries for Owner/Type pair
/// </summary>
private bool SimianGetFirstGenericEntry(UUID ownerID, string type, out string key, out OSDMap map)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called ({1},{2})", System.Reflection.MethodBase.GetCurrentMethod().Name, ownerID, type);
NameValueCollection RequestArgs = new NameValueCollection
{
{ "RequestMethod", "GetGenerics" },
{ "OwnerID", ownerID.ToString() },
{ "Type", type }
};
OSDMap Response = CachedPostRequest(RequestArgs);
if (Response["Success"].AsBoolean() && Response["Entries"] is OSDArray)
{
OSDArray entryArray = (OSDArray)Response["Entries"];
if (entryArray.Count >= 1)
{
OSDMap entryMap = entryArray[0] as OSDMap;
key = entryMap["Key"].AsString();
map = (OSDMap)OSDParser.DeserializeJson(entryMap["Value"].AsString());
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] Generics Result {0}", entryMap["Value"].AsString());
return true;
}
else
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] No Generics Results");
}
}
else
{
m_log.WarnFormat("[SIMIAN GROUPS CONNECTOR]: Error retrieving group info ({0})", Response["Message"]);
}
key = null;
map = null;
return false;
}
private bool SimianGetFirstGenericEntry(string type, string key, out UUID ownerID, out OSDMap map)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called ({1},{2})", System.Reflection.MethodBase.GetCurrentMethod().Name, type, key);
NameValueCollection RequestArgs = new NameValueCollection
{
{ "RequestMethod", "GetGenerics" },
{ "Type", type },
{ "Key", key}
};
OSDMap Response = CachedPostRequest(RequestArgs);
if (Response["Success"].AsBoolean() && Response["Entries"] is OSDArray)
{
OSDArray entryArray = (OSDArray)Response["Entries"];
if (entryArray.Count >= 1)
{
OSDMap entryMap = entryArray[0] as OSDMap;
ownerID = entryMap["OwnerID"].AsUUID();
map = (OSDMap)OSDParser.DeserializeJson(entryMap["Value"].AsString());
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] Generics Result {0}", entryMap["Value"].AsString());
return true;
}
else
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] No Generics Results");
}
}
else
{
m_log.WarnFormat("[SIMIAN GROUPS CONNECTOR]: Error retrieving group info ({0})", Response["Message"]);
}
ownerID = UUID.Zero;
map = null;
return false;
}
private bool SimianGetGenericEntry(UUID ownerID, string type, string key, out OSDMap map)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called ({1},{2},{3})", System.Reflection.MethodBase.GetCurrentMethod().Name, ownerID, type, key);
NameValueCollection RequestArgs = new NameValueCollection
{
{ "RequestMethod", "GetGenerics" },
{ "OwnerID", ownerID.ToString() },
{ "Type", type },
{ "Key", key}
};
OSDMap Response = CachedPostRequest(RequestArgs);
if (Response["Success"].AsBoolean() && Response["Entries"] is OSDArray)
{
OSDArray entryArray = (OSDArray)Response["Entries"];
if (entryArray.Count == 1)
{
OSDMap entryMap = entryArray[0] as OSDMap;
key = entryMap["Key"].AsString();
map = (OSDMap)OSDParser.DeserializeJson(entryMap["Value"].AsString());
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] Generics Result {0}", entryMap["Value"].AsString());
return true;
}
else
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] No Generics Results");
}
}
else
{
m_log.WarnFormat("[SIMIAN GROUPS CONNECTOR]: Error retrieving group info ({0})", Response["Message"]);
}
map = null;
return false;
}
private bool SimianGetGenericEntries(UUID ownerID, string type, out Dictionary<string, OSDMap> maps)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called ({1},{2})", System.Reflection.MethodBase.GetCurrentMethod().Name,ownerID, type);
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetGenerics" },
{ "OwnerID", ownerID.ToString() },
{ "Type", type }
};
OSDMap response = CachedPostRequest(requestArgs);
if (response["Success"].AsBoolean() && response["Entries"] is OSDArray)
{
maps = new Dictionary<string, OSDMap>();
OSDArray entryArray = (OSDArray)response["Entries"];
foreach (OSDMap entryMap in entryArray)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] Generics Result {0}", entryMap["Value"].AsString());
maps.Add(entryMap["Key"].AsString(), (OSDMap)OSDParser.DeserializeJson(entryMap["Value"].AsString()));
}
if (maps.Count == 0)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] No Generics Results");
}
return true;
}
else
{
maps = null;
m_log.WarnFormat("[SIMIAN GROUPS CONNECTOR]: Error retrieving group info ({0})", response["Message"]);
}
return false;
}
private bool SimianGetGenericEntries(string type, string key, out Dictionary<UUID, OSDMap> maps)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called ({1},{2})", System.Reflection.MethodBase.GetCurrentMethod().Name, type, key);
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetGenerics" },
{ "Type", type },
{ "Key", key }
};
OSDMap response = CachedPostRequest(requestArgs);
if (response["Success"].AsBoolean() && response["Entries"] is OSDArray)
{
maps = new Dictionary<UUID, OSDMap>();
OSDArray entryArray = (OSDArray)response["Entries"];
foreach (OSDMap entryMap in entryArray)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] Generics Result {0}", entryMap["Value"].AsString());
maps.Add(entryMap["OwnerID"].AsUUID(), (OSDMap)OSDParser.DeserializeJson(entryMap["Value"].AsString()));
}
if (maps.Count == 0)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] No Generics Results");
}
return true;
}
else
{
maps = null;
m_log.WarnFormat("[SIMIAN-GROUPS-CONNECTOR]: Error retrieving group info ({0})", response["Message"]);
}
return false;
}
private bool SimianRemoveGenericEntry(UUID ownerID, string type, string key)
{
if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called ({1},{2},{3})", System.Reflection.MethodBase.GetCurrentMethod().Name, ownerID, type, key);
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "RemoveGeneric" },
{ "OwnerID", ownerID.ToString() },
{ "Type", type },
{ "Key", key }
};
OSDMap response = CachedPostRequest(requestArgs);
if (response["Success"].AsBoolean())
{
return true;
}
else
{
m_log.WarnFormat("[SIMIAN GROUPS CONNECTOR]: Error {0}, {1}, {2}, {3}", ownerID, type, key, response["Message"]);
return false;
}
}
#endregion
#region CheesyCache
OSDMap CachedPostRequest(NameValueCollection requestArgs)
{
// Immediately forward the request if the cache is disabled.
if (m_cacheTimeout == 0)
{
m_log.WarnFormat("[SIMIAN GROUPS CONNECTOR]: cache is disabled");
return WebUtil.PostToService(m_groupsServerURI, requestArgs);
}
// Check if this is an update or a request
if (requestArgs["RequestMethod"] == "RemoveGeneric"
|| requestArgs["RequestMethod"] == "AddGeneric")
{
m_log.WarnFormat("[SIMIAN GROUPS CONNECTOR]: clearing generics cache");
// Any and all updates cause the cache to clear
m_memoryCache.Clear();
// Send update to server, return the response without caching it
return WebUtil.PostToService(m_groupsServerURI, requestArgs);
}
// If we're not doing an update, we must be requesting data
// Create the cache key for the request and see if we have it cached
string CacheKey = WebUtil.BuildQueryString(requestArgs);
// This code uses a leader/follower pattern. On a cache miss, the request is added
// to a queue; the first thread to add it to the queue completes the request while
// follow on threads busy wait for the results, this situation seems to happen
// often when checking permissions
while (true)
{
OSDMap response = null;
bool firstRequest = false;
lock (m_memoryCache)
{
if (m_memoryCache.TryGetValue(CacheKey, out response))
return response;
if (! m_pendingRequests.ContainsKey(CacheKey))
{
m_pendingRequests.Add(CacheKey,true);
firstRequest = true;
}
}
if (firstRequest)
{
// if it wasn't in the cache, pass the request to the Simian Grid Services
try
{
response = WebUtil.PostToService(m_groupsServerURI, requestArgs);
}
catch (Exception)
{
m_log.ErrorFormat("[SIMIAN GROUPS CONNECTOR]: request failed {0}", CacheKey);
}
// and cache the response
lock (m_memoryCache)
{
m_memoryCache.AddOrUpdate(CacheKey, response, TimeSpan.FromSeconds(m_cacheTimeout));
m_pendingRequests.Remove(CacheKey);
}
return response;
}
Thread.Sleep(50); // waiting for a web request to complete, 50msecs is reasonable
}
// if (!m_memoryCache.TryGetValue(CacheKey, out response))
// {
// m_log.WarnFormat("[SIMIAN GROUPS CONNECTOR]: query not in the cache");
// Util.PrintCallStack();
// // if it wasn't in the cache, pass the request to the Simian Grid Services
// response = WebUtil.PostToService(m_groupsServerURI, requestArgs);
// // and cache the response
// m_memoryCache.AddOrUpdate(CacheKey, response, TimeSpan.FromSeconds(m_cacheTimeout));
// }
// // return cached response
// return response;
}
#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.
namespace System.ServiceModel
{
using System;
using System.Text;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.Net;
using System.Net.Security;
using System.Runtime.Serialization;
using System.Security.Principal;
using System.ServiceModel.Channels;
using System.ServiceModel.Security;
using Microsoft.Xml;
public class WSHttpBinding : WSHttpBindingBase
{
private static readonly MessageSecurityVersion s_WSMessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10;
private WSHttpSecurity _security = new WSHttpSecurity();
public WSHttpBinding(string configName)
: this()
{
// TODO: ApplyConfiguration(configName);
}
public WSHttpBinding()
: base()
{
}
public WSHttpBinding(SecurityMode securityMode)
: this(securityMode, false)
{
}
public WSHttpBinding(SecurityMode securityMode, bool reliableSessionEnabled)
: base(reliableSessionEnabled)
{
_security.Mode = securityMode;
}
internal WSHttpBinding(WSHttpSecurity security, bool reliableSessionEnabled)
: base(reliableSessionEnabled)
{
_security = security == null ? new WSHttpSecurity() : security;
}
[DefaultValue(HttpTransportDefaults.AllowCookies)]
public bool AllowCookies
{
get { return HttpTransport.AllowCookies; }
set
{
HttpTransport.AllowCookies = value;
HttpsTransport.AllowCookies = value;
}
}
public WSHttpSecurity Security
{
get { return _security; }
set
{
if (value == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("value"));
}
_security = value;
}
}
public override IChannelFactory<TChannel> BuildChannelFactory<TChannel>(BindingParameterCollection parameters)
{
if ((_security.Mode == SecurityMode.Transport) &&
_security.Transport.ClientCredentialType == HttpClientCredentialType.InheritedFromHost)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(string.Format(SRServiceModel.HttpClientCredentialTypeInvalid, _security.Transport.ClientCredentialType)));
}
return base.BuildChannelFactory<TChannel>(parameters);
}
public override BindingElementCollection CreateBindingElements()
{
if (ReliableSession.Enabled)
{
if (_security.Mode == SecurityMode.Transport)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SRServiceModel.WSHttpDoesNotSupportRMWithHttps));
}
return base.CreateBindingElements();
}
// if you make changes here, see also WS2007HttpBinding.TryCreate()
internal static bool TryCreate(SecurityBindingElement sbe, TransportBindingElement transport, ReliableSessionBindingElement rsbe, TransactionFlowBindingElement tfbe, out Binding binding)
{
bool isReliableSession = (rsbe != null);
binding = null;
// reverse GetTransport
HttpTransportSecurity transportSecurity = WSHttpSecurity.GetDefaultHttpTransportSecurity();
UnifiedSecurityMode mode;
if (!GetSecurityModeFromTransport(transport, transportSecurity, out mode))
{
return false;
}
HttpsTransportBindingElement httpsBinding = transport as HttpsTransportBindingElement;
if (httpsBinding != null && httpsBinding.MessageSecurityVersion != null)
{
if (httpsBinding.MessageSecurityVersion.SecurityPolicyVersion != s_WSMessageSecurityVersion.SecurityPolicyVersion)
{
return false;
}
}
WSHttpSecurity security;
if (TryCreateSecurity(sbe, mode, transportSecurity, isReliableSession, out security))
{
WSHttpBinding wsHttpBinding = new WSHttpBinding(security, isReliableSession);
bool allowCookies;
if (!TryGetAllowCookiesFromTransport(transport, out allowCookies))
{
return false;
}
wsHttpBinding.AllowCookies = allowCookies;
binding = wsHttpBinding;
}
if (rsbe != null && rsbe.ReliableMessagingVersion != ReliableMessagingVersion.WSReliableMessagingFebruary2005)
{
return false;
}
if (tfbe != null && tfbe.TransactionProtocol != TransactionProtocol.WSAtomicTransactionOctober2004)
{
return false;
}
return binding != null;
}
protected override TransportBindingElement GetTransport()
{
if (_security.Mode == SecurityMode.None || _security.Mode == SecurityMode.Message)
{
this.HttpTransport.ExtendedProtectionPolicy = _security.Transport.ExtendedProtectionPolicy;
return this.HttpTransport;
}
else
{
_security.ApplyTransportSecurity(this.HttpsTransport);
return this.HttpsTransport;
}
}
internal static bool GetSecurityModeFromTransport(TransportBindingElement transport, HttpTransportSecurity transportSecurity, out UnifiedSecurityMode mode)
{
mode = UnifiedSecurityMode.None;
if (transport is HttpsTransportBindingElement)
{
mode = UnifiedSecurityMode.Transport | UnifiedSecurityMode.TransportWithMessageCredential;
WSHttpSecurity.ApplyTransportSecurity((HttpsTransportBindingElement)transport, transportSecurity);
}
else if (transport is HttpTransportBindingElement)
{
mode = UnifiedSecurityMode.None | UnifiedSecurityMode.Message;
}
else
{
return false;
}
return true;
}
internal static bool TryGetAllowCookiesFromTransport(TransportBindingElement transport, out bool allowCookies)
{
HttpTransportBindingElement httpTransportBindingElement = transport as HttpTransportBindingElement;
if (httpTransportBindingElement == null)
{
allowCookies = false;
return false;
}
else
{
allowCookies = httpTransportBindingElement.AllowCookies;
return true;
}
}
protected override SecurityBindingElement CreateMessageSecurity()
{
return _security.CreateMessageSecurity(this.ReliableSession.Enabled, s_WSMessageSecurityVersion);
}
// if you make changes here, see also WS2007HttpBinding.TryCreateSecurity()
private static bool TryCreateSecurity(SecurityBindingElement sbe, UnifiedSecurityMode mode, HttpTransportSecurity transportSecurity, bool isReliableSession, out WSHttpSecurity security)
{
if (!WSHttpSecurity.TryCreate(sbe, mode, transportSecurity, isReliableSession, out security))
return false;
// the last check: make sure that security binding element match the incoming security
return System.ServiceModel.Configuration.SecurityElement.AreBindingsMatching(security.CreateMessageSecurity(isReliableSession, s_WSMessageSecurityVersion), sbe);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using JetBrains.Annotations;
namespace LinqToDB.DataProvider.SqlServer
{
using Configuration;
using Data;
public static class SqlServerTools
{
#region Init
static readonly SqlServerDataProvider _sqlServerDataProvider2000 = new SqlServerDataProvider(ProviderName.SqlServer2000, SqlServerVersion.v2000);
static readonly SqlServerDataProvider _sqlServerDataProvider2005 = new SqlServerDataProvider(ProviderName.SqlServer2005, SqlServerVersion.v2005);
static readonly SqlServerDataProvider _sqlServerDataProvider2008 = new SqlServerDataProvider(ProviderName.SqlServer2008, SqlServerVersion.v2008);
static readonly SqlServerDataProvider _sqlServerDataProvider2012 = new SqlServerDataProvider(ProviderName.SqlServer2012, SqlServerVersion.v2012);
public static bool AutoDetectProvider { get; set; }
static SqlServerTools()
{
AutoDetectProvider = true;
DataConnection.AddDataProvider(ProviderName.SqlServer, _sqlServerDataProvider2008);
DataConnection.AddDataProvider(ProviderName.SqlServer2014, _sqlServerDataProvider2012);
DataConnection.AddDataProvider(_sqlServerDataProvider2012);
DataConnection.AddDataProvider(_sqlServerDataProvider2008);
DataConnection.AddDataProvider(_sqlServerDataProvider2005);
DataConnection.AddDataProvider(_sqlServerDataProvider2000);
DataConnection.AddProviderDetector(ProviderDetector);
}
static IDataProvider ProviderDetector(IConnectionStringSettings css, string connectionString)
{
//if (css.IsGlobal /* DataConnection.IsMachineConfig(css)*/)
// return null;
switch (css.ProviderName)
{
case "" :
case null :
if (css.Name == "SqlServer")
goto case "SqlServer";
break;
case "SqlServer2000" :
case "SqlServer.2000" : return _sqlServerDataProvider2000;
case "SqlServer2005" :
case "SqlServer.2005" : return _sqlServerDataProvider2005;
case "SqlServer2008" :
case "SqlServer.2008" : return _sqlServerDataProvider2008;
case "SqlServer2012" :
case "SqlServer.2012" : return _sqlServerDataProvider2012;
case "SqlServer2014" :
case "SqlServer.2014" : return _sqlServerDataProvider2012;
case "SqlServer" :
case "System.Data.SqlClient" :
if (css.Name.Contains("2000")) return _sqlServerDataProvider2000;
if (css.Name.Contains("2005")) return _sqlServerDataProvider2005;
if (css.Name.Contains("2008")) return _sqlServerDataProvider2008;
if (css.Name.Contains("2012")) return _sqlServerDataProvider2012;
if (css.Name.Contains("2014")) return _sqlServerDataProvider2012;
if (AutoDetectProvider)
{
try
{
var cs = string.IsNullOrWhiteSpace(connectionString) ? css.ConnectionString : connectionString;
using (var conn = new SqlConnection(cs))
{
conn.Open();
if (int.TryParse(conn.ServerVersion.Split('.')[0], out var version))
{
switch (version)
{
case 8 : return _sqlServerDataProvider2000;
case 9 : return _sqlServerDataProvider2005;
case 10 : return _sqlServerDataProvider2008;
case 11 : return _sqlServerDataProvider2012;
case 12 : return _sqlServerDataProvider2012;
default :
if (version > 12)
return _sqlServerDataProvider2012;
break;
}
}
}
}
catch (Exception)
{
}
}
break;
}
return null;
}
#endregion
#region Public Members
public static IDataProvider GetDataProvider(SqlServerVersion version = SqlServerVersion.v2008)
{
switch (version)
{
case SqlServerVersion.v2000 : return _sqlServerDataProvider2000;
case SqlServerVersion.v2005 : return _sqlServerDataProvider2005;
case SqlServerVersion.v2012 : return _sqlServerDataProvider2012;
}
return _sqlServerDataProvider2008;
}
public static void AddUdtType(Type type, string udtName)
{
_sqlServerDataProvider2000.AddUdtType(type, udtName);
_sqlServerDataProvider2005.AddUdtType(type, udtName);
_sqlServerDataProvider2008.AddUdtType(type, udtName);
_sqlServerDataProvider2012.AddUdtType(type, udtName);
}
public static void AddUdtType<T>(string udtName, T nullValue, DataType dataType = DataType.Undefined)
{
_sqlServerDataProvider2000.AddUdtType(udtName, nullValue, dataType);
_sqlServerDataProvider2005.AddUdtType(udtName, nullValue, dataType);
_sqlServerDataProvider2008.AddUdtType(udtName, nullValue, dataType);
_sqlServerDataProvider2012.AddUdtType(udtName, nullValue, dataType);
}
public static void ResolveSqlTypes([NotNull] string path)
{
if (path == null) throw new ArgumentNullException("path");
new AssemblyResolver(path, "Microsoft.SqlServer.Types");
}
public static void ResolveSqlTypes([NotNull] Assembly assembly)
{
var types = assembly.GetTypes();
SqlHierarchyIdType = types.First(t => t.Name == "SqlHierarchyId");
SqlGeographyType = types.First(t => t.Name == "SqlGeography");
SqlGeometryType = types.First(t => t.Name == "SqlGeometry");
}
internal static Type SqlHierarchyIdType;
internal static Type SqlGeographyType;
internal static Type SqlGeometryType;
public static void SetSqlTypes(Type sqlHierarchyIdType, Type sqlGeographyType, Type sqlGeometryType)
{
SqlHierarchyIdType = sqlHierarchyIdType;
SqlGeographyType = sqlGeographyType;
SqlGeometryType = sqlGeometryType;
}
#endregion
#region CreateDataConnection
public static DataConnection CreateDataConnection(string connectionString, SqlServerVersion version = SqlServerVersion.v2008)
{
switch (version)
{
case SqlServerVersion.v2000 : return new DataConnection(_sqlServerDataProvider2000, connectionString);
case SqlServerVersion.v2005 : return new DataConnection(_sqlServerDataProvider2005, connectionString);
case SqlServerVersion.v2012 : return new DataConnection(_sqlServerDataProvider2012, connectionString);
}
return new DataConnection(_sqlServerDataProvider2008, connectionString);
}
public static DataConnection CreateDataConnection(IDbConnection connection, SqlServerVersion version = SqlServerVersion.v2008)
{
switch (version)
{
case SqlServerVersion.v2000 : return new DataConnection(_sqlServerDataProvider2000, connection);
case SqlServerVersion.v2005 : return new DataConnection(_sqlServerDataProvider2005, connection);
case SqlServerVersion.v2012 : return new DataConnection(_sqlServerDataProvider2012, connection);
}
return new DataConnection(_sqlServerDataProvider2008, connection);
}
public static DataConnection CreateDataConnection(IDbTransaction transaction, SqlServerVersion version = SqlServerVersion.v2008)
{
switch (version)
{
case SqlServerVersion.v2000 : return new DataConnection(_sqlServerDataProvider2000, transaction);
case SqlServerVersion.v2005 : return new DataConnection(_sqlServerDataProvider2005, transaction);
case SqlServerVersion.v2012 : return new DataConnection(_sqlServerDataProvider2012, transaction);
}
return new DataConnection(_sqlServerDataProvider2008, transaction);
}
#endregion
#region BulkCopy
private static BulkCopyType _defaultBulkCopyType = BulkCopyType.ProviderSpecific;
public static BulkCopyType DefaultBulkCopyType
{
get { return _defaultBulkCopyType; }
set { _defaultBulkCopyType = value; }
}
// public static int MultipleRowsCopy<T>(DataConnection dataConnection, IEnumerable<T> source, int maxBatchSize = 1000)
// {
// return dataConnection.BulkCopy(
// new BulkCopyOptions
// {
// BulkCopyType = BulkCopyType.MultipleRows,
// MaxBatchSize = maxBatchSize,
// }, source);
// }
public static BulkCopyRowsCopied ProviderSpecificBulkCopy<T>(
DataConnection dataConnection,
IEnumerable<T> source,
int? maxBatchSize = null,
int? bulkCopyTimeout = null,
bool keepIdentity = false,
bool checkConstraints = false,
int notifyAfter = 0,
Action<BulkCopyRowsCopied> rowsCopiedCallback = null)
{
return dataConnection.BulkCopy(
new BulkCopyOptions
{
BulkCopyType = BulkCopyType.ProviderSpecific,
MaxBatchSize = maxBatchSize,
BulkCopyTimeout = bulkCopyTimeout,
KeepIdentity = keepIdentity,
CheckConstraints = checkConstraints,
NotifyAfter = notifyAfter,
RowsCopiedCallback = rowsCopiedCallback,
}, source);
}
#endregion
#region Extensions
public static void SetIdentityInsert<T>(this DataConnection dataConnection, ITable<T> table, bool isOn)
{
dataConnection.Execute("SET IDENTITY_INSERT ");
}
#endregion
public static class Sql
{
public const string OptionRecompile = "OPTION(RECOMPILE)";
}
public static Func<IDataReader,int,decimal> DataReaderGetMoney = (dr, i) => dr.GetDecimal(i);
public static Func<IDataReader,int,decimal> DataReaderGetDecimal = (dr, i) => dr.GetDecimal(i);
}
}
| |
// Copyright 2008-2011. This work is licensed under the BSD license, available at
// http://www.movesinstitute.org/licenses
//
// Orignal authors: DMcG, Jason Nelson
// Modified for use with C#:
// - Peter Smith (Naval Air Warfare Center - Training Systems Division)
// - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si)
using System;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
namespace OpenDis.Enumerations.Warfare
{
/// <summary>
/// Enumeration values for Warhead (warfare.burstdescriptor.warhead, Warhead,
/// section 5.1.1)
/// The enumeration values are generated from the SISO DIS XML EBV document (R35), which was
/// obtained from http://discussions.sisostds.org/default.asp?action=10&fd=31
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Serializable]
public enum Warhead : ushort
{
/// <summary>
/// Other.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Other.")]
Other = 0,
/// <summary>
/// Cargo (Variable Submunitions).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Cargo (Variable Submunitions).")]
CargoVariableSubmunitions = 10,
/// <summary>
/// Fuel/Air Explosive.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Fuel/Air Explosive.")]
FuelAirExplosive = 20,
/// <summary>
/// Glass Beads.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Glass Beads.")]
GlassBeads = 30,
/// <summary>
/// 1 um.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("1 um.")]
_1Um = 31,
/// <summary>
/// 5 um.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("5 um.")]
_5Um = 32,
/// <summary>
/// 10 um.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("10 um.")]
_10Um = 33,
/// <summary>
/// High Explosive (HE).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("High Explosive (HE).")]
HighExplosiveHE = 1000,
/// <summary>
/// HE, Plastic.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("HE, Plastic.")]
HEPlastic = 1100,
/// <summary>
/// HE, Incendiary.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("HE, Incendiary.")]
HEIncendiary = 1200,
/// <summary>
/// HE, Fragmentation.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("HE, Fragmentation.")]
HEFragmentation = 1300,
/// <summary>
/// HE, Antitank.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("HE, Antitank.")]
HEAntitank = 1400,
/// <summary>
/// HE, Bomblets.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("HE, Bomblets.")]
HEBomblets = 1500,
/// <summary>
/// HE, Shaped Charge.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("HE, Shaped Charge.")]
HEShapedCharge = 1600,
/// <summary>
/// HE, Continuous Rod.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("HE, Continuous Rod.")]
HEContinuousRod = 1610,
/// <summary>
/// HE, Tungsten Ball.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("HE, Tungsten Ball.")]
HETungstenBall = 1615,
/// <summary>
/// HE, Blast Fragmentation.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("HE, Blast Fragmentation.")]
HEBlastFragmentation = 1620,
/// <summary>
/// HE, Steerable Darts with HE.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("HE, Steerable Darts with HE.")]
HESteerableDartsWithHE = 1625,
/// <summary>
/// HE, Darts.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("HE, Darts.")]
HEDarts = 1630,
/// <summary>
/// HE, Flechettes.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("HE, Flechettes.")]
HEFlechettes = 1635,
/// <summary>
/// HE, Directed Fragmentation.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("HE, Directed Fragmentation.")]
HEDirectedFragmentation = 1640,
/// <summary>
/// HE, Semi-Armor Piercing (SAP).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("HE, Semi-Armor Piercing (SAP).")]
HESemiArmorPiercingSAP = 1645,
/// <summary>
/// HE, Shaped Charge Fragmentation.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("HE, Shaped Charge Fragmentation.")]
HEShapedChargeFragmentation = 1650,
/// <summary>
/// HE, Semi-Armor Piercing, Fragmentation.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("HE, Semi-Armor Piercing, Fragmentation.")]
HESemiArmorPiercingFragmentation = 1655,
/// <summary>
/// HE, Hollow Charge.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("HE, Hollow Charge.")]
HEHollowCharge = 1660,
/// <summary>
/// HE, Double Hollow Charge.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("HE, Double Hollow Charge.")]
HEDoubleHollowCharge = 1665,
/// <summary>
/// HE, General Purpose.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("HE, General Purpose.")]
HEGeneralPurpose = 1670,
/// <summary>
/// HE, Blast Penetrator.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("HE, Blast Penetrator.")]
HEBlastPenetrator = 1675,
/// <summary>
/// HE, Rod Penetrator.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("HE, Rod Penetrator.")]
HERodPenetrator = 1680,
/// <summary>
/// HE, Antipersonnel.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("HE, Antipersonnel.")]
HEAntipersonnel = 1685,
/// <summary>
/// Smoke.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Smoke.")]
Smoke = 2000,
/// <summary>
/// Illumination.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Illumination.")]
Illumination = 3000,
/// <summary>
/// Practice.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Practice.")]
Practice = 4000,
/// <summary>
/// Kinetic.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Kinetic.")]
Kinetic = 5000,
/// <summary>
/// Mines.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Mines.")]
Mines = 6000,
/// <summary>
/// Nuclear.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Nuclear.")]
Nuclear = 7000,
/// <summary>
/// Nuclear, IMT.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Nuclear, IMT.")]
NuclearIMT = 7010,
/// <summary>
/// Chemical, General.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Chemical, General.")]
ChemicalGeneral = 8000,
/// <summary>
/// Chemical, Blister Agent.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Chemical, Blister Agent.")]
ChemicalBlisterAgent = 8100,
/// <summary>
/// HD (Mustard).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("HD (Mustard).")]
HDMustard = 8110,
/// <summary>
/// Thickened HD (Mustard).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Thickened HD (Mustard).")]
ThickenedHDMustard = 8115,
/// <summary>
/// Dusty HD (Mustard).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Dusty HD (Mustard).")]
DustyHDMustard = 8120,
/// <summary>
/// Chemical, Blood Agent.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Chemical, Blood Agent.")]
ChemicalBloodAgent = 8200,
/// <summary>
/// AC (HCN).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("AC (HCN).")]
ACHCN = 8210,
/// <summary>
/// CK (CNCI).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("CK (CNCI).")]
CKCNCI = 8215,
/// <summary>
/// CG (Phosgene).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("CG (Phosgene).")]
CGPhosgene = 8220,
/// <summary>
/// Chemical, Nerve Agent.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Chemical, Nerve Agent.")]
ChemicalNerveAgent = 8300,
/// <summary>
/// VX.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("VX.")]
VX = 8310,
/// <summary>
/// Thickened VX.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Thickened VX.")]
ThickenedVX = 8315,
/// <summary>
/// Dusty VX.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Dusty VX.")]
DustyVX = 8320,
/// <summary>
/// GA (Tabun).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("GA (Tabun).")]
GATabun = 8325,
/// <summary>
/// Thickened GA (Tabun).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Thickened GA (Tabun).")]
ThickenedGATabun = 8330,
/// <summary>
/// Dusty GA (Tabun).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Dusty GA (Tabun).")]
DustyGATabun = 8335,
/// <summary>
/// GB (Sarin).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("GB (Sarin).")]
GBSarin = 8340,
/// <summary>
/// Thickened GB (Sarin).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Thickened GB (Sarin).")]
ThickenedGBSarin = 8345,
/// <summary>
/// Dusty GB (Sarin).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Dusty GB (Sarin).")]
DustyGBSarin = 8350,
/// <summary>
/// GD (Soman).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("GD (Soman).")]
GDSoman = 8355,
/// <summary>
/// Thickened GD (Soman).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Thickened GD (Soman).")]
ThickenedGDSoman = 8360,
/// <summary>
/// Dusty GD (Soman).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Dusty GD (Soman).")]
DustyGDSoman = 8365,
/// <summary>
/// GF.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("GF.")]
GF = 8370,
/// <summary>
/// Thickened GF.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Thickened GF.")]
ThickenedGF = 8375,
/// <summary>
/// Dusty GF.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Dusty GF.")]
DustyGF = 8380,
/// <summary>
/// Biological.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Biological.")]
Biological = 9000,
/// <summary>
/// Biological, Virus.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Biological, Virus.")]
BiologicalVirus = 9100,
/// <summary>
/// Biological, Bacteria.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Biological, Bacteria.")]
BiologicalBacteria = 9200,
/// <summary>
/// Biological, Rickettsia.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Biological, Rickettsia.")]
BiologicalRickettsia = 9300,
/// <summary>
/// Biological, Genetically Modified Micro-organisms.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Biological, Genetically Modified Micro-organisms.")]
BiologicalGeneticallyModifiedMicroOrganisms = 9400,
/// <summary>
/// Biological, Toxin.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Biological, Toxin.")]
BiologicalToxin = 9500
}
}
| |
//
// Rectangle.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2011 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.Collections;
using System.Globalization;
namespace Xwt
{
[Serializable]
public struct Rectangle : IEquatable<Rectangle>
{
public double X { get; set; }
public double Y { get; set; }
public double Width { get; set; }
public double Height { get; set; }
public static Rectangle Zero = new Rectangle ();
public override string ToString ()
{
return String.Format ("{{X={0} Y={1} Width={2} Height={3}}}", X.ToString (CultureInfo.InvariantCulture), Y.ToString (CultureInfo.InvariantCulture), Width.ToString (CultureInfo.InvariantCulture), Height.ToString (CultureInfo.InvariantCulture));
}
// constructors
public Rectangle (double x, double y, double width, double height): this ()
{
X = x;
Y = y;
Width = width;
Height = height;
}
public Rectangle (Point loc, Size sz) : this (loc.X, loc.Y, sz.Width, sz.Height) {}
public static Rectangle FromLTRB (double left, double top, double right, double bottom)
{
return new Rectangle (left, top, right - left, bottom - top);
}
// Equality
public override bool Equals (object o)
{
if (!(o is Rectangle))
return false;
return (this == (Rectangle) o);
}
public bool Equals(Rectangle other)
{
return this == other;
}
public override int GetHashCode ()
{
unchecked {
var hash = X.GetHashCode ();
hash = (hash * 397) ^ Y.GetHashCode ();
hash = (hash * 397) ^ Width.GetHashCode ();
hash = (hash * 397) ^ Height.GetHashCode ();
return hash;
}
}
public static bool operator == (Rectangle r1, Rectangle r2)
{
return ((r1.Location == r2.Location) && (r1.Size == r2.Size));
}
public static bool operator != (Rectangle r1, Rectangle r2)
{
return !(r1 == r2);
}
// Hit Testing / Intersection / Union
public bool Contains (Rectangle rect)
{
return X <= rect.X && Right >= rect.Right && Y <= rect.Y && Bottom >= rect.Bottom;
}
public bool Contains (Point pt)
{
return Contains (pt.X, pt.Y);
}
public bool Contains (double x, double y)
{
return ((x >= Left) && (x < Right) &&
(y >= Top) && (y < Bottom));
}
public bool IntersectsWith (Rectangle r)
{
return !((Left >= r.Right) || (Right <= r.Left) ||
(Top >= r.Bottom) || (Bottom <= r.Top));
}
public Rectangle Union (Rectangle r)
{
return Union (this, r);
}
public static Rectangle Union (Rectangle r1, Rectangle r2)
{
return FromLTRB (Math.Min (r1.Left, r2.Left),
Math.Min (r1.Top, r2.Top),
Math.Max (r1.Right, r2.Right),
Math.Max (r1.Bottom, r2.Bottom));
}
public Rectangle Intersect (Rectangle r)
{
return Intersect (this, r);
}
public static Rectangle Intersect (Rectangle r1, Rectangle r2)
{
var x = Math.Max (r1.X, r2.X);
var y = Math.Max (r1.Y, r2.Y);
var width = Math.Min (r1.Right, r2.Right) - x;
var height = Math.Min (r1.Bottom, r2.Bottom) - y;
if (width < 0 || height < 0)
{
return Rectangle.Zero;
}
return new Rectangle (x, y, width, height);
}
// Position/Size
public double Top {
get { return Y; }
set { Y = value; }
}
public double Bottom {
get { return Y + Height; }
set { Height = value - Y; }
}
public double Right {
get { return X + Width; }
set { Width = value - X; }
}
public double Left {
get { return X; }
set { X = value; }
}
public bool IsEmpty {
get { return (Width <= 0) || (Height <= 0); }
}
public Size Size {
get {
return new Size (Width, Height);
}
set {
Width = value.Width;
Height = value.Height;
}
}
public Point Location {
get {
return new Point (X, Y);
}
set {
X = value.X;
Y = value.Y;
}
}
public Point Center {
get {
return new Point (X + Width / 2, Y + Height / 2);
}
}
// Inflate and Offset
public Rectangle Inflate (Size sz)
{
return Inflate (sz.Width, sz.Height);
}
public Rectangle Inflate (double width, double height)
{
Rectangle r = this;
r.X -= width;
r.Y -= height;
r.Width += width * 2;
r.Height += height * 2;
return r;
}
public Rectangle Offset (double dx, double dy)
{
Rectangle r = this;
r.X += dx;
r.Y += dy;
return r;
}
public Rectangle Offset (Point dr)
{
return Offset (dr.X, dr.Y);
}
public Rectangle Round ()
{
return new Rectangle (
Math.Round (X),
Math.Round (Y),
Math.Round (Width),
Math.Round (Height)
);
}
/// <summary>
/// Returns a copy of the rectangle, ensuring that the width and height are greater or equal to zero
/// </summary>
/// <returns>The new rectangle</returns>
public Rectangle WithPositiveSize ()
{
return new Rectangle (
X,
Y,
Width >= 0 ? Width : 0,
Height >= 0 ? Height : 0
);
}
}
}
| |
// 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 gagvc = Google.Ads.GoogleAds.V9.Common;
using gagve = Google.Ads.GoogleAds.V9.Enums;
using gagvr = Google.Ads.GoogleAds.V9.Resources;
using gaxgrpc = Google.Api.Gax.Grpc;
using gr = Google.Rpc;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using NUnit.Framework;
using Google.Ads.GoogleAds.V9.Services;
namespace Google.Ads.GoogleAds.Tests.V9.Services
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedAssetGroupAssetServiceClientTest
{
[Category("Autogenerated")][Test]
public void GetAssetGroupAssetRequestObject()
{
moq::Mock<AssetGroupAssetService.AssetGroupAssetServiceClient> mockGrpcClient = new moq::Mock<AssetGroupAssetService.AssetGroupAssetServiceClient>(moq::MockBehavior.Strict);
GetAssetGroupAssetRequest request = new GetAssetGroupAssetRequest
{
ResourceNameAsAssetGroupAssetName = gagvr::AssetGroupAssetName.FromCustomerAssetGroupAssetFieldType("[CUSTOMER_ID]", "[ASSET_GROUP_ID]", "[ASSET_ID]", "[FIELD_TYPE]"),
};
gagvr::AssetGroupAsset expectedResponse = new gagvr::AssetGroupAsset
{
ResourceNameAsAssetGroupAssetName = gagvr::AssetGroupAssetName.FromCustomerAssetGroupAssetFieldType("[CUSTOMER_ID]", "[ASSET_GROUP_ID]", "[ASSET_ID]", "[FIELD_TYPE]"),
AssetGroupAsAssetGroupName = gagvr::AssetGroupName.FromCustomerAssetGroup("[CUSTOMER_ID]", "[ASSET_GROUP_ID]"),
AssetAsAssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"),
FieldType = gagve::AssetFieldTypeEnum.Types.AssetFieldType.Callout,
Status = gagve::AssetLinkStatusEnum.Types.AssetLinkStatus.Paused,
PerformanceLabel = gagve::AssetPerformanceLabelEnum.Types.AssetPerformanceLabel.Pending,
PolicySummary = new gagvc::PolicySummary(),
};
mockGrpcClient.Setup(x => x.GetAssetGroupAsset(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AssetGroupAssetServiceClient client = new AssetGroupAssetServiceClientImpl(mockGrpcClient.Object, null);
gagvr::AssetGroupAsset response = client.GetAssetGroupAsset(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetAssetGroupAssetRequestObjectAsync()
{
moq::Mock<AssetGroupAssetService.AssetGroupAssetServiceClient> mockGrpcClient = new moq::Mock<AssetGroupAssetService.AssetGroupAssetServiceClient>(moq::MockBehavior.Strict);
GetAssetGroupAssetRequest request = new GetAssetGroupAssetRequest
{
ResourceNameAsAssetGroupAssetName = gagvr::AssetGroupAssetName.FromCustomerAssetGroupAssetFieldType("[CUSTOMER_ID]", "[ASSET_GROUP_ID]", "[ASSET_ID]", "[FIELD_TYPE]"),
};
gagvr::AssetGroupAsset expectedResponse = new gagvr::AssetGroupAsset
{
ResourceNameAsAssetGroupAssetName = gagvr::AssetGroupAssetName.FromCustomerAssetGroupAssetFieldType("[CUSTOMER_ID]", "[ASSET_GROUP_ID]", "[ASSET_ID]", "[FIELD_TYPE]"),
AssetGroupAsAssetGroupName = gagvr::AssetGroupName.FromCustomerAssetGroup("[CUSTOMER_ID]", "[ASSET_GROUP_ID]"),
AssetAsAssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"),
FieldType = gagve::AssetFieldTypeEnum.Types.AssetFieldType.Callout,
Status = gagve::AssetLinkStatusEnum.Types.AssetLinkStatus.Paused,
PerformanceLabel = gagve::AssetPerformanceLabelEnum.Types.AssetPerformanceLabel.Pending,
PolicySummary = new gagvc::PolicySummary(),
};
mockGrpcClient.Setup(x => x.GetAssetGroupAssetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::AssetGroupAsset>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AssetGroupAssetServiceClient client = new AssetGroupAssetServiceClientImpl(mockGrpcClient.Object, null);
gagvr::AssetGroupAsset responseCallSettings = await client.GetAssetGroupAssetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::AssetGroupAsset responseCancellationToken = await client.GetAssetGroupAssetAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetAssetGroupAsset()
{
moq::Mock<AssetGroupAssetService.AssetGroupAssetServiceClient> mockGrpcClient = new moq::Mock<AssetGroupAssetService.AssetGroupAssetServiceClient>(moq::MockBehavior.Strict);
GetAssetGroupAssetRequest request = new GetAssetGroupAssetRequest
{
ResourceNameAsAssetGroupAssetName = gagvr::AssetGroupAssetName.FromCustomerAssetGroupAssetFieldType("[CUSTOMER_ID]", "[ASSET_GROUP_ID]", "[ASSET_ID]", "[FIELD_TYPE]"),
};
gagvr::AssetGroupAsset expectedResponse = new gagvr::AssetGroupAsset
{
ResourceNameAsAssetGroupAssetName = gagvr::AssetGroupAssetName.FromCustomerAssetGroupAssetFieldType("[CUSTOMER_ID]", "[ASSET_GROUP_ID]", "[ASSET_ID]", "[FIELD_TYPE]"),
AssetGroupAsAssetGroupName = gagvr::AssetGroupName.FromCustomerAssetGroup("[CUSTOMER_ID]", "[ASSET_GROUP_ID]"),
AssetAsAssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"),
FieldType = gagve::AssetFieldTypeEnum.Types.AssetFieldType.Callout,
Status = gagve::AssetLinkStatusEnum.Types.AssetLinkStatus.Paused,
PerformanceLabel = gagve::AssetPerformanceLabelEnum.Types.AssetPerformanceLabel.Pending,
PolicySummary = new gagvc::PolicySummary(),
};
mockGrpcClient.Setup(x => x.GetAssetGroupAsset(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AssetGroupAssetServiceClient client = new AssetGroupAssetServiceClientImpl(mockGrpcClient.Object, null);
gagvr::AssetGroupAsset response = client.GetAssetGroupAsset(request.ResourceName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetAssetGroupAssetAsync()
{
moq::Mock<AssetGroupAssetService.AssetGroupAssetServiceClient> mockGrpcClient = new moq::Mock<AssetGroupAssetService.AssetGroupAssetServiceClient>(moq::MockBehavior.Strict);
GetAssetGroupAssetRequest request = new GetAssetGroupAssetRequest
{
ResourceNameAsAssetGroupAssetName = gagvr::AssetGroupAssetName.FromCustomerAssetGroupAssetFieldType("[CUSTOMER_ID]", "[ASSET_GROUP_ID]", "[ASSET_ID]", "[FIELD_TYPE]"),
};
gagvr::AssetGroupAsset expectedResponse = new gagvr::AssetGroupAsset
{
ResourceNameAsAssetGroupAssetName = gagvr::AssetGroupAssetName.FromCustomerAssetGroupAssetFieldType("[CUSTOMER_ID]", "[ASSET_GROUP_ID]", "[ASSET_ID]", "[FIELD_TYPE]"),
AssetGroupAsAssetGroupName = gagvr::AssetGroupName.FromCustomerAssetGroup("[CUSTOMER_ID]", "[ASSET_GROUP_ID]"),
AssetAsAssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"),
FieldType = gagve::AssetFieldTypeEnum.Types.AssetFieldType.Callout,
Status = gagve::AssetLinkStatusEnum.Types.AssetLinkStatus.Paused,
PerformanceLabel = gagve::AssetPerformanceLabelEnum.Types.AssetPerformanceLabel.Pending,
PolicySummary = new gagvc::PolicySummary(),
};
mockGrpcClient.Setup(x => x.GetAssetGroupAssetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::AssetGroupAsset>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AssetGroupAssetServiceClient client = new AssetGroupAssetServiceClientImpl(mockGrpcClient.Object, null);
gagvr::AssetGroupAsset responseCallSettings = await client.GetAssetGroupAssetAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::AssetGroupAsset responseCancellationToken = await client.GetAssetGroupAssetAsync(request.ResourceName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetAssetGroupAssetResourceNames()
{
moq::Mock<AssetGroupAssetService.AssetGroupAssetServiceClient> mockGrpcClient = new moq::Mock<AssetGroupAssetService.AssetGroupAssetServiceClient>(moq::MockBehavior.Strict);
GetAssetGroupAssetRequest request = new GetAssetGroupAssetRequest
{
ResourceNameAsAssetGroupAssetName = gagvr::AssetGroupAssetName.FromCustomerAssetGroupAssetFieldType("[CUSTOMER_ID]", "[ASSET_GROUP_ID]", "[ASSET_ID]", "[FIELD_TYPE]"),
};
gagvr::AssetGroupAsset expectedResponse = new gagvr::AssetGroupAsset
{
ResourceNameAsAssetGroupAssetName = gagvr::AssetGroupAssetName.FromCustomerAssetGroupAssetFieldType("[CUSTOMER_ID]", "[ASSET_GROUP_ID]", "[ASSET_ID]", "[FIELD_TYPE]"),
AssetGroupAsAssetGroupName = gagvr::AssetGroupName.FromCustomerAssetGroup("[CUSTOMER_ID]", "[ASSET_GROUP_ID]"),
AssetAsAssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"),
FieldType = gagve::AssetFieldTypeEnum.Types.AssetFieldType.Callout,
Status = gagve::AssetLinkStatusEnum.Types.AssetLinkStatus.Paused,
PerformanceLabel = gagve::AssetPerformanceLabelEnum.Types.AssetPerformanceLabel.Pending,
PolicySummary = new gagvc::PolicySummary(),
};
mockGrpcClient.Setup(x => x.GetAssetGroupAsset(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AssetGroupAssetServiceClient client = new AssetGroupAssetServiceClientImpl(mockGrpcClient.Object, null);
gagvr::AssetGroupAsset response = client.GetAssetGroupAsset(request.ResourceNameAsAssetGroupAssetName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetAssetGroupAssetResourceNamesAsync()
{
moq::Mock<AssetGroupAssetService.AssetGroupAssetServiceClient> mockGrpcClient = new moq::Mock<AssetGroupAssetService.AssetGroupAssetServiceClient>(moq::MockBehavior.Strict);
GetAssetGroupAssetRequest request = new GetAssetGroupAssetRequest
{
ResourceNameAsAssetGroupAssetName = gagvr::AssetGroupAssetName.FromCustomerAssetGroupAssetFieldType("[CUSTOMER_ID]", "[ASSET_GROUP_ID]", "[ASSET_ID]", "[FIELD_TYPE]"),
};
gagvr::AssetGroupAsset expectedResponse = new gagvr::AssetGroupAsset
{
ResourceNameAsAssetGroupAssetName = gagvr::AssetGroupAssetName.FromCustomerAssetGroupAssetFieldType("[CUSTOMER_ID]", "[ASSET_GROUP_ID]", "[ASSET_ID]", "[FIELD_TYPE]"),
AssetGroupAsAssetGroupName = gagvr::AssetGroupName.FromCustomerAssetGroup("[CUSTOMER_ID]", "[ASSET_GROUP_ID]"),
AssetAsAssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"),
FieldType = gagve::AssetFieldTypeEnum.Types.AssetFieldType.Callout,
Status = gagve::AssetLinkStatusEnum.Types.AssetLinkStatus.Paused,
PerformanceLabel = gagve::AssetPerformanceLabelEnum.Types.AssetPerformanceLabel.Pending,
PolicySummary = new gagvc::PolicySummary(),
};
mockGrpcClient.Setup(x => x.GetAssetGroupAssetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::AssetGroupAsset>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AssetGroupAssetServiceClient client = new AssetGroupAssetServiceClientImpl(mockGrpcClient.Object, null);
gagvr::AssetGroupAsset responseCallSettings = await client.GetAssetGroupAssetAsync(request.ResourceNameAsAssetGroupAssetName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::AssetGroupAsset responseCancellationToken = await client.GetAssetGroupAssetAsync(request.ResourceNameAsAssetGroupAssetName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void MutateAssetGroupAssetsRequestObject()
{
moq::Mock<AssetGroupAssetService.AssetGroupAssetServiceClient> mockGrpcClient = new moq::Mock<AssetGroupAssetService.AssetGroupAssetServiceClient>(moq::MockBehavior.Strict);
MutateAssetGroupAssetsRequest request = new MutateAssetGroupAssetsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new AssetGroupAssetOperation(),
},
PartialFailure = false,
ValidateOnly = true,
};
MutateAssetGroupAssetsResponse expectedResponse = new MutateAssetGroupAssetsResponse
{
Results =
{
new MutateAssetGroupAssetResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateAssetGroupAssets(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AssetGroupAssetServiceClient client = new AssetGroupAssetServiceClientImpl(mockGrpcClient.Object, null);
MutateAssetGroupAssetsResponse response = client.MutateAssetGroupAssets(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task MutateAssetGroupAssetsRequestObjectAsync()
{
moq::Mock<AssetGroupAssetService.AssetGroupAssetServiceClient> mockGrpcClient = new moq::Mock<AssetGroupAssetService.AssetGroupAssetServiceClient>(moq::MockBehavior.Strict);
MutateAssetGroupAssetsRequest request = new MutateAssetGroupAssetsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new AssetGroupAssetOperation(),
},
PartialFailure = false,
ValidateOnly = true,
};
MutateAssetGroupAssetsResponse expectedResponse = new MutateAssetGroupAssetsResponse
{
Results =
{
new MutateAssetGroupAssetResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateAssetGroupAssetsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateAssetGroupAssetsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AssetGroupAssetServiceClient client = new AssetGroupAssetServiceClientImpl(mockGrpcClient.Object, null);
MutateAssetGroupAssetsResponse responseCallSettings = await client.MutateAssetGroupAssetsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
MutateAssetGroupAssetsResponse responseCancellationToken = await client.MutateAssetGroupAssetsAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void MutateAssetGroupAssets()
{
moq::Mock<AssetGroupAssetService.AssetGroupAssetServiceClient> mockGrpcClient = new moq::Mock<AssetGroupAssetService.AssetGroupAssetServiceClient>(moq::MockBehavior.Strict);
MutateAssetGroupAssetsRequest request = new MutateAssetGroupAssetsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new AssetGroupAssetOperation(),
},
};
MutateAssetGroupAssetsResponse expectedResponse = new MutateAssetGroupAssetsResponse
{
Results =
{
new MutateAssetGroupAssetResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateAssetGroupAssets(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AssetGroupAssetServiceClient client = new AssetGroupAssetServiceClientImpl(mockGrpcClient.Object, null);
MutateAssetGroupAssetsResponse response = client.MutateAssetGroupAssets(request.CustomerId, request.Operations);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task MutateAssetGroupAssetsAsync()
{
moq::Mock<AssetGroupAssetService.AssetGroupAssetServiceClient> mockGrpcClient = new moq::Mock<AssetGroupAssetService.AssetGroupAssetServiceClient>(moq::MockBehavior.Strict);
MutateAssetGroupAssetsRequest request = new MutateAssetGroupAssetsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new AssetGroupAssetOperation(),
},
};
MutateAssetGroupAssetsResponse expectedResponse = new MutateAssetGroupAssetsResponse
{
Results =
{
new MutateAssetGroupAssetResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateAssetGroupAssetsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateAssetGroupAssetsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AssetGroupAssetServiceClient client = new AssetGroupAssetServiceClientImpl(mockGrpcClient.Object, null);
MutateAssetGroupAssetsResponse responseCallSettings = await client.MutateAssetGroupAssetsAsync(request.CustomerId, request.Operations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
MutateAssetGroupAssetsResponse responseCancellationToken = await client.MutateAssetGroupAssetsAsync(request.CustomerId, request.Operations, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Azure.Core.TestFramework;
using Azure.Data.Tables.Models;
using Azure.Data.Tables.Sas;
using NUnit.Framework;
namespace Azure.Data.Tables.Tests
{
/// <summary>
/// The suite of tests for the <see cref="TableServiceClient"/> class.
/// </summary>
/// <remarks>
/// These tests have a dependency on live Azure services and may incur costs for the associated
/// Azure subscription.
/// </remarks>
public class TableServiceClientLiveTests : TableServiceLiveTestsBase
{
public TableServiceClientLiveTests(bool isAsync, TableEndpointType endpointType) : base(isAsync, endpointType /* To record tests, add this argument, RecordedTestMode.Record */)
{ }
/// <summary>
/// Validates the functionality of the TableClient.
/// </summary>
[RecordedTest]
public async Task CreateTableIfNotExists()
{
// Call CreateTableIfNotExists when the table already exists.
Assert.That(async () => await CosmosThrottleWrapper(async () => await service.CreateTableIfNotExistsAsync(tableName).ConfigureAwait(false)), Throws.Nothing);
// Call CreateTableIfNotExists when the table does not already exists.
var newTableName = Recording.GenerateAlphaNumericId("testtable", useOnlyLowercase: true);
try
{
TableItem table = await CosmosThrottleWrapper(async () => await service.CreateTableIfNotExistsAsync(newTableName).ConfigureAwait(false));
Assert.That(table.TableName, Is.EqualTo(newTableName));
}
finally
{
// Delete the table using the TableClient method.
await CosmosThrottleWrapper(async () => await service.DeleteTableAsync(newTableName).ConfigureAwait(false));
}
}
[RecordedTest]
public void ValidateAccountSasCredentialsWithPermissions()
{
// Create a SharedKeyCredential that we can use to sign the SAS token
var credential = new TableSharedKeyCredential(TestEnvironment.StorageAccountName, TestEnvironment.PrimaryStorageAccountKey);
// Build a shared access signature with only Delete permissions and access to all service resource types.
TableAccountSasBuilder sasDelete = service.GetSasBuilder(TableAccountSasPermissions.Delete, TableAccountSasResourceTypes.All, new DateTime(2040, 1, 1, 1, 1, 0, DateTimeKind.Utc));
string tokenDelete = sasDelete.Sign(credential);
// Build a shared access signature with the Write and Delete permissions and access to all service resource types.
TableAccountSasBuilder sasWriteDelete = service.GetSasBuilder(TableAccountSasPermissions.Write, TableAccountSasResourceTypes.All, new DateTime(2040, 1, 1, 1, 1, 0, DateTimeKind.Utc));
string tokenWriteDelete = sasWriteDelete.Sign(credential);
// Build SAS URIs.
UriBuilder sasUriDelete = new UriBuilder(ServiceUri)
{
Query = tokenDelete
};
UriBuilder sasUriWriteDelete = new UriBuilder(ServiceUri)
{
Query = tokenWriteDelete
};
// Create the TableServiceClients using the SAS URIs.
var sasAuthedServiceDelete = InstrumentClient(new TableServiceClient(new Uri(ServiceUri), new AzureSasCredential(tokenDelete), InstrumentClientOptions(new TableClientOptions())));
var sasAuthedServiceWriteDelete = InstrumentClient(new TableServiceClient(new Uri(ServiceUri), new AzureSasCredential(tokenWriteDelete), InstrumentClientOptions(new TableClientOptions())));
// Validate that we are unable to create a table using the SAS URI with only Delete permissions.
var sasTableName = Recording.GenerateAlphaNumericId("testtable", useOnlyLowercase: true);
var ex = Assert.ThrowsAsync<RequestFailedException>(async () => await sasAuthedServiceDelete.CreateTableAsync(sasTableName).ConfigureAwait(false));
Assert.That(ex.Status, Is.EqualTo((int)HttpStatusCode.Forbidden));
Assert.That(ex.ErrorCode, Is.EqualTo(TableErrorCode.AuthorizationPermissionMismatch.ToString()));
// Validate that we are able to create a table using the SAS URI with Write and Delete permissions.
Assert.That(async () => await sasAuthedServiceWriteDelete.CreateTableAsync(sasTableName).ConfigureAwait(false), Throws.Nothing);
// Validate that we are able to delete a table using the SAS URI with only Delete permissions.
Assert.That(async () => await sasAuthedServiceDelete.DeleteTableAsync(sasTableName).ConfigureAwait(false), Throws.Nothing);
}
[RecordedTest]
public void ValidateAccountSasCredentialsWithResourceTypes()
{
// Create a SharedKeyCredential that we can use to sign the SAS token
var credential = new TableSharedKeyCredential(TestEnvironment.StorageAccountName, TestEnvironment.PrimaryStorageAccountKey);
// Build a shared access signature with all permissions and access to only Service resource types.
TableAccountSasBuilder sasService = service.GetSasBuilder(TableAccountSasPermissions.All, TableAccountSasResourceTypes.Service, new DateTime(2040, 1, 1, 1, 1, 0, DateTimeKind.Utc));
string tokenService = sasService.Sign(credential);
// Build a shared access signature with all permissions and access to Service and Container resource types.
TableAccountSasBuilder sasServiceContainer = service.GetSasBuilder(TableAccountSasPermissions.All, TableAccountSasResourceTypes.Service | TableAccountSasResourceTypes.Container, new DateTime(2040, 1, 1, 1, 1, 0, DateTimeKind.Utc));
string tokenServiceContainer = sasServiceContainer.Sign(credential);
// Build SAS URIs.
UriBuilder sasUriService = new UriBuilder(ServiceUri)
{
Query = tokenService
};
UriBuilder sasUriServiceContainer = new UriBuilder(ServiceUri)
{
Query = tokenServiceContainer
};
// Create the TableServiceClients using the SAS URIs.
var sasAuthedServiceClientService = InstrumentClient(new TableServiceClient(new Uri(ServiceUri), new AzureSasCredential(tokenService), InstrumentClientOptions(new TableClientOptions())));
var sasAuthedServiceClientServiceContainer = InstrumentClient(new TableServiceClient(new Uri(ServiceUri), new AzureSasCredential(tokenServiceContainer), InstrumentClientOptions(new TableClientOptions())));
// Validate that we are unable to create a table using the SAS URI with access to Service resource types.
var sasTableName = Recording.GenerateAlphaNumericId("testtable", useOnlyLowercase: true);
var ex = Assert.ThrowsAsync<RequestFailedException>(async () => await sasAuthedServiceClientService.CreateTableAsync(sasTableName).ConfigureAwait(false));
Assert.That(ex.Status, Is.EqualTo((int)HttpStatusCode.Forbidden));
Assert.That(ex.ErrorCode, Is.EqualTo(TableErrorCode.AuthorizationResourceTypeMismatch.ToString()));
// Validate that we are able to create a table using the SAS URI with access to Service and Container resource types.
Assert.That(async () => await sasAuthedServiceClientServiceContainer.CreateTableAsync(sasTableName).ConfigureAwait(false), Throws.Nothing);
// Validate that we are able to get table service properties using the SAS URI with access to Service resource types.
Assert.That(async () => await sasAuthedServiceClientService.GetPropertiesAsync().ConfigureAwait(false), Throws.Nothing);
// Validate that we are able to get table service properties using the SAS URI with access to Service and Container resource types.
Assert.That(async () => await sasAuthedServiceClientService.GetPropertiesAsync().ConfigureAwait(false), Throws.Nothing);
// Validate that we are able to delete a table using the SAS URI with access to Service and Container resource types.
Assert.That(async () => await sasAuthedServiceClientServiceContainer.DeleteTableAsync(sasTableName).ConfigureAwait(false), Throws.Nothing);
}
/// <summary>
/// Validates the functionality of the TableServiceClient.
/// </summary>
[RecordedTest]
[TestCase(null)]
[TestCase(5)]
public async Task GetTablesReturnsTablesWithAndWithoutPagination(int? pageCount)
{
var createdTables = new List<string>() { tableName };
try
{
// Create some extra tables.
for (int i = 0; i < 10; i++)
{
var table = Recording.GenerateAlphaNumericId("testtable", useOnlyLowercase: true);
createdTables.Add(table);
await CosmosThrottleWrapper(async () => await service.CreateTableAsync(table).ConfigureAwait(false));
}
// Get the table list.
var remainingItems = createdTables.Count;
await foreach (var page in service.GetTablesAsync(/*maxPerPage: pageCount*/).AsPages(pageSizeHint: pageCount))
{
Assert.That(page.Values, Is.Not.Empty);
if (pageCount.HasValue)
{
Assert.That(page.Values.Count, Is.EqualTo(Math.Min(pageCount.Value, remainingItems)));
remainingItems -= page.Values.Count;
}
else
{
Assert.That(page.Values.Count, Is.EqualTo(createdTables.Count));
}
Assert.That(page.Values.All(r => createdTables.Contains(r.TableName)));
}
}
finally
{
foreach (var table in createdTables)
{
await service.DeleteTableAsync(table);
}
}
}
/// <summary>
/// Validates the functionality of the TableServiceClient.
/// </summary>
[RecordedTest]
public async Task GetTablesReturnsTablesWithFilter()
{
var createdTables = new List<string>();
try
{
// Create some extra tables.
for (int i = 0; i < 10; i++)
{
var table = Recording.GenerateAlphaNumericId("testtable", useOnlyLowercase: true);
await CosmosThrottleWrapper(async () => await service.CreateTableAsync(table).ConfigureAwait(false));
createdTables.Add(table);
}
// Query with a filter.
var tableResponses = (await service.GetTablesAsync(filter: $"TableName eq '{tableName}'").ToEnumerableAsync().ConfigureAwait(false)).ToList();
Assert.That(() => tableResponses, Is.Not.Empty);
Assert.AreEqual(tableName, tableResponses.Select(r => r.TableName).SingleOrDefault());
// Query with a filter.
tableResponses = (await service.GetTablesAsync(filter: t => t.TableName == tableName).ToEnumerableAsync().ConfigureAwait(false)).ToList();
Assert.That(() => tableResponses, Is.Not.Empty);
Assert.AreEqual(tableName, tableResponses.Select(r => r.TableName).SingleOrDefault());
}
finally
{
foreach (var table in createdTables)
{
await service.DeleteTableAsync(table);
}
}
}
[RecordedTest]
public async Task GetPropertiesReturnsProperties()
{
// Get current properties
TableServiceProperties responseToChange = await service.GetPropertiesAsync().ConfigureAwait(false);
// Change a property
responseToChange.Logging.Read = !responseToChange.Logging.Read;
// Set properties to the changed one
await service.SetPropertiesAsync(responseToChange).ConfigureAwait(false);
// Get configured properties
// A delay is required to ensure properties are updated in the service
TableServiceProperties changedResponse = await RetryUntilExpectedResponse(
async () => await service.GetPropertiesAsync().ConfigureAwait(false),
result => result.Value.Logging.Read == responseToChange.Logging.Read,
15000).ConfigureAwait(false);
// Test each property
CompareServiceProperties(responseToChange, changedResponse);
}
[RecordedTest]
public async Task GetTableServiceStatsReturnsStats()
{
// Get statistics
TableServiceStatistics stats = await service.GetStatisticsAsync().ConfigureAwait(false);
// Test that the secondary location is live
Assert.AreEqual(new TableGeoReplicationStatus("live"), stats.GeoReplication.Status);
}
private void CompareServiceProperties(TableServiceProperties expected, TableServiceProperties actual)
{
Assert.AreEqual(expected.Logging.Read, actual.Logging.Read);
Assert.AreEqual(expected.Logging.Version, actual.Logging.Version);
Assert.AreEqual(expected.Logging.Write, actual.Logging.Write);
Assert.AreEqual(expected.Logging.Delete, actual.Logging.Delete);
Assert.AreEqual(expected.Logging.RetentionPolicy.Enabled, actual.Logging.RetentionPolicy.Enabled);
Assert.AreEqual(expected.Logging.RetentionPolicy.Days, actual.Logging.RetentionPolicy.Days);
Assert.AreEqual(expected.HourMetrics.Enabled, actual.HourMetrics.Enabled);
Assert.AreEqual(expected.HourMetrics.Version, actual.HourMetrics.Version);
Assert.AreEqual(expected.HourMetrics.IncludeApis, actual.HourMetrics.IncludeApis);
Assert.AreEqual(expected.HourMetrics.RetentionPolicy.Enabled, actual.HourMetrics.RetentionPolicy.Enabled);
Assert.AreEqual(expected.HourMetrics.RetentionPolicy.Days, actual.HourMetrics.RetentionPolicy.Days);
Assert.AreEqual(expected.MinuteMetrics.Enabled, actual.MinuteMetrics.Enabled);
Assert.AreEqual(expected.MinuteMetrics.Version, actual.MinuteMetrics.Version);
Assert.AreEqual(expected.MinuteMetrics.IncludeApis, actual.MinuteMetrics.IncludeApis);
Assert.AreEqual(expected.MinuteMetrics.RetentionPolicy.Enabled, actual.MinuteMetrics.RetentionPolicy.Enabled);
Assert.AreEqual(expected.MinuteMetrics.RetentionPolicy.Days, actual.MinuteMetrics.RetentionPolicy.Days);
Assert.AreEqual(expected.Cors.Count, actual.Cors.Count);
for (int i = 0; i < expected.Cors.Count; i++)
{
TableCorsRule expectedRule = expected.Cors[i];
TableCorsRule actualRule = actual.Cors[i];
Assert.AreEqual(expectedRule.AllowedHeaders, actualRule.AllowedHeaders);
Assert.AreEqual(expectedRule.AllowedMethods, actualRule.AllowedMethods);
Assert.AreEqual(expectedRule.AllowedOrigins, actualRule.AllowedOrigins);
Assert.AreEqual(expectedRule.MaxAgeInSeconds, actualRule.MaxAgeInSeconds);
Assert.AreEqual(expectedRule.ExposedHeaders, actualRule.ExposedHeaders);
}
}
}
}
| |
// Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors.
// All rights reserved. Licensed under the BSD 3-Clause License; see License.txt.
using System;
using System.Threading.Tasks;
using Xunit;
namespace Moq.Tests
{
public class ReturnsExtensionsFixture
{
public interface IAsyncInterface
{
Task NoParametersNonGenericTaskReturnType();
Task<string> NoParametersRefReturnType();
Task<int> NoParametersValueReturnType();
Task<string> RefParameterRefReturnType(string value);
Task<int> RefParameterValueReturnType(string value);
Task<string> ValueParameterRefReturnType(int value);
Task<int> ValueParameterValueReturnType(int value);
Task<Guid> NewGuidAsync();
Task<object> NoParametersObjectReturnType();
Task<object> OneParameterObjectReturnType(string value);
Task<object> ManyParametersObjectReturnType(string arg1, bool arg2, float arg3);
}
public interface IValueTaskAsyncInterface
{
ValueTask<string> NoParametersRefReturnType();
ValueTask<int> NoParametersValueReturnType();
ValueTask<string> RefParameterRefReturnType(string value);
ValueTask<int> RefParameterValueReturnType(string value);
ValueTask<string> ValueParameterRefReturnType(int value);
ValueTask<int> ValueParameterValueReturnType(int value);
ValueTask<Guid> NewGuidAsync();
ValueTask<object> NoParametersObjectReturnType();
ValueTask<object> OneParameterObjectReturnType(string value);
ValueTask<object> ManyParametersObjectReturnType(string arg1, bool arg2, float arg3);
}
[Fact]
public void ReturnsAsync_on_NoParametersRefReturnType()
{
var mock = new Mock<IAsyncInterface>();
mock.Setup(x => x.NoParametersRefReturnType()).ReturnsAsync("TestString");
var task = mock.Object.NoParametersRefReturnType();
Assert.True(task.IsCompleted);
Assert.Equal("TestString", task.Result);
}
[Fact]
public void ReturnsAsync_on_NoParametersValueReturnType()
{
var mock = new Mock<IAsyncInterface>();
mock.Setup(x => x.NoParametersValueReturnType()).ReturnsAsync(36);
var task = mock.Object.NoParametersValueReturnType();
Assert.True(task.IsCompleted);
Assert.Equal(36, task.Result);
}
[Fact]
public void ReturnsAsync_on_RefParameterRefReturnType()
{
var mock = new Mock<IAsyncInterface>();
mock.Setup(x => x.RefParameterRefReturnType("Param1")).ReturnsAsync("TestString");
var task = mock.Object.RefParameterRefReturnType("Param1");
Assert.True(task.IsCompleted);
Assert.Equal("TestString", task.Result);
}
[Fact]
public void ReturnsAsync_on_RefParameterValueReturnType()
{
var mock = new Mock<IAsyncInterface>();
mock.Setup(x => x.RefParameterValueReturnType("Param1")).ReturnsAsync(36);
var task = mock.Object.RefParameterValueReturnType("Param1");
Assert.True(task.IsCompleted);
Assert.Equal(36, task.Result);
}
[Fact]
public void ReturnsAsync_on_ValueParameterRefReturnType()
{
var mock = new Mock<IAsyncInterface>();
mock.Setup(x => x.ValueParameterRefReturnType(36)).ReturnsAsync("TestString");
var task = mock.Object.ValueParameterRefReturnType(36);
Assert.True(task.IsCompleted);
Assert.Equal("TestString", task.Result);
}
[Fact]
public void ReturnsAsync_on_ValueParameterValueReturnType()
{
var mock = new Mock<IAsyncInterface>();
mock.Setup(x => x.ValueParameterValueReturnType(36)).ReturnsAsync(37);
var task = mock.Object.ValueParameterValueReturnType(36);
Assert.True(task.IsCompleted);
Assert.Equal(37, task.Result);
}
[Fact]
public void ReturnsAsyncFunc_on_NoParametersRefReturnType()
{
var mock = new Mock<IAsyncInterface>();
mock.Setup(x => x.NoParametersRefReturnType()).ReturnsAsync(() => "TestString");
var task = mock.Object.NoParametersRefReturnType();
Assert.True(task.IsCompleted);
Assert.Equal("TestString", task.Result);
}
[Fact]
public void ReturnsAsyncFunc_on_NoParametersValueReturnType()
{
var mock = new Mock<IAsyncInterface>();
mock.Setup(x => x.NoParametersValueReturnType()).ReturnsAsync(() => 36);
var task = mock.Object.NoParametersValueReturnType();
Assert.True(task.IsCompleted);
Assert.Equal(36, task.Result);
}
[Fact]
public void ReturnsAsyncFunc_on_RefParameterRefReturnType()
{
var mock = new Mock<IAsyncInterface>();
mock.Setup(x => x.RefParameterRefReturnType("Param1")).ReturnsAsync(() => "TestString");
var task = mock.Object.RefParameterRefReturnType("Param1");
Assert.True(task.IsCompleted);
Assert.Equal("TestString", task.Result);
}
[Fact]
public void ReturnsAsyncFunc_on_RefParameterValueReturnType()
{
var mock = new Mock<IAsyncInterface>();
mock.Setup(x => x.RefParameterValueReturnType("Param1")).ReturnsAsync(() => 36);
var task = mock.Object.RefParameterValueReturnType("Param1");
Assert.True(task.IsCompleted);
Assert.Equal(36, task.Result);
}
[Fact]
public void ReturnsAsyncFunc_on_ValueParameterRefReturnType()
{
var mock = new Mock<IAsyncInterface>();
mock.Setup(x => x.ValueParameterRefReturnType(36)).ReturnsAsync(() => "TestString");
var task = mock.Object.ValueParameterRefReturnType(36);
Assert.True(task.IsCompleted);
Assert.Equal("TestString", task.Result);
}
[Fact]
public void ReturnsAsyncFunc_on_ValueParameterValueReturnType()
{
var mock = new Mock<IAsyncInterface>();
mock.Setup(x => x.ValueParameterValueReturnType(36)).ReturnsAsync(() => 37);
var task = mock.Object.ValueParameterValueReturnType(36);
Assert.True(task.IsCompleted);
Assert.Equal(37, task.Result);
}
[Fact]
public void ReturnsAsyncFunc_onEachInvocation_ValueReturnTypeLazyEvaluation()
{
var mock = new Mock<IAsyncInterface>();
mock.Setup(x => x.NewGuidAsync()).ReturnsAsync(Guid.NewGuid);
Guid firstEvaluationResult = mock.Object.NewGuidAsync().Result;
Guid secondEvaluationResult = mock.Object.NewGuidAsync().Result;
Assert.NotEqual(firstEvaluationResult, secondEvaluationResult);
}
[Fact]
public void ReturnsAsyncFunc_onEachInvocation_RefReturnTypeLazyEvaluation()
{
var mock = new Mock<IAsyncInterface>();
mock.Setup(x => x.ValueParameterRefReturnType(36)).ReturnsAsync(() => new string(new[] { 'M', 'o', 'q', '4' }));
string firstEvaluationResult = mock.Object.ValueParameterRefReturnType(36).Result;
string secondEvaluationResult = mock.Object.ValueParameterRefReturnType(36).Result;
Assert.NotSame(firstEvaluationResult, secondEvaluationResult);
}
[Fact]
public void ThrowsAsync_on_NoParametersNonGenericTaskReturnType()
{
var mock = new Mock<IAsyncInterface>();
var exception = new InvalidOperationException();
mock.Setup(x => x.NoParametersNonGenericTaskReturnType()).ThrowsAsync(exception);
var task = mock.Object.NoParametersNonGenericTaskReturnType();
Assert.True(task.IsFaulted);
Assert.Equal(exception, task.Exception.InnerException);
}
[Fact]
public void ThrowsAsync_on_NoParametersRefReturnType()
{
var mock = new Mock<IAsyncInterface>();
var exception = new InvalidOperationException();
mock.Setup(x => x.NoParametersRefReturnType()).ThrowsAsync(exception);
var task = mock.Object.NoParametersRefReturnType();
Assert.True(task.IsFaulted);
Assert.Equal(exception, task.Exception.InnerException);
}
[Fact]
public void ThrowsAsync_on_NoParametersValueReturnType()
{
var mock = new Mock<IAsyncInterface>();
var exception = new InvalidOperationException();
mock.Setup(x => x.NoParametersValueReturnType()).ThrowsAsync(exception);
var task = mock.Object.NoParametersValueReturnType();
Assert.True(task.IsFaulted);
Assert.Equal(exception, task.Exception.InnerException);
}
[Fact]
public void ThrowsAsync_on_RefParameterRefReturnType()
{
var mock = new Mock<IAsyncInterface>();
var exception = new InvalidOperationException();
mock.Setup(x => x.RefParameterRefReturnType("Param1")).ThrowsAsync(exception);
var task = mock.Object.RefParameterRefReturnType("Param1");
Assert.True(task.IsFaulted);
Assert.Equal(exception, task.Exception.InnerException);
}
[Fact]
public void ThrowsAsync_on_RefParameterValueReturnType()
{
var mock = new Mock<IAsyncInterface>();
var exception = new InvalidOperationException();
mock.Setup(x => x.RefParameterValueReturnType("Param1")).ThrowsAsync(exception);
var task = mock.Object.RefParameterValueReturnType("Param1");
Assert.True(task.IsFaulted);
Assert.Equal(exception, task.Exception.InnerException);
}
[Fact]
public void ThrowsAsync_on_ValueParameterRefReturnType()
{
var mock = new Mock<IAsyncInterface>();
var exception = new InvalidOperationException();
mock.Setup(x => x.ValueParameterRefReturnType(36)).ThrowsAsync(exception);
var task = mock.Object.ValueParameterRefReturnType(36);
Assert.True(task.IsFaulted);
Assert.Equal(exception, task.Exception.InnerException);
}
[Fact]
public void ThrowsAsync_on_ValueParameterValueReturnType()
{
var mock = new Mock<IAsyncInterface>();
var exception = new InvalidOperationException();
mock.Setup(x => x.ValueParameterValueReturnType(36)).ThrowsAsync(exception);
var task = mock.Object.ValueParameterValueReturnType(36);
Assert.True(task.IsFaulted);
Assert.Equal(exception, task.Exception.InnerException);
}
// The test below is dependent on the timings (too much of a 'works-on-my-machine' smell)
//[Theory]
//[InlineData(true)]
//[InlineData(false)]
//public async Task ReturnsAsyncWithDelayTriggersRealAsyncBehaviour(bool useDelay)
//{
// var mock = new Mock<IAsyncInterface>();
// var setup = mock.Setup(x => x.RefParameterValueReturnType("test"));
// if (useDelay)
// setup.ReturnsAsync(5, TimeSpan.FromMilliseconds(1));
// else
// setup.ReturnsAsync(5);
// var thread1 = Thread.CurrentThread;
// await mock.Object.RefParameterValueReturnType("test");
// var thread2 = Thread.CurrentThread;
// if (useDelay)
// Assert.NotEqual(thread1, thread2);
// else
// Assert.Equal(thread1, thread2);
//}
[Fact]
public void ReturnsAsyncWithDelayDoesNotImmediatelyComplete()
{
var longEnoughForAnyBuildServer = TimeSpan.FromSeconds(5);
var mock = new Mock<IAsyncInterface>();
mock.Setup(x => x.RefParameterValueReturnType("test")).ReturnsAsync(5, longEnoughForAnyBuildServer);
var task = mock.Object.RefParameterValueReturnType("test");
Assert.False(task.IsCompleted);
}
[Theory]
[InlineData(-1, true)]
[InlineData(0, true)]
[InlineData(1, false)]
public void DelayMustBePositive(int ticks, bool mustThrow)
{
var mock = new Mock<IAsyncInterface>();
Action setup = () => mock
.Setup(x => x.RefParameterValueReturnType("test"))
.ReturnsAsync(5, TimeSpan.FromTicks(ticks));
if (mustThrow)
Assert.Throws<ArgumentException>(setup);
else
setup();
}
[Fact]
public async Task ReturnsAsyncWithDelayReturnsValue()
{
var mock = new Mock<IAsyncInterface>();
mock.Setup(x => x.RefParameterValueReturnType("test")).ReturnsAsync(5, TimeSpan.FromMilliseconds(1));
var value = await mock.Object.RefParameterValueReturnType("test");
Assert.Equal(5, value);
}
[Fact]
public async Task ReturnsAsyncWithMinAndMaxDelayReturnsValue()
{
var mock = new Mock<IAsyncInterface>();
mock.Setup(x => x.RefParameterValueReturnType("test")).ReturnsAsync(5, TimeSpan.FromMilliseconds(1), TimeSpan.FromMilliseconds(2));
var value = await mock.Object.RefParameterValueReturnType("test");
Assert.Equal(5, value);
}
[Fact]
public async Task ReturnsAsyncWithMinAndMaxDelayAndOwnRandomGeneratorReturnsValue()
{
var mock = new Mock<IAsyncInterface>();
mock.Setup(x => x.RefParameterValueReturnType("test")).ReturnsAsync(5, TimeSpan.FromMilliseconds(1), TimeSpan.FromMilliseconds(2), new Random());
var value = await mock.Object.RefParameterValueReturnType("test");
Assert.Equal(5, value);
}
[Fact]
public void ReturnsAsyncWithNullRandomGenerator()
{
var mock = new Mock<IAsyncInterface>();
Action setup = () => mock
.Setup(x => x.RefParameterValueReturnType("test"))
.ReturnsAsync(5, TimeSpan.FromMilliseconds(1), TimeSpan.FromMilliseconds(2), null);
var paramName = Assert.Throws<ArgumentNullException>(setup).ParamName;
Assert.Equal("random", paramName);
}
[Fact]
public async Task ThrowsWithDelay()
{
var mock = new Mock<IAsyncInterface>();
mock
.Setup(x => x.RefParameterValueReturnType("test"))
.ThrowsAsync(new ArithmeticException("yikes"), TimeSpan.FromMilliseconds(1));
Func<Task<int>> test = () => mock.Object.RefParameterValueReturnType("test");
var exception = await Assert.ThrowsAsync<ArithmeticException>(test);
Assert.Equal("yikes", exception.Message);
}
[Fact]
public async Task ThrowsWithRandomDelay()
{
var mock = new Mock<IAsyncInterface>();
var minDelay = TimeSpan.FromMilliseconds(1);
var maxDelay = TimeSpan.FromMilliseconds(2);
mock
.Setup(x => x.RefParameterValueReturnType("test"))
.ThrowsAsync(new ArithmeticException("yikes"), minDelay, maxDelay);
Func<Task<int>> test = () => mock.Object.RefParameterValueReturnType("test");
var exception = await Assert.ThrowsAsync<ArithmeticException>(test);
Assert.Equal("yikes", exception.Message);
}
[Fact]
public async Task ThrowsWithRandomDelayAndOwnRandomGenerator()
{
var mock = new Mock<IAsyncInterface>();
var minDelay = TimeSpan.FromMilliseconds(1);
var maxDelay = TimeSpan.FromMilliseconds(2);
mock
.Setup(x => x.RefParameterValueReturnType("test"))
.ThrowsAsync(new ArithmeticException("yikes"), minDelay, maxDelay, new Random());
Func<Task<int>> test = () => mock.Object.RefParameterValueReturnType("test");
var exception = await Assert.ThrowsAsync<ArithmeticException>(test);
Assert.Equal("yikes", exception.Message);
}
[Fact]
public void ThrowsAsyncWithNullRandomGenerator()
{
var mock = new Mock<IAsyncInterface>();
Action setup = () =>
{
var anyException = new Exception();
var minDelay = TimeSpan.FromMilliseconds(1);
var maxDelay = TimeSpan.FromMilliseconds(2);
mock
.Setup(x => x.RefParameterValueReturnType("test"))
.ThrowsAsync(anyException, minDelay, maxDelay, null);
};
var paramName = Assert.Throws<ArgumentNullException>(setup).ParamName;
Assert.Equal("random", paramName);
}
[Fact]
public void ValueTaskReturnsAsync_on_NoParametersRefReturnType()
{
var mock = new Mock<IValueTaskAsyncInterface>();
mock.Setup(x => x.NoParametersRefReturnType()).ReturnsAsync("TestString");
var task = mock.Object.NoParametersRefReturnType();
Assert.IsType<ValueTask<string>>(task);
Assert.True(task.IsCompleted);
Assert.Equal("TestString", task.Result);
}
[Fact]
public void ValueTaskReturnsAsync_on_NoParametersValueReturnType()
{
var mock = new Mock<IValueTaskAsyncInterface>();
mock.Setup(x => x.NoParametersValueReturnType()).ReturnsAsync(36);
var task = mock.Object.NoParametersValueReturnType();
Assert.IsType<ValueTask<int>>(task);
Assert.True(task.IsCompleted);
Assert.Equal(36, task.Result);
}
[Fact]
public void ValueTaskReturnsAsync_on_RefParameterRefReturnType()
{
var mock = new Mock<IValueTaskAsyncInterface>();
mock.Setup(x => x.RefParameterRefReturnType("Param1")).ReturnsAsync("TestString");
var task = mock.Object.RefParameterRefReturnType("Param1");
Assert.IsType<ValueTask<string>>(task);
Assert.True(task.IsCompleted);
Assert.Equal("TestString", task.Result);
}
[Fact]
public void ValueTaskReturnsAsync_on_RefParameterValueReturnType()
{
var mock = new Mock<IValueTaskAsyncInterface>();
mock.Setup(x => x.RefParameterValueReturnType("Param1")).ReturnsAsync(36);
var task = mock.Object.RefParameterValueReturnType("Param1");
Assert.IsType<ValueTask<int>>(task);
Assert.True(task.IsCompleted);
Assert.Equal(36, task.Result);
}
[Fact]
public void ValueTaskReturnsAsync_on_ValueParameterRefReturnType()
{
var mock = new Mock<IValueTaskAsyncInterface>();
mock.Setup(x => x.ValueParameterRefReturnType(36)).ReturnsAsync("TestString");
var task = mock.Object.ValueParameterRefReturnType(36);
Assert.IsType<ValueTask<string>>(task);
Assert.True(task.IsCompleted);
Assert.Equal("TestString", task.Result);
}
[Fact]
public void ValueTaskReturnsAsync_on_ValueParameterValueReturnType()
{
var mock = new Mock<IValueTaskAsyncInterface>();
mock.Setup(x => x.ValueParameterValueReturnType(36)).ReturnsAsync(37);
var task = mock.Object.ValueParameterValueReturnType(36);
Assert.IsType<ValueTask<int>>(task);
Assert.True(task.IsCompleted);
Assert.Equal(37, task.Result);
}
[Fact]
public void ValueTaskReturnsAsyncFunc_on_NoParametersRefReturnType()
{
var mock = new Mock<IValueTaskAsyncInterface>();
mock.Setup(x => x.NoParametersRefReturnType()).ReturnsAsync(() => "TestString");
var task = mock.Object.NoParametersRefReturnType();
Assert.IsType<ValueTask<string>>(task);
Assert.True(task.IsCompleted);
Assert.Equal("TestString", task.Result);
}
[Fact]
public void ValueTaskReturnsAsyncFunc_on_NoParametersValueReturnType()
{
var mock = new Mock<IValueTaskAsyncInterface>();
mock.Setup(x => x.NoParametersValueReturnType()).ReturnsAsync(() => 36);
var task = mock.Object.NoParametersValueReturnType();
Assert.IsType<ValueTask<int>>(task);
Assert.True(task.IsCompleted);
Assert.Equal(36, task.Result);
}
[Fact]
public void ValueTaskReturnsAsyncFunc_on_RefParameterRefReturnType()
{
var mock = new Mock<IValueTaskAsyncInterface>();
mock.Setup(x => x.RefParameterRefReturnType("Param1")).ReturnsAsync(() => "TestString");
var task = mock.Object.RefParameterRefReturnType("Param1");
Assert.IsType<ValueTask<string>>(task);
Assert.True(task.IsCompleted);
Assert.Equal("TestString", task.Result);
}
[Fact]
public void ValueTaskReturnsAsyncFunc_on_RefParameterValueReturnType()
{
var mock = new Mock<IValueTaskAsyncInterface>();
mock.Setup(x => x.RefParameterValueReturnType("Param1")).ReturnsAsync(() => 36);
var task = mock.Object.RefParameterValueReturnType("Param1");
Assert.IsType<ValueTask<int>>(task);
Assert.True(task.IsCompleted);
Assert.Equal(36, task.Result);
}
[Fact]
public void ValueTaskReturnsAsyncFunc_on_ValueParameterRefReturnType()
{
var mock = new Mock<IValueTaskAsyncInterface>();
mock.Setup(x => x.ValueParameterRefReturnType(36)).ReturnsAsync(() => "TestString");
var task = mock.Object.ValueParameterRefReturnType(36);
Assert.IsType<ValueTask<string>>(task);
Assert.True(task.IsCompleted);
Assert.Equal("TestString", task.Result);
}
[Fact]
public void ValueTaskReturnsAsyncFunc_on_ValueParameterValueReturnType()
{
var mock = new Mock<IValueTaskAsyncInterface>();
mock.Setup(x => x.ValueParameterValueReturnType(36)).ReturnsAsync(() => 37);
var task = mock.Object.ValueParameterValueReturnType(36);
Assert.IsType<ValueTask<int>>(task);
Assert.True(task.IsCompleted);
Assert.Equal(37, task.Result);
}
[Fact]
public void ValueTaskReturnsAsyncFunc_onEachInvocation_ValueReturnTypeLazyEvaluation()
{
var mock = new Mock<IValueTaskAsyncInterface>();
mock.Setup(x => x.NewGuidAsync()).ReturnsAsync(Guid.NewGuid);
var firstTask = mock.Object.NewGuidAsync();
var secondTask = mock.Object.NewGuidAsync();
Assert.IsType<ValueTask<Guid>>(firstTask);
Assert.IsType<ValueTask<Guid>>(secondTask);
Assert.NotEqual(firstTask.Result, secondTask.Result);
}
[Fact]
public void ValueTaskReturnsAsyncFunc_onEachInvocation_RefReturnTypeLazyEvaluation()
{
var mock = new Mock<IValueTaskAsyncInterface>();
mock.Setup(x => x.ValueParameterRefReturnType(36)).ReturnsAsync(() => new string(new[] { 'M', 'o', 'q', '4' }));
var firstTask = mock.Object.ValueParameterRefReturnType(36);
var secondTask = mock.Object.ValueParameterRefReturnType(36);
Assert.IsType<ValueTask<string>>(firstTask);
Assert.IsType<ValueTask<string>>(secondTask);
Assert.NotSame(firstTask.Result, secondTask.Result);
}
[Fact]
public void ValueTaskThrowsAsync_on_NoParametersRefReturnType()
{
var mock = new Mock<IValueTaskAsyncInterface>();
var exception = new InvalidOperationException();
mock.Setup(x => x.NoParametersRefReturnType()).ThrowsAsync(exception);
var task = mock.Object.NoParametersRefReturnType();
Assert.IsType<ValueTask<string>>(task);
Assert.True(task.IsFaulted);
Assert.Equal(exception, task.AsTask().Exception.InnerException);
}
[Fact]
public void ValueTaskThrowsAsync_on_NoParametersValueReturnType()
{
var mock = new Mock<IValueTaskAsyncInterface>();
var exception = new InvalidOperationException();
mock.Setup(x => x.NoParametersValueReturnType()).ThrowsAsync(exception);
var task = mock.Object.NoParametersValueReturnType();
Assert.IsType<ValueTask<int>>(task);
Assert.True(task.IsFaulted);
Assert.Equal(exception, task.AsTask().Exception.InnerException);
}
[Fact]
public void ValueTaskThrowsAsync_on_RefParameterRefReturnType()
{
var mock = new Mock<IValueTaskAsyncInterface>();
var exception = new InvalidOperationException();
mock.Setup(x => x.RefParameterRefReturnType("Param1")).ThrowsAsync(exception);
var task = mock.Object.RefParameterRefReturnType("Param1");
Assert.IsType<ValueTask<string>>(task);
Assert.True(task.IsFaulted);
Assert.Equal(exception, task.AsTask().Exception.InnerException);
}
[Fact]
public void ValueTaskThrowsAsync_on_RefParameterValueReturnType()
{
var mock = new Mock<IValueTaskAsyncInterface>();
var exception = new InvalidOperationException();
mock.Setup(x => x.RefParameterValueReturnType("Param1")).ThrowsAsync(exception);
var task = mock.Object.RefParameterValueReturnType("Param1");
Assert.IsType<ValueTask<int>>(task);
Assert.True(task.IsFaulted);
Assert.Equal(exception, task.AsTask().Exception.InnerException);
}
[Fact]
public void ValueTaskThrowsAsync_on_ValueParameterRefReturnType()
{
var mock = new Mock<IValueTaskAsyncInterface>();
var exception = new InvalidOperationException();
mock.Setup(x => x.ValueParameterRefReturnType(36)).ThrowsAsync(exception);
var task = mock.Object.ValueParameterRefReturnType(36);
Assert.IsType<ValueTask<string>>(task);
Assert.True(task.IsFaulted);
Assert.Equal(exception, task.AsTask().Exception.InnerException);
}
[Fact]
public void ValueTaskThrowsAsync_on_ValueParameterValueReturnType()
{
var mock = new Mock<IValueTaskAsyncInterface>();
var exception = new InvalidOperationException();
mock.Setup(x => x.ValueParameterValueReturnType(36)).ThrowsAsync(exception);
var task = mock.Object.ValueParameterValueReturnType(36);
Assert.IsType<ValueTask<int>>(task);
Assert.True(task.IsFaulted);
Assert.Equal(exception, task.AsTask().Exception.InnerException);
}
[Fact]
public void ValueTaskReturnsAsyncWithDelayDoesNotImmediatelyComplete()
{
var longEnoughForAnyBuildServer = TimeSpan.FromSeconds(5);
var mock = new Mock<IValueTaskAsyncInterface>();
mock.Setup(x => x.RefParameterValueReturnType("test")).ReturnsAsync(5, longEnoughForAnyBuildServer);
var task = mock.Object.RefParameterValueReturnType("test");
Assert.IsType<ValueTask<int>>(task);
Assert.False(task.IsCompleted);
}
[Theory]
[InlineData(-1, true)]
[InlineData(0, true)]
[InlineData(1, false)]
public void ValueTaskDelayMustBePositive(int ticks, bool mustThrow)
{
var mock = new Mock<IValueTaskAsyncInterface>();
Action setup = () => mock
.Setup(x => x.RefParameterValueReturnType("test"))
.ReturnsAsync(5, TimeSpan.FromTicks(ticks));
if (mustThrow)
Assert.Throws<ArgumentException>(setup);
else
setup();
}
[Fact]
public async Task ValueTaskReturnsAsyncWithDelayReturnsValue()
{
var mock = new Mock<IValueTaskAsyncInterface>();
mock.Setup(x => x.RefParameterValueReturnType("test")).ReturnsAsync(5, TimeSpan.FromMilliseconds(1));
var task = mock.Object.RefParameterValueReturnType("test");
var value = await Assert.IsType<ValueTask<int>>(task);
Assert.Equal(5, value);
}
[Fact]
public async Task ValueTaskReturnsAsyncWithMinAndMaxDelayReturnsValue()
{
var mock = new Mock<IValueTaskAsyncInterface>();
mock.Setup(x => x.RefParameterValueReturnType("test")).ReturnsAsync(5, TimeSpan.FromMilliseconds(1), TimeSpan.FromMilliseconds(2));
var task = mock.Object.RefParameterValueReturnType("test");
var value = await Assert.IsType<ValueTask<int>>(task);
Assert.Equal(5, value);
}
[Fact]
public async Task ValueTaskReturnsAsyncWithMinAndMaxDelayAndOwnRandomGeneratorReturnsValue()
{
var mock = new Mock<IValueTaskAsyncInterface>();
mock.Setup(x => x.RefParameterValueReturnType("test")).ReturnsAsync(5, TimeSpan.FromMilliseconds(1), TimeSpan.FromMilliseconds(2), new Random());
var task = mock.Object.RefParameterValueReturnType("test");
var value = await Assert.IsType<ValueTask<int>>(task);
Assert.Equal(5, value);
}
[Fact]
public void ValueTaskReturnsAsyncWithNullRandomGenerator()
{
var mock = new Mock<IValueTaskAsyncInterface>();
Action setup = () => mock
.Setup(x => x.RefParameterValueReturnType("test"))
.ReturnsAsync(5, TimeSpan.FromMilliseconds(1), TimeSpan.FromMilliseconds(2), null);
var paramName = Assert.Throws<ArgumentNullException>(setup).ParamName;
Assert.Equal("random", paramName);
}
[Fact]
public async Task ValueTaskThrowsWithDelay()
{
var mock = new Mock<IValueTaskAsyncInterface>();
mock
.Setup(x => x.RefParameterValueReturnType("test"))
.ThrowsAsync(new ArithmeticException("yikes"), TimeSpan.FromMilliseconds(1));
Func<ValueTask<int>> test = () => mock.Object.RefParameterValueReturnType("test");
var exception = await Assert.ThrowsAsync<ArithmeticException>(() => test().AsTask());
Assert.Equal("yikes", exception.Message);
}
[Fact]
public async Task ValueTaskThrowsWithRandomDelay()
{
var mock = new Mock<IValueTaskAsyncInterface>();
var minDelay = TimeSpan.FromMilliseconds(1);
var maxDelay = TimeSpan.FromMilliseconds(2);
mock
.Setup(x => x.RefParameterValueReturnType("test"))
.ThrowsAsync(new ArithmeticException("yikes"), minDelay, maxDelay);
Func<ValueTask<int>> test = () => mock.Object.RefParameterValueReturnType("test");
var exception = await Assert.ThrowsAsync<ArithmeticException>(() => test().AsTask());
Assert.Equal("yikes", exception.Message);
}
[Fact]
public async Task ValueTaskThrowsWithRandomDelayAndOwnRandomGenerator()
{
var mock = new Mock<IValueTaskAsyncInterface>();
var minDelay = TimeSpan.FromMilliseconds(1);
var maxDelay = TimeSpan.FromMilliseconds(2);
mock
.Setup(x => x.RefParameterValueReturnType("test"))
.ThrowsAsync(new ArithmeticException("yikes"), minDelay, maxDelay, new Random());
Func<ValueTask<int>> test = () => mock.Object.RefParameterValueReturnType("test");
var exception = await Assert.ThrowsAsync<ArithmeticException>(() => test().AsTask());
Assert.Equal("yikes", exception.Message);
}
[Fact]
public void ValueTaskThrowsAsyncWithNullRandomGenerator()
{
var mock = new Mock<IValueTaskAsyncInterface>();
Action setup = () =>
{
var anyException = new Exception();
var minDelay = TimeSpan.FromMilliseconds(1);
var maxDelay = TimeSpan.FromMilliseconds(2);
mock
.Setup(x => x.RefParameterValueReturnType("test"))
.ThrowsAsync(anyException, minDelay, maxDelay, null);
};
var paramName = Assert.Throws<ArgumentNullException>(setup).ParamName;
Assert.Equal("random", paramName);
}
[Fact]
public async void No_parameters_object_return_type__ReturnsAsync_null__returns_completed_Task_with_null_result()
{
var mock = new Mock<IAsyncInterface>();
mock.Setup(m => m.NoParametersObjectReturnType()).ReturnsAsync(null);
var result = await mock.Object.NoParametersObjectReturnType();
Assert.Null(result);
}
[Fact]
public async void One_parameter_object_return_type__ReturnsAsync_null__returns_completed_Task_with_null_result()
{
var mock = new Mock<IAsyncInterface>();
mock.Setup(m => m.OneParameterObjectReturnType("")).ReturnsAsync(null);
var result = await mock.Object.OneParameterObjectReturnType("");
Assert.Null(result);
}
[Fact]
public async void Many_parameters_object_return_type__ReturnsAsync_null__returns_completed_Task_with_null_result()
{
var mock = new Mock<IAsyncInterface>();
mock.Setup(m => m.ManyParametersObjectReturnType("", false, 0f)).ReturnsAsync(null);
var result = await mock.Object.ManyParametersObjectReturnType("", false, 0f);
Assert.Null(result);
}
[Fact]
public async void No_parameters_object_return_type__ReturnsAsync_null__returns_completed_ValueTask_with_null_result()
{
var mock = new Mock<IValueTaskAsyncInterface>();
mock.Setup(m => m.NoParametersObjectReturnType()).ReturnsAsync(null);
var result = await mock.Object.NoParametersObjectReturnType();
Assert.Null(result);
}
[Fact]
public async void One_parameter_object_return_type__ReturnsAsync_null__returns_completed_ValueTask_with_null_result()
{
var mock = new Mock<IValueTaskAsyncInterface>();
mock.Setup(m => m.OneParameterObjectReturnType("")).ReturnsAsync(null);
var result = await mock.Object.OneParameterObjectReturnType("");
Assert.Null(result);
}
[Fact]
public async void Many_parameters_object_return_type__ReturnsAsync_null__returns_completed_ValueTask_with_null_result()
{
var mock = new Mock<IValueTaskAsyncInterface>();
mock.Setup(m => m.ManyParametersObjectReturnType("", false, 0f)).ReturnsAsync(null);
var result = await mock.Object.ManyParametersObjectReturnType("", false, 0f);
Assert.Null(result);
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King; 2014 Extesla, LLC.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Security;
using OpenGamingLibrary.Json.Linq;
using OpenGamingLibrary.Json.Utilities;
using System.Runtime.Serialization;
#if NET20
using OpenGamingLibrary.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace OpenGamingLibrary.Json.Serialization
{
internal class JsonSerializerInternalWriter : JsonSerializerInternalBase
{
private JsonContract _rootContract;
private int _rootLevel;
private readonly List<object> _serializeStack = new List<object>();
private JsonSerializerProxy _internalSerializer;
public JsonSerializerInternalWriter(JsonSerializer serializer)
: base(serializer)
{
}
public void Serialize(JsonWriter jsonWriter, object value, Type objectType)
{
if (jsonWriter == null)
throw new ArgumentNullException("jsonWriter");
_rootContract = (objectType != null) ? Serializer._contractResolver.ResolveContract(objectType) : null;
_rootLevel = _serializeStack.Count + 1;
JsonContract contract = GetContractSafe(value);
try
{
SerializeValue(jsonWriter, value, contract, null, null, null);
}
catch (Exception ex)
{
if (IsErrorHandled(null, contract, null, null, jsonWriter.Path, ex))
{
HandleError(jsonWriter, 0);
}
else
{
// clear context in case serializer is being used inside a converter
// if the converter wraps the error then not clearing the context will cause this error:
// "Current error context error is different to requested error."
ClearErrorContext();
throw;
}
}
finally
{
// clear root contract to ensure that if level was > 1 then it won't
// accidently be used for non root values
_rootContract = null;
}
}
private JsonSerializerProxy GetInternalSerializer()
{
if (_internalSerializer == null)
_internalSerializer = new JsonSerializerProxy(this);
return _internalSerializer;
}
private JsonContract GetContractSafe(object value)
{
if (value == null)
return null;
return Serializer._contractResolver.ResolveContract(value.GetType());
}
private void SerializePrimitive(JsonWriter writer, object value, JsonPrimitiveContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
{
if (contract.TypeCode == PrimitiveTypeCode.Bytes)
{
// if type name handling is enabled then wrap the base64 byte string in an object with the type name
bool includeTypeDetails = ShouldWriteType(TypeNameHandling.Objects, contract, member, containerContract, containerProperty);
if (includeTypeDetails)
{
writer.WriteStartObject();
WriteTypeProperty(writer, contract.CreatedType);
writer.WritePropertyName(JsonTypeReflector.ValuePropertyName, false);
JsonWriter.WriteValue(writer, contract.TypeCode, value);
writer.WriteEndObject();
return;
}
}
JsonWriter.WriteValue(writer, contract.TypeCode, value);
}
private void SerializeValue(JsonWriter writer, object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
{
if (value == null)
{
writer.WriteNull();
return;
}
JsonConverter converter =
((member != null) ? member.Converter : null) ??
((containerProperty != null) ? containerProperty.ItemConverter : null) ??
((containerContract != null) ? containerContract.ItemConverter : null) ??
valueContract.Converter ??
Serializer.GetMatchingConverter(valueContract.UnderlyingType) ??
valueContract.InternalConverter;
if (converter != null && converter.CanWrite)
{
SerializeConvertable(writer, converter, value, valueContract, containerContract, containerProperty);
return;
}
switch (valueContract.ContractType)
{
case JsonContractType.Object:
SerializeObject(writer, value, (JsonObjectContract)valueContract, member, containerContract, containerProperty);
break;
case JsonContractType.Array:
JsonArrayContract arrayContract = (JsonArrayContract)valueContract;
if (!arrayContract.IsMultidimensionalArray)
SerializeList(writer, (IEnumerable)value, arrayContract, member, containerContract, containerProperty);
else
SerializeMultidimensionalArray(writer, (Array)value, arrayContract, member, containerContract, containerProperty);
break;
case JsonContractType.Primitive:
SerializePrimitive(writer, value, (JsonPrimitiveContract)valueContract, member, containerContract, containerProperty);
break;
case JsonContractType.String:
SerializeString(writer, value, (JsonStringContract)valueContract);
break;
case JsonContractType.Dictionary:
JsonDictionaryContract dictionaryContract = (JsonDictionaryContract)valueContract;
SerializeDictionary(writer, (value is IDictionary) ? (IDictionary)value : dictionaryContract.CreateWrapper(value), dictionaryContract, member, containerContract, containerProperty);
break;
case JsonContractType.Serializable:
SerializeISerializable(writer, (ISerializable)value, (JsonISerializableContract)valueContract, member, containerContract, containerProperty);
break;
case JsonContractType.Linq:
((JToken)value).WriteTo(writer, Serializer.Converters.ToArray());
break;
}
}
private bool? ResolveIsReference(JsonContract contract, JsonProperty property, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
bool? isReference = null;
// value could be coming from a dictionary or array and not have a property
if (property != null)
isReference = property.IsReference;
if (isReference == null && containerProperty != null)
isReference = containerProperty.ItemIsReference;
if (isReference == null && collectionContract != null)
isReference = collectionContract.ItemIsReference;
if (isReference == null)
isReference = contract.IsReference;
return isReference;
}
private bool ShouldWriteReference(object value, JsonProperty property, JsonContract valueContract, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
if (value == null)
return false;
if (valueContract.ContractType == JsonContractType.Primitive || valueContract.ContractType == JsonContractType.String)
return false;
bool? isReference = ResolveIsReference(valueContract, property, collectionContract, containerProperty);
if (isReference == null)
{
if (valueContract.ContractType == JsonContractType.Array)
isReference = HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Arrays);
else
isReference = HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Objects);
}
if (!isReference.Value)
return false;
return Serializer.GetReferenceResolver().IsReferenced(this, value);
}
private bool ShouldWriteProperty(object memberValue, JsonProperty property)
{
if (property.NullValueHandling.GetValueOrDefault(Serializer._nullValueHandling) == NullValueHandling.Ignore &&
memberValue == null)
return false;
if (HasFlag(property.DefaultValueHandling.GetValueOrDefault(Serializer._defaultValueHandling), DefaultValueHandling.Ignore)
&& MiscellaneousUtils.ValueEquals(memberValue, property.GetResolvedDefaultValue()))
return false;
return true;
}
private bool CheckForCircularReference(JsonWriter writer, object value, JsonProperty property, JsonContract contract, JsonContainerContract containerContract, JsonProperty containerProperty)
{
if (value == null || contract.ContractType == JsonContractType.Primitive || contract.ContractType == JsonContractType.String)
return true;
ReferenceLoopHandling? referenceLoopHandling = null;
if (property != null)
referenceLoopHandling = property.ReferenceLoopHandling;
if (referenceLoopHandling == null && containerProperty != null)
referenceLoopHandling = containerProperty.ItemReferenceLoopHandling;
if (referenceLoopHandling == null && containerContract != null)
referenceLoopHandling = containerContract.ItemReferenceLoopHandling;
if (_serializeStack.IndexOf(value) != -1)
{
string message = "Self referencing loop detected";
if (property != null)
message += " for property '{0}'".FormatWith(CultureInfo.InvariantCulture, property.PropertyName);
message += " with type '{0}'.".FormatWith(CultureInfo.InvariantCulture, value.GetType());
switch (referenceLoopHandling.GetValueOrDefault(Serializer._referenceLoopHandling))
{
case ReferenceLoopHandling.Error:
throw JsonSerializationException.Create(null, writer.ContainerPath, message, null);
case ReferenceLoopHandling.Ignore:
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, message + ". Skipping serializing self referenced value."), null);
return false;
case ReferenceLoopHandling.Serialize:
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, message + ". Serializing self referenced value."), null);
return true;
}
}
return true;
}
private void WriteReference(JsonWriter writer, object value)
{
string reference = GetReference(writer, value);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Writing object reference to Id '{0}' for {1}.".FormatWith(CultureInfo.InvariantCulture, reference, value.GetType())), null);
writer.WriteStartObject();
writer.WritePropertyName(JsonTypeReflector.RefPropertyName, false);
writer.WriteValue(reference);
writer.WriteEndObject();
}
private string GetReference(JsonWriter writer, object value)
{
try
{
string reference = Serializer.GetReferenceResolver().GetReference(this, value);
return reference;
}
catch (Exception ex)
{
throw JsonSerializationException.Create(null, writer.ContainerPath, "Error writing object reference for '{0}'.".FormatWith(CultureInfo.InvariantCulture, value.GetType()), ex);
}
}
internal static bool TryConvertToString(object value, Type type, out string s)
{
#if !(NETFX_CORE || PORTABLE40 || PORTABLE)
TypeConverter converter = ConvertUtils.GetConverter(type);
// use the objectType's TypeConverter if it has one and can convert to a string
if (converter != null
&& !(converter is ComponentConverter)
&& converter.GetType() != typeof(TypeConverter))
{
if (converter.CanConvertTo(typeof(string)))
{
s = converter.ConvertToInvariantString(value);
return true;
}
}
#endif
#if NETFX_CORE || PORTABLE
if (value is Guid || value is Uri || value is TimeSpan)
{
s = value.ToString();
return true;
}
#endif
if (value is Type)
{
s = ((Type)value).AssemblyQualifiedName;
return true;
}
s = null;
return false;
}
private void SerializeString(JsonWriter writer, object value, JsonStringContract contract)
{
OnSerializing(writer, contract, value);
string s;
TryConvertToString(value, contract.UnderlyingType, out s);
writer.WriteValue(s);
OnSerialized(writer, contract, value);
}
private void OnSerializing(JsonWriter writer, JsonContract contract, object value)
{
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Started serializing {0}".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)), null);
contract.InvokeOnSerializing(value, Serializer._context);
}
private void OnSerialized(JsonWriter writer, JsonContract contract, object value)
{
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Finished serializing {0}".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)), null);
contract.InvokeOnSerialized(value, Serializer._context);
}
private void SerializeObject(JsonWriter writer, object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
OnSerializing(writer, contract, value);
_serializeStack.Add(value);
WriteObjectStart(writer, value, contract, member, collectionContract, containerProperty);
int initialDepth = writer.Top;
for (int index = 0; index < contract.Properties.Count; index++)
{
JsonProperty property = contract.Properties[index];
try
{
object memberValue;
JsonContract memberContract;
if (!CalculatePropertyValues(writer, value, contract, member, property, out memberContract, out memberValue))
continue;
property.WritePropertyName(writer);
SerializeValue(writer, memberValue, memberContract, property, contract, member);
}
catch (Exception ex)
{
if (IsErrorHandled(value, contract, property.PropertyName, null, writer.ContainerPath, ex))
HandleError(writer, initialDepth);
else
throw;
}
}
if (contract.ExtensionDataGetter != null)
{
IEnumerable<KeyValuePair<object, object>> extensionData = contract.ExtensionDataGetter(value);
if (extensionData != null)
{
foreach (KeyValuePair<object, object> e in extensionData)
{
JsonContract keyContract = GetContractSafe(e.Key);
JsonContract valueContract = GetContractSafe(e.Value);
bool escape;
string propertyName = GetPropertyName(writer, e.Key, keyContract, out escape);
if (ShouldWriteReference(e.Value, null, valueContract, contract, member))
{
writer.WritePropertyName(propertyName);
WriteReference(writer, e.Value);
}
else
{
if (!CheckForCircularReference(writer, e.Value, null, valueContract, contract, member))
continue;
writer.WritePropertyName(propertyName);
SerializeValue(writer, e.Value, valueContract, null, contract, member);
}
}
}
}
writer.WriteEndObject();
_serializeStack.RemoveAt(_serializeStack.Count - 1);
OnSerialized(writer, contract, value);
}
private bool CalculatePropertyValues(JsonWriter writer, object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, out JsonContract memberContract, out object memberValue)
{
if (!property.Ignored && property.Readable && ShouldSerialize(writer, property, value) && IsSpecified(writer, property, value))
{
if (property.PropertyContract == null)
property.PropertyContract = Serializer._contractResolver.ResolveContract(property.PropertyType);
memberValue = property.ValueProvider.GetValue(value);
memberContract = (property.PropertyContract.IsSealed) ? property.PropertyContract : GetContractSafe(memberValue);
if (ShouldWriteProperty(memberValue, property))
{
if (ShouldWriteReference(memberValue, property, memberContract, contract, member))
{
property.WritePropertyName(writer);
WriteReference(writer, memberValue);
return false;
}
if (!CheckForCircularReference(writer, memberValue, property, memberContract, contract, member))
return false;
if (memberValue == null)
{
JsonObjectContract objectContract = contract as JsonObjectContract;
Required resolvedRequired = property._required ?? ((objectContract != null) ? objectContract.ItemRequired : null) ?? Required.Default;
if (resolvedRequired == Required.Always)
throw JsonSerializationException.Create(null, writer.ContainerPath, "Cannot write a null value for property '{0}'. Property requires a value.".FormatWith(CultureInfo.InvariantCulture, property.PropertyName), null);
}
return true;
}
}
memberContract = null;
memberValue = null;
return false;
}
private void WriteObjectStart(JsonWriter writer, object value, JsonContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
writer.WriteStartObject();
bool isReference = ResolveIsReference(contract, member, collectionContract, containerProperty) ?? HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Objects);
if (isReference)
{
WriteReferenceIdProperty(writer, contract.UnderlyingType, value);
}
if (ShouldWriteType(TypeNameHandling.Objects, contract, member, collectionContract, containerProperty))
{
WriteTypeProperty(writer, contract.UnderlyingType);
}
}
private void WriteReferenceIdProperty(JsonWriter writer, Type type, object value)
{
string reference = GetReference(writer, value);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "Writing object reference Id '{0}' for {1}.".FormatWith(CultureInfo.InvariantCulture, reference, type)), null);
writer.WritePropertyName(JsonTypeReflector.IdPropertyName, false);
writer.WriteValue(reference);
}
private void WriteTypeProperty(JsonWriter writer, Type type)
{
string typeName = ReflectionUtils.GetTypeName(type, Serializer._typeNameAssemblyFormat, Serializer._binder);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "Writing type name '{0}' for {1}.".FormatWith(CultureInfo.InvariantCulture, typeName, type)), null);
writer.WritePropertyName(JsonTypeReflector.TypePropertyName, false);
writer.WriteValue(typeName);
}
private bool HasFlag(DefaultValueHandling value, DefaultValueHandling flag)
{
return ((value & flag) == flag);
}
private bool HasFlag(PreserveReferencesHandling value, PreserveReferencesHandling flag)
{
return ((value & flag) == flag);
}
private bool HasFlag(TypeNameHandling value, TypeNameHandling flag)
{
return ((value & flag) == flag);
}
private void SerializeConvertable(JsonWriter writer, JsonConverter converter, object value, JsonContract contract, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
if (ShouldWriteReference(value, null, contract, collectionContract, containerProperty))
{
WriteReference(writer, value);
}
else
{
if (!CheckForCircularReference(writer, value, null, contract, collectionContract, containerProperty))
return;
_serializeStack.Add(value);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Started serializing {0} with converter {1}.".FormatWith(CultureInfo.InvariantCulture, value.GetType(), converter.GetType())), null);
converter.WriteJson(writer, value, GetInternalSerializer());
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Finished serializing {0} with converter {1}.".FormatWith(CultureInfo.InvariantCulture, value.GetType(), converter.GetType())), null);
_serializeStack.RemoveAt(_serializeStack.Count - 1);
}
}
private void SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
IWrappedCollection wrappedCollection = values as IWrappedCollection;
object underlyingList = wrappedCollection != null ? wrappedCollection.UnderlyingCollection : values;
OnSerializing(writer, contract, underlyingList);
_serializeStack.Add(underlyingList);
bool hasWrittenMetadataObject = WriteStartArray(writer, underlyingList, contract, member, collectionContract, containerProperty);
writer.WriteStartArray();
int initialDepth = writer.Top;
int index = 0;
// note that an error in the IEnumerable won't be caught
foreach (object value in values)
{
try
{
JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value);
if (ShouldWriteReference(value, null, valueContract, contract, member))
{
WriteReference(writer, value);
}
else
{
if (CheckForCircularReference(writer, value, null, valueContract, contract, member))
{
SerializeValue(writer, value, valueContract, null, contract, member);
}
}
}
catch (Exception ex)
{
if (IsErrorHandled(underlyingList, contract, index, null, writer.ContainerPath, ex))
HandleError(writer, initialDepth);
else
throw;
}
finally
{
index++;
}
}
writer.WriteEndArray();
if (hasWrittenMetadataObject)
writer.WriteEndObject();
_serializeStack.RemoveAt(_serializeStack.Count - 1);
OnSerialized(writer, contract, underlyingList);
}
private void SerializeMultidimensionalArray(JsonWriter writer, Array values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
OnSerializing(writer, contract, values);
_serializeStack.Add(values);
bool hasWrittenMetadataObject = WriteStartArray(writer, values, contract, member, collectionContract, containerProperty);
SerializeMultidimensionalArray(writer, values, contract, member, writer.Top, new int[0]);
if (hasWrittenMetadataObject)
writer.WriteEndObject();
_serializeStack.RemoveAt(_serializeStack.Count - 1);
OnSerialized(writer, contract, values);
}
private void SerializeMultidimensionalArray(JsonWriter writer, Array values, JsonArrayContract contract, JsonProperty member, int initialDepth, int[] indices)
{
int dimension = indices.Length;
int[] newIndices = new int[dimension + 1];
for (int i = 0; i < dimension; i++)
{
newIndices[i] = indices[i];
}
writer.WriteStartArray();
for (int i = 0; i < values.GetLength(dimension); i++)
{
newIndices[dimension] = i;
bool isTopLevel = (newIndices.Length == values.Rank);
if (isTopLevel)
{
object value = values.GetValue(newIndices);
try
{
JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value);
if (ShouldWriteReference(value, null, valueContract, contract, member))
{
WriteReference(writer, value);
}
else
{
if (CheckForCircularReference(writer, value, null, valueContract, contract, member))
{
SerializeValue(writer, value, valueContract, null, contract, member);
}
}
}
catch (Exception ex)
{
if (IsErrorHandled(values, contract, i, null, writer.ContainerPath, ex))
HandleError(writer, initialDepth + 1);
else
throw;
}
}
else
{
SerializeMultidimensionalArray(writer, values, contract, member, initialDepth + 1, newIndices);
}
}
writer.WriteEndArray();
}
private bool WriteStartArray(JsonWriter writer, object values, JsonArrayContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
{
bool isReference = ResolveIsReference(contract, member, containerContract, containerProperty) ?? HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Arrays);
bool includeTypeDetails = ShouldWriteType(TypeNameHandling.Arrays, contract, member, containerContract, containerProperty);
bool writeMetadataObject = isReference || includeTypeDetails;
if (writeMetadataObject)
{
writer.WriteStartObject();
if (isReference)
{
WriteReferenceIdProperty(writer, contract.UnderlyingType, values);
}
if (includeTypeDetails)
{
WriteTypeProperty(writer, values.GetType());
}
writer.WritePropertyName(JsonTypeReflector.ArrayValuesPropertyName, false);
}
if (contract.ItemContract == null)
contract.ItemContract = Serializer._contractResolver.ResolveContract(contract.CollectionItemType ?? typeof(object));
return writeMetadataObject;
}
private void SerializeISerializable(JsonWriter writer, ISerializable value, JsonISerializableContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
if (!JsonTypeReflector.FullyTrusted)
{
throw JsonSerializationException.Create(null, writer.ContainerPath, @"Type '{0}' implements ISerializable but cannot be serialized using the ISerializable interface because the current application is not fully trusted and ISerializable can expose secure data.
To fix this error either change the environment to be fully trusted, change the application to not deserialize the type, add JsonObjectAttribute to the type or change the JsonSerializer setting ContractResolver to use a new DefaultContractResolver with IgnoreSerializableInterface set to true.".FormatWith(CultureInfo.InvariantCulture, value.GetType()), null);
}
OnSerializing(writer, contract, value);
_serializeStack.Add(value);
WriteObjectStart(writer, value, contract, member, collectionContract, containerProperty);
SerializationInfo serializationInfo = new SerializationInfo(contract.UnderlyingType, new FormatterConverter());
value.GetObjectData(serializationInfo, Serializer._context);
foreach (SerializationEntry serializationEntry in serializationInfo)
{
JsonContract valueContract = GetContractSafe(serializationEntry.Value);
if (CheckForCircularReference(writer, serializationEntry.Value, null, valueContract, contract, member))
{
writer.WritePropertyName(serializationEntry.Name);
SerializeValue(writer, serializationEntry.Value, valueContract, null, contract, member);
}
}
writer.WriteEndObject();
_serializeStack.RemoveAt(_serializeStack.Count - 1);
OnSerialized(writer, contract, value);
}
private bool ShouldWriteDynamicProperty(object memberValue)
{
if (Serializer._nullValueHandling == NullValueHandling.Ignore && memberValue == null)
return false;
if (HasFlag(Serializer._defaultValueHandling, DefaultValueHandling.Ignore) &&
(memberValue == null || MiscellaneousUtils.ValueEquals(memberValue, ReflectionUtils.GetDefaultValue(memberValue.GetType()))))
return false;
return true;
}
private bool ShouldWriteType(TypeNameHandling typeNameHandlingFlag, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
{
TypeNameHandling resolvedTypeNameHandling =
((member != null) ? member.TypeNameHandling : null)
?? ((containerProperty != null) ? containerProperty.ItemTypeNameHandling : null)
?? ((containerContract != null) ? containerContract.ItemTypeNameHandling : null)
?? Serializer._typeNameHandling;
if (HasFlag(resolvedTypeNameHandling, typeNameHandlingFlag))
return true;
// instance type and the property's type's contract default type are different (no need to put the type in JSON because the type will be created by default)
if (HasFlag(resolvedTypeNameHandling, TypeNameHandling.Auto))
{
if (member != null)
{
if (contract.UnderlyingType != member.PropertyContract.CreatedType)
return true;
}
else if (containerContract != null)
{
if (containerContract.ItemContract == null || contract.UnderlyingType != containerContract.ItemContract.CreatedType)
return true;
}
else if (_rootContract != null && _serializeStack.Count == _rootLevel)
{
if (contract.UnderlyingType != _rootContract.CreatedType)
return true;
}
}
return false;
}
private void SerializeDictionary(JsonWriter writer, IDictionary values, JsonDictionaryContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
IWrappedDictionary wrappedDictionary = values as IWrappedDictionary;
object underlyingDictionary = wrappedDictionary != null ? wrappedDictionary.UnderlyingDictionary : values;
OnSerializing(writer, contract, underlyingDictionary);
_serializeStack.Add(underlyingDictionary);
WriteObjectStart(writer, underlyingDictionary, contract, member, collectionContract, containerProperty);
if (contract.ItemContract == null)
contract.ItemContract = Serializer._contractResolver.ResolveContract(contract.DictionaryValueType ?? typeof(object));
if (contract.KeyContract == null)
contract.KeyContract = Serializer._contractResolver.ResolveContract(contract.DictionaryKeyType ?? typeof(object));
int initialDepth = writer.Top;
foreach (DictionaryEntry entry in values)
{
bool escape;
string propertyName = GetPropertyName(writer, entry.Key, contract.KeyContract, out escape);
propertyName = (contract.PropertyNameResolver != null)
? contract.PropertyNameResolver(propertyName)
: propertyName;
try
{
object value = entry.Value;
JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value);
if (ShouldWriteReference(value, null, valueContract, contract, member))
{
writer.WritePropertyName(propertyName, escape);
WriteReference(writer, value);
}
else
{
if (!CheckForCircularReference(writer, value, null, valueContract, contract, member))
continue;
writer.WritePropertyName(propertyName, escape);
SerializeValue(writer, value, valueContract, null, contract, member);
}
}
catch (Exception ex)
{
if (IsErrorHandled(underlyingDictionary, contract, propertyName, null, writer.ContainerPath, ex))
HandleError(writer, initialDepth);
else
throw;
}
}
writer.WriteEndObject();
_serializeStack.RemoveAt(_serializeStack.Count - 1);
OnSerialized(writer, contract, underlyingDictionary);
}
private string GetPropertyName(JsonWriter writer, object name, JsonContract contract, out bool escape)
{
string propertyName;
if (contract.ContractType == JsonContractType.Primitive)
{
JsonPrimitiveContract primitiveContract = (JsonPrimitiveContract)contract;
if (primitiveContract.TypeCode == PrimitiveTypeCode.DateTime || primitiveContract.TypeCode == PrimitiveTypeCode.DateTimeNullable)
{
escape = false;
StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
DateTimeUtils.WriteDateTimeString(sw, (DateTime)name, writer.DateFormatHandling, writer.DateFormatString, writer.Culture);
return sw.ToString();
}
#if !NET20
else if (primitiveContract.TypeCode == PrimitiveTypeCode.DateTimeOffset || primitiveContract.TypeCode == PrimitiveTypeCode.DateTimeOffsetNullable)
{
escape = false;
StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
DateTimeUtils.WriteDateTimeOffsetString(sw, (DateTimeOffset)name, writer.DateFormatHandling, writer.DateFormatString, writer.Culture);
return sw.ToString();
}
#endif
else
{
escape = true;
return Convert.ToString(name, CultureInfo.InvariantCulture);
}
}
else if (TryConvertToString(name, name.GetType(), out propertyName))
{
escape = true;
return propertyName;
}
else
{
escape = true;
return name.ToString();
}
}
private void HandleError(JsonWriter writer, int initialDepth)
{
ClearErrorContext();
if (writer.WriteState == WriteState.Property)
writer.WriteNull();
while (writer.Top > initialDepth)
{
writer.WriteEnd();
}
}
private bool ShouldSerialize(JsonWriter writer, JsonProperty property, object target)
{
if (property.ShouldSerialize == null)
return true;
bool shouldSerialize = property.ShouldSerialize(target);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "ShouldSerialize result for property '{0}' on {1}: {2}".FormatWith(CultureInfo.InvariantCulture, property.PropertyName, property.DeclaringType, shouldSerialize)), null);
return shouldSerialize;
}
private bool IsSpecified(JsonWriter writer, JsonProperty property, object target)
{
if (property.GetIsSpecified == null)
return true;
bool isSpecified = property.GetIsSpecified(target);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "IsSpecified result for property '{0}' on {1}: {2}".FormatWith(CultureInfo.InvariantCulture, property.PropertyName, property.DeclaringType, isSpecified)), null);
return isSpecified;
}
}
}
| |
//---------------------------------------------------------------------------
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
//---------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows;
using System.Windows.Automation.Peers;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Automation;
using MS.Internal;
namespace System.Windows.Controls.Primitives
{
/// <summary>
/// Container for the Column header object. This is instantiated by the DataGridColumnHeadersPresenter.
/// </summary>
[TemplatePart(Name = "PART_LeftHeaderGripper", Type = typeof(Thumb))]
[TemplatePart(Name = "PART_RightHeaderGripper", Type = typeof(Thumb))]
public class DataGridColumnHeader : ButtonBase, IProvideDataGridColumn
{
#region Constructors
static DataGridColumnHeader()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(DataGridColumnHeader), new FrameworkPropertyMetadata(typeof(DataGridColumnHeader)));
ContentProperty.OverrideMetadata(typeof(DataGridColumnHeader), new FrameworkPropertyMetadata(OnNotifyPropertyChanged, OnCoerceContent));
ContentTemplateProperty.OverrideMetadata(typeof(DataGridColumnHeader), new FrameworkPropertyMetadata(null, OnNotifyPropertyChanged, OnCoerceContentTemplate));
ContentTemplateSelectorProperty.OverrideMetadata(typeof(DataGridColumnHeader), new FrameworkPropertyMetadata(null, OnNotifyPropertyChanged, OnCoerceContentTemplateSelector));
ContentStringFormatProperty.OverrideMetadata(typeof(DataGridColumnHeader), new FrameworkPropertyMetadata(null, OnNotifyPropertyChanged, OnCoerceStringFormat));
StyleProperty.OverrideMetadata(typeof(DataGridColumnHeader), new FrameworkPropertyMetadata(null, OnNotifyPropertyChanged, OnCoerceStyle));
HeightProperty.OverrideMetadata(typeof(DataGridColumnHeader), new FrameworkPropertyMetadata(OnNotifyPropertyChanged, OnCoerceHeight));
FocusableProperty.OverrideMetadata(typeof(DataGridColumnHeader), new FrameworkPropertyMetadata(false));
ClipProperty.OverrideMetadata(typeof(DataGridColumnHeader), new FrameworkPropertyMetadata(null, OnCoerceClip));
AutomationProperties.IsOffscreenBehaviorProperty.OverrideMetadata(typeof(DataGridColumnHeader), new FrameworkPropertyMetadata(IsOffscreenBehavior.FromClip));
}
/// <summary>
/// Instantiates a new instance of this class.
/// </summary>
public DataGridColumnHeader()
{
_tracker = new ContainerTracking<DataGridColumnHeader>(this);
}
#endregion
#region Public API
/// <summary>
/// The Column associated with this DataGridColumnHeader.
/// </summary>
public DataGridColumn Column
{
get
{
return _column;
}
}
/// <summary>
/// Property that indicates the brush to use when drawing seperators between headers.
/// </summary>
public Brush SeparatorBrush
{
get { return (Brush)GetValue(SeparatorBrushProperty); }
set { SetValue(SeparatorBrushProperty, value); }
}
/// <summary>
/// DependencyProperty for SeperatorBrush.
/// </summary>
public static readonly DependencyProperty SeparatorBrushProperty =
DependencyProperty.Register("SeparatorBrush", typeof(Brush), typeof(DataGridColumnHeader), new FrameworkPropertyMetadata(null));
/// <summary>
/// Property that indicates the Visibility for the header seperators.
/// </summary>
public Visibility SeparatorVisibility
{
get { return (Visibility)GetValue(SeparatorVisibilityProperty); }
set { SetValue(SeparatorVisibilityProperty, value); }
}
/// <summary>
/// DependencyProperty for SeperatorBrush.
/// </summary>
public static readonly DependencyProperty SeparatorVisibilityProperty =
DependencyProperty.Register("SeparatorVisibility", typeof(Visibility), typeof(DataGridColumnHeader), new FrameworkPropertyMetadata(Visibility.Visible));
#endregion
#region Column Header Generation
/// <summary>
/// Prepares a column header to be used. Sets up the association between the column header and its column.
/// </summary>
internal void PrepareColumnHeader(object item, DataGridColumn column)
{
Debug.Assert(column != null, "This header must have been generated with for a particular column");
Debug.Assert(column.Header == item, "The data item for a ColumnHeader is the Header property of a column");
_column = column;
TabIndex = column.DisplayIndex;
DataGridHelper.TransferProperty(this, ContentProperty);
DataGridHelper.TransferProperty(this, ContentTemplateProperty);
DataGridHelper.TransferProperty(this, ContentTemplateSelectorProperty);
DataGridHelper.TransferProperty(this, ContentStringFormatProperty);
DataGridHelper.TransferProperty(this, StyleProperty);
DataGridHelper.TransferProperty(this, HeightProperty);
CoerceValue(CanUserSortProperty);
CoerceValue(SortDirectionProperty);
CoerceValue(IsFrozenProperty);
CoerceValue(ClipProperty);
CoerceValue(DisplayIndexProperty);
}
internal void ClearHeader()
{
_column = null;
}
/// <summary>
/// Used by the DataGridRowGenerator owner to send notifications to the cell container.
/// </summary>
internal ContainerTracking<DataGridColumnHeader> Tracker
{
get { return _tracker; }
}
#endregion
#region Resize Gripper
/// <summary>
/// DependencyPropertyKey for DisplayIndex property
/// </summary>
private static readonly DependencyPropertyKey DisplayIndexPropertyKey =
DependencyProperty.RegisterReadOnly(
"DisplayIndex",
typeof(int),
typeof(DataGridColumnHeader),
new FrameworkPropertyMetadata(-1, new PropertyChangedCallback(OnDisplayIndexChanged), new CoerceValueCallback(OnCoerceDisplayIndex)));
/// <summary>
/// The DependencyProperty for the DisplayIndex property.
/// </summary>
public static readonly DependencyProperty DisplayIndexProperty = DisplayIndexPropertyKey.DependencyProperty;
/// <summary>
/// The property which represents the displayindex of the column corresponding to this header
/// </summary>
public int DisplayIndex
{
get { return (int)GetValue(DisplayIndexProperty); }
}
/// <summary>
/// Coercion callback for DisplayIndex property
/// </summary>
private static object OnCoerceDisplayIndex(DependencyObject d, object baseValue)
{
DataGridColumnHeader header = (DataGridColumnHeader)d;
DataGridColumn column = header.Column;
if (column != null)
{
return column.DisplayIndex;
}
return -1;
}
/// <summary>
/// Property changed call back for DisplayIndex property.
/// Sets the visibility of resize grippers accordingly
/// </summary>
/// <param name="d"></param>
/// <param name="e"></param>
private static void OnDisplayIndexChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
DataGridColumnHeader header = (DataGridColumnHeader)d;
DataGridColumn column = header.Column;
if (column != null)
{
DataGrid dataGrid = column.DataGridOwner;
if (dataGrid != null)
{
header.SetLeftGripperVisibility();
DataGridColumnHeader nextColumnHeader = dataGrid.ColumnHeaderFromDisplayIndex(header.DisplayIndex + 1);
if (nextColumnHeader != null)
{
nextColumnHeader.SetLeftGripperVisibility(column.CanUserResize);
}
}
}
}
/// <summary>
/// Override for <see cref="System.Windows.FrameworkElement.OnApplyTemplate">FrameworkElement.OnApplyTemplate</see>
/// </summary>
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
HookupGripperEvents();
}
/// <summary>
/// Find grippers and register drag events
///
/// The default style for DataGridHeader is
/// +-------------------------------+
/// +---------+ +---------+
/// + Gripper + Header + Gripper +
/// + + + +
/// +---------+ +---------+
/// +-------------------------------+
///
/// The reason we have two grippers is we can't extend the right gripper to straddle the line between two
/// headers; the header to the right would render on top of it.
/// We resize a column by grabbing the gripper to the right; the leftmost gripper thus adjusts the width of
/// the column to its left.
/// </summary>
private void HookupGripperEvents()
{
UnhookGripperEvents();
_leftGripper = GetTemplateChild(LeftHeaderGripperTemplateName) as Thumb;
_rightGripper = GetTemplateChild(RightHeaderGripperTemplateName) as Thumb;
if (_leftGripper != null)
{
_leftGripper.DragStarted += new DragStartedEventHandler(OnColumnHeaderGripperDragStarted);
_leftGripper.DragDelta += new DragDeltaEventHandler(OnColumnHeaderResize);
_leftGripper.DragCompleted += new DragCompletedEventHandler(OnColumnHeaderGripperDragCompleted);
_leftGripper.MouseDoubleClick += new MouseButtonEventHandler(OnGripperDoubleClicked);
SetLeftGripperVisibility();
}
if (_rightGripper != null)
{
_rightGripper.DragStarted += new DragStartedEventHandler(OnColumnHeaderGripperDragStarted);
_rightGripper.DragDelta += new DragDeltaEventHandler(OnColumnHeaderResize);
_rightGripper.DragCompleted += new DragCompletedEventHandler(OnColumnHeaderGripperDragCompleted);
_rightGripper.MouseDoubleClick += new MouseButtonEventHandler(OnGripperDoubleClicked);
SetRightGripperVisibility();
}
}
/// <summary>
/// Clear gripper event
/// </summary>
private void UnhookGripperEvents()
{
if (_leftGripper != null)
{
_leftGripper.DragStarted -= new DragStartedEventHandler(OnColumnHeaderGripperDragStarted);
_leftGripper.DragDelta -= new DragDeltaEventHandler(OnColumnHeaderResize);
_leftGripper.DragCompleted -= new DragCompletedEventHandler(OnColumnHeaderGripperDragCompleted);
_leftGripper.MouseDoubleClick -= new MouseButtonEventHandler(OnGripperDoubleClicked);
_leftGripper = null;
}
if (_rightGripper != null)
{
_rightGripper.DragStarted -= new DragStartedEventHandler(OnColumnHeaderGripperDragStarted);
_rightGripper.DragDelta -= new DragDeltaEventHandler(OnColumnHeaderResize);
_rightGripper.DragCompleted -= new DragCompletedEventHandler(OnColumnHeaderGripperDragCompleted);
_rightGripper.MouseDoubleClick -= new MouseButtonEventHandler(OnGripperDoubleClicked);
_rightGripper = null;
}
}
/// <summary>
/// Returns either this header or the one before it depending on which Gripper fired the event.
/// </summary>
/// <param name="sender"></param>
private DataGridColumnHeader HeaderToResize(object gripper)
{
return (gripper == _rightGripper) ? this : PreviousVisibleHeader;
}
// Save the original widths before header resize
private void OnColumnHeaderGripperDragStarted(object sender, DragStartedEventArgs e)
{
DataGridColumnHeader header = HeaderToResize(sender);
if (header != null)
{
if (header.Column != null)
{
DataGrid dataGrid = header.Column.DataGridOwner;
if (dataGrid != null)
{
dataGrid.InternalColumns.OnColumnResizeStarted();
}
}
e.Handled = true;
}
}
private void OnColumnHeaderResize(object sender, DragDeltaEventArgs e)
{
DataGridColumnHeader header = HeaderToResize(sender);
if (header != null)
{
RecomputeColumnWidthsOnColumnResize(header, e.HorizontalChange);
e.Handled = true;
}
}
/// <summary>
/// Method which recomputes the widths of columns on resize of a header
/// </summary>
private static void RecomputeColumnWidthsOnColumnResize(DataGridColumnHeader header, double horizontalChange)
{
Debug.Assert(header != null, "Header should not be null");
DataGridColumn resizingColumn = header.Column;
if (resizingColumn == null)
{
return;
}
DataGrid dataGrid = resizingColumn.DataGridOwner;
if (dataGrid == null)
{
return;
}
dataGrid.InternalColumns.RecomputeColumnWidthsOnColumnResize(resizingColumn, horizontalChange, false);
}
private void OnColumnHeaderGripperDragCompleted(object sender, DragCompletedEventArgs e)
{
DataGridColumnHeader header = HeaderToResize(sender);
if (header != null)
{
if (header.Column != null)
{
DataGrid dataGrid = header.Column.DataGridOwner;
if (dataGrid != null)
{
dataGrid.InternalColumns.OnColumnResizeCompleted(e.Canceled);
}
}
e.Handled = true;
}
}
private void OnGripperDoubleClicked(object sender, MouseButtonEventArgs e)
{
DataGridColumnHeader header = HeaderToResize(sender);
if (header != null && header.Column != null)
{
// DataGridLength is a struct, so setting to Auto resets desired and display widths to 0.0.
header.Column.Width = DataGridLength.Auto;
e.Handled = true;
}
}
private DataGridLength ColumnWidth
{
get { return Column != null ? Column.Width : DataGridLength.Auto; }
}
private double ColumnActualWidth
{
get { return Column != null ? Column.ActualWidth : ActualWidth; }
}
#endregion
#region Property Change Notification Propagation
/// <summary>
/// Notifies the Header of a property change.
/// </summary>
private static void OnNotifyPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((DataGridColumnHeader)d).NotifyPropertyChanged(d, e);
}
/// <summary>
/// Notification for column header-related DependencyProperty changes from the grid or from columns.
/// </summary>
internal void NotifyPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
DataGridColumn column = d as DataGridColumn;
if ((column != null) && (column != Column))
{
// This notification does not apply to this column header
return;
}
if (e.Property == DataGridColumn.WidthProperty)
{
DataGridHelper.OnColumnWidthChanged(this, e);
}
else if (e.Property == DataGridColumn.HeaderProperty || e.Property == ContentProperty)
{
DataGridHelper.TransferProperty(this, ContentProperty);
}
else if (e.Property == DataGridColumn.HeaderTemplateProperty || e.Property == ContentTemplateProperty)
{
DataGridHelper.TransferProperty(this, ContentTemplateProperty);
}
else if (e.Property == DataGridColumn.HeaderTemplateSelectorProperty || e.Property == ContentTemplateSelectorProperty)
{
DataGridHelper.TransferProperty(this, ContentTemplateSelectorProperty);
}
else if (e.Property == DataGridColumn.HeaderStringFormatProperty || e.Property == ContentStringFormatProperty)
{
DataGridHelper.TransferProperty(this, ContentStringFormatProperty);
}
else if (e.Property == DataGrid.ColumnHeaderStyleProperty || e.Property == DataGridColumn.HeaderStyleProperty || e.Property == StyleProperty)
{
DataGridHelper.TransferProperty(this, StyleProperty);
}
else if (e.Property == DataGrid.ColumnHeaderHeightProperty || e.Property == HeightProperty)
{
DataGridHelper.TransferProperty(this, HeightProperty);
}
else if (e.Property == DataGridColumn.DisplayIndexProperty)
{
CoerceValue(DisplayIndexProperty);
TabIndex = column.DisplayIndex;
}
else if (e.Property == DataGrid.CanUserResizeColumnsProperty)
{
OnCanUserResizeColumnsChanged();
}
else if (e.Property == DataGridColumn.CanUserSortProperty)
{
CoerceValue(CanUserSortProperty);
}
else if (e.Property == DataGridColumn.SortDirectionProperty)
{
CoerceValue(SortDirectionProperty);
}
else if (e.Property == DataGridColumn.IsFrozenProperty)
{
CoerceValue(IsFrozenProperty);
}
else if (e.Property == DataGridColumn.CanUserResizeProperty)
{
OnCanUserResizeChanged();
}
else if (e.Property == DataGridColumn.VisibilityProperty)
{
OnColumnVisibilityChanged(e);
}
}
private void OnCanUserResizeColumnsChanged()
{
Debug.Assert(Column != null, "column can't be null if we got a notification for this property change");
if (Column.DataGridOwner != null)
{
SetLeftGripperVisibility();
SetRightGripperVisibility();
}
}
private void OnCanUserResizeChanged()
{
Debug.Assert(Column != null, "column can't be null if we got a notification for this property change");
DataGrid dataGrid = Column.DataGridOwner;
if (dataGrid != null)
{
SetNextHeaderLeftGripperVisibility(Column.CanUserResize);
SetRightGripperVisibility();
}
}
private void SetLeftGripperVisibility()
{
if (_leftGripper == null || Column == null)
{
return;
}
DataGrid dataGridOwner = Column.DataGridOwner;
bool canPrevColumnResize = false;
for (int index = DisplayIndex - 1; index >= 0; index--)
{
DataGridColumn column = dataGridOwner.ColumnFromDisplayIndex(index);
if (column.IsVisible)
{
canPrevColumnResize = column.CanUserResize;
break;
}
}
SetLeftGripperVisibility(canPrevColumnResize);
}
private void SetLeftGripperVisibility(bool canPreviousColumnResize)
{
if (_leftGripper == null || Column == null)
{
return;
}
DataGrid dataGrid = Column.DataGridOwner;
if (dataGrid != null && dataGrid.CanUserResizeColumns && canPreviousColumnResize)
{
_leftGripper.Visibility = Visibility.Visible;
}
else
{
_leftGripper.Visibility = Visibility.Collapsed;
}
}
private void SetRightGripperVisibility()
{
if (_rightGripper == null || Column == null)
{
return;
}
DataGrid dataGrid = Column.DataGridOwner;
if (dataGrid != null && dataGrid.CanUserResizeColumns && Column.CanUserResize)
{
_rightGripper.Visibility = Visibility.Visible;
}
else
{
_rightGripper.Visibility = Visibility.Collapsed;
}
}
private void SetNextHeaderLeftGripperVisibility(bool canUserResize)
{
DataGrid dataGrid = Column.DataGridOwner;
int columnCount = dataGrid.Columns.Count;
for (int index = DisplayIndex + 1; index < columnCount; index++)
{
if (dataGrid.ColumnFromDisplayIndex(index).IsVisible)
{
DataGridColumnHeader nextHeader = dataGrid.ColumnHeaderFromDisplayIndex(index);
if (nextHeader != null)
{
nextHeader.SetLeftGripperVisibility(canUserResize);
}
break;
}
}
}
private void OnColumnVisibilityChanged(DependencyPropertyChangedEventArgs e)
{
Debug.Assert(Column != null, "column can't be null if we got a notification for this property change");
DataGrid dataGrid = Column.DataGridOwner;
if (dataGrid != null)
{
bool oldIsVisible = (((Visibility)e.OldValue) == Visibility.Visible);
bool newIsVisible = (((Visibility)e.NewValue) == Visibility.Visible);
if (oldIsVisible != newIsVisible)
{
if (newIsVisible)
{
SetLeftGripperVisibility();
SetRightGripperVisibility();
SetNextHeaderLeftGripperVisibility(Column.CanUserResize);
}
else
{
bool canPrevColumnResize = false;
for (int index = DisplayIndex - 1; index >= 0; index--)
{
DataGridColumn column = dataGrid.ColumnFromDisplayIndex(index);
if (column.IsVisible)
{
canPrevColumnResize = column.CanUserResize;
break;
}
}
SetNextHeaderLeftGripperVisibility(canPrevColumnResize);
}
}
}
}
#endregion
#region Style and Template Coercion callbacks
/// <summary>
/// Coerces the Content property. We're choosing a value between Column.Header and the Content property on ColumnHeader.
/// </summary>
private static object OnCoerceContent(DependencyObject d, object baseValue)
{
var header = d as DataGridColumnHeader;
object content = DataGridHelper.GetCoercedTransferPropertyValue(
header,
baseValue,
ContentProperty,
header.Column,
DataGridColumn.HeaderProperty);
// if content is a WPF element with a logical parent, disconnect it now
// so that it can be connected to the DGColumnHeader. This happens during
// a theme change - see Dev11 146729.
FrameworkObject fo = new FrameworkObject(content as DependencyObject);
if (fo.Parent != null && fo.Parent != header)
{
fo.ChangeLogicalParent(null);
}
return content;
}
/// <summary>
/// Coerces the ContentTemplate property based on the templates defined on the Column.
/// </summary>
private static object OnCoerceContentTemplate(DependencyObject d, object baseValue)
{
var columnHeader = d as DataGridColumnHeader;
return DataGridHelper.GetCoercedTransferPropertyValue(
columnHeader,
baseValue,
ContentTemplateProperty,
columnHeader.Column,
DataGridColumn.HeaderTemplateProperty);
}
/// <summary>
/// Coerces the ContentTemplateSelector property based on the selector defined on the Column.
/// </summary>
private static object OnCoerceContentTemplateSelector(DependencyObject d, object baseValue)
{
var columnHeader = d as DataGridColumnHeader;
return DataGridHelper.GetCoercedTransferPropertyValue(
columnHeader,
baseValue,
ContentTemplateSelectorProperty,
columnHeader.Column,
DataGridColumn.HeaderTemplateSelectorProperty);
}
/// <summary>
/// Coerces the ContentStringFormat property based on the templates defined on the Column.
/// </summary>
private static object OnCoerceStringFormat(DependencyObject d, object baseValue)
{
var columnHeader = d as DataGridColumnHeader;
return DataGridHelper.GetCoercedTransferPropertyValue(
columnHeader,
baseValue,
ContentStringFormatProperty,
columnHeader.Column,
DataGridColumn.HeaderStringFormatProperty);
}
/// <summary>
/// Coerces the Style property based on the templates defined on the Column or DataGrid.
/// </summary>
private static object OnCoerceStyle(DependencyObject d, object baseValue)
{
var columnHeader = (DataGridColumnHeader)d;
DataGridColumn column = columnHeader.Column;
DataGrid dataGrid = null;
// Propagate style changes to any filler column headers.
if (column == null)
{
DataGridColumnHeadersPresenter presenter = columnHeader.TemplatedParent as DataGridColumnHeadersPresenter;
if (presenter != null)
{
dataGrid = presenter.ParentDataGrid;
}
}
else
{
dataGrid = column.DataGridOwner;
}
return DataGridHelper.GetCoercedTransferPropertyValue(
columnHeader,
baseValue,
StyleProperty,
column,
DataGridColumn.HeaderStyleProperty,
dataGrid,
DataGrid.ColumnHeaderStyleProperty);
}
#endregion
#region Auto Sort
/// <summary>
/// DependencyPropertyKey for CanUserSort property
/// </summary>
private static readonly DependencyPropertyKey CanUserSortPropertyKey =
DependencyProperty.RegisterReadOnly(
"CanUserSort",
typeof(bool),
typeof(DataGridColumnHeader),
new FrameworkPropertyMetadata(true, null, new CoerceValueCallback(OnCoerceCanUserSort)));
/// <summary>
/// The DependencyProperty for the CanUserSort property.
/// </summary>
public static readonly DependencyProperty CanUserSortProperty = CanUserSortPropertyKey.DependencyProperty;
/// <summary>
/// CanUserSort is the flag which determines if the datagrid can be sorted based on the column of this header
/// </summary>
public bool CanUserSort
{
get { return (bool)GetValue(CanUserSortProperty); }
}
/// <summary>
/// DependencyPropertyKey for SortDirection property
/// </summary>
private static readonly DependencyPropertyKey SortDirectionPropertyKey =
DependencyProperty.RegisterReadOnly(
"SortDirection",
typeof(Nullable<ListSortDirection>),
typeof(DataGridColumnHeader),
new FrameworkPropertyMetadata(null, OnVisualStatePropertyChanged, new CoerceValueCallback(OnCoerceSortDirection)));
/// <summary>
/// The DependencyProperty for the SortDirection property.
/// </summary>
public static readonly DependencyProperty SortDirectionProperty = SortDirectionPropertyKey.DependencyProperty;
/// <summary>
/// The property for current sort direction of the column of this header
/// </summary>
public Nullable<ListSortDirection> SortDirection
{
get { return (Nullable<ListSortDirection>)GetValue(SortDirectionProperty); }
}
/// <summary>
/// The override of ButtonBase.OnClick.
/// Informs the owning datagrid to sort itself after the execution of usual button stuff
/// </summary>
protected override void OnClick()
{
if (!SuppressClickEvent)
{
if (AutomationPeer.ListenerExists(AutomationEvents.InvokePatternOnInvoked))
{
AutomationPeer peer = UIElementAutomationPeer.CreatePeerForElement(this);
if (peer != null)
{
peer.RaiseAutomationEvent(AutomationEvents.InvokePatternOnInvoked);
}
}
base.OnClick();
if (Column != null &&
Column.DataGridOwner != null)
{
Column.DataGridOwner.PerformSort(Column);
}
}
}
/// <summary>
/// Coercion callback for Height property.
/// </summary>
private static object OnCoerceHeight(DependencyObject d, object baseValue)
{
var columnHeader = (DataGridColumnHeader)d;
DataGridColumn column = columnHeader.Column;
DataGrid dataGrid = null;
// Propagate style changes to any filler column headers.
if (column == null)
{
DataGridColumnHeadersPresenter presenter = columnHeader.TemplatedParent as DataGridColumnHeadersPresenter;
if (presenter != null)
{
dataGrid = presenter.ParentDataGrid;
}
}
else
{
dataGrid = column.DataGridOwner;
}
return DataGridHelper.GetCoercedTransferPropertyValue(
columnHeader,
baseValue,
HeightProperty,
dataGrid,
DataGrid.ColumnHeaderHeightProperty);
}
/// <summary>
/// Coercion callback for CanUserSort property. Checks for the value of CanUserSort on owning column
/// and returns accordingly
/// </summary>
private static object OnCoerceCanUserSort(DependencyObject d, object baseValue)
{
DataGridColumnHeader header = (DataGridColumnHeader)d;
DataGridColumn column = header.Column;
if (column != null)
{
return column.CanUserSort;
}
return baseValue;
}
/// <summary>
/// Coercion callback for SortDirection property
/// </summary>
private static object OnCoerceSortDirection(DependencyObject d, object baseValue)
{
DataGridColumnHeader header = (DataGridColumnHeader)d;
DataGridColumn column = header.Column;
if (column != null)
{
return column.SortDirection;
}
return baseValue;
}
#endregion
#region Automation
protected override System.Windows.Automation.Peers.AutomationPeer OnCreateAutomationPeer()
{
return new System.Windows.Automation.Peers.DataGridColumnHeaderAutomationPeer(this);
}
// Called from DataGridColumnHeaderAutomationPeer
internal void Invoke()
{
this.OnClick();
}
#endregion
#region Frozen Columns
/// <summary>
/// DependencyPropertyKey for IsFrozen property
/// </summary>
private static readonly DependencyPropertyKey IsFrozenPropertyKey =
DependencyProperty.RegisterReadOnly(
"IsFrozen",
typeof(bool),
typeof(DataGridColumnHeader),
new FrameworkPropertyMetadata(false, null, new CoerceValueCallback(OnCoerceIsFrozen)));
/// <summary>
/// The DependencyProperty for the IsFrozen property.
/// </summary>
public static readonly DependencyProperty IsFrozenProperty = IsFrozenPropertyKey.DependencyProperty;
/// <summary>
/// The property to determine if the column corresponding to this header is frozen or not
/// </summary>
public bool IsFrozen
{
get { return (bool)GetValue(IsFrozenProperty); }
}
/// <summary>
/// Coercion callback for IsFrozen property
/// </summary>
private static object OnCoerceIsFrozen(DependencyObject d, object baseValue)
{
DataGridColumnHeader header = (DataGridColumnHeader)d;
DataGridColumn column = header.Column;
if (column != null)
{
return column.IsFrozen;
}
return baseValue;
}
/// <summary>
/// Coercion call back for clip property which ensures that the header overlapping with frozen
/// column gets clipped appropriately.
/// </summary>
private static object OnCoerceClip(DependencyObject d, object baseValue)
{
DataGridColumnHeader header = (DataGridColumnHeader)d;
Geometry geometry = baseValue as Geometry;
Geometry frozenGeometry = DataGridHelper.GetFrozenClipForCell(header);
if (frozenGeometry != null)
{
if (geometry == null)
{
return frozenGeometry;
}
geometry = new CombinedGeometry(GeometryCombineMode.Intersect, geometry, frozenGeometry);
}
return geometry;
}
#endregion
#region Column Reordering
internal DataGridColumnHeadersPresenter ParentPresenter
{
get
{
if (_parentPresenter == null)
{
_parentPresenter = ItemsControl.ItemsControlFromItemContainer(this) as DataGridColumnHeadersPresenter;
}
return _parentPresenter;
}
}
/// <summary>
/// Property which determines if click event has to raised or not. Used during column drag drop which could
/// be mis-interpreted as a click
/// </summary>
internal bool SuppressClickEvent
{
get
{
return _suppressClickEvent;
}
set
{
_suppressClickEvent = value;
}
}
protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
{
base.OnMouseLeftButtonDown(e);
DataGridColumnHeadersPresenter parentPresenter = ParentPresenter;
if (parentPresenter != null)
{
// If clickmode is hover then during the mouse move the hover events will be sent
// all the headers in the path. To avoid that we are using a capture
if (ClickMode == ClickMode.Hover && e.ButtonState == MouseButtonState.Pressed)
{
CaptureMouse();
}
parentPresenter.OnHeaderMouseLeftButtonDown(e);
e.Handled = true;
}
}
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
DataGridColumnHeadersPresenter parentPresenter = ParentPresenter;
if (parentPresenter != null)
{
parentPresenter.OnHeaderMouseMove(e);
e.Handled = true;
}
}
protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e)
{
base.OnMouseLeftButtonUp(e);
DataGridColumnHeadersPresenter parentPresenter = ParentPresenter;
if (parentPresenter != null)
{
if (ClickMode == ClickMode.Hover && IsMouseCaptured)
{
ReleaseMouseCapture();
}
parentPresenter.OnHeaderMouseLeftButtonUp(e);
e.Handled = true;
}
}
protected override void OnLostMouseCapture(MouseEventArgs e)
{
base.OnLostMouseCapture(e);
DataGridColumnHeadersPresenter parentPresenter = ParentPresenter;
if (parentPresenter != null)
{
parentPresenter.OnHeaderLostMouseCapture(e);
e.Handled = true;
}
}
/// <summary>
/// Style key for DataGridColumnDropSeparator
/// </summary>
public static ComponentResourceKey ColumnHeaderDropSeparatorStyleKey
{
get
{
return SystemResourceKey.DataGridColumnHeaderColumnHeaderDropSeparatorStyleKey;
}
}
/// <summary>
/// Style key for DataGridColumnFloatingHeader
/// </summary>
public static ComponentResourceKey ColumnFloatingHeaderStyleKey
{
get
{
return SystemResourceKey.DataGridColumnHeaderColumnFloatingHeaderStyleKey;
}
}
#endregion
#region VSM
internal override void ChangeVisualState(bool useTransitions)
{
// Common States
if (IsPressed)
{
VisualStates.GoToState(this, useTransitions, VisualStates.StatePressed, VisualStates.StateMouseOver, VisualStates.StateNormal);
}
else if (IsMouseOver)
{
VisualStates.GoToState(this, useTransitions, VisualStates.StateMouseOver, VisualStates.StateNormal);
}
else
{
VisualStateManager.GoToState(this, VisualStates.StateNormal, useTransitions);
}
// Sort States
var sortDirection = SortDirection;
if (sortDirection != null)
{
if (sortDirection == ListSortDirection.Ascending)
{
VisualStates.GoToState(this, useTransitions, VisualStates.StateSortAscending, VisualStates.StateUnsorted);
}
if (sortDirection == ListSortDirection.Descending)
{
VisualStates.GoToState(this, useTransitions, VisualStates.StateSortDescending, VisualStates.StateUnsorted);
}
}
else
{
VisualStateManager.GoToState(this, VisualStates.StateUnsorted, useTransitions);
}
// Don't call base.ChangeVisualState because we dont want to pick up the button's state changes.
// This is because SL didn't declare several of the states that Button defines, and we need to be
// compatible with them.
ChangeValidationVisualState(useTransitions);
}
#endregion
#region Helpers
DataGridColumn IProvideDataGridColumn.Column
{
get
{
return _column;
}
}
private Panel ParentPanel
{
get
{
return VisualParent as Panel;
}
}
/// <summary>
/// Used by the resize code -- this is the header that the left gripper should be resizing.
/// </summary>
private DataGridColumnHeader PreviousVisibleHeader
{
get
{
//
DataGridColumn column = Column;
if (column != null)
{
DataGrid dataGridOwner = column.DataGridOwner;
if (dataGridOwner != null)
{
for (int index = DisplayIndex - 1; index >= 0; index--)
{
if (dataGridOwner.ColumnFromDisplayIndex(index).IsVisible)
{
return dataGridOwner.ColumnHeaderFromDisplayIndex(index);
}
}
}
}
return null;
}
}
#endregion
#region Data
private DataGridColumn _column;
private ContainerTracking<DataGridColumnHeader> _tracker;
private DataGridColumnHeadersPresenter _parentPresenter;
private Thumb _leftGripper, _rightGripper;
private bool _suppressClickEvent;
private const string LeftHeaderGripperTemplateName = "PART_LeftHeaderGripper";
private const string RightHeaderGripperTemplateName = "PART_RightHeaderGripper";
#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 Xunit;
using Xunit.Abstractions;
using System.IO;
using System.Xml.Schema;
namespace System.Xml.Tests
{
//[TestCase(Name = "TC_SchemaSet_Reprocess", Desc = "", Priority = 1)]
public class TC_SchemaSet_Reprocess : TC_SchemaSetBase
{
private ITestOutputHelper _output;
public TC_SchemaSet_Reprocess(ITestOutputHelper output)
{
_output = output;
}
public bool bWarningCallback = false;
public bool bErrorCallback = false;
public void ValidateSchemaSet(XmlSchemaSet ss, int schCount, bool isCompiled, int countGT, int countGE, int countGA, string str)
{
_output.WriteLine(str);
Assert.Equal(ss.Count, schCount);
Assert.Equal(ss.IsCompiled, isCompiled);
Assert.Equal(ss.GlobalTypes.Count, countGT);
Assert.Equal(ss.GlobalElements.Count, countGE);
Assert.Equal(ss.GlobalAttributes.Count, countGA);
}
public void ValidationCallback(object sender, ValidationEventArgs args)
{
if (args.Severity == XmlSeverityType.Warning)
{
_output.WriteLine("WARNING: ");
bWarningCallback = true;
}
else if (args.Severity == XmlSeverityType.Error)
{
_output.WriteLine("ERROR: ");
bErrorCallback = true;
}
_output.WriteLine(args.Message); // Print the error to the screen.
}
//-----------------------------------------------------------------------------------
//[Variation(Desc = "v1 - Reprocess: Reprocess with null", Priority = 0)]
[InlineData()]
[Theory]
public void v1()
{
XmlSchemaSet sc = new XmlSchemaSet();
try
{
sc.Reprocess(null);
}
catch (ArgumentNullException e)
{
_output.WriteLine(e.ToString());
CError.Compare(sc.Count, 0, "AddCount");
CError.Compare(sc.IsCompiled, false, "AddIsCompiled");
return;
}
Assert.True(false);
}
//-----------------------------------------------------------------------------------
//[Variation(Desc = "v2 - Reprocess: Schema not present in set", Priority = 1)]
[InlineData()]
[Theory]
public void v2()
{
XmlSchemaSet sc = new XmlSchemaSet();
try
{
XmlSchema Schema1 = sc.Add(null, TestData._XsdAuthor);
CError.Compare(sc.Count, 1, "AddCount");
CError.Compare(sc.Contains(Schema1), true, "AddContains");
CError.Compare(sc.IsCompiled, false, "AddIsCompiled");
XmlSchema Schema2 = XmlSchema.Read(new StreamReader(new FileStream(TestData._XsdNoNs, FileMode.Open, FileAccess.Read)), null);
sc.Compile();
CError.Compare(sc.Count, 1, "Compile");
CError.Compare(sc.Contains(Schema1), true, "Contains");
sc.Reprocess(Schema2);
CError.Compare(sc.Count, 1, "Reprocess");
CError.Compare(sc.Contains(Schema2), true, "Contains");
}
catch (ArgumentException e)
{
_output.WriteLine(e.ToString());
CError.Compare(sc.Count, 1, "AE");
return;
}
Assert.True(false);
}
//-----------------------------------------------------------------------------------
//[Variation(Desc = "v3 - Reprocess: Without changing any content of the schema", Priority = 0)]
[InlineData()]
[Theory]
public void v3()
{
XmlSchemaSet sc = new XmlSchemaSet();
XmlSchema Schema1 = sc.Add(null, TestData._XsdAuthor);
CError.Compare(sc.Count, 1, "AddCount");
CError.Compare(sc.Contains(Schema1), true, "AddContains");
CError.Compare(sc.IsCompiled, false, "AddIsCompiled");
sc.Compile();
CError.Compare(sc.Count, 1, "Compile");
CError.Compare(sc.Contains(Schema1), true, "Compile Contains");
CError.Compare(sc.IsCompiled, true, "Compile IsCompiled");
sc.Reprocess(Schema1);
CError.Compare(sc.Count, 1, "IsCompiled on set");
CError.Compare(sc.IsCompiled, false, "Reprocess IsCompiled");
CError.Compare(sc.Contains(Schema1), true, "Reprocess Contains");
return;
}
//-----------------------------------------------------------------------------------
//[Variation(Desc = "v4 - Reprocess: Insert a valid element", Priority = 1)]
[InlineData()]
[Theory]
public void v4()
{
XmlSchemaSet sc = new XmlSchemaSet();
XmlSchema Schema1 = sc.Add(null, TestData._XsdAuthor);
CError.Compare(sc.Count, 1, "AddCount");
CError.Compare(sc.Contains(Schema1), true, "AddContains");
CError.Compare(sc.IsCompiled, false, "AddIsCompiled");
sc.Compile();
CError.Compare(sc.Count, 1, "Compile Count");
CError.Compare(sc.Contains(Schema1), true, "CompileContains");
//edit
XmlSchemaElement elementDog = new XmlSchemaElement();
Schema1.Items.Add(elementDog);
elementDog.Name = "dog";
elementDog.SchemaTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");
sc.Reprocess(Schema1);
CError.Compare(sc.Count, 1, "ReprocessCount");
CError.Compare(sc.Contains(Schema1), true, "ReprocessContains");
CError.Compare(sc.IsCompiled, false, "ReprocessIsCompiled");
sc.Compile();
CError.Compare(sc.Count, 1, "Compile");
CError.Compare(sc.IsCompiled, true, "CompileIsCompiled");
CError.Compare(Schema1.IsCompiled, true, "CompileIsCompiled on SOM");
CError.Compare(sc.Contains(Schema1), true, "CompileContains");
return;
}
//-----------------------------------------------------------------------------------
//[Variation(Desc = "v5 - Reprocess: Insert a valid attribute", Priority = 1)]
[InlineData()]
[Theory]
public void v5()
{
XmlSchemaSet sc = new XmlSchemaSet();
XmlSchema Schema1 = sc.Add(null, TestData._XsdAuthor);
CError.Compare(sc.Count, 1, "AddCount");
CError.Compare(sc.Contains(Schema1), true, "AddContains");
CError.Compare(sc.IsCompiled, false, "AddIsCompiled");
sc.Compile();
CError.Compare(sc.Count, 1, "CompileCount");
CError.Compare(sc.Contains(Schema1), true, "CompileContains");
//edit
XmlSchemaAttribute attributeDog = new XmlSchemaAttribute();
Schema1.Items.Add(attributeDog);
attributeDog.Name = "dog";
attributeDog.SchemaTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");
sc.Reprocess(Schema1);
CError.Compare(sc.Count, 1, "ReprocessCount");
CError.Compare(sc.Contains(Schema1), true, "ReprocessContains");
CError.Compare(sc.IsCompiled, false, "ReprocessIsCompiled");
sc.Compile();
CError.Compare(sc.Count, 1, "Count Compile");
CError.Compare(sc.IsCompiled, true, "IsCompiled Compile");
CError.Compare(Schema1.IsCompiled, true, "IsCompiled on SOM Compile");
return;
}
//-----------------------------------------------------------------------------------
//[Variation(Desc = "v6 - Reprocess: Insert an element with an invalid type", Priority = 1)]
[InlineData()]
[Theory]
public void v6()
{
try
{
XmlSchemaSet sc = new XmlSchemaSet();
XmlSchema Schema1 = sc.Add(null, TestData._XsdAuthor);
CError.Compare(sc.Count, 1, "Count after add");
CError.Compare(sc.Contains(Schema1), true, "Contains after add");
sc.Compile();
CError.Compare(sc.Count, 1, "Count");
CError.Compare(sc.Contains(Schema1), true, "Contains");
XmlSchemaElement elementDog = new XmlSchemaElement();
Schema1.Items.Add(elementDog);
elementDog.Name = "dog";
elementDog.SchemaTypeName = new XmlQualifiedName("sstring", "http://www.w3.org/2001/XMLSchema");
sc.Reprocess(Schema1);
CError.Compare(sc.Count, 1, "Count");
CError.Compare(sc.Contains(Schema1), true, "Contains");
CError.Compare(sc.IsCompiled, false, "IsCompiled");
sc.Compile();
CError.Compare(sc.IsCompiled, true, "IsCompiled");
CError.Compare(Schema1.IsCompiled, true, "IsCompiled on SOM");
}
catch (XmlSchemaException e)
{
_output.WriteLine(e.ToString());
return;
}
Assert.True(false);
}
//-----------------------------------------------------------------------------------
//[Variation(Desc = "v7 - Reprocess: Insert an attribute with an invalid type", Priority = 1)]
[InlineData()]
[Theory]
public void v7()
{
try
{
XmlSchemaSet sc = new XmlSchemaSet();
XmlSchema Schema1 = sc.Add(null, TestData._XsdAuthor);
CError.Compare(sc.Count, 1, "Count after add");
CError.Compare(sc.Contains(Schema1), true, "Contains after add");
sc.Compile();
CError.Compare(sc.Count, 1, "Count");
CError.Compare(sc.Contains(Schema1), true, "Contains");
//edit
XmlSchemaAttribute attributeDog = new XmlSchemaAttribute();
Schema1.Items.Add(attributeDog);
attributeDog.Name = "dog";
attributeDog.SchemaTypeName = new XmlQualifiedName("blah", "http://www.w3.org/2001/XMLSchema");
sc.Reprocess(Schema1);
CError.Compare(sc.Count, 1, "Count");
CError.Compare(sc.Contains(Schema1), true, "Contains");
CError.Compare(sc.IsCompiled, false, "IsCompiled");
sc.Compile();
CError.Compare(sc.IsCompiled, true, "IsCompiled");
CError.Compare(Schema1.IsCompiled, true, "IsCompiled on SOM");
}
catch (XmlSchemaException e)
{
_output.WriteLine(e.ToString());
return;
}
Assert.True(false);
}
//-----------------------------------------------------------------------------------
//[Variation(Desc = "v8 - Reprocess: Change an import statement to unresolvable", Priority = 1)]
[InlineData()]
[Theory]
public void v8()
{
bWarningCallback = false;
bErrorCallback = false;
XmlSchemaSet sc = new XmlSchemaSet();
sc.XmlResolver = new XmlUrlResolver();
sc.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
XmlSchema Schema1 = sc.Add(null, Path.Combine(TestData._Root, "import_v1_a.xsd"));
CError.Compare(sc.Count, 2, "Count after add");
CError.Compare(sc.Contains(Schema1), true, "Contains after add");
sc.Compile();
CError.Compare(sc.Count, 2, "Count");
CError.Compare(sc.Contains(Schema1), true, "Contains");
//edit
foreach (XmlSchemaImport imp in Schema1.Includes)
{
imp.SchemaLocation = "bogus";
imp.Schema = null;
}
sc.Reprocess(Schema1);
CError.Compare(bWarningCallback, true, "Warning");
CError.Compare(bErrorCallback, false, "Error");
CError.Compare(sc.Count, 2, "Count");
CError.Compare(sc.Contains(Schema1), true, "Contains");
CError.Compare(sc.IsCompiled, false, "IsCompiled");
sc.Compile();
CError.Compare(sc.IsCompiled, true, "IsCompiled");
CError.Compare(Schema1.IsCompiled, true, "IsCompiled on SOM");
return;
}
//-----------------------------------------------------------------------------------
//[Variation(Desc = "v9 - Reprocess: Change an import statement added to import another schema", Priority = 1)]
[InlineData()]
[Theory]
public void v9()
{
bWarningCallback = false;
bErrorCallback = false;
XmlSchemaSet sc = new XmlSchemaSet();
sc.XmlResolver = new XmlUrlResolver();
sc.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
XmlSchema Schema1 = sc.Add(null, Path.Combine(TestData._Root, "reprocess_v9_a.xsd"));
CError.Compare(sc.Count, 2, "Count after add");
CError.Compare(sc.Contains(Schema1), true, "Contains after add");
sc.Compile();
CError.Compare(sc.Count, 2, "Count");
CError.Compare(sc.Contains(Schema1), true, "Contains");
//edit
XmlSchemaImport imp = new XmlSchemaImport();
imp.Namespace = "ns-c";
imp.SchemaLocation = "reprocess_v9_c.xsd";
Schema1.Includes.Add(imp);
sc.Reprocess(Schema1);
CError.Compare(bWarningCallback, false, "Warning");
CError.Compare(bErrorCallback, false, "Error");
CError.Compare(sc.Count, 3, "Count");
CError.Compare(sc.Contains(Schema1), true, "Contains");
CError.Compare(sc.IsCompiled, false, "IsCompiled");
sc.Compile();
CError.Compare(sc.IsCompiled, true, "IsCompiled");
CError.Compare(Schema1.IsCompiled, true, "IsCompiled on SOM");
return;
}
//-----------------------------------------------------------------------------------
//[Variation(Desc = "v10 - Reprocess: Add an invalid import statement, Import self", Priority = 1)]
[InlineData()]
[Theory]
public void v10()
{
bWarningCallback = false;
bErrorCallback = false;
XmlSchemaSet sc = new XmlSchemaSet();
sc.XmlResolver = new XmlUrlResolver();
sc.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
XmlSchema Schema1 = sc.Add(null, Path.Combine(TestData._Root, "reprocess_v9_a.xsd"));
CError.Compare(sc.Count, 2, "Count after add");
CError.Compare(sc.Contains(Schema1), true, "Contains after add");
sc.Compile();
CError.Compare(sc.Count, 2, "Count after add/comp");
CError.Compare(sc.Contains(Schema1), true, "Contains after add/comp");
//edit
XmlSchemaImport imp = new XmlSchemaImport();
imp.Namespace = "ns-a";
imp.SchemaLocation = "reprocess_v9_a.xsd";
Schema1.Includes.Add(imp);
sc.Reprocess(Schema1);
ValidateSchemaSet(sc, 2, false, 2, 1, 0, "Validation after edit/reprocess");
CError.Compare(bWarningCallback, false, "Warning repr");
CError.Compare(bErrorCallback, true, "Error repr");
sc.Compile();
ValidateSchemaSet(sc, 2, false, 2, 1, 0, "Validation after comp/reprocess");
CError.Compare(bWarningCallback, false, "Warning comp");
CError.Compare(bErrorCallback, true, "Error comp");
CError.Compare(Schema1.IsCompiled, false, "IsCompiled on SOM");
return;
}
//-----------------------------------------------------------------------------------
//[Variation(Desc = "v11 - Reprocess: Change Include statement to unresolvable", Priority = 1)]
[InlineData()]
[Theory]
public void v11()
{
bWarningCallback = false;
bErrorCallback = false;
XmlSchemaSet sc = new XmlSchemaSet();
sc.XmlResolver = new XmlUrlResolver();
sc.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
XmlSchema Schema1 = sc.Add(null, Path.Combine(TestData._Root, "include_v1_a.xsd"));
CError.Compare(sc.Count, 1, "Count after add");
CError.Compare(sc.Contains(Schema1), true, "Contains after add");
sc.Compile();
CError.Compare(sc.Count, 1, "Count after add/comp");
CError.Compare(sc.Contains(Schema1), true, "Contains after add/comp");
//edit
foreach (XmlSchemaInclude inc in Schema1.Includes)
{
inc.SchemaLocation = "bogus";
inc.Schema = null;
}
sc.Reprocess(Schema1);
ValidateSchemaSet(sc, 1, false, 1, 0, 0, "Validation after edit/reprocess");
CError.Compare(bWarningCallback, true, "Warning repr");
CError.Compare(bErrorCallback, false, "Error repr");
sc.Compile();
ValidateSchemaSet(sc, 1, true, 2, 2, 0, "Validation after comp/reprocess");
CError.Compare(bWarningCallback, true, "Warning comp");
CError.Compare(bErrorCallback, false, "Error comp");
CError.Compare(Schema1.IsCompiled, true, "IsCompiled on SOM");
return;
}
//-----------------------------------------------------------------------------------
//[Variation(Desc = "v12 - Reprocess: Add invalid include statement", Priority = 1)]
[InlineData()]
[Theory]
public void v12()
{
bWarningCallback = false;
bErrorCallback = false;
XmlSchemaSet sc = new XmlSchemaSet();
sc.XmlResolver = new XmlUrlResolver();
sc.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
XmlSchema Schema1 = sc.Add(null, Path.Combine(TestData._Root, "include_v1_a.xsd"));
CError.Compare(sc.Count, 1, "Count after add");
CError.Compare(sc.Contains(Schema1), true, "Contains after add");
sc.Compile();
CError.Compare(sc.Count, 1, "Count after add/comp");
CError.Compare(sc.Contains(Schema1), true, "Contains after add/comp");
///edit
XmlSchemaInclude inc = new XmlSchemaInclude();
inc.SchemaLocation = "include_v2.xsd";
Schema1.Includes.Add(inc);
sc.Reprocess(Schema1);
ValidateSchemaSet(sc, 1, false, 1, 0, 0, "Validation after edit/reprocess");
CError.Compare(bWarningCallback, false, "Warning repr");
CError.Compare(bErrorCallback, true, "Error repr");
sc.Compile();
ValidateSchemaSet(sc, 1, false, 1, 0, 0, "Validation after comp/reprocess");
CError.Compare(bWarningCallback, false, "Warning comp");
CError.Compare(bErrorCallback, true, "Error comp");
CError.Compare(Schema1.IsCompiled, false, "IsCompiled on SOM");
return;
}
//-----------------------------------------------------------------------------------
//[Variation(Desc = "Regression bug 346902 - Types should be removed of a schema when SchemaSet.Reprocess is called", Priority = 1)]
[InlineData()]
[Theory]
public void v50()
{
bWarningCallback = false;
bErrorCallback = false;
XmlSchemaSet schemaSet = new XmlSchemaSet();
XmlSchema schema = new XmlSchema();
schemaSet.Add(schema);
schema.TargetNamespace = "http://myns/";
//type
XmlSchemaType schemaType = new XmlSchemaComplexType();
schemaType.Name = "MySimpleType";
schema.Items.Add(schemaType);
schemaSet.Reprocess(schema);
schemaSet.Compile();
//element
XmlSchemaElement schemaElement = new XmlSchemaElement();
schemaElement.Name = "MyElement";
schema.Items.Add(schemaElement);
schemaSet.Reprocess(schema);
schemaSet.Compile();
//attribute
XmlSchemaAttribute schemaAttribute = new XmlSchemaAttribute();
schemaAttribute.Name = "MyAttribute";
schema.Items.Add(schemaAttribute);
schemaSet.Reprocess(schema);
schemaSet.Compile();
schemaSet.Reprocess(schema);
schemaSet.Compile();
schema.Items.Remove(schemaType);//what is the best way to remove it?
schema.Items.Remove(schemaElement);
schema.Items.Remove(schemaAttribute);
schemaSet.Reprocess(schema);
schemaSet.Compile();
schemaType = new XmlSchemaComplexType();
schemaType.Name = "MySimpleType";
schema.Items.Add(schemaType);
schema.Items.Add(schemaElement);
schema.Items.Add(schemaAttribute);
schemaSet.Reprocess(schema);
schemaSet.Compile();
CError.Compare(schemaSet.GlobalElements.Count, 1, "Element count mismatch!");
CError.Compare(schemaSet.GlobalAttributes.Count, 1, "Attributes count mismatch!");
CError.Compare(schemaSet.GlobalTypes.Count, 2, "Types count mismatch!");
return;
}
//[Variation(Desc = "v53 Regression bug 382119 - XmlEditor: Changes within an include is not getting picked up as expected - include", Priority = 1, Params = new object[] { "bug382119_a.xsd", "bug382119_inc.xsd", "bug382119_inc1.xsd", false })]
[InlineData("bug382119_a.xsd", "bug382119_inc.xsd", "bug382119_inc1.xsd", false)]
//[Variation(Desc = "v52 Regression bug 382119 - XmlEditor: Changes within an include is not getting picked up as expected - import", Priority = 1, Params = new object[] { "bug382119_b.xsd", "bug382119_imp.xsd", "bug382119_imp1.xsd", true })]
[InlineData("bug382119_b.xsd", "bug382119_imp.xsd", "bug382119_imp1.xsd", true)]
//[Variation(Desc = "v51 Regression bug 382119 - XmlEditor: Changes within an include is not getting picked up as expected - redefine", Priority = 1, Params = new object[] { "bug382119_c.xsd", "bug382119_red.xsd", "bug382119_red1.xsd", false })]
[InlineData("bug382119_c.xsd", "bug382119_red.xsd", "bug382119_red1.xsd", false)]
[Theory]
public void v51(object param0, object param1, object param2, object param3)
{
bWarningCallback = false;
bErrorCallback = false;
string mainFile = Path.Combine(TestData._Root, param0.ToString());
string include1 = Path.Combine(TestData._Root, param1.ToString());
string include2 = Path.Combine(TestData._Root, param2.ToString());
string xmlFile = Path.Combine(TestData._Root, "bug382119.xml");
bool IsImport = (bool)param3;
XmlSchemaSet set1 = new XmlSchemaSet();
set1.XmlResolver = new XmlUrlResolver();
set1.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
XmlSchema includedSchema = set1.Add(null, include1);
set1.Compile();
XmlSchemaSet set = new XmlSchemaSet();
set.XmlResolver = new XmlUrlResolver();
set.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
XmlSchema mainSchema = set.Add(null, mainFile);
set.Compile();
_output.WriteLine("First validation ***************");
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
settings.ValidationType = ValidationType.Schema;
settings.Schemas = set;
XmlReader reader = XmlReader.Create(xmlFile, settings);
while (reader.Read()) { }
CError.Compare(bWarningCallback, false, "Warning count mismatch");
CError.Compare(bErrorCallback, true, "Error count mismatch");
if (IsImport == true)
set.Remove(((XmlSchemaExternal)mainSchema.Includes[0]).Schema);
_output.WriteLine("re-setting include");
XmlSchema reParsedInclude = LoadSchema(include2, include1);
((XmlSchemaExternal)mainSchema.Includes[0]).Schema = reParsedInclude;
_output.WriteLine("Calling reprocess");
set.Reprocess(mainSchema);
set.Compile();
bWarningCallback = false;
bErrorCallback = false;
_output.WriteLine("Second validation ***************");
settings.Schemas = set;
reader = XmlReader.Create(xmlFile, settings);
while (reader.Read()) { }
CError.Compare(bWarningCallback, false, "Warning count mismatch");
CError.Compare(bErrorCallback, false, "Error count mismatch");
//Editing the include again
_output.WriteLine("Re-adding include to set1");
XmlSchema reParsedInclude2 = LoadSchema(include1, include1);
set1.Remove(includedSchema);
set1.Add(reParsedInclude2);
set1.Compile();
if (IsImport == true)
set.Remove(((XmlSchemaExternal)mainSchema.Includes[0]).Schema);
((XmlSchemaExternal)mainSchema.Includes[0]).Schema = reParsedInclude2;
set.Reprocess(mainSchema);
set.Compile();
bWarningCallback = false;
bErrorCallback = false;
_output.WriteLine("Third validation, Expecting errors ***************");
settings.Schemas = set;
reader = XmlReader.Create(xmlFile, settings);
while (reader.Read()) { }
CError.Compare(bWarningCallback, false, "Warning count mismatch");
CError.Compare(bErrorCallback, true, "Error count mismatch");
return;
}
public XmlSchema LoadSchema(string path, string baseuri)
{
string includeUri = Path.GetFullPath(baseuri);
string correctUri = Path.GetFullPath(path);
_output.WriteLine("Include uri: " + includeUri);
_output.WriteLine("Correct uri: " + correctUri);
Stream s = new FileStream(Path.GetFullPath(path), FileMode.Open, FileAccess.Read, FileShare.Read, 1);
XmlReader r = XmlReader.Create(s, new XmlReaderSettings(), includeUri);
_output.WriteLine("Reader uri: " + r.BaseURI);
XmlSchema som = null;
using (r)
{
som = XmlSchema.Read(r, new ValidationEventHandler(ValidationCallback));
}
return som;
}
}
}
| |
// Copyright (c) MOSA Project. Licensed under the New BSD License.
using Mosa.Compiler.Common;
using Mosa.Compiler.Framework.CIL;
using Mosa.Compiler.Framework.IR;
using Mosa.Compiler.MosaTypeSystem;
using System.Diagnostics;
namespace Mosa.Compiler.Framework.Stages
{
/// <summary>
/// Represents the CIL decoding compilation stage.
/// </summary>
/// <remarks>
/// The CIL decoding stage takes a stream of bytes and decodes the
/// instructions represented into an MSIL based intermediate
/// representation. The instructions are grouped into basic Blocks
/// for easier local optimizations in later compiler stages.
/// </remarks>
public sealed class CILDecodingStage : BaseMethodCompilerStage, IInstructionDecoder
{
#region Data members
/// <summary>
/// The instruction being decoded.
/// </summary>
private MosaInstruction instruction;
/// <summary>
/// The block instruction beings too
/// </summary>
private BasicBlock block;
private int[] counts;
#endregion Data members
protected override void Run()
{
if (IsPlugged)
{
var plugMethod = MethodCompiler.Compiler.PlugSystem.GetPlugMethod(MethodCompiler.Method);
Debug.Assert(plugMethod != null);
var plugSymbol = Operand.CreateSymbolFromMethod(TypeSystem, plugMethod);
var context = CreateNewBlockContext(-1);
context.AppendInstruction(IRInstruction.Jmp, null, plugSymbol);
BasicBlocks.AddHeadBlock(context.Block);
return;
}
// No CIL decoding if this is a linker generated method
if (MethodCompiler.Method.IsLinkerGenerated)
return;
if (MethodCompiler.Method.Code.Count == 0)
{
if (DelegatePatcher.PatchDelegate(MethodCompiler))
return;
MethodCompiler.Stop();
return;
}
if (MethodCompiler.Compiler.CompilerOptions.EnableStatistics)
{
counts = new int[CILInstruction.MaxOpCodeValue];
}
MethodCompiler.SetLocalVariables(MethodCompiler.Method.LocalVariables);
// Create the prologue block
var prologue = CreateNewBlock(BasicBlock.PrologueLabel);
BasicBlocks.AddHeadBlock(prologue);
var jmpNode = new InstructionNode();
jmpNode.Label = BasicBlock.PrologueLabel;
jmpNode.Block = prologue;
prologue.First.Insert(jmpNode);
// Create starting block
var startBlock = CreateNewBlock(0);
jmpNode.SetInstruction(IRInstruction.Jmp, startBlock);
DecodeInstructionTargets();
DecodeProtectedRegionTargets();
/* Decode the instructions */
DecodeInstructions();
foreach (var block in BasicBlocks)
{
if (!block.HasPreviousBlocks && !BasicBlocks.HeadBlocks.Contains(block))
{
// block was targeted (probably by an leave instruction within a protected region)
BasicBlocks.AddHeadBlock(block);
}
}
// This makes it easier to review --- it's not necessary
BasicBlocks.OrderByLabel();
}
protected override void Finish()
{
if (counts == null)
return;
int total = 0;
for (int op = 0; op < counts.Length; op++)
{
int count = counts[op];
if (count == 0)
continue;
var cil = CILInstruction.Get((OpCode)op);
UpdateCounter("CILDecodingStage.OpCode." + cil.InstructionName, count);
total = total + count;
}
UpdateCounter("CILDecodingStage.CILInstructions", total);
}
#region Internals
private void DecodeProtectedRegionTargets()
{
foreach (var handler in MethodCompiler.Method.ExceptionHandlers)
{
if (handler.TryStart != 0)
{
var block = GetBlockByLabel(handler.TryStart);
}
if (handler.TryEnd != 0)
{
var block = GetBlockByLabel(handler.TryEnd);
}
if (handler.HandlerStart != 0)
{
var block = GetBlockByLabel(handler.HandlerStart);
BasicBlocks.AddHeadBlock(block);
BasicBlocks.AddHandlerHeadBlock(block);
}
if (handler.FilterStart != null)
{
var block = GetBlockByLabel(handler.FilterStart.Value);
BasicBlocks.AddHeadBlock(block);
BasicBlocks.AddHandlerHeadBlock(block);
}
}
}
private void DecodeInstructionTargets()
{
bool branched = false;
for (int i = 0; i < MethodCompiler.Method.Code.Count; i++)
{
instruction = MethodCompiler.Method.Code[i];
if (branched)
{
GetBlockByLabel(instruction.Offset);
branched = false;
}
var op = (OpCode)instruction.OpCode;
var cil = CILInstruction.Get(op);
++counts[(int)op];
branched = cil.DecodeTargets(this);
}
}
/// <summary>
/// Decodes the instruction stream of the reader and populates the compiler.
/// </summary>
/// <exception cref="InvalidMetadataException"></exception>
private void DecodeInstructions()
{
block = null;
// Prefix instruction
bool prefix = false;
for (int i = 0; i < MethodCompiler.Method.Code.Count; i++)
{
instruction = MethodCompiler.Method.Code[i];
block = BasicBlocks.GetByLabel(instruction.Offset) ?? block;
var op = (OpCode)instruction.OpCode;
var cil = CILInstruction.Get(op);
if (cil == null)
{
throw new InvalidMetadataException();
}
// Create and initialize the corresponding instruction
var node = new InstructionNode();
node.Label = instruction.Offset;
node.HasPrefix = prefix;
node.Instruction = cil;
block.BeforeLast.Insert(node);
cil.Decode(node, this);
prefix = (cil is PrefixInstruction);
instructionCount++;
bool addjmp = false;
var flow = node.Instruction.FlowControl;
if (flow == FlowControl.Next || flow == FlowControl.Call || flow == FlowControl.ConditionalBranch || flow == FlowControl.Switch)
{
var nextInstruction = MethodCompiler.Method.Code[i + 1];
if (BasicBlocks.GetByLabel(nextInstruction.Offset) != null)
{
var target = GetBlockByLabel(nextInstruction.Offset);
var jmpNode = new InstructionNode(IRInstruction.Jmp, target);
jmpNode.Label = instruction.Offset;
block.BeforeLast.Insert(jmpNode);
}
}
}
}
private BasicBlock GetBlockByLabel(int label)
{
var block = BasicBlocks.GetByLabel(label);
if (block == null)
{
block = CreateNewBlock(label);
}
return block;
}
#endregion Internals
#region IInstructionDecoder Members
/// <summary>
/// Gets the compiler, that is currently executing.
/// </summary>
/// <value></value>
BaseMethodCompiler IInstructionDecoder.Compiler { get { return MethodCompiler; } }
/// <summary>
/// Gets the MosaMethod being compiled.
/// </summary>
/// <value></value>
MosaMethod IInstructionDecoder.Method { get { return MethodCompiler.Method; } }
/// <summary>
/// Gets the Instruction being decoded.
/// </summary>
MosaInstruction IInstructionDecoder.Instruction { get { return instruction; } }
/// <summary>
/// Gets the type system.
/// </summary>
/// <value>
/// The type system.
/// </value>
TypeSystem IInstructionDecoder.TypeSystem { get { return TypeSystem; } }
/// <summary>
/// Gets the block.
/// </summary>
/// <param name="label">The label.</param>
/// <returns></returns>
BasicBlock IInstructionDecoder.GetBlock(int label)
{
return GetBlockByLabel(label);
}
#endregion IInstructionDecoder Members
//var trace = CreateTraceLog("Inlined");
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Drawing
{
using System.Diagnostics;
using System.Drawing.Imaging;
/// <devdoc>
/// Animates one or more images that have time-based frames.
/// This file contains the nested ImageInfo class - See ImageAnimator.cs for the definition of the outer class.
/// </devdoc>
public sealed partial class ImageAnimator
{
/// <devdoc>
/// ImageAnimator nested helper class used to store extra image state info.
/// </devdoc>
private class ImageInfo
{
private const int PropertyTagFrameDelay = 0x5100;
private Image _image;
private int _frame;
private int _frameCount;
private bool _frameDirty;
private bool _animated;
private EventHandler _onFrameChangedHandler;
private int[] _frameDelay;
private int _frameTimer;
/// <devdoc>
/// </devdoc>
public ImageInfo(Image image)
{
_image = image;
_animated = ImageAnimator.CanAnimate(image);
if (_animated)
{
_frameCount = image.GetFrameCount(FrameDimension.Time);
PropertyItem frameDelayItem = image.GetPropertyItem(PropertyTagFrameDelay);
// If the image does not have a frame delay, we just return 0.
//
if (frameDelayItem != null)
{
// Convert the frame delay from byte[] to int
//
byte[] values = frameDelayItem.Value;
Debug.Assert(values.Length == 4 * FrameCount, "PropertyItem has invalid value byte array");
_frameDelay = new int[FrameCount];
for (int i = 0; i < FrameCount; ++i)
{
_frameDelay[i] = values[i * 4] + 256 * values[i * 4 + 1] + 256 * 256 * values[i * 4 + 2] + 256 * 256 * 256 * values[i * 4 + 3];
}
}
}
else
{
_frameCount = 1;
}
if (_frameDelay == null)
{
_frameDelay = new int[FrameCount];
}
}
/// <devdoc>
/// Whether the image supports animation.
/// </devdoc>
public bool Animated
{
get
{
return _animated;
}
}
/// <devdoc>
/// The current frame.
/// </devdoc>
public int Frame
{
get
{
return _frame;
}
set
{
if (_frame != value)
{
if (value < 0 || value >= FrameCount)
{
throw new ArgumentException(SR.Format(SR.InvalidFrame), "value");
}
if (Animated)
{
_frame = value;
_frameDirty = true;
OnFrameChanged(EventArgs.Empty);
}
}
}
}
/// <devdoc>
/// The current frame has not been updated.
/// </devdoc>
public bool FrameDirty
{
get
{
return _frameDirty;
}
}
/// <devdoc>
/// </devdoc>
public EventHandler FrameChangedHandler
{
get
{
return _onFrameChangedHandler;
}
set
{
_onFrameChangedHandler = value;
}
}
/// <devdoc>
/// The number of frames in the image.
/// </devdoc>
public int FrameCount
{
get
{
return _frameCount;
}
}
/// <devdoc>
/// The delay associated with the frame at the specified index.
/// </devdoc>
public int FrameDelay(int frame)
{
return _frameDelay[frame];
}
/// <devdoc>
/// </devdoc>
internal int FrameTimer
{
get
{
return _frameTimer;
}
set
{
_frameTimer = value;
}
}
/// <devdoc>
/// The image this object wraps.
/// </devdoc>
internal Image Image
{
get
{
return _image;
}
}
/// <devdoc>
/// Selects the current frame as the active frame in the image.
/// </devdoc>
internal void UpdateFrame()
{
if (_frameDirty)
{
_image.SelectActiveFrame(FrameDimension.Time, Frame);
_frameDirty = false;
}
}
/// <devdoc>
/// Raises the FrameChanged event.
/// </devdoc>
protected void OnFrameChanged(EventArgs e)
{
if (_onFrameChangedHandler != null)
{
_onFrameChangedHandler(_image, e);
}
}
}
}
}
| |
#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
using System;
using System.Collections.Generic;
using System.IO;
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
using System.Numerics;
#endif
using Newtonsoft.Json.Utilities;
using System.Globalization;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace Newtonsoft.Json
{
/// <summary>
/// Represents a writer that provides a fast, non-cached, forward-only way of generating Json data.
/// </summary>
public abstract class JsonWriter : IDisposable
{
internal enum State
{
Start,
Property,
ObjectStart,
Object,
ArrayStart,
Array,
ConstructorStart,
Constructor,
Closed,
Error
}
// array that gives a new state based on the current state an the token being written
private static readonly State[][] StateArray;
internal static readonly State[][] StateArrayTempate = new[]
{
// Start PropertyName ObjectStart Object ArrayStart Array ConstructorStart Constructor Closed Error
//
/* None */new[] { State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error },
/* StartObject */new[] { State.ObjectStart, State.ObjectStart, State.Error, State.Error, State.ObjectStart, State.ObjectStart, State.ObjectStart, State.ObjectStart, State.Error, State.Error },
/* StartArray */new[] { State.ArrayStart, State.ArrayStart, State.Error, State.Error, State.ArrayStart, State.ArrayStart, State.ArrayStart, State.ArrayStart, State.Error, State.Error },
/* StartConstructor */new[] { State.ConstructorStart, State.ConstructorStart, State.Error, State.Error, State.ConstructorStart, State.ConstructorStart, State.ConstructorStart, State.ConstructorStart, State.Error, State.Error },
/* Property */new[] { State.Property, State.Error, State.Property, State.Property, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error },
/* Comment */new[] { State.Start, State.Property, State.ObjectStart, State.Object, State.ArrayStart, State.Array, State.Constructor, State.Constructor, State.Error, State.Error },
/* Raw */new[] { State.Start, State.Property, State.ObjectStart, State.Object, State.ArrayStart, State.Array, State.Constructor, State.Constructor, State.Error, State.Error },
/* Value (this will be copied) */new[] { State.Start, State.Object, State.Error, State.Error, State.Array, State.Array, State.Constructor, State.Constructor, State.Error, State.Error }
};
internal static State[][] BuildStateArray()
{
var allStates = StateArrayTempate.ToList();
var errorStates = StateArrayTempate[0];
var valueStates = StateArrayTempate[7];
foreach (JsonToken valueToken in EnumUtils.GetValues(typeof(JsonToken)))
{
if (allStates.Count <= (int)valueToken)
{
switch (valueToken)
{
case JsonToken.Integer:
case JsonToken.Float:
case JsonToken.String:
case JsonToken.Boolean:
case JsonToken.Null:
case JsonToken.Undefined:
case JsonToken.Date:
case JsonToken.Bytes:
allStates.Add(valueStates);
break;
default:
allStates.Add(errorStates);
break;
}
}
}
return allStates.ToArray();
}
static JsonWriter()
{
StateArray = BuildStateArray();
}
private readonly List<JsonPosition> _stack;
private JsonPosition _currentPosition;
private State _currentState;
private Formatting _formatting;
/// <summary>
/// Gets or sets a value indicating whether the underlying stream or
/// <see cref="TextReader"/> should be closed when the writer is closed.
/// </summary>
/// <value>
/// true to close the underlying stream or <see cref="TextReader"/> when
/// the writer is closed; otherwise false. The default is true.
/// </value>
public bool CloseOutput { get; set; }
/// <summary>
/// Gets the top.
/// </summary>
/// <value>The top.</value>
protected internal int Top
{
get
{
int depth = _stack.Count;
if (Peek() != JsonContainerType.None)
depth++;
return depth;
}
}
/// <summary>
/// Gets the state of the writer.
/// </summary>
public WriteState WriteState
{
get
{
switch (_currentState)
{
case State.Error:
return WriteState.Error;
case State.Closed:
return WriteState.Closed;
case State.Object:
case State.ObjectStart:
return WriteState.Object;
case State.Array:
case State.ArrayStart:
return WriteState.Array;
case State.Constructor:
case State.ConstructorStart:
return WriteState.Constructor;
case State.Property:
return WriteState.Property;
case State.Start:
return WriteState.Start;
default:
throw JsonWriterException.Create(this, "Invalid state: " + _currentState, null);
}
}
}
internal string ContainerPath
{
get
{
if (_currentPosition.Type == JsonContainerType.None)
return string.Empty;
return JsonPosition.BuildPath(_stack);
}
}
/// <summary>
/// Gets the path of the writer.
/// </summary>
public string Path
{
get
{
if (_currentPosition.Type == JsonContainerType.None)
return string.Empty;
bool insideContainer = (_currentState != State.ArrayStart
&& _currentState != State.ConstructorStart
&& _currentState != State.ObjectStart);
IEnumerable<JsonPosition> positions = (!insideContainer)
? _stack
: _stack.Concat(new[] { _currentPosition });
return JsonPosition.BuildPath(positions);
}
}
private DateFormatHandling _dateFormatHandling;
private DateTimeZoneHandling _dateTimeZoneHandling;
private StringEscapeHandling _stringEscapeHandling;
private FloatFormatHandling _floatFormatHandling;
private string _dateFormatString;
private CultureInfo _culture;
/// <summary>
/// Indicates how JSON text output is formatted.
/// </summary>
public Formatting Formatting
{
get { return _formatting; }
set { _formatting = value; }
}
/// <summary>
/// Get or set how dates are written to JSON text.
/// </summary>
public DateFormatHandling DateFormatHandling
{
get { return _dateFormatHandling; }
set { _dateFormatHandling = value; }
}
/// <summary>
/// Get or set how <see cref="DateTime"/> time zones are handling when writing JSON text.
/// </summary>
public DateTimeZoneHandling DateTimeZoneHandling
{
get { return _dateTimeZoneHandling; }
set { _dateTimeZoneHandling = value; }
}
/// <summary>
/// Get or set how strings are escaped when writing JSON text.
/// </summary>
public StringEscapeHandling StringEscapeHandling
{
get { return _stringEscapeHandling; }
set
{
_stringEscapeHandling = value;
OnStringEscapeHandlingChanged();
}
}
internal virtual void OnStringEscapeHandlingChanged()
{
// hacky but there is a calculated value that relies on StringEscapeHandling
}
/// <summary>
/// Get or set how special floating point numbers, e.g. <see cref="F:System.Double.NaN"/>,
/// <see cref="F:System.Double.PositiveInfinity"/> and <see cref="F:System.Double.NegativeInfinity"/>,
/// are written to JSON text.
/// </summary>
public FloatFormatHandling FloatFormatHandling
{
get { return _floatFormatHandling; }
set { _floatFormatHandling = value; }
}
/// <summary>
/// Get or set how <see cref="DateTime"/> and <see cref="DateTimeOffset"/> values are formatting when writing JSON text.
/// </summary>
public string DateFormatString
{
get { return _dateFormatString; }
set { _dateFormatString = value; }
}
/// <summary>
/// Gets or sets the culture used when writing JSON. Defaults to <see cref="CultureInfo.InvariantCulture"/>.
/// </summary>
public CultureInfo Culture
{
get { return _culture ?? CultureInfo.InvariantCulture; }
set { _culture = value; }
}
/// <summary>
/// Creates an instance of the <c>JsonWriter</c> class.
/// </summary>
protected JsonWriter()
{
_stack = new List<JsonPosition>(4);
_currentState = State.Start;
_formatting = Formatting.None;
_dateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind;
CloseOutput = true;
}
internal void UpdateScopeWithFinishedValue()
{
if (_currentPosition.HasIndex)
_currentPosition.Position++;
}
private void Push(JsonContainerType value)
{
if (_currentPosition.Type != JsonContainerType.None)
_stack.Add(_currentPosition);
_currentPosition = new JsonPosition(value);
}
private JsonContainerType Pop()
{
JsonPosition oldPosition = _currentPosition;
if (_stack.Count > 0)
{
_currentPosition = _stack[_stack.Count - 1];
_stack.RemoveAt(_stack.Count - 1);
}
else
{
_currentPosition = new JsonPosition();
}
return oldPosition.Type;
}
private JsonContainerType Peek()
{
return _currentPosition.Type;
}
/// <summary>
/// Flushes whatever is in the buffer to the underlying streams and also flushes the underlying stream.
/// </summary>
public abstract void Flush();
/// <summary>
/// Closes this stream and the underlying stream.
/// </summary>
public virtual void Close()
{
AutoCompleteAll();
}
/// <summary>
/// Writes the beginning of a Json object.
/// </summary>
public virtual void WriteStartObject()
{
InternalWriteStart(JsonToken.StartObject, JsonContainerType.Object);
}
/// <summary>
/// Writes the end of a Json object.
/// </summary>
public virtual void WriteEndObject()
{
InternalWriteEnd(JsonContainerType.Object);
}
/// <summary>
/// Writes the beginning of a Json array.
/// </summary>
public virtual void WriteStartArray()
{
InternalWriteStart(JsonToken.StartArray, JsonContainerType.Array);
}
/// <summary>
/// Writes the end of an array.
/// </summary>
public virtual void WriteEndArray()
{
InternalWriteEnd(JsonContainerType.Array);
}
/// <summary>
/// Writes the start of a constructor with the given name.
/// </summary>
/// <param name="name">The name of the constructor.</param>
public virtual void WriteStartConstructor(string name)
{
InternalWriteStart(JsonToken.StartConstructor, JsonContainerType.Constructor);
}
/// <summary>
/// Writes the end constructor.
/// </summary>
public virtual void WriteEndConstructor()
{
InternalWriteEnd(JsonContainerType.Constructor);
}
/// <summary>
/// Writes the property name of a name/value pair on a JSON object.
/// </summary>
/// <param name="name">The name of the property.</param>
public virtual void WritePropertyName(string name)
{
InternalWritePropertyName(name);
}
/// <summary>
/// Writes the property name of a name/value pair on a JSON object.
/// </summary>
/// <param name="name">The name of the property.</param>
/// <param name="escape">A flag to indicate whether the text should be escaped when it is written as a JSON property name.</param>
public virtual void WritePropertyName(string name, bool escape)
{
WritePropertyName(name);
}
/// <summary>
/// Writes the end of the current Json object or array.
/// </summary>
public virtual void WriteEnd()
{
WriteEnd(Peek());
}
/// <summary>
/// Writes the current <see cref="JsonReader"/> token and its children.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read the token from.</param>
public void WriteToken(JsonReader reader)
{
WriteToken(reader, true, true);
}
/// <summary>
/// Writes the current <see cref="JsonReader"/> token.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read the token from.</param>
/// <param name="writeChildren">A flag indicating whether the current token's children should be written.</param>
public void WriteToken(JsonReader reader, bool writeChildren)
{
ValidationUtils.ArgumentNotNull(reader, "reader");
WriteToken(reader, writeChildren, true);
}
internal void WriteToken(JsonReader reader, bool writeChildren, bool writeDateConstructorAsDate)
{
int initialDepth;
if (reader.TokenType == JsonToken.None)
initialDepth = -1;
else if (!IsStartToken(reader.TokenType))
initialDepth = reader.Depth + 1;
else
initialDepth = reader.Depth;
WriteToken(reader, initialDepth, writeChildren, writeDateConstructorAsDate);
}
internal void WriteToken(JsonReader reader, int initialDepth, bool writeChildren, bool writeDateConstructorAsDate)
{
do
{
switch (reader.TokenType)
{
case JsonToken.None:
// read to next
break;
case JsonToken.StartObject:
WriteStartObject();
break;
case JsonToken.StartArray:
WriteStartArray();
break;
case JsonToken.StartConstructor:
string constructorName = reader.Value.ToString();
// write a JValue date when the constructor is for a date
if (writeDateConstructorAsDate && string.Equals(constructorName, "Date", StringComparison.Ordinal))
WriteConstructorDate(reader);
else
WriteStartConstructor(reader.Value.ToString());
break;
case JsonToken.PropertyName:
WritePropertyName(reader.Value.ToString());
break;
case JsonToken.Comment:
WriteComment((reader.Value != null) ? reader.Value.ToString() : null);
break;
case JsonToken.Integer:
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
if (reader.Value is BigInteger)
{
WriteValue((BigInteger)reader.Value);
}
else
#endif
{
WriteValue(Convert.ToInt64(reader.Value, CultureInfo.InvariantCulture));
}
break;
case JsonToken.Float:
object value = reader.Value;
if (value is decimal)
WriteValue((decimal)value);
else if (value is double)
WriteValue((double)value);
else if (value is float)
WriteValue((float)value);
else
WriteValue(Convert.ToDouble(value, CultureInfo.InvariantCulture));
break;
case JsonToken.String:
WriteValue(reader.Value.ToString());
break;
case JsonToken.Boolean:
WriteValue(Convert.ToBoolean(reader.Value, CultureInfo.InvariantCulture));
break;
case JsonToken.Null:
WriteNull();
break;
case JsonToken.Undefined:
WriteUndefined();
break;
case JsonToken.EndObject:
WriteEndObject();
break;
case JsonToken.EndArray:
WriteEndArray();
break;
case JsonToken.EndConstructor:
WriteEndConstructor();
break;
case JsonToken.Date:
#if !NET20
if (reader.Value is DateTimeOffset)
WriteValue((DateTimeOffset)reader.Value);
else
#endif
WriteValue(Convert.ToDateTime(reader.Value, CultureInfo.InvariantCulture));
break;
case JsonToken.Raw:
WriteRawValue((reader.Value != null) ? reader.Value.ToString() : null);
break;
case JsonToken.Bytes:
WriteValue((byte[])reader.Value);
break;
default:
throw MiscellaneousUtils.CreateArgumentOutOfRangeException("TokenType", reader.TokenType, "Unexpected token type.");
}
} while (
// stop if we have reached the end of the token being read
initialDepth - 1 < reader.Depth - (IsEndToken(reader.TokenType) ? 1 : 0)
&& writeChildren
&& reader.Read());
}
private void WriteConstructorDate(JsonReader reader)
{
if (!reader.Read())
throw JsonWriterException.Create(this, "Unexpected end when reading date constructor.", null);
if (reader.TokenType != JsonToken.Integer)
throw JsonWriterException.Create(this, "Unexpected token when reading date constructor. Expected Integer, got " + reader.TokenType, null);
long ticks = (long)reader.Value;
DateTime date = DateTimeUtils.ConvertJavaScriptTicksToDateTime(ticks);
if (!reader.Read())
throw JsonWriterException.Create(this, "Unexpected end when reading date constructor.", null);
if (reader.TokenType != JsonToken.EndConstructor)
throw JsonWriterException.Create(this, "Unexpected token when reading date constructor. Expected EndConstructor, got " + reader.TokenType, null);
WriteValue(date);
}
internal static bool IsEndToken(JsonToken token)
{
switch (token)
{
case JsonToken.EndObject:
case JsonToken.EndArray:
case JsonToken.EndConstructor:
return true;
default:
return false;
}
}
internal static bool IsStartToken(JsonToken token)
{
switch (token)
{
case JsonToken.StartObject:
case JsonToken.StartArray:
case JsonToken.StartConstructor:
return true;
default:
return false;
}
}
private void WriteEnd(JsonContainerType type)
{
switch (type)
{
case JsonContainerType.Object:
WriteEndObject();
break;
case JsonContainerType.Array:
WriteEndArray();
break;
case JsonContainerType.Constructor:
WriteEndConstructor();
break;
default:
throw JsonWriterException.Create(this, "Unexpected type when writing end: " + type, null);
}
}
private void AutoCompleteAll()
{
while (Top > 0)
{
WriteEnd();
}
}
private JsonToken GetCloseTokenForType(JsonContainerType type)
{
switch (type)
{
case JsonContainerType.Object:
return JsonToken.EndObject;
case JsonContainerType.Array:
return JsonToken.EndArray;
case JsonContainerType.Constructor:
return JsonToken.EndConstructor;
default:
throw JsonWriterException.Create(this, "No close token for type: " + type, null);
}
}
private void AutoCompleteClose(JsonContainerType type)
{
// write closing symbol and calculate new state
int levelsToComplete = 0;
if (_currentPosition.Type == type)
{
levelsToComplete = 1;
}
else
{
int top = Top - 2;
for (int i = top; i >= 0; i--)
{
int currentLevel = top - i;
if (_stack[currentLevel].Type == type)
{
levelsToComplete = i + 2;
break;
}
}
}
if (levelsToComplete == 0)
throw JsonWriterException.Create(this, "No token to close.", null);
for (int i = 0; i < levelsToComplete; i++)
{
JsonToken token = GetCloseTokenForType(Pop());
if (_currentState == State.Property)
WriteNull();
if (_formatting == Formatting.Indented)
{
if (_currentState != State.ObjectStart && _currentState != State.ArrayStart)
WriteIndent();
}
WriteEnd(token);
JsonContainerType currentLevelType = Peek();
switch (currentLevelType)
{
case JsonContainerType.Object:
_currentState = State.Object;
break;
case JsonContainerType.Array:
_currentState = State.Array;
break;
case JsonContainerType.Constructor:
_currentState = State.Array;
break;
case JsonContainerType.None:
_currentState = State.Start;
break;
default:
throw JsonWriterException.Create(this, "Unknown JsonType: " + currentLevelType, null);
}
}
}
/// <summary>
/// Writes the specified end token.
/// </summary>
/// <param name="token">The end token to write.</param>
protected virtual void WriteEnd(JsonToken token)
{
}
/// <summary>
/// Writes indent characters.
/// </summary>
protected virtual void WriteIndent()
{
}
/// <summary>
/// Writes the JSON value delimiter.
/// </summary>
protected virtual void WriteValueDelimiter()
{
}
/// <summary>
/// Writes an indent space.
/// </summary>
protected virtual void WriteIndentSpace()
{
}
internal void AutoComplete(JsonToken tokenBeingWritten)
{
// gets new state based on the current state and what is being written
State newState = StateArray[(int)tokenBeingWritten][(int)_currentState];
if (newState == State.Error)
throw JsonWriterException.Create(this, "Token {0} in state {1} would result in an invalid JSON object.".FormatWith(CultureInfo.InvariantCulture, tokenBeingWritten.ToString(), _currentState.ToString()), null);
if ((_currentState == State.Object || _currentState == State.Array || _currentState == State.Constructor) && tokenBeingWritten != JsonToken.Comment)
{
WriteValueDelimiter();
}
if (_formatting == Formatting.Indented)
{
if (_currentState == State.Property)
WriteIndentSpace();
// don't indent a property when it is the first token to be written (i.e. at the start)
if ((_currentState == State.Array || _currentState == State.ArrayStart || _currentState == State.Constructor || _currentState == State.ConstructorStart)
|| (tokenBeingWritten == JsonToken.PropertyName && _currentState != State.Start))
WriteIndent();
}
_currentState = newState;
}
#region WriteValue methods
/// <summary>
/// Writes a null value.
/// </summary>
public virtual void WriteNull()
{
InternalWriteValue(JsonToken.Null);
}
/// <summary>
/// Writes an undefined value.
/// </summary>
public virtual void WriteUndefined()
{
InternalWriteValue(JsonToken.Undefined);
}
/// <summary>
/// Writes raw JSON without changing the writer's state.
/// </summary>
/// <param name="json">The raw JSON to write.</param>
public virtual void WriteRaw(string json)
{
InternalWriteRaw();
}
/// <summary>
/// Writes raw JSON where a value is expected and updates the writer's state.
/// </summary>
/// <param name="json">The raw JSON to write.</param>
public virtual void WriteRawValue(string json)
{
// hack. want writer to change state as if a value had been written
UpdateScopeWithFinishedValue();
AutoComplete(JsonToken.Undefined);
WriteRaw(json);
}
/// <summary>
/// Writes a <see cref="String"/> value.
/// </summary>
/// <param name="value">The <see cref="String"/> value to write.</param>
public virtual void WriteValue(string value)
{
InternalWriteValue(JsonToken.String);
}
/// <summary>
/// Writes a <see cref="Int32"/> value.
/// </summary>
/// <param name="value">The <see cref="Int32"/> value to write.</param>
public virtual void WriteValue(int value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="UInt32"/> value.
/// </summary>
/// <param name="value">The <see cref="UInt32"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(uint value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Int64"/> value.
/// </summary>
/// <param name="value">The <see cref="Int64"/> value to write.</param>
public virtual void WriteValue(long value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="UInt64"/> value.
/// </summary>
/// <param name="value">The <see cref="UInt64"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(ulong value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Single"/> value.
/// </summary>
/// <param name="value">The <see cref="Single"/> value to write.</param>
public virtual void WriteValue(float value)
{
InternalWriteValue(JsonToken.Float);
}
/// <summary>
/// Writes a <see cref="Double"/> value.
/// </summary>
/// <param name="value">The <see cref="Double"/> value to write.</param>
public virtual void WriteValue(double value)
{
InternalWriteValue(JsonToken.Float);
}
/// <summary>
/// Writes a <see cref="Boolean"/> value.
/// </summary>
/// <param name="value">The <see cref="Boolean"/> value to write.</param>
public virtual void WriteValue(bool value)
{
InternalWriteValue(JsonToken.Boolean);
}
/// <summary>
/// Writes a <see cref="Int16"/> value.
/// </summary>
/// <param name="value">The <see cref="Int16"/> value to write.</param>
public virtual void WriteValue(short value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="UInt16"/> value.
/// </summary>
/// <param name="value">The <see cref="UInt16"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(ushort value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Char"/> value.
/// </summary>
/// <param name="value">The <see cref="Char"/> value to write.</param>
public virtual void WriteValue(char value)
{
InternalWriteValue(JsonToken.String);
}
/// <summary>
/// Writes a <see cref="Byte"/> value.
/// </summary>
/// <param name="value">The <see cref="Byte"/> value to write.</param>
public virtual void WriteValue(byte value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="SByte"/> value.
/// </summary>
/// <param name="value">The <see cref="SByte"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(sbyte value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Decimal"/> value.
/// </summary>
/// <param name="value">The <see cref="Decimal"/> value to write.</param>
public virtual void WriteValue(decimal value)
{
InternalWriteValue(JsonToken.Float);
}
/// <summary>
/// Writes a <see cref="DateTime"/> value.
/// </summary>
/// <param name="value">The <see cref="DateTime"/> value to write.</param>
public virtual void WriteValue(DateTime value)
{
InternalWriteValue(JsonToken.Date);
}
#if !NET20
/// <summary>
/// Writes a <see cref="DateTimeOffset"/> value.
/// </summary>
/// <param name="value">The <see cref="DateTimeOffset"/> value to write.</param>
public virtual void WriteValue(DateTimeOffset value)
{
InternalWriteValue(JsonToken.Date);
}
#endif
/// <summary>
/// Writes a <see cref="Guid"/> value.
/// </summary>
/// <param name="value">The <see cref="Guid"/> value to write.</param>
public virtual void WriteValue(Guid value)
{
InternalWriteValue(JsonToken.String);
}
/// <summary>
/// Writes a <see cref="TimeSpan"/> value.
/// </summary>
/// <param name="value">The <see cref="TimeSpan"/> value to write.</param>
public virtual void WriteValue(TimeSpan value)
{
InternalWriteValue(JsonToken.String);
}
/// <summary>
/// Writes a <see cref="Nullable{Int32}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Int32}"/> value to write.</param>
public virtual void WriteValue(int? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{UInt32}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{UInt32}"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(uint? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Int64}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Int64}"/> value to write.</param>
public virtual void WriteValue(long? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{UInt64}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{UInt64}"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(ulong? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Single}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Single}"/> value to write.</param>
public virtual void WriteValue(float? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Double}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Double}"/> value to write.</param>
public virtual void WriteValue(double? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Boolean}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Boolean}"/> value to write.</param>
public virtual void WriteValue(bool? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Int16}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Int16}"/> value to write.</param>
public virtual void WriteValue(short? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{UInt16}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{UInt16}"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(ushort? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Char}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Char}"/> value to write.</param>
public virtual void WriteValue(char? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Byte}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Byte}"/> value to write.</param>
public virtual void WriteValue(byte? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{SByte}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{SByte}"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(sbyte? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Decimal}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Decimal}"/> value to write.</param>
public virtual void WriteValue(decimal? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{DateTime}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{DateTime}"/> value to write.</param>
public virtual void WriteValue(DateTime? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
#if !NET20
/// <summary>
/// Writes a <see cref="Nullable{DateTimeOffset}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{DateTimeOffset}"/> value to write.</param>
public virtual void WriteValue(DateTimeOffset? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
#endif
/// <summary>
/// Writes a <see cref="Nullable{Guid}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Guid}"/> value to write.</param>
public virtual void WriteValue(Guid? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{TimeSpan}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{TimeSpan}"/> value to write.</param>
public virtual void WriteValue(TimeSpan? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="T:Byte[]"/> value.
/// </summary>
/// <param name="value">The <see cref="T:Byte[]"/> value to write.</param>
public virtual void WriteValue(byte[] value)
{
if (value == null)
WriteNull();
else
InternalWriteValue(JsonToken.Bytes);
}
/// <summary>
/// Writes a <see cref="Uri"/> value.
/// </summary>
/// <param name="value">The <see cref="Uri"/> value to write.</param>
public virtual void WriteValue(Uri value)
{
if (value == null)
WriteNull();
else
InternalWriteValue(JsonToken.String);
}
/// <summary>
/// Writes a <see cref="Object"/> value.
/// An error will raised if the value cannot be written as a single JSON token.
/// </summary>
/// <param name="value">The <see cref="Object"/> value to write.</param>
public virtual void WriteValue(object value)
{
if (value == null)
{
WriteNull();
}
else
{
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
// this is here because adding a WriteValue(BigInteger) to JsonWriter will
// mean the user has to add a reference to System.Numerics.dll
if (value is BigInteger)
throw CreateUnsupportedTypeException(this, value);
#endif
WriteValue(this, ConvertUtils.GetTypeCode(value), value);
}
}
#endregion
/// <summary>
/// Writes out a comment <code>/*...*/</code> containing the specified text.
/// </summary>
/// <param name="text">Text to place inside the comment.</param>
public virtual void WriteComment(string text)
{
InternalWriteComment();
}
/// <summary>
/// Writes out the given white space.
/// </summary>
/// <param name="ws">The string of white space characters.</param>
public virtual void WriteWhitespace(string ws)
{
InternalWriteWhitespace(ws);
}
void IDisposable.Dispose()
{
Dispose(true);
}
private void Dispose(bool disposing)
{
if (_currentState != State.Closed)
Close();
}
internal static void WriteValue(JsonWriter writer, PrimitiveTypeCode typeCode, object value)
{
switch (typeCode)
{
case PrimitiveTypeCode.Char:
writer.WriteValue((char)value);
break;
case PrimitiveTypeCode.CharNullable:
writer.WriteValue((value == null) ? (char?)null : (char)value);
break;
case PrimitiveTypeCode.Boolean:
writer.WriteValue((bool)value);
break;
case PrimitiveTypeCode.BooleanNullable:
writer.WriteValue((value == null) ? (bool?)null : (bool)value);
break;
case PrimitiveTypeCode.SByte:
writer.WriteValue((sbyte)value);
break;
case PrimitiveTypeCode.SByteNullable:
writer.WriteValue((value == null) ? (sbyte?)null : (sbyte)value);
break;
case PrimitiveTypeCode.Int16:
writer.WriteValue((short)value);
break;
case PrimitiveTypeCode.Int16Nullable:
writer.WriteValue((value == null) ? (short?)null : (short)value);
break;
case PrimitiveTypeCode.UInt16:
writer.WriteValue((ushort)value);
break;
case PrimitiveTypeCode.UInt16Nullable:
writer.WriteValue((value == null) ? (ushort?)null : (ushort)value);
break;
case PrimitiveTypeCode.Int32:
writer.WriteValue((int)value);
break;
case PrimitiveTypeCode.Int32Nullable:
writer.WriteValue((value == null) ? (int?)null : (int)value);
break;
case PrimitiveTypeCode.Byte:
writer.WriteValue((byte)value);
break;
case PrimitiveTypeCode.ByteNullable:
writer.WriteValue((value == null) ? (byte?)null : (byte)value);
break;
case PrimitiveTypeCode.UInt32:
writer.WriteValue((uint)value);
break;
case PrimitiveTypeCode.UInt32Nullable:
writer.WriteValue((value == null) ? (uint?)null : (uint)value);
break;
case PrimitiveTypeCode.Int64:
writer.WriteValue((long)value);
break;
case PrimitiveTypeCode.Int64Nullable:
writer.WriteValue((value == null) ? (long?)null : (long)value);
break;
case PrimitiveTypeCode.UInt64:
writer.WriteValue((ulong)value);
break;
case PrimitiveTypeCode.UInt64Nullable:
writer.WriteValue((value == null) ? (ulong?)null : (ulong)value);
break;
case PrimitiveTypeCode.Single:
writer.WriteValue((float)value);
break;
case PrimitiveTypeCode.SingleNullable:
writer.WriteValue((value == null) ? (float?)null : (float)value);
break;
case PrimitiveTypeCode.Double:
writer.WriteValue((double)value);
break;
case PrimitiveTypeCode.DoubleNullable:
writer.WriteValue((value == null) ? (double?)null : (double)value);
break;
case PrimitiveTypeCode.DateTime:
writer.WriteValue((DateTime)value);
break;
case PrimitiveTypeCode.DateTimeNullable:
writer.WriteValue((value == null) ? (DateTime?)null : (DateTime)value);
break;
#if !NET20
case PrimitiveTypeCode.DateTimeOffset:
writer.WriteValue((DateTimeOffset)value);
break;
case PrimitiveTypeCode.DateTimeOffsetNullable:
writer.WriteValue((value == null) ? (DateTimeOffset?)null : (DateTimeOffset)value);
break;
#endif
case PrimitiveTypeCode.Decimal:
writer.WriteValue((decimal)value);
break;
case PrimitiveTypeCode.DecimalNullable:
writer.WriteValue((value == null) ? (decimal?)null : (decimal)value);
break;
case PrimitiveTypeCode.Guid:
writer.WriteValue((Guid)value);
break;
case PrimitiveTypeCode.GuidNullable:
writer.WriteValue((value == null) ? (Guid?)null : (Guid)value);
break;
case PrimitiveTypeCode.TimeSpan:
writer.WriteValue((TimeSpan)value);
break;
case PrimitiveTypeCode.TimeSpanNullable:
writer.WriteValue((value == null) ? (TimeSpan?)null : (TimeSpan)value);
break;
#if !(PORTABLE || PORTABLE40 || NET35 || NET20)
case PrimitiveTypeCode.BigInteger:
// this will call to WriteValue(object)
writer.WriteValue((BigInteger)value);
break;
case PrimitiveTypeCode.BigIntegerNullable:
// this will call to WriteValue(object)
writer.WriteValue((value == null) ? (BigInteger?)null : (BigInteger)value);
break;
#endif
case PrimitiveTypeCode.Uri:
writer.WriteValue((Uri)value);
break;
case PrimitiveTypeCode.String:
writer.WriteValue((string)value);
break;
case PrimitiveTypeCode.Bytes:
writer.WriteValue((byte[])value);
break;
#if !(PORTABLE || NETFX_CORE)
case PrimitiveTypeCode.DBNull:
writer.WriteNull();
break;
#endif
default:
#if !(PORTABLE || NETFX_CORE)
if (value is IConvertible)
{
// the value is a non-standard IConvertible
// convert to the underlying value and retry
IConvertible convertable = (IConvertible)value;
TypeInformation typeInformation = ConvertUtils.GetTypeInformation(convertable);
// if convertable has an underlying typecode of Object then attempt to convert it to a string
PrimitiveTypeCode resolvedTypeCode = (typeInformation.TypeCode == PrimitiveTypeCode.Object) ? PrimitiveTypeCode.String : typeInformation.TypeCode;
Type resolvedType = (typeInformation.TypeCode == PrimitiveTypeCode.Object) ? typeof(string) : typeInformation.Type;
object convertedValue = convertable.ToType(resolvedType, CultureInfo.InvariantCulture);
WriteValue(writer, resolvedTypeCode, convertedValue);
break;
}
else
#endif
{
throw CreateUnsupportedTypeException(writer, value);
}
}
}
private static JsonWriterException CreateUnsupportedTypeException(JsonWriter writer, object value)
{
return JsonWriterException.Create(writer, "Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.".FormatWith(CultureInfo.InvariantCulture, value.GetType()), null);
}
/// <summary>
/// Sets the state of the JsonWriter,
/// </summary>
/// <param name="token">The JsonToken being written.</param>
/// <param name="value">The value being written.</param>
protected void SetWriteState(JsonToken token, object value)
{
switch (token)
{
case JsonToken.StartObject:
InternalWriteStart(token, JsonContainerType.Object);
break;
case JsonToken.StartArray:
InternalWriteStart(token, JsonContainerType.Array);
break;
case JsonToken.StartConstructor:
InternalWriteStart(token, JsonContainerType.Constructor);
break;
case JsonToken.PropertyName:
if (!(value is string))
throw new ArgumentException("A name is required when setting property name state.", "value");
InternalWritePropertyName((string)value);
break;
case JsonToken.Comment:
InternalWriteComment();
break;
case JsonToken.Raw:
InternalWriteRaw();
break;
case JsonToken.Integer:
case JsonToken.Float:
case JsonToken.String:
case JsonToken.Boolean:
case JsonToken.Date:
case JsonToken.Bytes:
case JsonToken.Null:
case JsonToken.Undefined:
InternalWriteValue(token);
break;
case JsonToken.EndObject:
InternalWriteEnd(JsonContainerType.Object);
break;
case JsonToken.EndArray:
InternalWriteEnd(JsonContainerType.Array);
break;
case JsonToken.EndConstructor:
InternalWriteEnd(JsonContainerType.Constructor);
break;
default:
throw new ArgumentOutOfRangeException("token");
}
}
internal void InternalWriteEnd(JsonContainerType container)
{
AutoCompleteClose(container);
}
internal void InternalWritePropertyName(string name)
{
_currentPosition.PropertyName = name;
AutoComplete(JsonToken.PropertyName);
}
internal void InternalWriteRaw()
{
}
internal void InternalWriteStart(JsonToken token, JsonContainerType container)
{
UpdateScopeWithFinishedValue();
AutoComplete(token);
Push(container);
}
internal void InternalWriteValue(JsonToken token)
{
UpdateScopeWithFinishedValue();
AutoComplete(token);
}
internal void InternalWriteWhitespace(string ws)
{
if (ws != null)
{
if (!StringUtils.IsWhiteSpace(ws))
throw JsonWriterException.Create(this, "Only white space characters should be used.", null);
}
}
internal void InternalWriteComment()
{
AutoComplete(JsonToken.Comment);
}
}
}
| |
using System;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Xml;
using Epi;
using Epi.Data;
namespace Epi.Fields
{
/// <summary>
/// Image field
/// </summary>
public class ImageField : InputFieldWithSeparatePrompt
{
#region Private Members
/// <summary>
/// Boolean setting that determines if the image should keep its true size thus effectively cropped to the size of the image control.
/// </summary>
private bool shouldRetainImageSize;
/// <summary>
/// The full path of the image file to be displayed.
/// </summary>
private string fileName = string.Empty;
/// <summary>
/// The Xml view element of the ImageField.
/// </summary>
private XmlElement viewElement;
/// <summary>
/// Xml Node representation of ImageField.
/// </summary>
private XmlNode fieldNode;
private BackgroundWorker _updater;
private BackgroundWorker _inserter;
#endregion Private Members
#region Public Events
#endregion Public Events
#region Constructors
/// <summary>
/// Constructor for the class
/// </summary>
/// <param name="page">The page this field belongs to</param>
public ImageField(Page page) : base(page)
{
construct();
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="page">The page this field belongs to</param>
/// <param name="viewElement">The Xml view element of the ImageField.</param>
public ImageField(Page page, XmlElement viewElement) : base(page)
{
construct();
this.viewElement = viewElement;
this.Page = page;
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="view">The view this field belongs to</param>
public ImageField(View view) : base(view)
{
construct();
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="view">The view this field belongs to</param>
/// <param name="fieldNode">Xml Node representation of ImageField.</param>
public ImageField(View view, XmlNode fieldNode) : base(view)
{
construct();
this.fieldNode = fieldNode;
this.view.Project.Metadata.GetFieldData(this, this.fieldNode);
}
private void construct()
{
genericDbColumnType = GenericDbColumnType.Object;
this.dbColumnType = DbType.Object;
}
/// <summary>
/// Load ImageField from a System.Data.DataRow
/// </summary>
/// <param name="row"></param>
public override void LoadFromRow(DataRow row)
{
base.LoadFromRow(row);
shouldRetainImageSize = (bool)row["ShouldRetainImageSize"];
}
public ImageField Clone()
{
ImageField clone = (ImageField)this.MemberwiseClone();
base.AssignMembers(clone);
return clone;
}
#endregion Constructors
#region Public Properties
/// <summary>
/// Returns field type
/// </summary>
public override MetaFieldType FieldType
{
get
{
return MetaFieldType.Image;
}
}
/// <summary>
/// Gets/sets whether the image size is retained
/// </summary>
public bool ShouldRetainImageSize
{
get
{
return shouldRetainImageSize;
}
set
{
shouldRetainImageSize = value;
}
}
/// <summary>
/// Gets/sets the Xml view element of the field
/// </summary>
public XmlElement ViewElement
{
get
{
return viewElement;
}
set
{
viewElement = value;
}
}
/// <summary>
/// Returns a fully-typed current record value
/// </summary>
public byte[] CurrentRecordValue
{
get
{
if (base.CurrentRecordValueObject == null) return null;
else return (byte[])CurrentRecordValueObject;
}
set
{
base.CurrentRecordValueObject = value;
}
}
public override string GetDbSpecificColumnType()
{
return GetProject().CollectedData.GetDatabase().GetDbSpecificColumnType(GenericDbColumnType.Image);
}
#endregion Public Properties
#region Protected Properties
#endregion Protected Properties
#region Public Methods
/// <summary>
/// Deletes the field
/// </summary>
public override void Delete()
{
GetMetadata().DeleteField(this);
view.MustRefreshFieldCollection = true;
}
#endregion
#region Private Methods
/// <summary>
/// Inserts the field to the database
/// </summary>
protected override void InsertField()
{
this.Id = GetMetadata().CreateField(this);
base.OnFieldAdded();
}
/// <summary>
/// Update the field to the database
/// </summary>
protected override void UpdateField()
{
GetMetadata().UpdateField(this);
}
///// <summary>
///// Inserts the field to the database
///// </summary>
//protected override void InsertField()
//{
// insertStarted = true;
// _inserter = new BackgroundWorker();
// _inserter.DoWork += new DoWorkEventHandler(inserter_DoWork);
// _inserter.RunWorkerCompleted += new RunWorkerCompletedEventHandler(_inserter_RunWorkerCompleted);
// _inserter.RunWorkerAsync();
//}
//void _inserter_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
//{
// OnFieldInserted(this);
//}
//void inserter_DoWork(object sender, DoWorkEventArgs e)
//{
// fieldsWaitingToUpdate++;
// lock (view.FieldLockToken)
// {
// this.Id = GetMetadata().CreateField(this);
// base.OnFieldAdded();
// fieldsWaitingToUpdate--;
// }
//}
///// <summary>
///// Update the field to the database
///// </summary>
//protected override void UpdateField()
//{
// _updater = new BackgroundWorker();
// _updater.DoWork += new DoWorkEventHandler(DoWork);
// _updater.RunWorkerCompleted += new RunWorkerCompletedEventHandler(_updater_RunWorkerCompleted);
// _updater.RunWorkerAsync();
//}
//void _updater_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
//{
// OnFieldUpdated(this);
//}
//private void DoWork(object sender, DoWorkEventArgs e)
//{
// fieldsWaitingToUpdate++;
// lock (view.FieldLockToken)
// {
// GetMetadata().UpdateField(this);
// fieldsWaitingToUpdate--;
// }
//}
#endregion
#region Event Handlers
#endregion Event Handlers
}
}
| |
// 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.Linq;
using System.Text;
using SampleMetadata;
using Xunit;
namespace System.Reflection.Tests
{
public static class TypeInvariants
{
[Fact]
public static void TestInvariantCode()
{
// These run some *runtime*-implemented Type objects through our invariant battery.
// This is to ensure that the invariant testing code is actually correct.
typeof(object).TestTypeDefinitionInvariants();
typeof(OuterType1.InnerType1).TestTypeDefinitionInvariants();
typeof(IList<>).TestTypeDefinitionInvariants();
typeof(IDictionary<,>).TestTypeDefinitionInvariants();
typeof(object[]).TestSzArrayInvariants();
typeof(object).MakeArrayType(1).TestMdArrayInvariants();
typeof(object[,]).TestMdArrayInvariants();
typeof(object[,,]).TestMdArrayInvariants();
typeof(object).MakeByRefType().TestByRefInvariants();
typeof(int).MakePointerType().TestPointerInvariants();
typeof(IList<int>).TestConstructedGenericTypeInvariants();
typeof(IDictionary<int, string>).TestConstructedGenericTypeInvariants();
Type theT = typeof(IList<>).GetTypeInfo().GenericTypeParameters[0];
theT.TestGenericTypeParameterInvariants();
Type theV = typeof(IDictionary<,>).GetTypeInfo().GenericTypeParameters[1];
theT.TestGenericTypeParameterInvariants();
MethodInfo genericMethod = typeof(ClassWithGenericMethods1).GetMethod("GenericMethod1", BindingFlags.Public | BindingFlags.Instance);
Debug.Assert(genericMethod != null);
Type theM = genericMethod.GetGenericArguments()[0];
theM.TestGenericMethodParameterInvariants();
Type theN = genericMethod.GetGenericArguments()[1];
theN.TestGenericMethodParameterInvariants();
Type openSzArray = theN.MakeArrayType();
openSzArray.TestSzArrayInvariants();
Type openMdArrayRank1 = theN.MakeArrayType(1);
openMdArrayRank1.TestMdArrayInvariants();
Type openMdArrayRank2 = theN.MakeArrayType(2);
openMdArrayRank2.TestMdArrayInvariants();
Type openByRef = theN.MakeByRefType();
openByRef.TestByRefInvariants();
Type openPointer = theN.MakePointerType();
openPointer.TestPointerInvariants();
Type openDictionary = typeof(IDictionary<,>).MakeGenericType(typeof(int), theN);
openDictionary.TestConstructedGenericTypeInvariants();
}
internal static void TestTypeInvariants(this Type type)
{
if (type.IsTypeDefinition())
type.TestTypeDefinitionInvariants();
else if (type.HasElementType)
type.TestHasElementTypeInvariants();
else if (type.IsConstructedGenericType)
type.TestConstructedGenericTypeInvariants();
else if (type.IsGenericParameter)
type.TestGenericParameterInvariants();
else
Assert.True(false, "Type does not identify as any of the known flavors: " + type);
}
internal static void TestTypeDefinitionInvariants(this Type type)
{
Assert.True(type.IsTypeDefinition());
if (type.IsGenericTypeDefinition)
{
type.TestGenericTypeDefinitionInvariants();
}
else
{
type.TestTypeDefinitionCommonInvariants();
}
}
internal static void TestGenericTypeDefinitionInvariants(this Type type)
{
Assert.True(type.IsGenericTypeDefinition);
type.TestTypeDefinitionCommonInvariants();
Type[] gps = type.GetTypeInfo().GenericTypeParameters;
Assert.NotNull(gps);
Assert.NotEqual(0, gps.Length);
Type[] gps2 = type.GetTypeInfo().GenericTypeParameters;
Assert.NotSame(gps, gps2);
Assert.Equal<Type>(gps, gps2);
for (int i = 0; i < gps.Length; i++)
{
Type gp = gps[i];
Assert.Equal(i, gp.GenericParameterPosition);
Assert.Equal(type, gp.DeclaringType);
}
}
internal static void TestHasElementTypeInvariants(this Type type)
{
Assert.True(type.HasElementType);
if (type.IsSZArray())
type.TestSzArrayInvariants();
else if (type.IsVariableBoundArray())
type.TestMdArrayInvariants();
else if (type.IsByRef)
type.TestByRefInvariants();
else if (type.IsPointer)
type.TestPointerInvariants();
}
internal static void TestArrayInvariants(this Type type)
{
Assert.True(type.IsArray);
if (type.IsSZArray())
type.TestSzArrayInvariants();
else if (type.IsVariableBoundArray())
type.TestMdArrayInvariants();
else
Assert.True(false, "Array type does not identify as either Sz or VariableBound: " + type);
BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;
MemberInfo[] mems;
mems = type.GetEvents(bf);
Assert.Equal(0, mems.Length);
mems = type.GetFields(bf);
Assert.Equal(0, mems.Length);
mems = type.GetProperties(bf);
Assert.Equal(0, mems.Length);
mems = type.GetNestedTypes(bf);
Assert.Equal(0, mems.Length);
}
internal static void TestSzArrayInvariants(this Type type)
{
Assert.True(type.IsSZArray());
type.TestArrayCommonInvariants();
Type et = type.GetElementType();
string name = type.Name;
string fullName = type.FullName;
string suffix = "[]";
Assert.Equal(et.Name + suffix, name);
if (fullName != null)
{
Assert.Equal(et.FullName + suffix, fullName);
}
}
internal static void TestMdArrayInvariants(this Type type)
{
Assert.True(type.IsVariableBoundArray());
type.TestArrayCommonInvariants();
string name = type.Name;
string fullName = type.FullName;
Type et = type.GetElementType();
int rank = type.GetArrayRank();
string suffix = (rank == 1) ? "[*]" : "[" + new string(',', rank - 1) + "]";
Assert.Equal(et.Name + suffix, name);
if (fullName != null)
{
Assert.Equal(et.FullName + suffix, fullName);
}
Type systemInt32 = type.BaseType.Assembly.GetType("System.Int32", throwOnError: true);
ConstructorInfo[] cis = type.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly);
Assert.Equal(cis.Length, 2);
ConstructorInfo c1 = cis.Single(c => c.GetParameters().Length == rank);
foreach (ParameterInfo p in c1.GetParameters())
Assert.Equal(p.ParameterType, systemInt32);
ConstructorInfo c2 = cis.Single(c => c.GetParameters().Length == rank * 2);
foreach (ParameterInfo p in c2.GetParameters())
Assert.Equal(p.ParameterType, systemInt32);
}
internal static void TestByRefInvariants(this Type type)
{
Assert.True(type.IsByRef);
type.TestHasElementTypeCommonInvariants();
string name = type.Name;
string fullName = type.FullName;
Type et = type.GetElementType();
string suffix = "&";
Assert.Equal(et.Name + suffix, name);
if (fullName != null)
{
Assert.Equal(et.FullName + suffix, fullName);
}
// No base type, interfaces
Assert.Null(type.BaseType);
Assert.Equal(0, type.GetInterfaces().Length);
// No members
BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;
MemberInfo[] members = type.GetMembers(bf);
Assert.Equal(0, members.Length);
}
internal static void TestPointerInvariants(this Type type)
{
Assert.True(type.IsPointer);
type.TestHasElementTypeCommonInvariants();
string name = type.Name;
string fullName = type.FullName;
Type et = type.GetElementType();
string suffix = "*";
Assert.Equal(et.Name + suffix, name);
if (fullName != null)
{
Assert.Equal(et.FullName + suffix, fullName);
}
// No base type, interfaces
Assert.Null(type.BaseType);
Assert.Equal(0, type.GetInterfaces().Length);
// No members
BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;
MemberInfo[] members = type.GetMembers(bf);
Assert.Equal(0, members.Length);
}
internal static void TestConstructedGenericTypeInvariants(this Type type)
{
type.TestConstructedGenericTypeCommonInvariants();
}
internal static void TestGenericParameterInvariants(this Type type)
{
Assert.True(type.IsGenericParameter);
type.TestTypeCommonInvariants();
// No members
BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;
MemberInfo[] members = type.GetMembers(bf);
Assert.Equal(0, members.Length);
}
internal static void TestGenericTypeParameterInvariants(this Type type)
{
Assert.True(type.IsGenericTypeParameter());
type.TestGenericParameterCommonInvariants();
Assert.Null(type.DeclaringMethod);
int position = type.GenericParameterPosition;
Type declaringType = type.DeclaringType;
Assert.NotNull(declaringType);
Assert.True(declaringType.IsGenericTypeDefinition);
Type[] gps = declaringType.GetTypeInfo().GenericTypeParameters;
Assert.Equal(gps[position], type);
}
internal static void TestGenericMethodParameterInvariants(this Type type)
{
Assert.True(type.IsGenericMethodParameter());
type.TestGenericParameterCommonInvariants();
int position = type.GenericParameterPosition;
MethodInfo declaringMethod = (MethodInfo)type.DeclaringMethod;
Assert.NotNull(declaringMethod);
Assert.True(declaringMethod.IsGenericMethodDefinition);
Type declaringType = type.DeclaringType;
Assert.NotNull(declaringType);
Assert.Equal(declaringMethod.DeclaringType, declaringType);
Type[] gps = declaringMethod.GetGenericArguments();
Assert.Equal(gps[position], type);
// There is only one generic parameter instance even if it was queried from a method from an instantiated type or
// a method with an alternate ReflectedType.
Assert.False(declaringType.IsConstructedGenericType);
Assert.Equal(declaringType, declaringMethod.ReflectedType);
}
private static void TestTypeCommonInvariants(this Type type)
{
// Ensure that ToString() doesn't throw and that it returns some non-null value. Exact contents are considered implementation detail.
string typeString = type.ToString();
Assert.NotNull(typeString);
// These properties are mutually exclusive and exactly one of them must be true.
int isCount = 0;
isCount += type.IsTypeDefinition() ? 1 : 0;
isCount += type.IsSZArray() ? 1 : 0;
isCount += type.IsVariableBoundArray() ? 1 : 0;
isCount += type.IsByRef ? 1 : 0;
isCount += type.IsPointer ? 1 : 0;
isCount += type.IsConstructedGenericType ? 1 : 0;
isCount += type.IsGenericTypeParameter() ? 1 : 0;
isCount += type.IsGenericMethodParameter() ? 1 : 0;
Assert.Equal(1, isCount);
Assert.Equal(type.IsGenericType, type.IsGenericTypeDefinition || type.IsConstructedGenericType);
Assert.Equal(type.HasElementType, type.IsArray || type.IsByRef || type.IsPointer);
Assert.Equal(type.IsArray, type.IsSZArray() || type.IsVariableBoundArray());
Assert.Equal(type.IsGenericParameter, type.IsGenericTypeParameter() || type.IsGenericMethodParameter());
Assert.Same(type, type.GetTypeInfo());
Assert.Same(type, type.GetTypeInfo().AsType());
Assert.Same(type, type.UnderlyingSystemType);
Assert.Same(type.DeclaringType, type.ReflectedType);
Assert.Equal(type.IsPublic || type.IsNotPublic ? MemberTypes.TypeInfo : MemberTypes.NestedType, type.MemberType);
Assert.False(type.IsCOMObject);
Module module = type.Module;
Assembly assembly = type.Assembly;
Assert.Equal(module.Assembly, assembly);
string name = type.Name;
string ns = type.Namespace;
string fullName = type.FullName;
string aqn = type.AssemblyQualifiedName;
if (type.ContainsGenericParameters && !type.IsGenericTypeDefinition)
{
// Open types return null for FullName as such types cannot roundtrip through Type.GetType(string)
Assert.Null(fullName);
Assert.Null(aqn);
}
else
{
Assert.NotNull(fullName);
Assert.NotNull(aqn);
string expectedAqn = fullName + ", " + assembly.FullName;
Assert.Equal(expectedAqn, aqn);
}
if (fullName != null)
{
Type roundTrip = assembly.GetType(fullName, throwOnError: true, ignoreCase: false);
Assert.Same(type, roundTrip);
Type roundTrip2 = module.GetType(fullName, throwOnError: true, ignoreCase: false);
Assert.Same(type, roundTrip2);
}
Assert.Equal<Type>(type.GetInterfaces(), type.GetTypeInfo().ImplementedInterfaces);
TestUtils.AssertNewObjectReturnedEachTime(() => type.GenericTypeArguments);
TestUtils.AssertNewObjectReturnedEachTime(() => type.GetTypeInfo().GenericTypeParameters);
TestUtils.AssertNewObjectReturnedEachTime(() => type.GetGenericArguments());
TestUtils.AssertNewObjectReturnedEachTime(() => type.GetInterfaces());
TestUtils.AssertNewObjectReturnedEachTime(() => type.GetTypeInfo().ImplementedInterfaces);
CustomAttributeTests.ValidateCustomAttributesAllocatesFreshObjectsEachTime(() => type.CustomAttributes);
const BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.FlattenHierarchy;
foreach (MemberInfo mem in type.GetMember("*", MemberTypes.All, bf))
{
string s = mem.ToString();
Assert.Equal(type, mem.ReflectedType);
Type declaringType = mem.DeclaringType;
Assert.True(type == declaringType || type.IsSubclassOf(declaringType));
if (mem is MethodBase methodBase)
methodBase.TestMethodBaseInvariants();
if (type.Assembly.ReflectionOnly)
{
ICustomAttributeProvider icp = mem;
Assert.Throws<InvalidOperationException>(() => icp.IsDefined(null, inherit: false));
Assert.Throws<InvalidOperationException>(() => icp.GetCustomAttributes(null, inherit: false)); ;
Assert.Throws<InvalidOperationException>(() => icp.GetCustomAttributes(inherit: false));
if (mem is MethodBase mb)
{
Assert.Throws<InvalidOperationException>(() => mb.MethodHandle);
Assert.Throws<InvalidOperationException>(() => mb.Invoke(null,null));
}
}
}
TestUtils.AssertNewObjectReturnedEachTime(() => type.GetMember("*", MemberTypes.All, bf));
// Test some things that common to types that are not of a particular bucket.
// (The Test*CommonInvariants() methods will cover the other half.)
if (!type.IsTypeDefinition())
{
Assert.False(type.IsGenericTypeDefinition);
Assert.Equal(0, type.GetTypeInfo().GenericTypeParameters.Length);
}
if (!type.IsGenericTypeDefinition)
{
Assert.Throws<InvalidOperationException>(() => type.MakeGenericType(new Type[3]));
}
if (!type.HasElementType)
{
Assert.Null(type.GetElementType());
}
if (!type.IsArray)
{
Assert.False(type.IsSZArray() || type.IsVariableBoundArray());
Assert.Throws<ArgumentException>(() => type.GetArrayRank());
}
if (!type.IsByRef)
{
}
if (!type.IsPointer)
{
}
if (!type.IsConstructedGenericType)
{
Assert.Equal(0, type.GenericTypeArguments.Length);
if (!type.IsGenericTypeDefinition)
{
Assert.Throws<InvalidOperationException>(() => type.GetGenericTypeDefinition());
}
}
if (!type.IsGenericParameter)
{
Assert.Throws<InvalidOperationException>(() => type.GenericParameterAttributes);
Assert.Throws<InvalidOperationException>(() => type.GenericParameterPosition);
Assert.Throws<InvalidOperationException>(() => type.GetGenericParameterConstraints());
Assert.Throws<InvalidOperationException>(() => type.DeclaringMethod);
}
}
private static void TestTypeDefinitionCommonInvariants(this Type type)
{
type.TestTypeCommonInvariants();
Assert.True(type.IsTypeDefinition());
Assert.Equal(type.IsGenericTypeDefinition, type.ContainsGenericParameters);
string name = type.Name;
string ns = type.Namespace;
string fullName = type.FullName;
Assert.NotNull(name);
Assert.NotNull(fullName);
string expectedFullName;
if (type.IsNested)
{
expectedFullName = type.DeclaringType.FullName + "+" + name;
}
else
{
expectedFullName = (ns == null) ? name : ns + "." + name;
}
Assert.Equal(expectedFullName, fullName);
Type declaringType = type.DeclaringType;
if (declaringType != null)
{
Assert.True(declaringType.IsTypeDefinition());
Type[] nestedTypes = declaringType.GetNestedTypes(BindingFlags.Public | BindingFlags.NonPublic);
Assert.True(nestedTypes.Any(nt => object.ReferenceEquals(nt, type)));
}
Assert.Equal<Type>(type.GetTypeInfo().GenericTypeParameters, type.GetGenericArguments());
int metadataToken = type.MetadataToken;
Assert.Equal(0x02000000, metadataToken & 0xff000000);
}
private static void TestHasElementTypeCommonInvariants(this Type type)
{
type.TestTypeCommonInvariants();
Assert.True(type.HasElementType);
Assert.True(type.IsArray || type.IsByRef || type.IsPointer);
Type et = type.GetElementType();
Assert.NotNull(et);
string ns = type.Namespace;
Assert.Equal(et.Namespace, ns);
Assert.Equal(et.Assembly, type.Assembly);
Assert.Equal(et.Module, type.Module);
Assert.Equal(et.ContainsGenericParameters, type.ContainsGenericParameters);
Assert.Null(type.DeclaringType);
Assert.False(type.IsByRefLike());
Assert.Equal(default(Guid), type.GUID);
Assert.Equal(0x02000000, type.MetadataToken);
Type rootElementType = type;
while (rootElementType.HasElementType)
{
rootElementType = rootElementType.GetElementType();
}
Assert.Equal<Type>(rootElementType.GetGenericArguments(), type.GetGenericArguments());
}
private static void TestArrayCommonInvariants(this Type type)
{
type.TestHasElementTypeCommonInvariants();
Assert.True(type.IsArray);
}
private static void TestConstructedGenericTypeCommonInvariants(this Type type)
{
Assert.True(type.IsConstructedGenericType);
type.TestTypeCommonInvariants();
string name = type.Name;
string ns = type.Namespace;
string fullName = type.FullName;
Type gd = type.GetGenericTypeDefinition();
Assert.Equal(gd.Name, name);
Assert.Equal(gd.Namespace, ns);
if (fullName != null)
{
StringBuilder expectedFullName = new StringBuilder();
expectedFullName.Append(gd.FullName);
expectedFullName.Append('[');
Type[] genericTypeArguments = type.GenericTypeArguments;
for (int i = 0; i < genericTypeArguments.Length; i++)
{
if (i != 0)
expectedFullName.Append(',');
expectedFullName.Append('[');
expectedFullName.Append(genericTypeArguments[i].AssemblyQualifiedName);
expectedFullName.Append(']');
}
expectedFullName.Append(']');
Assert.Equal(expectedFullName.ToString(), fullName);
}
Assert.Equal(type.GenericTypeArguments.Any(gta => gta.ContainsGenericParameters), type.ContainsGenericParameters);
Type[] gas = type.GenericTypeArguments;
Assert.NotNull(gas);
Assert.NotEqual(0, gas.Length);
Type[] gas2 = type.GenericTypeArguments;
Assert.NotSame(gas, gas2);
Assert.Equal<Type>(gas, gas2);
Assert.Same(type.GetGenericTypeDefinition().DeclaringType, type.DeclaringType);
Assert.Equal<Type>(type.GenericTypeArguments, type.GetGenericArguments());
Assert.Equal(type.GetGenericTypeDefinition().MetadataToken, type.MetadataToken);
}
private static void TestGenericParameterCommonInvariants(this Type type)
{
type.TestTypeCommonInvariants();
Assert.True(type.IsGenericParameter);
Assert.True(type.ContainsGenericParameters);
string ns = type.Namespace;
Assert.Equal(type.DeclaringType.Namespace, ns);
Assert.Null(type.FullName);
// Make sure these don't throw.
int position = type.GenericParameterPosition;
Assert.True(position >= 0);
GenericParameterAttributes attributes = type.GenericParameterAttributes;
Assert.Equal<Type>(Array.Empty<Type>(), type.GetGenericArguments());
Assert.False(type.IsByRefLike());
Assert.Equal(default(Guid), type.GUID);
int metadataToken = type.MetadataToken;
Assert.Equal(0x2a000000, metadataToken & 0xff000000);
// No members
BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;
MemberInfo[] members = type.GetMembers(bf);
Assert.Equal(0, members.Length);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace StudentSystem.Api.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
#region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
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
#if !NET35
using System;
using System.Abstract;
using System.Collections.Generic;
namespace Munq.Abstract
{
/// <summary>
/// IMunqServiceLocator
/// </summary>
public interface IMunqServiceLocator : IServiceLocator
{
/// <summary>
/// Gets the container.
/// </summary>
IocContainer Container { get; }
}
/// <summary>
/// MunqServiceLocator
/// </summary>
[Serializable]
public class MunqServiceLocator : IMunqServiceLocator, IDisposable, ServiceLocatorManager.ISetupRegistration
{
private IocContainer _container;
private MunqServiceRegistrar _registrar;
static MunqServiceLocator() { ServiceLocatorManager.EnsureRegistration(); }
/// <summary>
/// Initializes a new instance of the <see cref="MunqServiceLocator"/> class.
/// </summary>
public MunqServiceLocator()
: this(new IocContainer()) { }
/// <summary>
/// Initializes a new instance of the <see cref="MunqServiceLocator"/> class.
/// </summary>
/// <param name="container">The container.</param>
public MunqServiceLocator(object container)
{
if (container == null)
throw new ArgumentNullException("container");
Container = (container as IocContainer);
if (Container == null)
throw new ArgumentOutOfRangeException("container", "Must be of type Munq.IocContainer");
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
if (_container != null)
{
var container = _container;
_container = null;
_registrar = null;
// prevent cyclical dispose
if (container != null)
container.Dispose();
}
}
Action<IServiceLocator, string> ServiceLocatorManager.ISetupRegistration.DefaultServiceRegistrar
{
get { return (locator, name) => ServiceLocatorManager.RegisterInstance<IMunqServiceLocator>(this, locator, name); }
}
/// <summary>
/// Gets the service object of the specified type.
/// </summary>
/// <param name="serviceType">An object that specifies the type of service object to get.</param>
/// <returns>
/// A service object of type <paramref name="serviceType"/>.-or- null if there is no service object of type <paramref name="serviceType"/>.
/// </returns>
public object GetService(Type serviceType) { return Resolve(serviceType); }
/// <summary>
/// Creates the child.
/// </summary>
/// <returns></returns>
public IServiceLocator CreateChild(object tag) { throw new NotSupportedException(); }
/// <summary>
/// Gets the underlying container.
/// </summary>
/// <typeparam name="TContainer">The type of the container.</typeparam>
/// <returns></returns>
public TContainer GetUnderlyingContainer<TContainer>()
where TContainer : class { return (_container as TContainer); }
// registrar
/// <summary>
/// Gets the registrar.
/// </summary>
public IServiceRegistrar Registrar
{
get { return _registrar; }
}
// resolve
/// <summary>
/// Resolves this instance.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <returns></returns>
public TService Resolve<TService>()
where TService : class
{
try { return _container.Resolve<TService>(); }
catch (Exception ex) { throw new ServiceLocatorResolutionException(typeof(TService), ex); }
}
/// <summary>
/// Resolves the specified name.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <param name="name">The name.</param>
/// <returns></returns>
public TService Resolve<TService>(string name)
where TService : class
{
try { return _container.Resolve<TService>(name); }
catch (Exception ex) { throw new ServiceLocatorResolutionException(typeof(TService), ex); }
}
/// <summary>
/// Resolves the specified service type.
/// </summary>
/// <param name="serviceType">Type of the service.</param>
/// <returns></returns>
public object Resolve(Type serviceType)
{
try { return _container.Resolve(serviceType); }
catch (Exception ex) { throw new ServiceLocatorResolutionException(serviceType, ex); }
}
/// <summary>
/// Resolves the specified service type.
/// </summary>
/// <param name="serviceType">Type of the service.</param>
/// <param name="name">The name.</param>
/// <returns></returns>
public object Resolve(Type serviceType, string name)
{
try { return _container.Resolve(name, serviceType); }
catch (Exception ex) { throw new ServiceLocatorResolutionException(serviceType, ex); }
}
//
/// <summary>
/// Resolves all.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <returns></returns>
public IEnumerable<TService> ResolveAll<TService>()
where TService : class
{
try { return new List<TService>(_container.ResolveAll<TService>()); }
catch (Exception ex) { throw new ServiceLocatorResolutionException(typeof(TService), ex); }
}
/// <summary>
/// Resolves all.
/// </summary>
/// <param name="serviceType">Type of the service.</param>
/// <returns></returns>
public IEnumerable<object> ResolveAll(Type serviceType)
{
try { return new List<object>(_container.ResolveAll(serviceType)); }
catch (Exception ex) { throw new ServiceLocatorResolutionException(serviceType, ex); }
}
// inject
/// <summary>
/// Injects the specified instance.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <param name="instance">The instance.</param>
/// <returns></returns>
public TService Inject<TService>(TService instance)
where TService : class { throw new NotSupportedException(); }
// release and teardown
/// <summary>
/// Releases the specified instance.
/// </summary>
/// <param name="instance">The instance.</param>
[Obsolete("Not used for any real purposes.")]
public void Release(object instance) { throw new NotSupportedException(); }
/// <summary>
/// Tears down.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <param name="instance">The instance.</param>
[Obsolete("Not used for any real purposes.")]
public void TearDown<TService>(TService instance)
where TService : class { throw new NotSupportedException(); }
#region Domain specific
/// <summary>
/// Gets the container.
/// </summary>
public IocContainer Container
{
get { return _container; }
private set
{
_container = value;
_registrar = new MunqServiceRegistrar(this, value);
}
}
#endregion
}
}
#endif
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Text;
namespace WebsitePanel.Server
{
public class TerminalSession
{
private int sessionId;
private string username;
private string status;
public int SessionId
{
get { return this.sessionId; }
set { this.sessionId = value; }
}
public string Username
{
get { return this.username; }
set { this.username = value; }
}
public string Status
{
get { return this.status; }
set { this.status = value; }
}
}
public class WindowsProcess
{
private int pid;
private string name;
private string username;
private long cpuUsage;
private long memUsage;
public int Pid
{
get { return this.pid; }
set { this.pid = value; }
}
public string Name
{
get { return this.name; }
set { this.name = value; }
}
public string Username
{
get { return this.username; }
set { this.username = value; }
}
public long CpuUsage
{
get { return this.cpuUsage; }
set { this.cpuUsage = value; }
}
public long MemUsage
{
get { return this.memUsage; }
set { this.memUsage = value; }
}
}
public class WindowsService
{
private string id;
private string name;
private WindowsServiceStatus status;
private bool canStop;
private bool canPauseAndContinue;
public WindowsService()
{
}
public string Name
{
get { return this.name; }
set { this.name = value; }
}
public WindowsServiceStatus Status
{
get { return this.status; }
set { this.status = value; }
}
public bool CanStop
{
get { return this.canStop; }
set { this.canStop = value; }
}
public bool CanPauseAndContinue
{
get { return this.canPauseAndContinue; }
set { this.canPauseAndContinue = value; }
}
public string Id
{
get { return this.id; }
set { this.id = value; }
}
}
public enum WindowsServiceStatus
{
ContinuePending = 1,
Paused = 2,
PausePending = 3,
Running = 4,
StartPending = 5,
Stopped = 6,
StopPending = 7
}
public class SystemLogEntriesPaged
{
private int count;
private SystemLogEntry[] entries;
public int Count
{
get { return count; }
set { count = value; }
}
public SystemLogEntry[] Entries
{
get { return entries; }
set { entries = value; }
}
}
public class SystemLogEntry
{
private SystemLogEntryType entryType;
private DateTime created;
private string source;
private string category;
private long eventId;
private string userName;
private string machineName;
private string message;
public SystemLogEntryType EntryType
{
get { return entryType; }
set { entryType = value; }
}
public DateTime Created
{
get { return created; }
set { created = value; }
}
public string Source
{
get { return source; }
set { source = value; }
}
public string Category
{
get { return category; }
set { category = value; }
}
public string UserName
{
get { return userName; }
set { userName = value; }
}
public string MachineName
{
get { return machineName; }
set { machineName = value; }
}
public long EventID
{
get { return eventId; }
set { eventId = value; }
}
public string Message
{
get { return message; }
set { message = value; }
}
}
public enum SystemLogEntryType
{
Information,
Warning,
Error,
SuccessAudit,
FailureAudit
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.ComponentModel;
using System.Drawing.Internal;
using Gdip = System.Drawing.SafeNativeMethods.Gdip;
namespace System.Drawing.Drawing2D
{
public sealed class PathGradientBrush : Brush
{
public PathGradientBrush(PointF[] points) : this(points, WrapMode.Clamp) { }
public unsafe PathGradientBrush(PointF[] points, WrapMode wrapMode)
{
if (points == null)
throw new ArgumentNullException(nameof(points));
if (wrapMode < WrapMode.Tile || wrapMode > WrapMode.Clamp)
throw new InvalidEnumArgumentException(nameof(wrapMode), unchecked((int)wrapMode), typeof(WrapMode));
// GdipCreatePathGradient returns InsufficientBuffer for less than 3 points, which we turn into
// OutOfMemoryException(). We used to copy nothing into an empty native buffer for zero points,
// which gives a valid pointer. Fixing an empty array gives a null pointer, which causes an
// InvalidParameter result, which we turn into an ArgumentException. Matching the old throw.
if (points.Length == 0)
throw new OutOfMemoryException();
fixed (PointF* p = points)
{
Gdip.CheckStatus(Gdip.GdipCreatePathGradient(
p, points.Length, wrapMode, out IntPtr nativeBrush));
SetNativeBrushInternal(nativeBrush);
}
}
public PathGradientBrush(Point[] points) : this(points, WrapMode.Clamp) { }
public unsafe PathGradientBrush(Point[] points, WrapMode wrapMode)
{
if (points == null)
throw new ArgumentNullException(nameof(points));
if (wrapMode < WrapMode.Tile || wrapMode > WrapMode.Clamp)
throw new InvalidEnumArgumentException(nameof(wrapMode), unchecked((int)wrapMode), typeof(WrapMode));
// GdipCreatePathGradient returns InsufficientBuffer for less than 3 points, which we turn into
// OutOfMemoryException(). We used to copy nothing into an empty native buffer for zero points,
// which gives a valid pointer. Fixing an empty array gives a null pointer, which causes an
// InvalidParameter result, which we turn into an ArgumentException. Matching the old throw.
if (points.Length == 0)
throw new OutOfMemoryException();
fixed (Point* p = points)
{
Gdip.CheckStatus(Gdip.GdipCreatePathGradientI(
p, points.Length, wrapMode, out IntPtr nativeBrush));
SetNativeBrushInternal(nativeBrush);
}
}
public PathGradientBrush(GraphicsPath path)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
Gdip.CheckStatus(Gdip.GdipCreatePathGradientFromPath(new HandleRef(path, path._nativePath), out IntPtr nativeBrush));
SetNativeBrushInternal(nativeBrush);
}
internal PathGradientBrush(IntPtr nativeBrush)
{
Debug.Assert(nativeBrush != IntPtr.Zero, "Initializing native brush with null.");
SetNativeBrushInternal(nativeBrush);
}
public override object Clone()
{
Gdip.CheckStatus(Gdip.GdipCloneBrush(new HandleRef(this, NativeBrush), out IntPtr clonedBrush));
return new PathGradientBrush(clonedBrush);
}
public Color CenterColor
{
get
{
Gdip.CheckStatus(Gdip.GdipGetPathGradientCenterColor(new HandleRef(this, NativeBrush), out int argb));
return Color.FromArgb(argb);
}
set
{
Gdip.CheckStatus(Gdip.GdipSetPathGradientCenterColor(new HandleRef(this, NativeBrush), value.ToArgb()));
}
}
public Color[] SurroundColors
{
get
{
Gdip.CheckStatus(Gdip.GdipGetPathGradientSurroundColorCount(
new HandleRef(this, NativeBrush),
out int count));
int[] argbs = new int[count];
Gdip.CheckStatus(Gdip.GdipGetPathGradientSurroundColorsWithCount(
new HandleRef(this, NativeBrush),
argbs,
ref count));
Color[] colors = new Color[count];
for (int i = 0; i < count; i++)
colors[i] = Color.FromArgb(argbs[i]);
return colors;
}
set
{
int count = value.Length;
int[] argbs = new int[count];
for (int i = 0; i < value.Length; i++)
argbs[i] = value[i].ToArgb();
Gdip.CheckStatus(Gdip.GdipSetPathGradientSurroundColorsWithCount(
new HandleRef(this, NativeBrush),
argbs,
ref count));
}
}
public PointF CenterPoint
{
get
{
Gdip.CheckStatus(Gdip.GdipGetPathGradientCenterPoint(new HandleRef(this, NativeBrush), out PointF point));
return point;
}
set
{
Gdip.CheckStatus(Gdip.GdipSetPathGradientCenterPoint(new HandleRef(this, NativeBrush), ref value));
}
}
public RectangleF Rectangle
{
get
{
Gdip.CheckStatus(Gdip.GdipGetPathGradientRect(new HandleRef(this, NativeBrush), out RectangleF rect));
return rect;
}
}
public Blend Blend
{
get
{
// Figure out the size of blend factor array
Gdip.CheckStatus(Gdip.GdipGetPathGradientBlendCount(new HandleRef(this, NativeBrush), out int retval));
// Allocate temporary native memory buffer
int count = retval;
var factors = new float[count];
var positions = new float[count];
// Retrieve horizontal blend factors
Gdip.CheckStatus(Gdip.GdipGetPathGradientBlend(new HandleRef(this, NativeBrush), factors, positions, count));
// Return the result in a managed array
Blend blend = new Blend(count)
{
Factors = factors,
Positions = positions
};
return blend;
}
set
{
// This is the behavior on Desktop
if (value == null || value.Factors == null)
throw new NullReferenceException();
// The Desktop implementation throws ArgumentNullException("source") because it never validates the value of value.Positions, and then passes it
// on to Marshal.Copy(value.Positions, 0, positions, count);. The first argument of Marshal.Copy is source, hence this exception.
if (value.Positions == null)
throw new ArgumentNullException("source");
int count = value.Factors.Length;
// Explicit argument validation, because libgdiplus does not correctly validate all parameters.
if (count == 0 || value.Positions.Length == 0)
throw new ArgumentException(SR.BlendObjectMustHaveTwoElements);
if (count >= 2 && count != value.Positions.Length)
throw new ArgumentOutOfRangeException();
if (count >= 2 && value.Positions[0] != 0.0F)
throw new ArgumentException(SR.BlendObjectFirstElementInvalid);
if (count >= 2 && value.Positions[count - 1] != 1.0F)
throw new ArgumentException(SR.BlendObjectLastElementInvalid);
// Allocate temporary native memory buffer
// and copy input blend factors into it.
IntPtr factors = IntPtr.Zero;
IntPtr positions = IntPtr.Zero;
try
{
int size = checked(4 * count);
factors = Marshal.AllocHGlobal(size);
positions = Marshal.AllocHGlobal(size);
Marshal.Copy(value.Factors, 0, factors, count);
Marshal.Copy(value.Positions, 0, positions, count);
// Set blend factors
Gdip.CheckStatus(Gdip.GdipSetPathGradientBlend(new HandleRef(this, NativeBrush), new HandleRef(null, factors), new HandleRef(null, positions), count));
}
finally
{
if (factors != IntPtr.Zero)
{
Marshal.FreeHGlobal(factors);
}
if (positions != IntPtr.Zero)
{
Marshal.FreeHGlobal(positions);
}
}
}
}
public void SetSigmaBellShape(float focus) => SetSigmaBellShape(focus, (float)1.0);
public void SetSigmaBellShape(float focus, float scale)
{
if (focus < 0 || focus > 1)
throw new ArgumentException(SR.GdiplusInvalidParameter, nameof(focus));
if (scale < 0 || scale > 1)
throw new ArgumentException(SR.GdiplusInvalidParameter, nameof(scale));
Gdip.CheckStatus(Gdip.GdipSetPathGradientSigmaBlend(new HandleRef(this, NativeBrush), focus, scale));
}
public void SetBlendTriangularShape(float focus) => SetBlendTriangularShape(focus, (float)1.0);
public void SetBlendTriangularShape(float focus, float scale)
{
if (focus < 0 || focus > 1)
throw new ArgumentException(SR.GdiplusInvalidParameter, nameof(focus));
if (scale < 0 || scale > 1)
throw new ArgumentException(SR.GdiplusInvalidParameter, nameof(scale));
Gdip.CheckStatus(Gdip.GdipSetPathGradientLinearBlend(new HandleRef(this, NativeBrush), focus, scale));
}
public ColorBlend InterpolationColors
{
get
{
// Figure out the size of blend factor array
Gdip.CheckStatus(Gdip.GdipGetPathGradientPresetBlendCount(new HandleRef(this, NativeBrush), out int count));
// If count is 0, then there is nothing to marshal.
// In this case, we'll return an empty ColorBlend...
if (count == 0)
return new ColorBlend();
int[] colors = new int[count];
float[] positions = new float[count];
ColorBlend blend = new ColorBlend(count);
// status would fail if we ask points or types with a < 2 count
if (count < 2)
return blend;
// Retrieve horizontal blend factors
Gdip.CheckStatus(Gdip.GdipGetPathGradientPresetBlend(new HandleRef(this, NativeBrush), colors, positions, count));
// Return the result in a managed array
blend.Positions = positions;
// copy ARGB values into Color array of ColorBlend
blend.Colors = new Color[count];
for (int i = 0; i < count; i++)
{
blend.Colors[i] = Color.FromArgb(colors[i]);
}
return blend;
}
set
{
// The Desktop implementation will throw various exceptions - ranging from NullReferenceExceptions to Argument(OutOfRange)Exceptions
// depending on how sane the input is. These checks exist to replicate the exact Desktop behavior.
int count = value.Colors.Length;
if (value.Positions == null)
throw new ArgumentNullException("source");
if (value.Colors.Length > value.Positions.Length)
throw new ArgumentOutOfRangeException();
if (value.Colors.Length < value.Positions.Length)
throw new ArgumentException();
float[] positions = value.Positions;
int[] argbs = new int[count];
for (int i = 0; i < count; i++)
{
argbs[i] = value.Colors[i].ToArgb();
}
// Set blend factors
Gdip.CheckStatus(Gdip.GdipSetPathGradientPresetBlend(new HandleRef(this, NativeBrush), argbs, positions, count));
}
}
public Matrix Transform
{
get
{
Matrix matrix = new Matrix();
Gdip.CheckStatus(Gdip.GdipGetPathGradientTransform(new HandleRef(this, NativeBrush), new HandleRef(matrix, matrix.NativeMatrix)));
return matrix;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
Gdip.CheckStatus(Gdip.GdipSetPathGradientTransform(new HandleRef(this, NativeBrush), new HandleRef(value, value.NativeMatrix)));
}
}
public void ResetTransform()
{
Gdip.CheckStatus(Gdip.GdipResetPathGradientTransform(new HandleRef(this, NativeBrush)));
}
public void MultiplyTransform(Matrix matrix) => MultiplyTransform(matrix, MatrixOrder.Prepend);
public void MultiplyTransform(Matrix matrix, MatrixOrder order)
{
if (matrix == null)
throw new ArgumentNullException(nameof(matrix));
// Multiplying the transform by a disposed matrix is a nop in GDI+, but throws
// with the libgdiplus backend. Simulate a nop for compatability with GDI+.
if (matrix.NativeMatrix == IntPtr.Zero)
return;
Gdip.CheckStatus(Gdip.GdipMultiplyPathGradientTransform(
new HandleRef(this, NativeBrush),
new HandleRef(matrix, matrix.NativeMatrix),
order));
}
public void TranslateTransform(float dx, float dy) => TranslateTransform(dx, dy, MatrixOrder.Prepend);
public void TranslateTransform(float dx, float dy, MatrixOrder order)
{
Gdip.CheckStatus(Gdip.GdipTranslatePathGradientTransform(new HandleRef(this, NativeBrush), dx, dy, order));
}
public void ScaleTransform(float sx, float sy) => ScaleTransform(sx, sy, MatrixOrder.Prepend);
public void ScaleTransform(float sx, float sy, MatrixOrder order)
{
Gdip.CheckStatus(Gdip.GdipScalePathGradientTransform(new HandleRef(this, NativeBrush), sx, sy, order));
}
public void RotateTransform(float angle) => RotateTransform(angle, MatrixOrder.Prepend);
public void RotateTransform(float angle, MatrixOrder order)
{
Gdip.CheckStatus(Gdip.GdipRotatePathGradientTransform(new HandleRef(this, NativeBrush), angle, order));
}
public PointF FocusScales
{
get
{
float[] scaleX = new float[] { 0.0f };
float[] scaleY = new float[] { 0.0f };
Gdip.CheckStatus(Gdip.GdipGetPathGradientFocusScales(new HandleRef(this, NativeBrush), scaleX, scaleY));
return new PointF(scaleX[0], scaleY[0]);
}
set
{
Gdip.CheckStatus(Gdip.GdipSetPathGradientFocusScales(new HandleRef(this, NativeBrush), value.X, value.Y));
}
}
public WrapMode WrapMode
{
get
{
Gdip.CheckStatus(Gdip.GdipGetPathGradientWrapMode(new HandleRef(this, NativeBrush), out int mode));
return (WrapMode)mode;
}
set
{
if (value < WrapMode.Tile || value > WrapMode.Clamp)
throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(WrapMode));
Gdip.CheckStatus(Gdip.GdipSetPathGradientWrapMode(new HandleRef(this, NativeBrush), unchecked((int)value)));
}
}
}
}
| |
using System;
using System.Net.Sockets;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
namespace M3U8downloader
{
public class NetworkServer
{
TcpListener listener;
TcpClient client;
NetworkStream stream;
StreamReader reader;
StreamWriter writer;
public NetworkServer (){}
public bool Abre(int puerto){
try{
Console.WriteLine ("Abriendo servidor en \"127.0.0.1:" + puerto + "\"...");
listener = new TcpListener (IPAddress.Loopback, puerto);
listener.Start ();
Console.WriteLine ("Servidor abierto.");
return true;
}
catch(Exception e){
Console.WriteLine ("h0");
Console.WriteLine (e);
return false;
}
}
public RespuestaHTTP Escucha ()
{
try{
client = listener.AcceptTcpClient ();
DDebug.WriteLine ("Conexion establecida");
stream = client.GetStream ();
reader = new StreamReader (stream);
writer = new StreamWriter (stream);
stream.ReadTimeout = 30000;
// limpiar stream
string entrada = "";
while (entrada.Length < 4 || entrada.Substring(entrada.Length - 4, 4) != "\r\n\r\n") {
entrada += (char) reader.Read();
}
DDebug.WriteLine(entrada);
stream.Flush();
string GETurl = entrada.Substring(0, entrada.IndexOf("\r\n"));
if(GETurl != null){
string pattern = " (.*?) HTTP";
MatchCollection matches = Regex.Matches (GETurl, pattern);
string url="";
if (matches.Count > 0) {
GroupCollection gc = matches[0].Groups;
CaptureCollection cc = gc[1].Captures;
url = cc[0].Value;
}
DDebug.WriteLine (url);
pattern = "\\?(&?([^=^&]+?)=([^&]*))*";
matches = Regex.Matches (url, pattern);
//Utilidades.print_r_regex(matches);
if (matches.Count > 0) {
GroupCollection gc = matches[0].Groups;
CaptureCollection variables = gc[2].Captures;
CaptureCollection valores = gc[3].Captures;
ParametroGet[] parametros = new ParametroGet[variables.Count];
for(int i = 0; i < variables.Count; i++){
parametros[i] = new ParametroGet(
Uri.UnescapeDataString(variables[i].Value).Replace("+", " "),
Uri.UnescapeDataString(valores[i].Value).Replace("+", " "));
}
return new RespuestaHTTP (url, parametros);
}
return new RespuestaHTTP (url);
}
return new RespuestaHTTP (false);
}
catch(Exception e){
Console.WriteLine ("h1");
Console.WriteLine (e);
CierraCliente ();
return new RespuestaHTTP (false);
}
}
public bool Envia (String que)
{
try {
DDebug.WriteLine ("Enviando desde Envia");
writer.WriteLine ("HTTP/1.1 200 OK");
writer.WriteLine ("Connection: Close");
writer.WriteLine ("Content-Type: text/html; charset=utf-8");
writer.WriteLine ("");
writer.Write (que);
writer.Flush();
CierraCliente ();
return true;
} catch (Exception e) {
Console.WriteLine ("h2");
Console.WriteLine (e);
return false;
}
}
public bool EnviaRaw(String contentType, byte[] contenido){
try {
DDebug.WriteLine ("Enviando desde EnviaRaw");
writer.WriteLine ("HTTP/1.1 200 OK");
writer.WriteLine ("Connection: Close");
writer.WriteLine ("Content-Type: "+contentType);
writer.WriteLine ("");
writer.Flush();
stream.Write(contenido, 0, contenido.Length);
CierraCliente ();
return true;
} catch (Exception e) {
Console.WriteLine ("h10");
Console.WriteLine (e);
return false;
}
}
public bool EnviaLocation (String que)
{
try {
DDebug.WriteLine ("EnviaLocation");
writer.WriteLine ("HTTP/1.1 302 OK");
writer.WriteLine ("Location: " + que);
writer.WriteLine ("Content-Length: 0");
writer.WriteLine ("");
writer.Flush();
CierraCliente ();
return true;
} catch (Exception e) {
Console.WriteLine("h3");
Console.WriteLine (e);
return false;
}
}
public void CierraCliente ()
{
try{
DDebug.WriteLine ("CierraCliente");
this.writer.Close ();
this.stream.Close ();
DDebug.WriteLine("Cliente cerrado.");
}
catch(Exception e){
Console.WriteLine("h4");
Console.WriteLine (e);
}
}
public void Cierra ()
{
try{
DDebug.WriteLine ("Cierra");
CierraCliente();
this.listener.Stop ();
Console.WriteLine("Servidor cerrado.");
}
catch(Exception e){
Console.WriteLine("h5");
Console.WriteLine (e);
}
}
}
public class RespuestaHTTP
{
public String url;
public String path;
public ParametroGet[] parametros;
bool _correcto;
public bool correcto{
get{
return _correcto;
}
set{ }
}
public RespuestaHTTP (String url)
{
this._correcto = true;
this.setURL(url);
}
public RespuestaHTTP (bool correcto)
{
this.correcto = correcto;
}
public RespuestaHTTP (String url, ParametroGet[] parametros)
{
this.setURL(url);
this.parametros = parametros;
this._correcto = true;
}
void setURL(String url){
this.url = url;
String pattern = "[^\\?]*";
MatchCollection matches = Regex.Matches (url, pattern);
//Utilidades.print_r_regex(matches);
this.path = matches[0].Groups[0].Captures[0].Value;
}
public bool tieneParametros(){
return parametros != null;
}
public bool existeParametro(String variable){
if (!tieneParametros())
return false;
for(int i = 0; i < parametros.Length; i++){
if (parametros[i].variable == variable)
return true;
}
return false;
}
public String getParametro(String variable){
if (!tieneParametros())
return "";
for (int i = 0; i < parametros.Length; i++) {
if (parametros [i].variable == variable)
return parametros [i].valor;
}
return "";
}
}
public class ParametroGet{
String _variable;
String _valor;
public String variable{
get{
return _variable;
}
set{ }
}
public String valor{
get{
return _valor;
}
set{ }
}
public ParametroGet (String variable, String valor)
{
this._variable = variable;
this._valor = valor;
}
}
}
| |
/*
* DocuSign REST API
*
* The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
*
* OpenAPI spec version: v2.1
* Contact: devcenter@docusign.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using RestSharp;
using DocuSign.eSign.Client;
using DocuSign.eSign.Model;
namespace DocuSign.eSign.Api
{
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public interface IDataFeedApi : IApiAccessor
{
#region Synchronous Operations
/// <summary>
/// Retrieves a Datafeed element by Id.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="DocuSign.eSign.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="accountId">The external account number (int) or account ID Guid.</param>/// <param name="dataFeedElementId"></param>
/// <returns></returns>
void GetDataFeedElement (string accountId, string dataFeedElementId);
/// <summary>
/// Retrieves a Datafeed element by Id.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="DocuSign.eSign.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="accountId">The external account number (int) or account ID Guid.</param>/// <param name="dataFeedElementId"></param>
/// <returns>ApiResponse of Object(void)</returns>
ApiResponse<Object> GetDataFeedElementWithHttpInfo (string accountId, string dataFeedElementId);
#endregion Synchronous Operations
#region Asynchronous Operations
/// <summary>
/// Retrieves a Datafeed element by Id.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="DocuSign.eSign.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="accountId">The external account number (int) or account ID Guid.</param>/// <param name="dataFeedElementId"></param>
/// <returns>Task of void</returns>
System.Threading.Tasks.Task GetDataFeedElementAsync (string accountId, string dataFeedElementId);
/// <summary>
/// Retrieves a Datafeed element by Id.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="DocuSign.eSign.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="accountId">The external account number (int) or account ID Guid.</param>/// <param name="dataFeedElementId"></param>
/// <returns>Task of ApiResponse</returns>
System.Threading.Tasks.Task<ApiResponse<Object>> GetDataFeedElementAsyncWithHttpInfo (string accountId, string dataFeedElementId);
#endregion Asynchronous Operations
}
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public partial class DataFeedApi : IDataFeedApi
{
private DocuSign.eSign.Client.ExceptionFactory _exceptionFactory = (name, response) => null;
/// <summary>
/// Initializes a new instance of the <see cref="DataFeedApi"/> class
/// using AplClient object
/// </summary>
/// <param name="aplClient">An instance of AplClient</param>
/// <returns></returns>
public DataFeedApi(ApiClient aplClient)
{
this.ApiClient = aplClient;
ExceptionFactory = Configuration.DefaultExceptionFactory;
}
/// <summary>
/// Gets the base path of the API client.
/// </summary>
/// <value>The base path</value>
public String GetBasePath()
{
return this.ApiClient.RestClient.BaseUrl.ToString();
}
/// <summary>
/// Gets or sets the ApiClient object
/// </summary>
/// <value>An instance of the ApiClient</value>
public ApiClient ApiClient { get; set; }
/// <summary>
/// Provides a factory method hook for the creation of exceptions.
/// </summary>
public DocuSign.eSign.Client.ExceptionFactory ExceptionFactory
{
get
{
if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1)
{
throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported.");
}
return _exceptionFactory;
}
set { _exceptionFactory = value; }
}
/// <summary>
/// Retrieves a Datafeed element by Id.
/// </summary>
/// <exception cref="DocuSign.eSign.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="accountId">The external account number (int) or account ID Guid.</param>/// <param name="dataFeedElementId"></param>
/// <returns></returns>
public void GetDataFeedElement (string accountId, string dataFeedElementId)
{
GetDataFeedElementWithHttpInfo(accountId, dataFeedElementId);
}
/// <summary>
/// Retrieves a Datafeed element by Id.
/// </summary>
/// <exception cref="DocuSign.eSign.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="accountId">The external account number (int) or account ID Guid.</param>/// <param name="dataFeedElementId"></param>
/// <returns>ApiResponse of Object(void)</returns>
public ApiResponse<Object> GetDataFeedElementWithHttpInfo (string accountId, string dataFeedElementId)
{
// verify the required parameter 'accountId' is set
if (accountId == null)
throw new ApiException(400, "Missing required parameter 'accountId' when calling DataFeedApi->GetDataFeedElement");
// verify the required parameter 'dataFeedElementId' is set
if (dataFeedElementId == null)
throw new ApiException(400, "Missing required parameter 'dataFeedElementId' when calling DataFeedApi->GetDataFeedElement");
var localVarPath = "/v2.1/accounts/{accountId}/data_feeds/data/{dataFeedElementId}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(this.ApiClient.Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = this.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = this.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (accountId != null) localVarPathParams.Add("accountId", this.ApiClient.ParameterToString(accountId)); // path parameter
if (dataFeedElementId != null) localVarPathParams.Add("dataFeedElementId", this.ApiClient.ParameterToString(dataFeedElementId)); // path parameter
// authentication (docusignAccessCode) required
// oauth required
if (!String.IsNullOrEmpty(this.ApiClient.Configuration.AccessToken))
{
localVarHeaderParams["Authorization"] = "Bearer " + this.ApiClient.Configuration.AccessToken;
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) this.ApiClient.CallApi(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("GetDataFeedElement", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<Object>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
null);
}
/// <summary>
/// Retrieves a Datafeed element by Id.
/// </summary>
/// <exception cref="DocuSign.eSign.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="accountId">The external account number (int) or account ID Guid.</param>/// <param name="dataFeedElementId"></param>
/// <returns>Task of void</returns>
public async System.Threading.Tasks.Task GetDataFeedElementAsync (string accountId, string dataFeedElementId)
{
await GetDataFeedElementAsyncWithHttpInfo(accountId, dataFeedElementId);
}
/// <summary>
/// Retrieves a Datafeed element by Id.
/// </summary>
/// <exception cref="DocuSign.eSign.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="accountId">The external account number (int) or account ID Guid.</param>/// <param name="dataFeedElementId"></param>
/// <returns>Task of ApiResponse</returns>
public async System.Threading.Tasks.Task<ApiResponse<Object>> GetDataFeedElementAsyncWithHttpInfo (string accountId, string dataFeedElementId)
{
// verify the required parameter 'accountId' is set
if (accountId == null)
throw new ApiException(400, "Missing required parameter 'accountId' when calling DataFeedApi->GetDataFeedElement");
// verify the required parameter 'dataFeedElementId' is set
if (dataFeedElementId == null)
throw new ApiException(400, "Missing required parameter 'dataFeedElementId' when calling DataFeedApi->GetDataFeedElement");
var localVarPath = "/v2.1/accounts/{accountId}/data_feeds/data/{dataFeedElementId}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(this.ApiClient.Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = this.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = this.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (accountId != null) localVarPathParams.Add("accountId", this.ApiClient.ParameterToString(accountId)); // path parameter
if (dataFeedElementId != null) localVarPathParams.Add("dataFeedElementId", this.ApiClient.ParameterToString(dataFeedElementId)); // path parameter
// authentication (docusignAccessCode) required
// oauth required
if (!String.IsNullOrEmpty(this.ApiClient.Configuration.AccessToken))
{
localVarHeaderParams["Authorization"] = "Bearer " + this.ApiClient.Configuration.AccessToken;
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await this.ApiClient.CallApiAsync(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("GetDataFeedElement", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<Object>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
null);
}
}
}
| |
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
// PURPOSE. IT CAN BE DISTRIBUTED FREE OF CHARGE AS LONG AS THIS HEADER
// REMAINS UNCHANGED.
//
// Email: gustavo_franco@hotmail.com
//
// Copyright (C) 2006 Franco, Gustavo
//
using System;
using System.Threading;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Algorithms
{
#region Enum
public enum HeuristicFormula
{
Manhattan = 1,
MaxDXDY = 2,
DiagonalShortCut = 3,
Euclidean = 4,
EuclideanNoSQR = 5,
Custom1 = 6
}
#endregion
public struct Location
{
public Location(int xy, int z)
{
this.xy = xy;
this.z = z;
}
public int xy;
public int z;
}
public class PathFinderFast
{
#region Structs
internal struct PathFinderNodeFast
{
#region Variables Declaration
public int F; // f = gone + heuristic
public int G;
public ushort PX; // Parent
public ushort PY;
public byte Status;
public byte PZ;
public short JumpLength;
#endregion
public PathFinderNodeFast UpdateStatus(byte newStatus)
{
PathFinderNodeFast newNode = this;
newNode.Status = newStatus;
return newNode;
}
}
#endregion
private List<PathFinderNodeFast>[] nodes;
private Stack<int> touchedLocations;
#region Variables Declaration
// Heap variables are initializated to default, but I like to do it anyway
private byte[,] mGrid = null;
private PriorityQueueB<Location> mOpen = null;
private List<Vector2i> mClose = null;
private bool mStop = false;
private bool mStopped = true;
private HeuristicFormula mFormula = HeuristicFormula.Manhattan;
private bool mDiagonals = true;
private int mHEstimate = 2;
private bool mPunishChangeDirection = false;
private bool mTieBreaker = false;
private bool mHeavyDiagonals = false;
private int mSearchLimit = 2000;
private double mCompletedTime = 0;
private bool mDebugProgress = false;
private bool mDebugFoundPath = false;
private byte mOpenNodeValue = 1;
private byte mCloseNodeValue = 2;
//Promoted local variables to member variables to avoid recreation between calls
private int mH = 0;
private Location mLocation ;
private int mNewLocation = 0;
private PathFinderNodeFast mNode;
private ushort mLocationX = 0;
private ushort mLocationY = 0;
private ushort mNewLocationX = 0;
private ushort mNewLocationY = 0;
private int mCloseNodeCounter = 0;
private ushort mGridX = 0;
private ushort mGridY = 0;
private ushort mGridXMinus1 = 0;
private ushort mGridXLog2 = 0;
private bool mFound = false;
private sbyte[,] mDirection = new sbyte[8,2]{{0,-1} , {1,0}, {0,1}, {-1,0}, {1,-1}, {1,1}, {-1,1}, {-1,-1}};
private int mEndLocation = 0;
private int mNewG = 0;
public Map mMap;
#endregion
#region Constructors
public PathFinderFast(byte[,] grid, Map map)
{
if (map == null)
throw new Exception("Map cannot be null");
if (grid == null)
throw new Exception("Grid cannot be null");
mMap = map;
mGrid = grid;
mGridX = (ushort) (mGrid.GetUpperBound(0) + 1);
mGridY = (ushort) (mGrid.GetUpperBound(1) + 1);
mGridXMinus1 = (ushort) (mGridX - 1);
mGridXLog2 = (ushort) Math.Log(mGridX, 2);
if (Math.Log(mGridX, 2) != (int) Math.Log(mGridX, 2) ||
Math.Log(mGridY, 2) != (int) Math.Log(mGridY, 2))
throw new Exception("Invalid Grid, size in X and Y must be power of 2");
if (nodes == null || nodes.Length != (mGridX * mGridY))
{
nodes = new List<PathFinderNodeFast>[mGridX * mGridY];
touchedLocations = new Stack<int>(mGridX * mGridY);
mClose = new List<Vector2i>(mGridX * mGridY);
}
for (var i = 0; i < nodes.Length; ++i)
nodes[i] = new List<PathFinderNodeFast>(1);
mOpen = new PriorityQueueB<Location>(new ComparePFNodeMatrix(nodes));
}
#endregion
#region Properties
public bool Stopped
{
get { return mStopped; }
}
public HeuristicFormula Formula
{
get { return mFormula; }
set { mFormula = value; }
}
public bool Diagonals
{
get { return mDiagonals; }
set
{
mDiagonals = value;
if (mDiagonals)
mDirection = new sbyte[8,2]{{0,-1} , {1,0}, {0,1}, {-1,0}, {1,-1}, {1,1}, {-1,1}, {-1,-1}};
else
mDirection = new sbyte[4,2]{{0,-1} , {1,0}, {0,1}, {-1,0}};
}
}
public bool HeavyDiagonals
{
get { return mHeavyDiagonals; }
set { mHeavyDiagonals = value; }
}
public int HeuristicEstimate
{
get { return mHEstimate; }
set { mHEstimate = value; }
}
public bool PunishChangeDirection
{
get { return mPunishChangeDirection; }
set { mPunishChangeDirection = value; }
}
public bool TieBreaker
{
get { return mTieBreaker; }
set { mTieBreaker = value; }
}
public int SearchLimit
{
get { return mSearchLimit; }
set { mSearchLimit = value; }
}
public double CompletedTime
{
get { return mCompletedTime; }
set { mCompletedTime = value; }
}
public bool DebugProgress
{
get { return mDebugProgress; }
set { mDebugProgress = value; }
}
public bool DebugFoundPath
{
get { return mDebugFoundPath; }
set { mDebugFoundPath = value; }
}
#endregion
#region Methods
public void FindPathStop()
{
mStop = true;
}
public List<Vector2i> FindPath(Vector2i start, Vector2i end, int characterWidth, int characterHeight, short maxCharacterJumpHeight)
{
lock(this)
{
while (touchedLocations.Count > 0)
nodes[touchedLocations.Pop()].Clear();
if (mGrid[end.x, end.y] == 0)
return null;
mFound = false;
mStop = false;
mStopped = false;
mCloseNodeCounter = 0;
mOpenNodeValue += 2;
mCloseNodeValue += 2;
mOpen.Clear();
mLocation.xy = (start.y << mGridXLog2) + start.x;
mLocation.z = 0;
mEndLocation = (end.y << mGridXLog2) + end.x;
PathFinderNodeFast firstNode = new PathFinderNodeFast();
firstNode.G = 0;
firstNode.F = mHEstimate;
firstNode.PX = (ushort)start.x;
firstNode.PY = (ushort)start.y;
firstNode.PZ = 0;
firstNode.Status = mOpenNodeValue;
if (mMap.IsGround(start.x, start.y - 1))
firstNode.JumpLength = 0;
else
firstNode.JumpLength = (short)(maxCharacterJumpHeight * 2);
nodes[mLocation.xy].Add(firstNode);
touchedLocations.Push(mLocation.xy);
mOpen.Push(mLocation);
while(mOpen.Count > 0 && !mStop)
{
mLocation = mOpen.Pop();
//Is it in closed list? means this node was already processed
if (nodes[mLocation.xy][mLocation.z].Status == mCloseNodeValue)
continue;
mLocationX = (ushort) (mLocation.xy & mGridXMinus1);
mLocationY = (ushort)(mLocation.xy >> mGridXLog2);
if (mLocation.xy == mEndLocation)
{
nodes[mLocation.xy][mLocation.z] = nodes[mLocation.xy][mLocation.z].UpdateStatus(mCloseNodeValue);
mFound = true;
break;
}
if (mCloseNodeCounter > mSearchLimit)
{
mStopped = true;
return null;
}
//Lets calculate each successors
for (var i=0; i<(mDiagonals ? 8 : 4); i++)
{
mNewLocationX = (ushort) (mLocationX + mDirection[i,0]);
mNewLocationY = (ushort) (mLocationY + mDirection[i,1]);
mNewLocation = (mNewLocationY << mGridXLog2) + mNewLocationX;
var onGround = false;
var atCeiling = false;
if (mGrid[mNewLocationX, mNewLocationY] == 0)
goto CHILDREN_LOOP_END;
if (mMap.IsGround(mNewLocationX, mNewLocationY - 1))
onGround = true;
else if (mGrid[mNewLocationX, mNewLocationY + characterHeight] == 0)
atCeiling = true;
//calculate a proper jumplength value for the successor
var jumpLength = nodes[mLocation.xy][mLocation.z].JumpLength;
short newJumpLength = jumpLength;
if (atCeiling)
{
if (mNewLocationX != mLocationX)
newJumpLength = (short)Mathf.Max(maxCharacterJumpHeight * 2 + 1, jumpLength + 1);
else
newJumpLength = (short)Mathf.Max(maxCharacterJumpHeight * 2, jumpLength + 2);
}
else if (onGround)
newJumpLength = 0;
else if (mNewLocationY > mLocationY)
{
if (jumpLength < 2) //first jump is always two block up instead of one up and optionally one to either right or left
newJumpLength = 3;
else if (jumpLength % 2 == 0)
newJumpLength = (short)(jumpLength + 2);
else
newJumpLength = (short)(jumpLength + 1);
}
else if (mNewLocationY < mLocationY)
{
if (jumpLength % 2 == 0)
newJumpLength = (short)Mathf.Max(maxCharacterJumpHeight * 2, jumpLength + 2);
else
newJumpLength = (short)Mathf.Max(maxCharacterJumpHeight * 2, jumpLength + 1);
}
else if (!onGround && mNewLocationX != mLocationX)
newJumpLength = (short)(jumpLength + 1);
if (jumpLength >= 0 && jumpLength % 2 != 0 && mLocationX != mNewLocationX)
continue;
//if we're falling and succeor's height is bigger than ours, skip that successor
if (jumpLength >= maxCharacterJumpHeight * 2 && mNewLocationY > mLocationY)
continue;
if (newJumpLength >= maxCharacterJumpHeight * 2 + 6 && mNewLocationX != mLocationX && (newJumpLength - (maxCharacterJumpHeight * 2 + 6)) % 8 != 3)
continue;
mNewG = nodes[mLocation.xy][mLocation.z].G + mGrid[mNewLocationX, mNewLocationY] + newJumpLength / 4;
if (nodes[mNewLocation].Count > 0)
{
int lowestJump = short.MaxValue;
bool couldMoveSideways = false;
for (int j = 0; j < nodes[mNewLocation].Count; ++j)
{
if (nodes[mNewLocation][j].JumpLength < lowestJump)
lowestJump = nodes[mNewLocation][j].JumpLength;
if (nodes[mNewLocation][j].JumpLength % 2 == 0 && nodes[mNewLocation][j].JumpLength < maxCharacterJumpHeight * 2 + 6)
couldMoveSideways = true;
}
if (lowestJump <= newJumpLength && (newJumpLength % 2 != 0 || newJumpLength >= maxCharacterJumpHeight * 2 + 6 || couldMoveSideways))
continue;
}
switch(mFormula)
{
default:
case HeuristicFormula.Manhattan:
mH = mHEstimate * (Mathf.Abs(mNewLocationX - end.x) + Mathf.Abs(mNewLocationY - end.y));
break;
case HeuristicFormula.MaxDXDY:
mH = mHEstimate * (Math.Max(Math.Abs(mNewLocationX - end.x), Math.Abs(mNewLocationY - end.y)));
break;
case HeuristicFormula.DiagonalShortCut:
var h_diagonal = Math.Min(Math.Abs(mNewLocationX - end.x), Math.Abs(mNewLocationY - end.y));
var h_straight = (Math.Abs(mNewLocationX - end.x) + Math.Abs(mNewLocationY - end.y));
mH = (mHEstimate * 2) * h_diagonal + mHEstimate * (h_straight - 2 * h_diagonal);
break;
case HeuristicFormula.Euclidean:
mH = (int) (mHEstimate * Math.Sqrt(Math.Pow((mNewLocationY - end.x) , 2) + Math.Pow((mNewLocationY - end.y), 2)));
break;
case HeuristicFormula.EuclideanNoSQR:
mH = (int) (mHEstimate * (Math.Pow((mNewLocationX - end.x) , 2) + Math.Pow((mNewLocationY - end.y), 2)));
break;
case HeuristicFormula.Custom1:
var dxy = new Vector2i(Math.Abs(end.x - mNewLocationX), Math.Abs(end.y - mNewLocationY));
var Orthogonal = Math.Abs(dxy.x - dxy.y);
var Diagonal = Math.Abs(((dxy.x + dxy.y) - Orthogonal) / 2);
mH = mHEstimate * (Diagonal + Orthogonal + dxy.x + dxy.y);
break;
}
PathFinderNodeFast newNode = new PathFinderNodeFast();
newNode.JumpLength = newJumpLength;
newNode.PX = mLocationX;
newNode.PY = mLocationY;
newNode.PZ = (byte)mLocation.z;
newNode.G = mNewG;
newNode.F = mNewG + mH;
newNode.Status = mOpenNodeValue;
if (nodes[mNewLocation].Count == 0)
touchedLocations.Push(mNewLocation);
nodes[mNewLocation].Add(newNode);
mOpen.Push(new Location(mNewLocation, nodes[mNewLocation].Count - 1));
CHILDREN_LOOP_END:
continue;
}
nodes[mLocation.xy][mLocation.z] = nodes[mLocation.xy][mLocation.z].UpdateStatus(mCloseNodeValue);
mCloseNodeCounter++;
}
if (mFound)
{
mClose.Clear();
var posX = end.x;
var posY = end.y;
var fPrevNodeTmp = new PathFinderNodeFast();
var fNodeTmp = nodes[mEndLocation][0];
var fNode = end;
var fPrevNode = end;
var loc = (fNodeTmp.PY << mGridXLog2) + fNodeTmp.PX;
while (fNode.x != fNodeTmp.PX || fNode.y != fNodeTmp.PY)
{
var fNextNodeTmp = nodes[loc][fNodeTmp.PZ];
if ((mClose.Count == 0)
|| (mMap.IsOneWayPlatform(fNode.x, fNode.y - 1))
|| (mGrid[fNode.x, fNode.y - 1] == 0 && mMap.IsOneWayPlatform(fPrevNode.x, fPrevNode.y - 1))
|| (fNodeTmp.JumpLength == 3)
|| (fNextNodeTmp.JumpLength != 0 && fNodeTmp.JumpLength == 0) //mark jumps starts
|| (fNodeTmp.JumpLength == 0 && fPrevNodeTmp.JumpLength != 0) //mark landings
|| (fNode.y > mClose[mClose.Count - 1].y && fNode.y > fNodeTmp.PY)
|| (fNode.y < mClose[mClose.Count - 1].y && fNode.y < fNodeTmp.PY)
|| ((mMap.IsGround(fNode.x - 1, fNode.y) || mMap.IsGround(fNode.x + 1, fNode.y))
&& fNode.y != mClose[mClose.Count - 1].y && fNode.x != mClose[mClose.Count - 1].x))
mClose.Add(fNode);
fPrevNode = fNode;
posX = fNodeTmp.PX;
posY = fNodeTmp.PY;
fPrevNodeTmp = fNodeTmp;
fNodeTmp = fNextNodeTmp;
loc = (fNodeTmp.PY << mGridXLog2) + fNodeTmp.PX;
fNode = new Vector2i(posX, posY);
}
mClose.Add(fNode);
mStopped = true;
return mClose;
}
mStopped = true;
return null;
}
}
#endregion
#region Inner Classes
internal class ComparePFNodeMatrix : IComparer<Location>
{
#region Variables Declaration
List<PathFinderNodeFast>[] mMatrix;
#endregion
#region Constructors
public ComparePFNodeMatrix(List<PathFinderNodeFast>[] matrix)
{
mMatrix = matrix;
}
#endregion
#region IComparer Members
public int Compare(Location a, Location b)
{
if (mMatrix[a.xy][a.z].F > mMatrix[b.xy][b.z].F)
return 1;
else if (mMatrix[a.xy][a.z].F < mMatrix[b.xy][b.z].F)
return -1;
return 0;
}
#endregion
}
#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.Linq;
using NodaTime;
using QuantConnect.Securities;
namespace QuantConnect.Scheduling
{
/// <summary>
/// Provides a builder class to allow for fluent syntax when constructing new events
/// </summary>
/// <remarks>
/// This builder follows the following steps for event creation:
///
/// 1. Specify an event name (optional)
/// 2. Specify an IDateRule
/// 3. Specify an ITimeRule
/// a. repeat 3. to define extra time rules (optional)
/// 4. Specify additional where clause (optional)
/// 5. Register event via call to Run
/// </remarks>
public class FluentScheduledEventBuilder : IFluentSchedulingDateSpecifier, IFluentSchedulingRunnable
{
private IDateRule _dateRule;
private ITimeRule _timeRule;
private Func<DateTime, bool> _predicate;
private readonly string _name;
private readonly ScheduleManager _schedule;
private readonly SecurityManager _securities;
/// <summary>
/// Initializes a new instance of the <see cref="FluentScheduledEventBuilder"/> class
/// </summary>
/// <param name="schedule">The schedule to send created events to</param>
/// <param name="securities">The algorithm's security manager</param>
/// <param name="name">A specific name for this event</param>
public FluentScheduledEventBuilder(ScheduleManager schedule, SecurityManager securities, string name = null)
{
_name = name;
_schedule = schedule;
_securities = securities;
}
private FluentScheduledEventBuilder SetTimeRule(ITimeRule rule)
{
// if it's not set, just set it
if (_timeRule == null)
{
_timeRule = rule;
return this;
}
// if it's already a composite, open it up and make a new composite
// prevent nesting composites
var compositeTimeRule = _timeRule as CompositeTimeRule;
if (compositeTimeRule != null)
{
var rules = compositeTimeRule.Rules;
_timeRule = new CompositeTimeRule(rules.Concat(new[] { rule }));
return this;
}
// create a composite from the existing rule and the new rules
_timeRule = new CompositeTimeRule(_timeRule, rule);
return this;
}
#region DateRules and TimeRules delegation
/// <summary>
/// Creates events on each of the specified day of week
/// </summary>
IFluentSchedulingTimeSpecifier IFluentSchedulingDateSpecifier.Every(params DayOfWeek[] days)
{
_dateRule = _schedule.DateRules.Every(days);
return this;
}
/// <summary>
/// Creates events on every day of the year
/// </summary>
IFluentSchedulingTimeSpecifier IFluentSchedulingDateSpecifier.EveryDay()
{
_dateRule = _schedule.DateRules.EveryDay();
return this;
}
/// <summary>
/// Creates events on every trading day of the year for the symbol
/// </summary>
IFluentSchedulingTimeSpecifier IFluentSchedulingDateSpecifier.EveryDay(Symbol symbol)
{
_dateRule = _schedule.DateRules.EveryDay(symbol);
return this;
}
/// <summary>
/// Creates events on the first day of the month
/// </summary>
IFluentSchedulingTimeSpecifier IFluentSchedulingDateSpecifier.MonthStart()
{
_dateRule = _schedule.DateRules.MonthStart();
return this;
}
/// <summary>
/// Creates events on the first trading day of the month
/// </summary>
IFluentSchedulingTimeSpecifier IFluentSchedulingDateSpecifier.MonthStart(Symbol symbol)
{
_dateRule = _schedule.DateRules.MonthStart(symbol);
return this;
}
/// <summary>
/// Filters the event times using the predicate
/// </summary>
IFluentSchedulingTimeSpecifier IFluentSchedulingDateSpecifier.Where(Func<DateTime, bool> predicate)
{
_predicate = _predicate == null
? predicate
: (time => _predicate(time) && predicate(time));
return this;
}
/// <summary>
/// Creates events that fire at the specific time of day in the algorithm's time zone
/// </summary>
IFluentSchedulingRunnable IFluentSchedulingTimeSpecifier.At(TimeSpan timeOfDay)
{
return SetTimeRule(_schedule.TimeRules.At(timeOfDay));
}
/// <summary>
/// Creates events that fire a specified number of minutes after market open
/// </summary>
IFluentSchedulingRunnable IFluentSchedulingTimeSpecifier.AfterMarketOpen(Symbol symbol, double minutesAfterOpen, bool extendedMarketOpen)
{
return SetTimeRule(_schedule.TimeRules.AfterMarketOpen(symbol, minutesAfterOpen, extendedMarketOpen));
}
/// <summary>
/// Creates events that fire a specified numer of minutes before market close
/// </summary>
IFluentSchedulingRunnable IFluentSchedulingTimeSpecifier.BeforeMarketClose(Symbol symbol, double minuteBeforeClose, bool extendedMarketClose)
{
return SetTimeRule(_schedule.TimeRules.BeforeMarketClose(symbol, minuteBeforeClose, extendedMarketClose));
}
/// <summary>
/// Creates events that fire on a period define by the specified interval
/// </summary>
IFluentSchedulingRunnable IFluentSchedulingTimeSpecifier.Every(TimeSpan interval)
{
return SetTimeRule(_schedule.TimeRules.Every(interval));
}
/// <summary>
/// Filters the event times using the predicate
/// </summary>
IFluentSchedulingTimeSpecifier IFluentSchedulingTimeSpecifier.Where(Func<DateTime, bool> predicate)
{
_predicate = _predicate == null
? predicate
: (time => _predicate(time) && predicate(time));
return this;
}
/// <summary>
/// Register the defined event with the callback
/// </summary>
ScheduledEvent IFluentSchedulingRunnable.Run(Action callback)
{
return ((IFluentSchedulingRunnable)this).Run((name, time) => callback());
}
/// <summary>
/// Register the defined event with the callback
/// </summary>
ScheduledEvent IFluentSchedulingRunnable.Run(Action<DateTime> callback)
{
return ((IFluentSchedulingRunnable)this).Run((name, time) => callback(time));
}
/// <summary>
/// Register the defined event with the callback
/// </summary>
ScheduledEvent IFluentSchedulingRunnable.Run(Action<string, DateTime> callback)
{
var name = _name ?? _dateRule.Name + ": " + _timeRule.Name;
// back the date up to ensure we get all events, the event scheduler will skip past events that whose time has passed
var dates = _dateRule.GetDates(_securities.UtcTime.Date.AddDays(-1), Time.EndOfTime);
var eventTimes = _timeRule.CreateUtcEventTimes(dates);
if (_predicate != null)
{
eventTimes = eventTimes.Where(_predicate);
}
var scheduledEvent = new ScheduledEvent(name, eventTimes, callback);
_schedule.Add(scheduledEvent);
return scheduledEvent;
}
/// <summary>
/// Filters the event times using the predicate
/// </summary>
IFluentSchedulingRunnable IFluentSchedulingRunnable.Where(Func<DateTime, bool> predicate)
{
_predicate = _predicate == null
? predicate
: (time => _predicate(time) && predicate(time));
return this;
}
/// <summary>
/// Filters the event times to only include times where the symbol's market is considered open
/// </summary>
IFluentSchedulingRunnable IFluentSchedulingRunnable.DuringMarketHours(Symbol symbol, bool extendedMarket)
{
var security = GetSecurity(symbol);
Func<DateTime, bool> predicate = time =>
{
var localTime = time.ConvertFromUtc(security.Exchange.TimeZone);
return security.Exchange.IsOpenDuringBar(localTime, localTime, extendedMarket);
};
_predicate = _predicate == null
? predicate
: (time => _predicate(time) && predicate(time));
return this;
}
IFluentSchedulingTimeSpecifier IFluentSchedulingDateSpecifier.On(int year, int month, int day)
{
_dateRule = _schedule.DateRules.On(year, month, day);
return this;
}
IFluentSchedulingTimeSpecifier IFluentSchedulingDateSpecifier.On(params DateTime[] dates)
{
_dateRule = _schedule.DateRules.On(dates);
return this;
}
IFluentSchedulingRunnable IFluentSchedulingTimeSpecifier.At(int hour, int minute, int second)
{
return SetTimeRule(_schedule.TimeRules.At(hour, minute, second));
}
IFluentSchedulingRunnable IFluentSchedulingTimeSpecifier.At(int hour, int minute, DateTimeZone timeZone)
{
return SetTimeRule(_schedule.TimeRules.At(hour, minute, 0, timeZone));
}
IFluentSchedulingRunnable IFluentSchedulingTimeSpecifier.At(int hour, int minute, int second, DateTimeZone timeZone)
{
return SetTimeRule(_schedule.TimeRules.At(hour, minute, second, timeZone));
}
IFluentSchedulingRunnable IFluentSchedulingTimeSpecifier.At(TimeSpan timeOfDay, DateTimeZone timeZone)
{
return SetTimeRule(_schedule.TimeRules.At(timeOfDay, timeZone));
}
private Security GetSecurity(Symbol symbol)
{
Security security;
if (!_securities.TryGetValue(symbol, out security))
{
throw new Exception(symbol.ToString() + " not found in portfolio. Request this data when initializing the algorithm.");
}
return security;
}
#endregion
}
/// <summary>
/// Specifies the date rule component of a scheduled event
/// </summary>
public interface IFluentSchedulingDateSpecifier
{
/// <summary>
/// Filters the event times using the predicate
/// </summary>
IFluentSchedulingTimeSpecifier Where(Func<DateTime, bool> predicate);
/// <summary>
/// Creates events only on the specified date
/// </summary>
IFluentSchedulingTimeSpecifier On(int year, int month, int day);
/// <summary>
/// Creates events only on the specified dates
/// </summary>
IFluentSchedulingTimeSpecifier On(params DateTime[] dates);
/// <summary>
/// Creates events on each of the specified day of week
/// </summary>
IFluentSchedulingTimeSpecifier Every(params DayOfWeek[] days);
/// <summary>
/// Creates events on every day of the year
/// </summary>
IFluentSchedulingTimeSpecifier EveryDay();
/// <summary>
/// Creates events on every trading day of the year for the symbol
/// </summary>
IFluentSchedulingTimeSpecifier EveryDay(Symbol symbol);
/// <summary>
/// Creates events on the first day of the month
/// </summary>
IFluentSchedulingTimeSpecifier MonthStart();
/// <summary>
/// Creates events on the first trading day of the month
/// </summary>
IFluentSchedulingTimeSpecifier MonthStart(Symbol symbol);
}
/// <summary>
/// Specifies the time rule component of a scheduled event
/// </summary>
public interface IFluentSchedulingTimeSpecifier
{
/// <summary>
/// Filters the event times using the predicate
/// </summary>
IFluentSchedulingTimeSpecifier Where(Func<DateTime, bool> predicate);
/// <summary>
/// Creates events that fire at the specified time of day in the specified time zone
/// </summary>
IFluentSchedulingRunnable At(int hour, int minute, int second = 0);
/// <summary>
/// Creates events that fire at the specified time of day in the specified time zone
/// </summary>
IFluentSchedulingRunnable At(int hour, int minute, DateTimeZone timeZone);
/// <summary>
/// Creates events that fire at the specified time of day in the specified time zone
/// </summary>
IFluentSchedulingRunnable At(int hour, int minute, int second, DateTimeZone timeZone);
/// <summary>
/// Creates events that fire at the specified time of day in the specified time zone
/// </summary>
IFluentSchedulingRunnable At(TimeSpan timeOfDay, DateTimeZone timeZone);
/// <summary>
/// Creates events that fire at the specific time of day in the algorithm's time zone
/// </summary>
IFluentSchedulingRunnable At(TimeSpan timeOfDay);
/// <summary>
/// Creates events that fire on a period define by the specified interval
/// </summary>
IFluentSchedulingRunnable Every(TimeSpan interval);
/// <summary>
/// Creates events that fire a specified number of minutes after market open
/// </summary>
IFluentSchedulingRunnable AfterMarketOpen(Symbol symbol, double minutesAfterOpen = 0, bool extendedMarketOpen = false);
/// <summary>
/// Creates events that fire a specified numer of minutes before market close
/// </summary>
IFluentSchedulingRunnable BeforeMarketClose(Symbol symbol, double minuteBeforeClose = 0, bool extendedMarketClose = false);
}
/// <summary>
/// Specifies the callback component of a scheduled event, as well as final filters
/// </summary>
public interface IFluentSchedulingRunnable : IFluentSchedulingTimeSpecifier
{
/// <summary>
/// Filters the event times using the predicate
/// </summary>
new IFluentSchedulingRunnable Where(Func<DateTime, bool> predicate);
/// <summary>
/// Filters the event times to only include times where the symbol's market is considered open
/// </summary>
IFluentSchedulingRunnable DuringMarketHours(Symbol symbol, bool extendedMarket = false);
/// <summary>
/// Register the defined event with the callback
/// </summary>
ScheduledEvent Run(Action callback);
/// <summary>
/// Register the defined event with the callback
/// </summary>
ScheduledEvent Run(Action<DateTime> callback);
/// <summary>
/// Register the defined event with the callback
/// </summary>
ScheduledEvent Run(Action<string, DateTime> callback);
}
}
| |
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using achihapi.ViewModels;
using System.Data;
using System.Data.SqlClient;
using achihapi.Utilities;
using Microsoft.AspNetCore.JsonPatch;
using System.Net;
using Microsoft.Extensions.Caching.Memory;
namespace achihapi.Controllers
{
[Produces("application/json")]
[Route("api/FinanceAssetSoldDocument")]
public class FinanceAssetSoldDocumentController : Controller
{
private IMemoryCache _cache;
public FinanceAssetSoldDocumentController(IMemoryCache cache)
{
_cache = cache;
}
// GET: api/FinanceAssetSoldDocument
[HttpGet]
[Authorize]
public IActionResult Get()
{
return BadRequest();
}
//// GET: api/FinanceAssetSoldDocument/5
//[HttpGet("{id}")]
//[Authorize]
//public async Task<IActionResult> Get([FromRoute]int id, [FromQuery]Int32 hid = 0)
//{
// if (hid <= 0)
// return BadRequest("Not HID inputted");
// String usrName = String.Empty;
// if (Startup.UnitTestMode)
// usrName = UnitTestUtility.UnitTestUser;
// else
// {
// var usrObj = HIHAPIUtility.GetUserClaim(this);
// usrName = usrObj.Value;
// }
// if (String.IsNullOrEmpty(usrName))
// return BadRequest("User cannot recognize");
// FinanceAssetDocumentUIViewModel vm = new FinanceAssetDocumentUIViewModel();
// SqlConnection conn = null;
// SqlCommand cmd = null;
// SqlDataReader reader = null;
// String queryString = "";
// String strErrMsg = "";
// HttpStatusCode errorCode = HttpStatusCode.OK;
// try
// {
// queryString = HIHDBUtility.getFinanceDocAssetQueryString(id, false, hid);
// using(conn = new SqlConnection(Startup.DBConnectionString))
// {
// await conn.OpenAsync();
// // Check Home assignment with current user
// try
// {
// HIHAPIUtility.CheckHIDAssignment(conn, hid, usrName);
// }
// catch (Exception)
// {
// errorCode = HttpStatusCode.BadRequest;
// throw;
// }
// cmd = new SqlCommand(queryString, conn);
// reader = cmd.ExecuteReader();
// if (!reader.HasRows)
// {
// errorCode = HttpStatusCode.NotFound;
// throw new Exception();
// }
// // Header
// while (reader.Read())
// {
// HIHDBUtility.FinDocHeader_DB2VM(reader, vm);
// }
// await reader.NextResultAsync();
// // Items
// while (reader.Read())
// {
// FinanceDocumentItemUIViewModel itemvm = new FinanceDocumentItemUIViewModel();
// HIHDBUtility.FinDocItem_DB2VM(reader, itemvm);
// vm.Items.Add(itemvm);
// }
// await reader.NextResultAsync();
// // Account
// while (reader.Read())
// {
// FinanceAccountUIViewModel vmAccount = new FinanceAccountUIViewModel();
// Int32 aidx = 0;
// aidx = HIHDBUtility.FinAccountHeader_DB2VM(reader, vmAccount, aidx);
// vmAccount.ExtraInfo_AS = new FinanceAccountExtASViewModel();
// HIHDBUtility.FinAccountAsset_DB2VM(reader, vmAccount.ExtraInfo_AS, aidx);
// vm.AccountVM = vmAccount;
// }
// await reader.NextResultAsync();
// // Tags
// if (reader.HasRows)
// {
// while (reader.Read())
// {
// Int32 itemID = reader.GetInt32(0);
// String sterm = reader.GetString(1);
// foreach (var vitem in vm.Items)
// {
// if (vitem.ItemID == itemID)
// {
// vitem.TagTerms.Add(sterm);
// }
// }
// }
// }
// }
// }
// catch (Exception exp)
// {
// System.Diagnostics.Debug.WriteLine(exp.Message);
// strErrMsg = exp.Message;
// if (errorCode == HttpStatusCode.OK)
// errorCode = HttpStatusCode.InternalServerError;
// }
// finally
// {
// if (reader != null)
// {
// reader.Dispose();
// reader = null;
// }
// if (cmd != null)
// {
// cmd.Dispose();
// cmd = null;
// }
// if (conn != null)
// {
// conn.Dispose();
// conn = null;
// }
// }
// if (errorCode != HttpStatusCode.OK)
// {
// switch (errorCode)
// {
// case HttpStatusCode.Unauthorized:
// return Unauthorized();
// case HttpStatusCode.NotFound:
// return NotFound();
// case HttpStatusCode.BadRequest:
// return BadRequest(strErrMsg);
// default:
// return StatusCode(500, strErrMsg);
// }
// }
// var setting = new Newtonsoft.Json.JsonSerializerSettings
// {
// DateFormatString = HIHAPIConstants.DateFormatPattern,
// ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
// };
// return new JsonResult(vm, setting);
//}
// POST: api/FinanceAssetSoldDocument
[HttpPost]
[Authorize]
public async Task<IActionResult> Post([FromBody]FinanceAssetSoldoutDocViewModel vm)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
// Perform checks
if (vm.HID <= 0)
return BadRequest("Not HID inputted");
if (vm.AssetAccountID <= 0)
return BadRequest("Asset Account is invalid");
if (vm.TranAmount <= 0)
return BadRequest("Amount is less than zero");
if (vm.Items.Count <= 0)
return BadRequest("No items inputted");
String usrName = String.Empty;
if (Startup.UnitTestMode)
usrName = UnitTestUtility.UnitTestUser;
else
{
var usrObj = HIHAPIUtility.GetUserClaim(this);
usrName = usrObj.Value;
}
if (String.IsNullOrEmpty(usrName))
return BadRequest("User cannot recognize");
// Construct the Doc.
var vmFIDoc = new FinanceDocumentUIViewModel();
vmFIDoc.DocType = FinanceDocTypeViewModel.DocType_AssetSoldOut;
vmFIDoc.Desp = vm.Desp;
vmFIDoc.TranDate = vm.TranDate;
vmFIDoc.HID = vm.HID;
vmFIDoc.TranCurr = vm.TranCurr;
Decimal totalAmt = 0;
var maxItemID = 0;
foreach (var di in vm.Items)
{
if (di.ItemID <= 0 || di.TranAmount == 0 || di.AccountID <= 0
|| di.TranType != FinanceTranTypeViewModel.TranType_AssetSoldoutIncome
|| (di.ControlCenterID <= 0 && di.OrderID <= 0))
return BadRequest("Invalid input data in items!");
totalAmt += di.TranAmount;
vmFIDoc.Items.Add(di);
if (maxItemID < di.ItemID)
maxItemID = di.ItemID;
}
if (Decimal.Compare(totalAmt, vm.TranAmount) != 0)
return BadRequest("Amount is not even");
var nitem = new FinanceDocumentItemUIViewModel();
nitem.ItemID = ++maxItemID;
nitem.AccountID = vm.AssetAccountID;
nitem.TranAmount = vm.TranAmount;
nitem.Desp = vmFIDoc.Desp;
nitem.TranType = FinanceTranTypeViewModel.TranType_AssetSoldout;
if (vm.ControlCenterID.HasValue)
nitem.ControlCenterID = vm.ControlCenterID.Value;
if (vm.OrderID.HasValue)
nitem.OrderID = vm.OrderID.Value;
vmFIDoc.Items.Add(nitem);
// Update the database
SqlConnection conn = null;
SqlCommand cmd = null;
SqlDataReader reader = null;
SqlTransaction tran = null;
String queryString = "";
Int32 nNewDocID = -1;
String strErrMsg = "";
Decimal dCurrBalance = 0;
HttpStatusCode errorCode = HttpStatusCode.OK;
try
{
// Basic check again
FinanceDocumentController.FinanceDocumentBasicCheck(vmFIDoc);
using (conn = new SqlConnection(Startup.DBConnectionString))
{
await conn.OpenAsync();
// Check Home assignment with current user
try
{
HIHAPIUtility.CheckHIDAssignment(conn, vm.HID, usrName);
}
catch (Exception)
{
errorCode = HttpStatusCode.BadRequest;
throw;
}
// Perfrom the doc. validation
await FinanceDocumentController.FinanceDocumentBasicValidationAsync(vmFIDoc, conn);
// Additional checks
SqlCommand cmdAddCheck = null;
SqlDataReader readerAddCheck = null;
try
{
// Check 1: check account is a valid asset?
String strsqls = @"SELECT
[t_fin_account].[STATUS]
,[t_fin_account_ext_as].[REFDOC_SOLD] AS [ASREFDOC_SOLD]
FROM [dbo].[t_fin_account]
INNER JOIN [dbo].[t_fin_account_ext_as]
ON [t_fin_account].[ID] = [t_fin_account_ext_as].[ACCOUNTID]
WHERE [t_fin_account].[ID] = " + vm.AssetAccountID.ToString()
+ " AND [t_fin_account].[HID] = " + vm.HID.ToString();
cmdAddCheck = new SqlCommand(strsqls, conn);
readerAddCheck = await cmdAddCheck.ExecuteReaderAsync();
if (readerAddCheck.HasRows)
{
while(readerAddCheck.Read())
{
if (!readerAddCheck.IsDBNull(0))
{
var acntStatus = (FinanceAccountStatus)readerAddCheck.GetByte(0);
if (acntStatus != FinanceAccountStatus.Normal)
{
throw new Exception("Account status is not normal");
}
}
else
{
// Status is NULL stands for Active Status
// throw new Exception("Account status is not normal");
}
if (!readerAddCheck.IsDBNull(1))
{
throw new Exception("Account has soldout doc already");
}
break;
}
}
readerAddCheck.Close();
readerAddCheck = null;
cmdAddCheck.Dispose();
cmdAddCheck = null;
// Check 2: check the inputted date is valid > must be the later than all existing transactions;
strsqls = @"SELECT MAX(t_fin_document.TRANDATE)
FROM [dbo].[t_fin_document_item]
INNER JOIN [dbo].[t_fin_document]
ON [dbo].[t_fin_document_item].[DOCID] = [dbo].[t_fin_document].[ID]
WHERE [dbo].[t_fin_document_item].[ACCOUNTID] = " + vm.AssetAccountID.ToString();
cmdAddCheck = new SqlCommand(strsqls, conn);
readerAddCheck = await cmdAddCheck.ExecuteReaderAsync();
if (readerAddCheck.HasRows)
{
while (readerAddCheck.Read())
{
var latestdate = readerAddCheck.GetDateTime(0);
if (vm.TranDate.Date < latestdate.Date)
{
throw new Exception("Invalid date");
}
break;
}
}
else
{
throw new Exception("Invalid account - no doc items");
}
readerAddCheck.Close();
readerAddCheck = null;
cmdAddCheck.Dispose();
cmdAddCheck = null;
// Check 3. Fetch current balance
strsqls = @"SELECT [balance]
FROM [dbo].[v_fin_report_bs] WHERE [accountid] = " + vm.AssetAccountID.ToString();
cmdAddCheck = new SqlCommand(strsqls, conn);
readerAddCheck = await cmdAddCheck.ExecuteReaderAsync();
if (readerAddCheck.HasRows)
{
while (readerAddCheck.Read())
{
dCurrBalance = readerAddCheck.GetDecimal(0);
if (dCurrBalance <= 0)
{
throw new Exception("Balance is zero");
}
break;
}
}
else
{
throw new Exception("Invalid account - no doc items");
}
readerAddCheck.Close();
readerAddCheck = null;
cmdAddCheck.Dispose();
cmdAddCheck = null;
var ncmprst = Decimal.Compare(dCurrBalance, vm.TranAmount);
if (ncmprst > 0)
{
var nitem2 = new FinanceDocumentItemUIViewModel();
nitem2.ItemID = ++maxItemID;
nitem2.AccountID = vm.AssetAccountID;
nitem2.TranAmount = Decimal.Subtract(dCurrBalance, vm.TranAmount);
nitem2.Desp = vmFIDoc.Desp;
nitem2.TranType = FinanceTranTypeViewModel.TranType_AssetValueDecrease;
if (vm.ControlCenterID.HasValue)
nitem2.ControlCenterID = vm.ControlCenterID.Value;
if (vm.OrderID.HasValue)
nitem2.OrderID = vm.OrderID.Value;
vmFIDoc.Items.Add(nitem2);
}
else if(ncmprst < 0)
{
var nitem2 = new FinanceDocumentItemUIViewModel();
nitem2.ItemID = ++maxItemID;
nitem2.AccountID = vm.AssetAccountID;
nitem2.TranAmount = Decimal.Subtract(vm.TranAmount, dCurrBalance);
nitem2.Desp = vmFIDoc.Desp;
nitem2.TranType = FinanceTranTypeViewModel.TranType_AssetValueIncrease;
if (vm.ControlCenterID.HasValue)
nitem2.ControlCenterID = vm.ControlCenterID.Value;
if (vm.OrderID.HasValue)
nitem2.OrderID = vm.OrderID.Value;
vmFIDoc.Items.Add(nitem2);
}
}
catch (Exception)
{
errorCode = HttpStatusCode.BadRequest;
throw;
}
finally
{
if (readerAddCheck != null)
{
readerAddCheck.Close();
readerAddCheck = null;
}
if (cmdAddCheck != null)
{
cmdAddCheck.Dispose();
cmdAddCheck = null;
}
}
// Begin the modification
tran = conn.BeginTransaction();
// First, craete the doc header => nNewDocID
queryString = HIHDBUtility.GetFinDocHeaderInsertString();
cmd = new SqlCommand(queryString, conn)
{
Transaction = tran
};
HIHDBUtility.BindFinDocHeaderInsertParameter(cmd, vmFIDoc, usrName);
SqlParameter idparam = cmd.Parameters.AddWithValue("@Identity", SqlDbType.Int);
idparam.Direction = ParameterDirection.Output;
Int32 nRst = await cmd.ExecuteNonQueryAsync();
nNewDocID = (Int32)idparam.Value;
cmd.Dispose();
cmd = null;
// Then, creating the items
foreach (FinanceDocumentItemUIViewModel ivm in vmFIDoc.Items)
{
queryString = HIHDBUtility.GetFinDocItemInsertString();
cmd = new SqlCommand(queryString, conn)
{
Transaction = tran
};
HIHDBUtility.BindFinDocItemInsertParameter(cmd, ivm, nNewDocID);
await cmd.ExecuteNonQueryAsync();
cmd.Dispose();
cmd = null;
// Tags
if (ivm.TagTerms.Count > 0)
{
// Create tags
foreach (var term in ivm.TagTerms)
{
queryString = HIHDBUtility.GetTagInsertString();
cmd = new SqlCommand(queryString, conn, tran);
HIHDBUtility.BindTagInsertParameter(cmd, vm.HID, HIHTagTypeEnum.FinanceDocumentItem, nNewDocID, term, ivm.ItemID);
await cmd.ExecuteNonQueryAsync();
cmd.Dispose();
cmd = null;
}
}
}
// Third, update the Account's status
queryString = HIHDBUtility.GetFinanceAccountStatusUpdateString();
cmd = new SqlCommand(queryString, conn)
{
Transaction = tran
};
// Close this account
HIHDBUtility.BindFinAccountStatusUpdateParameter(cmd, FinanceAccountStatus.Closed, vm.AssetAccountID, vm.HID, usrName);
nRst = await cmd.ExecuteNonQueryAsync();
cmd.Dispose();
cmd = null;
// Fourth, Update the Asset account part for sold doc
queryString = HIHDBUtility.GetFinanceAccountAssetUpdateSoldDocString();
cmd = new SqlCommand(queryString, conn)
{
Transaction = tran
};
HIHDBUtility.BindFinAccountAssetUpdateSoldDocParameter(cmd, nNewDocID, vm.AssetAccountID);
nRst = await cmd.ExecuteNonQueryAsync();
cmd.Dispose();
cmd = null;
// Do the commit
tran.Commit();
// Update the buffer
// Account List
try
{
var cacheKey = String.Format(CacheKeys.FinAccountList, vm.HID, null);
this._cache.Remove(cacheKey);
}
catch (Exception)
{
// Do nothing here.
}
// Account itself
try
{
var cacheKey = String.Format(CacheKeys.FinAccount, vm.HID, vm.AssetAccountID);
this._cache.Remove(cacheKey);
}
catch (Exception)
{
// Do nothing here.
}
}
}
catch (Exception exp)
{
#if DEBUG
System.Diagnostics.Debug.WriteLine(exp.Message);
#endif
strErrMsg = exp.Message;
if (errorCode == HttpStatusCode.OK)
errorCode = HttpStatusCode.InternalServerError;
if (tran != null)
tran.Rollback();
}
finally
{
if (tran != null)
{
tran.Dispose();
tran = null;
}
if (reader != null)
{
reader.Dispose();
reader = null;
}
if (cmd != null)
{
cmd.Dispose();
cmd = null;
}
if (conn != null)
{
conn.Dispose();
conn = null;
}
}
if (errorCode != HttpStatusCode.OK)
{
switch (errorCode)
{
case HttpStatusCode.Unauthorized:
return Unauthorized();
case HttpStatusCode.NotFound:
return NotFound();
case HttpStatusCode.BadRequest:
return BadRequest(strErrMsg);
default:
return StatusCode(500, strErrMsg);
}
}
// Return nothing
return Ok(nNewDocID);
}
// PUT: api/FinanceAssetSoldDocument/5
[HttpPut("{id}")]
[Authorize]
public IActionResult Put(int id, [FromBody]string value)
{
return BadRequest();
}
// PATCH:
//[HttpPatch("{id}")]
//public async Task<IActionResult> Patch(int id, [FromQuery]int hid, [FromBody]JsonPatchDocument<FinanceAssetDocumentUIViewModel> patch)
//{
// if (patch == null || id <= 0 || patch.Operations.Count <= 0)
// return BadRequest("No data is inputted");
// if (hid <= 0)
// return BadRequest("No home is inputted");
// // Update the database
// SqlConnection conn = null;
// SqlCommand cmd = null;
// SqlDataReader reader = null;
// String queryString = "";
// String strErrMsg = "";
// Boolean headTranDateUpdate = false;
// DateTime? headTranDate = null;
// Boolean headDespUpdate = false;
// String headDesp = null;
// HttpStatusCode errorCode = HttpStatusCode.OK;
// // Check the inputs.
// // Allowed to change:
// // 1. Header: Transaction date, Desp;
// // 2. Item: Transaction amount, Desp, Control Center ID, Order ID,
// foreach (var oper in patch.Operations)
// {
// switch (oper.path)
// {
// case "/tranDate":
// headTranDateUpdate = true;
// headTranDate = (DateTime)oper.value;
// break;
// case "/desp":
// headDespUpdate = true;
// headDesp = (String)oper.value;
// break;
// default:
// return BadRequest("Unsupport field found");
// }
// }
// // User name
// String usrName = String.Empty;
// if (Startup.UnitTestMode)
// usrName = UnitTestUtility.UnitTestUser;
// else
// {
// var usrObj = HIHAPIUtility.GetUserClaim(this);
// usrName = usrObj.Value;
// }
// if (String.IsNullOrEmpty(usrName))
// return BadRequest("User cannot recognize");
// try
// {
// queryString = HIHDBUtility.GetFinDocHeaderExistCheckString(id);
// using(conn = new SqlConnection(Startup.DBConnectionString))
// {
// await conn.OpenAsync();
// // Check Home assignment with current user
// try
// {
// HIHAPIUtility.CheckHIDAssignment(conn, hid, usrName);
// }
// catch (Exception)
// {
// errorCode = HttpStatusCode.BadRequest;
// throw;
// }
// cmd = new SqlCommand(queryString, conn);
// reader = cmd.ExecuteReader();
// if (!reader.HasRows)
// {
// errorCode = HttpStatusCode.BadRequest;
// throw new Exception("Doc ID not exist");
// }
// else
// {
// reader.Close();
// cmd.Dispose();
// cmd = null;
// //var vm = new FinanceAssetDocumentUIViewModel();
// //// Header
// //while (reader.Read())
// //{
// // HIHDBUtility.FinDocHeader_DB2VM(reader, vm);
// //}
// //reader.NextResult();
// //// Items
// //while (reader.Read())
// //{
// // FinanceDocumentItemUIViewModel itemvm = new FinanceDocumentItemUIViewModel();
// // HIHDBUtility.FinDocItem_DB2VM(reader, itemvm);
// // vm.Items.Add(itemvm);
// //}
// //reader.NextResult();
// //// Account
// //while (reader.Read())
// //{
// // FinanceAccountUIViewModel vmAccount = new FinanceAccountUIViewModel();
// // Int32 aidx = 0;
// // aidx = HIHDBUtility.FinAccountHeader_DB2VM(reader, vmAccount, aidx);
// // vmAccount.ExtraInfo_AS = new FinanceAccountExtASViewModel();
// // HIHDBUtility.FinAccountAsset_DB2VM(reader, vmAccount.ExtraInfo_AS, aidx);
// // vm.AccountVM = vmAccount;
// //}
// //reader.NextResult();
// //reader.Dispose();
// //reader = null;
// //cmd.Dispose();
// //cmd = null;
// //// Now go ahead for the update
// ////var patched = vm.Copy();
// //patch.ApplyTo(vm, ModelState);
// //if (!ModelState.IsValid)
// //{
// // return new BadRequestObjectResult(ModelState);
// //}
// // Optimized logic go ahead
// if (headTranDateUpdate || headDespUpdate)
// {
// queryString = HIHDBUtility.GetFinDocHeader_PatchString(headTranDateUpdate, headDespUpdate);
// cmd = new SqlCommand(queryString, conn);
// if (headTranDateUpdate)
// cmd.Parameters.AddWithValue("@TRANDATE", headTranDate);
// if (headDespUpdate)
// cmd.Parameters.AddWithValue("@DESP", headDesp);
// cmd.Parameters.AddWithValue("@UPDATEDAT", DateTime.Now);
// cmd.Parameters.AddWithValue("@UPDATEDBY", usrName);
// cmd.Parameters.AddWithValue("@ID", id);
// await cmd.ExecuteNonQueryAsync();
// }
// }
// }
// }
// catch (Exception exp)
// {
// System.Diagnostics.Debug.WriteLine(exp.Message);
// strErrMsg = exp.Message;
// if (errorCode == HttpStatusCode.OK)
// errorCode = HttpStatusCode.InternalServerError;
// }
// finally
// {
// if (reader != null)
// {
// reader.Dispose();
// reader = null;
// }
// if (cmd != null)
// {
// cmd.Dispose();
// cmd = null;
// }
// if (conn != null)
// {
// conn.Dispose();
// conn = null;
// }
// }
// if (errorCode != HttpStatusCode.OK)
// {
// switch (errorCode)
// {
// case HttpStatusCode.Unauthorized:
// return Unauthorized();
// case HttpStatusCode.NotFound:
// return NotFound();
// case HttpStatusCode.BadRequest:
// return BadRequest(strErrMsg);
// default:
// return StatusCode(500, strErrMsg);
// }
// }
// return Ok();
//}
// DELETE: api/FinanceAssetSoldDocument/5
[HttpDelete("{id}")]
[Authorize]
public IActionResult Delete(int id)
{
return BadRequest();
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) Under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You Under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed Under the License is distributed on an "AS Is" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations Under the License.
==================================================================== */
namespace NPOI.HSSF.Record
{
using System;
using System.Text;
using System.Collections;
using NPOI.Util;
/**
* Title: Row Record
* Description: stores the row information for the sheet.
* REFERENCE: PG 379 Microsoft Excel 97 Developer's Kit (ISBN: 1-57231-498-2)
* @author Andrew C. Oliver (acoliver at apache dot org)
* @author Jason Height (jheight at chariot dot net dot au)
* @version 2.0-pre
*/
internal class RowRecord : StandardRecord, IComparable
{
public const short sid = 0x208;
public static int ENCODED_SIZE = 20;
private const int OPTION_BITS_ALWAYS_SET = 0x0100;
private const int DEFAULT_HEIGHT_BIT = 0x8000;
/** The maximum row number that excel can handle (zero based) ie 65536 rows Is
* max number of rows.
*/
[Obsolete]
public const int MAX_ROW_NUMBER = 65535;
private int field_1_row_number;
private int field_2_first_col;
private int field_3_last_col; // plus 1
private short field_4_height;
private short field_5_optimize; // hint field for gui, can/should be Set to zero
// for generated sheets.
private short field_6_reserved;
/** 16 bit options flags */
private int field_7_option_flags;
private static BitField outlineLevel = BitFieldFactory.GetInstance(0x07);
// bit 3 reserved
private static BitField colapsed = BitFieldFactory.GetInstance(0x10);
private static BitField zeroHeight = BitFieldFactory.GetInstance(0x20);
private static BitField badFontHeight = BitFieldFactory.GetInstance(0x40);
private static BitField formatted = BitFieldFactory.GetInstance(0x80);
private short field_8_xf_index; // only if IsFormatted
public RowRecord(int rowNumber)
{
field_1_row_number = rowNumber;
//field_2_first_col = -1;
//field_3_last_col = -1;
field_4_height = (short)0x00FF;
field_5_optimize = (short)0;
field_6_reserved = (short)0;
field_7_option_flags = OPTION_BITS_ALWAYS_SET; // seems necessary for outlining
field_8_xf_index = (short)0xf;
SetEmpty();
}
/**
* Constructs a Row record and Sets its fields appropriately.
* @param in the RecordInputstream to Read the record from
*/
public RowRecord(RecordInputStream in1)
{
field_1_row_number = in1.ReadUShort();
field_2_first_col = in1.ReadShort();
field_3_last_col = in1.ReadShort();
field_4_height = in1.ReadShort();
field_5_optimize = in1.ReadShort();
field_6_reserved = in1.ReadShort();
field_7_option_flags = in1.ReadShort();
field_8_xf_index = in1.ReadShort();
}
public void SetEmpty()
{
field_2_first_col = 0;
field_3_last_col = 0;
}
/**
* Get the logical row number for this row (0 based index)
* @return row - the row number
*/
public bool IsEmpty
{
get
{
return (field_2_first_col | field_3_last_col) == 0;
}
}
//public short RowNumber
public int RowNumber
{
get
{
return field_1_row_number;
}
set { field_1_row_number = value; }
}
/**
* Get the logical col number for the first cell this row (0 based index)
* @return col - the col number
*/
public int FirstCol
{
get{return field_2_first_col;}
set { field_2_first_col = value; }
}
/**
* Get the logical col number for the last cell this row plus one (0 based index)
* @return col - the last col number + 1
*/
public int LastCol
{
get { return field_3_last_col; }
set { field_3_last_col = value; }
}
/**
* Get the height of the row
* @return height of the row
*/
public short Height
{
get{return field_4_height;}
set { field_4_height = value; }
}
/**
* Get whether to optimize or not (Set to 0)
* @return optimize (Set to 0)
*/
public short Optimize
{
get
{
return field_5_optimize;
}
set { field_5_optimize = value; }
}
/**
* Gets the option bitmask. (use the individual bit Setters that refer to this
* method)
* @return options - the bitmask
*/
public short OptionFlags
{
get
{
return (short)field_7_option_flags;
}
set { field_7_option_flags = value | (short)OPTION_BITS_ALWAYS_SET; }
}
// option bitfields
/**
* Get the outline level of this row
* @return ol - the outline level
* @see #GetOptionFlags()
*/
public short OutlineLevel
{
get { return (short)outlineLevel.GetValue(field_7_option_flags); }
set { field_7_option_flags = outlineLevel.SetValue(field_7_option_flags, value); }
}
/**
* Get whether or not to colapse this row
* @return c - colapse or not
* @see #GetOptionFlags()
*/
public bool Colapsed
{
get
{
return (colapsed.IsSet(field_7_option_flags));
}
set
{
field_7_option_flags = colapsed.SetBoolean(field_7_option_flags, value);
}
}
/**
* Get whether or not to Display this row with 0 height
* @return - z height is zero or not.
* @see #GetOptionFlags()
*/
public bool ZeroHeight
{
get
{
return zeroHeight.IsSet(field_7_option_flags);
}
set
{
field_7_option_flags = zeroHeight.SetBoolean(field_7_option_flags, value);
}
}
/**
* Get whether the font and row height are not compatible
* @return - f -true if they aren't compatible (damn not logic)
* @see #GetOptionFlags()
*/
public bool BadFontHeight
{
get
{
return badFontHeight.IsSet(field_7_option_flags);
}
set
{
field_7_option_flags = badFontHeight.SetBoolean(field_7_option_flags, value);
}
}
/**
* Get whether the row has been formatted (even if its got all blank cells)
* @return formatted or not
* @see #GetOptionFlags()
*/
public bool Formatted
{
get
{
return formatted.IsSet(field_7_option_flags);
}
set { field_7_option_flags = formatted.SetBoolean(field_7_option_flags, value); }
}
// end bitfields
/**
* if the row is formatted then this is the index to the extended format record
* @see org.apache.poi.hssf.record.ExtendedFormatRecord
* @return index to the XF record or bogus value (undefined) if Isn't formatted
*/
public short XFIndex
{
get { return field_8_xf_index; }
set { field_8_xf_index = value; }
}
public override String ToString()
{
StringBuilder buffer = new StringBuilder();
buffer.Append("[ROW]\n");
buffer.Append(" .rownumber = ")
.Append(StringUtil.ToHexString(RowNumber)).Append("\n");
buffer.Append(" .firstcol = ")
.Append(StringUtil.ToHexString(FirstCol)).Append("\n");
buffer.Append(" .lastcol = ")
.Append(StringUtil.ToHexString(LastCol)).Append("\n");
buffer.Append(" .height = ")
.Append(StringUtil.ToHexString(Height)).Append("\n");
buffer.Append(" .optimize = ")
.Append(StringUtil.ToHexString(Optimize)).Append("\n");
buffer.Append(" .reserved = ")
.Append(StringUtil.ToHexString(field_6_reserved)).Append("\n");
buffer.Append(" .optionflags = ")
.Append(StringUtil.ToHexString(OptionFlags)).Append("\n");
buffer.Append(" .outlinelvl = ")
.Append(StringUtil.ToHexString(OutlineLevel)).Append("\n");
buffer.Append(" .colapsed = ").Append(Colapsed)
.Append("\n");
buffer.Append(" .zeroheight = ").Append(ZeroHeight)
.Append("\n");
buffer.Append(" .badfontheig= ").Append(BadFontHeight)
.Append("\n");
buffer.Append(" .formatted = ").Append(Formatted)
.Append("\n");
buffer.Append(" .xFindex = ")
.Append(StringUtil.ToHexString(XFIndex)).Append("\n");
buffer.Append("[/ROW]\n");
return buffer.ToString();
}
public override void Serialize(ILittleEndianOutput out1)
{
out1.WriteShort(RowNumber);
out1.WriteShort(FirstCol == -1 ? (short)0 : FirstCol);
out1.WriteShort(LastCol == -1 ? (short)0 : LastCol);
out1.WriteShort(Height);
out1.WriteShort(Optimize);
out1.WriteShort(field_6_reserved);
out1.WriteShort(OptionFlags);
out1.WriteShort(XFIndex);
}
protected override int DataSize
{
get
{
return ENCODED_SIZE - 4;
}
}
public override int RecordSize
{
get { return 20; }
}
public override short Sid
{
get { return sid; }
}
public int CompareTo(Object obj)
{
RowRecord loc = (RowRecord)obj;
if (this.RowNumber == loc.RowNumber)
{
return 0;
}
if (this.RowNumber < loc.RowNumber)
{
return -1;
}
if (this.RowNumber > loc.RowNumber)
{
return 1;
}
return -1;
}
public override bool Equals(Object obj)
{
if (!(obj is RowRecord))
{
return false;
}
RowRecord loc = (RowRecord)obj;
if (this.RowNumber == loc.RowNumber)
{
return true;
}
return false;
}
public override int GetHashCode ()
{
return RowNumber;
}
public override Object Clone()
{
RowRecord rec = new RowRecord(field_1_row_number);
rec.field_2_first_col = field_2_first_col;
rec.field_3_last_col = field_3_last_col;
rec.field_4_height = field_4_height;
rec.field_5_optimize = field_5_optimize;
rec.field_6_reserved = field_6_reserved;
rec.field_7_option_flags = field_7_option_flags;
rec.field_8_xf_index = field_8_xf_index;
return rec;
}
}
}
| |
namespace android.app
{
[global::MonoJavaBridge.JavaClass()]
public partial class ProgressDialog : android.app.AlertDialog
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static ProgressDialog()
{
InitJNI();
}
protected ProgressDialog(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _onCreate730;
protected override void onCreate(android.os.Bundle arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.app.ProgressDialog._onCreate730, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.ProgressDialog.staticClass, global::android.app.ProgressDialog._onCreate730, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _onStart731;
public virtual new void onStart()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.app.ProgressDialog._onStart731);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.ProgressDialog.staticClass, global::android.app.ProgressDialog._onStart731);
}
internal static global::MonoJavaBridge.MethodId _onStop732;
protected override void onStop()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.app.ProgressDialog._onStop732);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.ProgressDialog.staticClass, global::android.app.ProgressDialog._onStop732);
}
internal static global::MonoJavaBridge.MethodId _setProgress733;
public virtual void setProgress(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.app.ProgressDialog._setProgress733, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.ProgressDialog.staticClass, global::android.app.ProgressDialog._setProgress733, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setSecondaryProgress734;
public virtual void setSecondaryProgress(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.app.ProgressDialog._setSecondaryProgress734, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.ProgressDialog.staticClass, global::android.app.ProgressDialog._setSecondaryProgress734, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _show735;
public static global::android.app.ProgressDialog show(android.content.Context arg0, java.lang.CharSequence arg1, java.lang.CharSequence arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.app.ProgressDialog.staticClass, global::android.app.ProgressDialog._show735, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as android.app.ProgressDialog;
}
internal static global::MonoJavaBridge.MethodId _show736;
public static global::android.app.ProgressDialog show(android.content.Context arg0, java.lang.CharSequence arg1, java.lang.CharSequence arg2, bool arg3, bool arg4)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.app.ProgressDialog.staticClass, global::android.app.ProgressDialog._show736, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4))) as android.app.ProgressDialog;
}
internal static global::MonoJavaBridge.MethodId _show737;
public static global::android.app.ProgressDialog show(android.content.Context arg0, java.lang.CharSequence arg1, java.lang.CharSequence arg2, bool arg3, bool arg4, android.content.DialogInterface_OnCancelListener arg5)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.app.ProgressDialog.staticClass, global::android.app.ProgressDialog._show737, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5))) as android.app.ProgressDialog;
}
internal static global::MonoJavaBridge.MethodId _show738;
public static global::android.app.ProgressDialog show(android.content.Context arg0, java.lang.CharSequence arg1, java.lang.CharSequence arg2, bool arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.app.ProgressDialog.staticClass, global::android.app.ProgressDialog._show738, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3))) as android.app.ProgressDialog;
}
internal static global::MonoJavaBridge.MethodId _setMessage739;
public override void setMessage(java.lang.CharSequence arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.app.ProgressDialog._setMessage739, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.ProgressDialog.staticClass, global::android.app.ProgressDialog._setMessage739, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public void setMessage(string arg0)
{
setMessage((global::java.lang.CharSequence)(global::java.lang.String)arg0);
}
internal static global::MonoJavaBridge.MethodId _getProgress740;
public virtual int getProgress()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.app.ProgressDialog._getProgress740);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.app.ProgressDialog.staticClass, global::android.app.ProgressDialog._getProgress740);
}
internal static global::MonoJavaBridge.MethodId _getSecondaryProgress741;
public virtual int getSecondaryProgress()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.app.ProgressDialog._getSecondaryProgress741);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.app.ProgressDialog.staticClass, global::android.app.ProgressDialog._getSecondaryProgress741);
}
internal static global::MonoJavaBridge.MethodId _getMax742;
public virtual int getMax()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.app.ProgressDialog._getMax742);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.app.ProgressDialog.staticClass, global::android.app.ProgressDialog._getMax742);
}
internal static global::MonoJavaBridge.MethodId _setMax743;
public virtual void setMax(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.app.ProgressDialog._setMax743, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.ProgressDialog.staticClass, global::android.app.ProgressDialog._setMax743, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _incrementProgressBy744;
public virtual void incrementProgressBy(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.app.ProgressDialog._incrementProgressBy744, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.ProgressDialog.staticClass, global::android.app.ProgressDialog._incrementProgressBy744, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _incrementSecondaryProgressBy745;
public virtual void incrementSecondaryProgressBy(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.app.ProgressDialog._incrementSecondaryProgressBy745, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.ProgressDialog.staticClass, global::android.app.ProgressDialog._incrementSecondaryProgressBy745, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setProgressDrawable746;
public virtual void setProgressDrawable(android.graphics.drawable.Drawable arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.app.ProgressDialog._setProgressDrawable746, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.ProgressDialog.staticClass, global::android.app.ProgressDialog._setProgressDrawable746, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setIndeterminateDrawable747;
public virtual void setIndeterminateDrawable(android.graphics.drawable.Drawable arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.app.ProgressDialog._setIndeterminateDrawable747, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.ProgressDialog.staticClass, global::android.app.ProgressDialog._setIndeterminateDrawable747, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setIndeterminate748;
public virtual void setIndeterminate(bool arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.app.ProgressDialog._setIndeterminate748, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.ProgressDialog.staticClass, global::android.app.ProgressDialog._setIndeterminate748, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _isIndeterminate749;
public virtual bool isIndeterminate()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.app.ProgressDialog._isIndeterminate749);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.app.ProgressDialog.staticClass, global::android.app.ProgressDialog._isIndeterminate749);
}
internal static global::MonoJavaBridge.MethodId _setProgressStyle750;
public virtual void setProgressStyle(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.app.ProgressDialog._setProgressStyle750, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.ProgressDialog.staticClass, global::android.app.ProgressDialog._setProgressStyle750, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _ProgressDialog751;
public ProgressDialog(android.content.Context arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.app.ProgressDialog.staticClass, global::android.app.ProgressDialog._ProgressDialog751, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
internal static global::MonoJavaBridge.MethodId _ProgressDialog752;
public ProgressDialog(android.content.Context arg0, int arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.app.ProgressDialog.staticClass, global::android.app.ProgressDialog._ProgressDialog752, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
Init(@__env, handle);
}
public static int STYLE_SPINNER
{
get
{
return 0;
}
}
public static int STYLE_HORIZONTAL
{
get
{
return 1;
}
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.app.ProgressDialog.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/app/ProgressDialog"));
global::android.app.ProgressDialog._onCreate730 = @__env.GetMethodIDNoThrow(global::android.app.ProgressDialog.staticClass, "onCreate", "(Landroid/os/Bundle;)V");
global::android.app.ProgressDialog._onStart731 = @__env.GetMethodIDNoThrow(global::android.app.ProgressDialog.staticClass, "onStart", "()V");
global::android.app.ProgressDialog._onStop732 = @__env.GetMethodIDNoThrow(global::android.app.ProgressDialog.staticClass, "onStop", "()V");
global::android.app.ProgressDialog._setProgress733 = @__env.GetMethodIDNoThrow(global::android.app.ProgressDialog.staticClass, "setProgress", "(I)V");
global::android.app.ProgressDialog._setSecondaryProgress734 = @__env.GetMethodIDNoThrow(global::android.app.ProgressDialog.staticClass, "setSecondaryProgress", "(I)V");
global::android.app.ProgressDialog._show735 = @__env.GetStaticMethodIDNoThrow(global::android.app.ProgressDialog.staticClass, "show", "(Landroid/content/Context;Ljava/lang/CharSequence;Ljava/lang/CharSequence;)Landroid/app/ProgressDialog;");
global::android.app.ProgressDialog._show736 = @__env.GetStaticMethodIDNoThrow(global::android.app.ProgressDialog.staticClass, "show", "(Landroid/content/Context;Ljava/lang/CharSequence;Ljava/lang/CharSequence;ZZ)Landroid/app/ProgressDialog;");
global::android.app.ProgressDialog._show737 = @__env.GetStaticMethodIDNoThrow(global::android.app.ProgressDialog.staticClass, "show", "(Landroid/content/Context;Ljava/lang/CharSequence;Ljava/lang/CharSequence;ZZLandroid/content/DialogInterface$OnCancelListener;)Landroid/app/ProgressDialog;");
global::android.app.ProgressDialog._show738 = @__env.GetStaticMethodIDNoThrow(global::android.app.ProgressDialog.staticClass, "show", "(Landroid/content/Context;Ljava/lang/CharSequence;Ljava/lang/CharSequence;Z)Landroid/app/ProgressDialog;");
global::android.app.ProgressDialog._setMessage739 = @__env.GetMethodIDNoThrow(global::android.app.ProgressDialog.staticClass, "setMessage", "(Ljava/lang/CharSequence;)V");
global::android.app.ProgressDialog._getProgress740 = @__env.GetMethodIDNoThrow(global::android.app.ProgressDialog.staticClass, "getProgress", "()I");
global::android.app.ProgressDialog._getSecondaryProgress741 = @__env.GetMethodIDNoThrow(global::android.app.ProgressDialog.staticClass, "getSecondaryProgress", "()I");
global::android.app.ProgressDialog._getMax742 = @__env.GetMethodIDNoThrow(global::android.app.ProgressDialog.staticClass, "getMax", "()I");
global::android.app.ProgressDialog._setMax743 = @__env.GetMethodIDNoThrow(global::android.app.ProgressDialog.staticClass, "setMax", "(I)V");
global::android.app.ProgressDialog._incrementProgressBy744 = @__env.GetMethodIDNoThrow(global::android.app.ProgressDialog.staticClass, "incrementProgressBy", "(I)V");
global::android.app.ProgressDialog._incrementSecondaryProgressBy745 = @__env.GetMethodIDNoThrow(global::android.app.ProgressDialog.staticClass, "incrementSecondaryProgressBy", "(I)V");
global::android.app.ProgressDialog._setProgressDrawable746 = @__env.GetMethodIDNoThrow(global::android.app.ProgressDialog.staticClass, "setProgressDrawable", "(Landroid/graphics/drawable/Drawable;)V");
global::android.app.ProgressDialog._setIndeterminateDrawable747 = @__env.GetMethodIDNoThrow(global::android.app.ProgressDialog.staticClass, "setIndeterminateDrawable", "(Landroid/graphics/drawable/Drawable;)V");
global::android.app.ProgressDialog._setIndeterminate748 = @__env.GetMethodIDNoThrow(global::android.app.ProgressDialog.staticClass, "setIndeterminate", "(Z)V");
global::android.app.ProgressDialog._isIndeterminate749 = @__env.GetMethodIDNoThrow(global::android.app.ProgressDialog.staticClass, "isIndeterminate", "()Z");
global::android.app.ProgressDialog._setProgressStyle750 = @__env.GetMethodIDNoThrow(global::android.app.ProgressDialog.staticClass, "setProgressStyle", "(I)V");
global::android.app.ProgressDialog._ProgressDialog751 = @__env.GetMethodIDNoThrow(global::android.app.ProgressDialog.staticClass, "<init>", "(Landroid/content/Context;)V");
global::android.app.ProgressDialog._ProgressDialog752 = @__env.GetMethodIDNoThrow(global::android.app.ProgressDialog.staticClass, "<init>", "(Landroid/content/Context;I)V");
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Controls.dll
// Description: The Windows Forms user interface controls like the map, legend, toolbox, ribbon and others.
// ********************************************************************************************************
// The contents of this file are subject to the MIT License (MIT)
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
// http://dotspatial.codeplex.com/license
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
// ANY KIND, either expressed or implied. See the License for the specific language governing rights and
// limitations under the License.
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 8/25/2008 2:46:23 PM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using DotSpatial.Data;
using DotSpatial.Symbology;
using GeoAPI.Geometries;
namespace DotSpatial.Controls
{
public class MapRasterLayer : RasterLayer, IMapRasterLayer
{
#region Events
/// <summary>
/// Fires an event that indicates to the parent map-frame that it should first
/// redraw the specified clip
/// </summary>
public event EventHandler<ClipArgs> BufferChanged;
#endregion
#region Private Variables
private Image _backBuffer; // draw to the back buffer, and swap to the stencil when done.
private Envelope _bufferExtent; // the geographic extent of the current buffer.
private Rectangle _bufferRectangle;
private bool _isInitialized;
private Image _stencil; // draw features to the stencil
#endregion
#region Constructors
/// <summary>
/// Creates a new raster layer from the specified fileName
/// </summary>
/// <param name="fileName"></param>
/// <param name="symbolizer"></param>
public MapRasterLayer(string fileName, IRasterSymbolizer symbolizer)
: base(fileName, symbolizer)
{
base.LegendText = Path.GetFileNameWithoutExtension(fileName);
if ((long)DataSet.NumRows * DataSet.NumColumns > MaxCellsInMemory)
{
string pyrFile = Path.ChangeExtension(fileName, ".mwi");
BitmapGetter = File.Exists(pyrFile) && File.Exists(Path.ChangeExtension(pyrFile, ".mwh"))
? new PyramidImage(pyrFile)
: CreatePyramidImage(pyrFile, DataManager.DefaultDataManager.ProgressHandler);
}
else
{
Bitmap bmp = new Bitmap(DataSet.NumColumns, DataSet.NumRows);
symbolizer.Raster = DataSet;
DataSet.DrawToBitmap(symbolizer, bmp);
var id = new InRamImage(bmp) { Bounds = DataSet.Bounds };
BitmapGetter = id;
}
}
/// <summary>
/// Creates a new instance of a MapRasterLayer and the specified image data to use for rendering it.
/// </summary>
public MapRasterLayer(IRaster baseRaster, ImageData baseImage)
: base(baseRaster)
{
base.LegendText = Path.GetFileNameWithoutExtension(baseRaster.Filename);
BitmapGetter = baseImage;
}
/// <summary>
/// Creates a new instance of a Raster layer, and will create a "FallLeaves" image based on the
/// raster values.
/// </summary>
/// <param name="raster">The raster to use</param>
public MapRasterLayer(IRaster raster)
: base(raster)
{
base.LegendText = Path.GetFileNameWithoutExtension(raster.Filename);
// string imageFile = Path.ChangeExtension(raster.Filename, ".png");
// if (File.Exists(imageFile)) File.Delete(imageFile);
if ((long)raster.NumRows * raster.NumColumns > MaxCellsInMemory)
{
// For huge images, assume that GDAL or something was needed anyway,
// and we would rather avoid having to re-create the pyramids if there is any chance
// that the old values will work ok.
string pyrFile = Path.ChangeExtension(raster.Filename, ".mwi");
if (File.Exists(pyrFile) && File.Exists(Path.ChangeExtension(pyrFile, ".mwh")))
{
BitmapGetter = new PyramidImage(pyrFile);
base.LegendText = Path.GetFileNameWithoutExtension(raster.Filename);
}
else
{
BitmapGetter = CreatePyramidImage(pyrFile, DataManager.DefaultDataManager.ProgressHandler);
}
}
else
{
// Ensure smaller images match the scheme.
Bitmap bmp = new Bitmap(raster.NumColumns, raster.NumRows);
raster.PaintColorSchemeToBitmap(Symbolizer, bmp, raster.ProgressHandler);
var id = new InRamImage(bmp) { Bounds = { AffineCoefficients = raster.Bounds.AffineCoefficients } };
BitmapGetter = id;
}
}
#endregion
#region Methods
/// <summary>
/// Call StartDrawing before using this.
/// </summary>
/// <param name="rectangles">The rectangular region in pixels to clear.</param>
/// <param name= "color">The color to use when clearing. Specifying transparent
/// will replace content with transparent pixels.</param>
public void Clear(List<Rectangle> rectangles, Color color)
{
if (_backBuffer == null) return;
Graphics g = Graphics.FromImage(_backBuffer);
foreach (Rectangle r in rectangles)
{
if (r.IsEmpty == false)
{
g.Clip = new Region(r);
g.Clear(color);
}
}
g.Dispose();
}
/// <summary>
/// This will draw any features that intersect this region. To specify the features
/// directly, use OnDrawFeatures. This will not clear existing buffer content.
/// For that call Initialize instead.
/// </summary>
/// <param name="args">A GeoArgs clarifying the transformation from geographic to image space</param>
/// <param name="regions">The geographic regions to draw</param>
public void DrawRegions(MapArgs args, List<Extent> regions)
{
List<Rectangle> clipRects = args.ProjToPixel(regions);
DrawWindows(args, regions, clipRects);
}
/// <summary>
/// Indicates that the drawing process has been finalized and swaps the back buffer
/// to the front buffer.
/// </summary>
public void FinishDrawing()
{
OnFinishDrawing();
if (_stencil != null && _stencil != _backBuffer) _stencil.Dispose();
_stencil = _backBuffer;
}
/// <summary>
/// Copies any current content to the back buffer so that drawing should occur on the
/// back buffer (instead of the fore-buffer). Calling draw methods without
/// calling this may cause exceptions.
/// </summary>
/// <param name="preserve">Boolean, true if the front buffer content should be copied to the back buffer
/// where drawing will be taking place.</param>
public void StartDrawing(bool preserve)
{
Bitmap backBuffer = new Bitmap(BufferRectangle.Width, BufferRectangle.Height);
if (Buffer != null)
{
if (Buffer.Width == backBuffer.Width && Buffer.Height == backBuffer.Height)
{
if (preserve)
{
Graphics g = Graphics.FromImage(backBuffer);
g.DrawImageUnscaled(Buffer, 0, 0);
}
}
}
if (BackBuffer != null && BackBuffer != Buffer) BackBuffer.Dispose();
BackBuffer = backBuffer;
OnStartDrawing();
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the back buffer that will be drawn to as part of the initialization process.
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ShallowCopy]
public Image BackBuffer
{
get { return _backBuffer; }
set { _backBuffer = value; }
}
/// <summary>
/// Gets the current buffer.
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ShallowCopy]
public Image Buffer
{
get { return _stencil; }
set { _stencil = value; }
}
/// <summary>
/// Gets or sets the geographic region represented by the buffer
/// Calling Initialize will set this automatically.
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ShallowCopy]
public Envelope BufferEnvelope
{
get { return _bufferExtent; }
set { _bufferExtent = value; }
}
/// <summary>
/// Gets or sets the rectangle in pixels to use as the back buffer.
/// Calling Initialize will set this automatically.
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ShallowCopy]
public Rectangle BufferRectangle
{
get { return _bufferRectangle; }
set { _bufferRectangle = value; }
}
/// <summary>
/// Gets or sets whether the image layer is initialized
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public new bool IsInitialized
{
get { return _isInitialized; }
set { _isInitialized = value; }
}
#endregion
#region Protected Methods
/// <summary>
/// Fires the OnBufferChanged event
/// </summary>
/// <param name="clipRectangles">The Rectangle in pixels</param>
protected virtual void OnBufferChanged(List<Rectangle> clipRectangles)
{
if (BufferChanged != null)
{
ClipArgs e = new ClipArgs(clipRectangles);
BufferChanged(this, e);
}
}
/// <summary>
/// Indicates that whatever drawing is going to occur has finished and the contents
/// are about to be flipped forward to the front buffer.
/// </summary>
protected virtual void OnFinishDrawing()
{
}
///// <summary>
///// This ensures that when the symbolic content for the layer is updated that we re-load the image.
///// </summary>
//protected override void OnItemChanged()
//{
// if (_baseImage == null) return;
// string imgFile = _baseImage.Filename;
// _baseImage.Open(imgFile);
// base.OnItemChanged();
//}
/// <summary>
/// Occurs when a new drawing is started, but after the BackBuffer has been established.
/// </summary>
protected virtual void OnStartDrawing()
{
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (_stencil != _backBuffer && _stencil != null)
{
_stencil.Dispose();
_stencil = null;
}
if (_backBuffer != null)
{
_backBuffer.Dispose();
_backBuffer = null;
}
_bufferExtent = null;
_bufferRectangle = Rectangle.Empty;
_isInitialized = false;
}
base.Dispose(disposing);
}
#endregion
#region Private Methods
/// <summary>
/// This draws to the back buffer. If the back buffer doesn't exist, this will create one.
/// This will not flip the back buffer to the front.
/// </summary>
/// <param name="args"></param>
/// <param name="regions"></param>
/// <param name="clipRectangles"></param>
private void DrawWindows(MapArgs args, IList<Extent> regions, IList<Rectangle> clipRectangles)
{
Graphics g;
if (args.Device != null)
{
g = args.Device; // A device on the MapArgs is optional, but overrides the normal buffering behaviors.
}
else
{
if (_backBuffer == null) _backBuffer = new Bitmap(_bufferRectangle.Width, _bufferRectangle.Height);
g = Graphics.FromImage(_backBuffer);
}
int numBounds = Math.Min(regions.Count, clipRectangles.Count);
for (int i = 0; i < numBounds; i++)
{
using (Bitmap bmp = BitmapGetter.GetBitmap(regions[i], clipRectangles[i]))
{
if (bmp != null) g.DrawImage(bmp, clipRectangles[i]);
}
}
if (args.Device == null) g.Dispose();
}
#endregion
}
}
| |
/******************************************************************************
* The MIT License
* Copyright (c) 2003 Novell Inc. www.novell.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the Software), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*******************************************************************************/
//
// Novell.Directory.Ldap.MessageAgent.cs
//
// Author:
// Sunil Kumar (Sunilk@novell.com)
//
// (C) 2003 Novell, Inc (http://www.novell.com)
//
using System;
using System.Diagnostics;
using System.Threading;
using Novell.Directory.Ldap.Utilclass;
namespace Novell.Directory.Ldap
{
/* package */
class MessageAgent
{
private void InitBlock()
{
messages = new MessageVector(5, 5);
}
/// <summary> empty and return all messages owned by this agent
///
///
/// </summary>
virtual internal object[] MessageArray
{
/* package */
get
{
return messages.ObjectArray;
}
}
/// <summary> Get a list of message ids controlled by this agent
///
/// </summary>
/// <returns> an array of integers representing the message ids
/// </returns>
virtual internal int[] MessageIDs
{
/* package */
get
{
int size = messages.Count;
int[] ids = new int[size];
Message info;
for (int i = 0; i < size; i++)
{
info = (Message)messages[i];
ids[i] = info.MessageID;
}
return ids;
}
}
/// <summary> Get the maessage agent number for debugging
///
/// </summary>
/// <returns> the agent number
/// </returns>
virtual internal string AgentName
{
/*packge*/
get
{
return name;
}
}
/// <summary> Get a count of all messages queued</summary>
virtual internal int Count
{
/* package */
get
{
int count = 0;
object[] msgs = messages.ToArray();
for (int i = 0; i < msgs.Length; i++)
{
Message m = (Message)msgs[i];
count += m.Count;
}
return count;
}
}
private MessageVector messages;
private int indexLastRead = 0;
private static object nameLock; // protect agentNum
private static int agentNum = 0; // Debug, agent number
private string name; // string name for debug
/* package */
internal MessageAgent()
{
InitBlock();
// Get a unique agent id for debug
}
/// <summary> merges two message agents
///
/// </summary>
/// <param name="fromAgent">the agent to be merged into this one
/// </param>
/* package */
internal void merge(MessageAgent fromAgent)
{
object[] msgs = fromAgent.MessageArray;
for (int i = 0; i < msgs.Length; i++)
{
messages.Add(msgs[i]);
((Message)(msgs[i])).Agent = this;
}
lock (messages)
{
if (msgs.Length > 1)
{
Monitor.PulseAll(messages); // wake all threads waiting for messages
}
else if (msgs.Length == 1)
{
Monitor.Pulse(messages); // only wake one thread
}
}
}
/// <summary> Wakes up any threads waiting for messages in the message agent
///
/// </summary>
/* package */
internal void sleepersAwake(bool all)
{
lock (messages)
{
if (all)
Monitor.PulseAll(messages);
else
Monitor.Pulse(messages);
}
}
/// <summary> Returns true if any responses are queued for any of the agent's messages
///
/// return false if no responses are queued, otherwise true
/// </summary>
/* package */
internal bool isResponseReceived()
{
int size = messages.Count;
int next = indexLastRead + 1;
Message info;
for (int i = 0; i < size; i++)
{
if (next == size)
{
next = 0;
}
info = (Message)messages[next];
if (info.hasReplies())
{
return true;
}
}
return false;
}
/// <summary> Returns true if any responses are queued for the specified msgId
///
/// return false if no responses are queued, otherwise true
/// </summary>
/* package */
internal bool isResponseReceived(int msgId)
{
try
{
Message info = messages.findMessageById(msgId);
return info.hasReplies();
}
catch (FieldAccessException ex)
{
return false;
}
}
/// <summary> Abandon the request associated with MsgId
///
/// </summary>
/// <param name="msgId">the message id to abandon
///
/// </param>
/// <param name="cons">constraints associated with this request
/// </param>
/* package */
internal void Abandon(int msgId, LdapConstraints cons)
//, boolean informUser)
{
Message info = null;
try
{
// Send abandon request and remove from connection list
info = messages.findMessageById(msgId);
SupportClass.VectorRemoveElement(messages, info); // This message is now dead
info.Abandon(cons, null);
}
catch (FieldAccessException ex)
{
}
}
/// <summary> Abandon all requests on this MessageAgent</summary>
/* package */
internal void AbandonAll()
{
int size = messages.Count;
Message info;
for (int i = 0; i < size; i++)
{
info = (Message)messages[i];
// Message complete and no more replies, remove from id list
SupportClass.VectorRemoveElement(messages, info);
info.Abandon(null, null);
}
}
/// <summary> Indicates whether a specific operation is complete
///
/// </summary>
/// <returns> true if a specific operation is complete
/// </returns>
/* package */
internal bool isComplete(int msgid)
{
try
{
Message info = messages.findMessageById(msgid);
if (!info.Complete)
{
return false;
}
}
catch (FieldAccessException ex)
{
// return true, if no message, it must be complete
}
return true;
}
/// <summary> Returns the Message object for a given messageID
///
/// </summary>
/// <param name="msgid">the message ID.
/// </param>
/* package */
internal Message getMessage(int msgid)
{
return messages.findMessageById(msgid);
}
/// <summary> Send a request to the server. A Message class is created
/// for the specified request which causes the message to be sent.
/// The request is added to the list of messages being managed by
/// this agent.
///
/// </summary>
/// <param name="conn">the connection that identifies the server.
///
/// </param>
/// <param name="msg">the LdapMessage to send
///
/// </param>
/// <param name="timeOut">the interval to wait for the message to complete or
/// <code>null</code> if infinite.
/// </param>
/// <param name="queue">the LdapMessageQueue associated with this request.
/// </param>
/* package */
internal void sendMessage(Connection conn, LdapMessage msg, int timeOut, LdapMessageQueue queue, BindProperties bindProps)
{
// creating a messageInfo causes the message to be sent
// and a timer to be started if needed.
Message message = new Message(msg, timeOut, conn, this, queue, bindProps);
messages.Add(message);
message.sendMessage(); // Now send message to server
}
/// <summary> Returns a response queued, or waits if none queued
///
/// </summary>
/* package */
// internal object getLdapMessage(System.Int32 msgId)
internal object getLdapMessage(int msgId)
{
return (getLdapMessage(new Integer32(msgId)));
}
internal object getLdapMessage(Integer32 msgId)
{
object rfcMsg;
// If no messages for this agent, just return null
if (messages.Count == 0)
{
return null;
}
if (msgId != null)
{
// Request messages for a specific ID
try
{
// Get message for this ID
// Message info = messages.findMessageById(msgId);
Message info = messages.findMessageById(msgId.intValue);
rfcMsg = info.waitForReply(); // blocks for a response
if (!info.acceptsReplies() && !info.hasReplies())
{
// Message complete and no more replies, remove from id list
SupportClass.VectorRemoveElement(messages, info);
info.Abandon(null, null); // Get rid of resources
}
return rfcMsg;
}
catch (FieldAccessException ex)
{
// no such message id
return null;
}
}
// A msgId was NOT specified, any message will do
lock (messages)
{
while (true)
{
int next = indexLastRead + 1;
Message info;
for (int i = 0; i < messages.Count; i++)
{
if (next >= messages.Count)
{
next = 0;
}
info = (Message)messages[next];
indexLastRead = next++;
rfcMsg = info.Reply;
// Check this request is complete
if (!info.acceptsReplies() && !info.hasReplies())
{
// Message complete & no more replies, remove from id list
SupportClass.VectorRemoveElement(messages, info); // remove from list
info.Abandon(null, null); // Get rid of resources
// Start loop at next message that is now moved
// to the current position in the Vector.
i -= 1;
}
if (rfcMsg != null)
{
// We got a reply
return rfcMsg;
}
} // end for loop */
// Messages can be removed in this loop, we we must
// check if any messages left for this agent
if (messages.Count == 0)
{
return null;
}
// No data, wait for something to come in.
try
{
Monitor.Wait(messages);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
} /* end while */
} /* end synchronized */
}
/// <summary> Debug code to print messages in message vector</summary>
private void debugDisplayMessages()
{
}
static MessageAgent()
{
nameLock = new object();
}
}
}
| |
using System;
using ClosedXML.Excel;
using NUnit.Framework;
namespace ClosedXML_Tests.Excel.CalcEngine
{
[TestFixture]
public class FunctionsTests
{
[SetUp]
public void Init()
{
// Make sure tests run on a deterministic culture
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
}
[Test]
public void Asc()
{
Object actual;
actual = XLWorkbook.EvaluateExpr(@"Asc(""Text"")");
Assert.AreEqual("Text", actual);
}
[Test]
public void Clean()
{
Object actual;
actual = XLWorkbook.EvaluateExpr(String.Format(@"Clean(""A{0}B"")", Environment.NewLine));
Assert.AreEqual("AB", actual);
}
[Test]
public void Combin()
{
object actual1 = XLWorkbook.EvaluateExpr("Combin(200, 2)");
Assert.AreEqual(19900.0, actual1);
object actual2 = XLWorkbook.EvaluateExpr("Combin(20.1, 2.9)");
Assert.AreEqual(190.0, actual2);
}
[Test]
public void Degrees()
{
object actual1 = XLWorkbook.EvaluateExpr("Degrees(180)");
Assert.IsTrue(Math.PI - (double) actual1 < XLHelper.Epsilon);
}
[Test]
public void Dollar()
{
object actual = XLWorkbook.EvaluateExpr("Dollar(12345.123)");
Assert.AreEqual(TestHelper.CurrencySymbol + "12,345.12", actual);
actual = XLWorkbook.EvaluateExpr("Dollar(12345.123, 1)");
Assert.AreEqual(TestHelper.CurrencySymbol + "12,345.1", actual);
}
[Test]
public void Even()
{
object actual = XLWorkbook.EvaluateExpr("Even(3)");
Assert.AreEqual(4, actual);
actual = XLWorkbook.EvaluateExpr("Even(2)");
Assert.AreEqual(2, actual);
actual = XLWorkbook.EvaluateExpr("Even(-1)");
Assert.AreEqual(-2, actual);
actual = XLWorkbook.EvaluateExpr("Even(-2)");
Assert.AreEqual(-2, actual);
actual = XLWorkbook.EvaluateExpr("Even(0)");
Assert.AreEqual(0, actual);
actual = XLWorkbook.EvaluateExpr("Even(1.5)");
Assert.AreEqual(2, actual);
actual = XLWorkbook.EvaluateExpr("Even(2.01)");
Assert.AreEqual(4, actual);
}
[Test]
public void Exact()
{
Object actual;
actual = XLWorkbook.EvaluateExpr("Exact(\"A\", \"A\")");
Assert.AreEqual(true, actual);
actual = XLWorkbook.EvaluateExpr("Exact(\"A\", \"a\")");
Assert.AreEqual(false, actual);
}
[Test]
public void Fact()
{
object actual = XLWorkbook.EvaluateExpr("Fact(5.9)");
Assert.AreEqual(120.0, actual);
}
[Test]
public void FactDouble()
{
object actual1 = XLWorkbook.EvaluateExpr("FactDouble(6)");
Assert.AreEqual(48.0, actual1);
object actual2 = XLWorkbook.EvaluateExpr("FactDouble(7)");
Assert.AreEqual(105.0, actual2);
}
[Test]
public void Fixed()
{
Object actual;
actual = XLWorkbook.EvaluateExpr("Fixed(12345.123)");
Assert.AreEqual("12,345.12", actual);
actual = XLWorkbook.EvaluateExpr("Fixed(12345.123, 1)");
Assert.AreEqual("12,345.1", actual);
actual = XLWorkbook.EvaluateExpr("Fixed(12345.123, 1, TRUE)");
Assert.AreEqual("12345.1", actual);
}
[Test]
public void Formula_from_another_sheet()
{
var wb = new XLWorkbook();
IXLWorksheet ws1 = wb.AddWorksheet("ws1");
ws1.FirstCell().SetValue(1).CellRight().SetFormulaA1("A1 + 1");
IXLWorksheet ws2 = wb.AddWorksheet("ws2");
ws2.FirstCell().SetFormulaA1("ws1!B1 + 1");
object v = ws2.FirstCell().Value;
Assert.AreEqual(3.0, v);
}
[Test]
public void Gcd()
{
object actual = XLWorkbook.EvaluateExpr("Gcd(24, 36)");
Assert.AreEqual(12, actual);
object actual1 = XLWorkbook.EvaluateExpr("Gcd(5, 0)");
Assert.AreEqual(5, actual1);
object actual2 = XLWorkbook.EvaluateExpr("Gcd(0, 5)");
Assert.AreEqual(5, actual2);
object actual3 = XLWorkbook.EvaluateExpr("Gcd(240, 360, 30)");
Assert.AreEqual(30, actual3);
}
[Test]
public void Lcm()
{
object actual = XLWorkbook.EvaluateExpr("Lcm(24, 36)");
Assert.AreEqual(72, actual);
object actual1 = XLWorkbook.EvaluateExpr("Lcm(5, 0)");
Assert.AreEqual(0, actual1);
object actual2 = XLWorkbook.EvaluateExpr("Lcm(0, 5)");
Assert.AreEqual(0, actual2);
object actual3 = XLWorkbook.EvaluateExpr("Lcm(240, 360, 30)");
Assert.AreEqual(720, actual3);
}
[Test]
public void MDetem()
{
IXLWorksheet ws = new XLWorkbook().AddWorksheet("Sheet1");
ws.Cell("A1").SetValue(2).CellRight().SetValue(4);
ws.Cell("A2").SetValue(3).CellRight().SetValue(5);
Object actual;
ws.Cell("A5").FormulaA1 = "MDeterm(A1:B2)";
actual = ws.Cell("A5").Value;
Assert.IsTrue(XLHelper.AreEqual(-2.0, (double) actual));
ws.Cell("A6").FormulaA1 = "Sum(A5)";
actual = ws.Cell("A6").Value;
Assert.IsTrue(XLHelper.AreEqual(-2.0, (double) actual));
ws.Cell("A7").FormulaA1 = "Sum(MDeterm(A1:B2))";
actual = ws.Cell("A7").Value;
Assert.IsTrue(XLHelper.AreEqual(-2.0, (double) actual));
}
[Test]
public void MInverse()
{
IXLWorksheet ws = new XLWorkbook().AddWorksheet("Sheet1");
ws.Cell("A1").SetValue(1).CellRight().SetValue(2).CellRight().SetValue(1);
ws.Cell("A2").SetValue(3).CellRight().SetValue(4).CellRight().SetValue(-1);
ws.Cell("A3").SetValue(0).CellRight().SetValue(2).CellRight().SetValue(0);
Object actual;
ws.Cell("A5").FormulaA1 = "MInverse(A1:C3)";
actual = ws.Cell("A5").Value;
Assert.IsTrue(XLHelper.AreEqual(0.25, (double) actual));
ws.Cell("A6").FormulaA1 = "Sum(A5)";
actual = ws.Cell("A6").Value;
Assert.IsTrue(XLHelper.AreEqual(0.25, (double) actual));
ws.Cell("A7").FormulaA1 = "Sum(MInverse(A1:C3))";
actual = ws.Cell("A7").Value;
Assert.IsTrue(XLHelper.AreEqual(0.5, (double) actual));
}
[Test]
public void MMult()
{
IXLWorksheet ws = new XLWorkbook().AddWorksheet("Sheet1");
ws.Cell("A1").SetValue(2).CellRight().SetValue(4);
ws.Cell("A2").SetValue(3).CellRight().SetValue(5);
ws.Cell("A3").SetValue(2).CellRight().SetValue(4);
ws.Cell("A4").SetValue(3).CellRight().SetValue(5);
Object actual;
ws.Cell("A5").FormulaA1 = "MMult(A1:B2, A3:B4)";
actual = ws.Cell("A5").Value;
Assert.AreEqual(16.0, actual);
ws.Cell("A6").FormulaA1 = "Sum(A5)";
actual = ws.Cell("A6").Value;
Assert.AreEqual(16.0, actual);
ws.Cell("A7").FormulaA1 = "Sum(MMult(A1:B2, A3:B4))";
actual = ws.Cell("A7").Value;
Assert.AreEqual(102.0, actual);
}
[Test]
public void MRound()
{
object actual = XLWorkbook.EvaluateExpr("MRound(10, 3)");
Assert.AreEqual(9m, actual);
object actual3 = XLWorkbook.EvaluateExpr("MRound(10.5, 3)");
Assert.AreEqual(12m, actual3);
object actual4 = XLWorkbook.EvaluateExpr("MRound(10.4, 3)");
Assert.AreEqual(9m, actual4);
object actual1 = XLWorkbook.EvaluateExpr("MRound(-10, -3)");
Assert.AreEqual(-9m, actual1);
object actual2 = XLWorkbook.EvaluateExpr("MRound(1.3, 0.2)");
Assert.AreEqual(1.4m, actual2);
}
[Test]
public void Mod()
{
object actual = XLWorkbook.EvaluateExpr("Mod(3, 2)");
Assert.AreEqual(1, actual);
object actual1 = XLWorkbook.EvaluateExpr("Mod(-3, 2)");
Assert.AreEqual(1, actual1);
object actual2 = XLWorkbook.EvaluateExpr("Mod(3, -2)");
Assert.AreEqual(-1, actual2);
object actual3 = XLWorkbook.EvaluateExpr("Mod(-3, -2)");
Assert.AreEqual(-1, actual3);
}
[Test]
public void Multinomial()
{
object actual = XLWorkbook.EvaluateExpr("Multinomial(2,3,4)");
Assert.AreEqual(1260.0, actual);
}
[Test]
public void Odd()
{
object actual = XLWorkbook.EvaluateExpr("Odd(1.5)");
Assert.AreEqual(3, actual);
object actual1 = XLWorkbook.EvaluateExpr("Odd(3)");
Assert.AreEqual(3, actual1);
object actual2 = XLWorkbook.EvaluateExpr("Odd(2)");
Assert.AreEqual(3, actual2);
object actual3 = XLWorkbook.EvaluateExpr("Odd(-1)");
Assert.AreEqual(-1, actual3);
object actual4 = XLWorkbook.EvaluateExpr("Odd(-2)");
Assert.AreEqual(-3, actual4);
actual = XLWorkbook.EvaluateExpr("Odd(0)");
Assert.AreEqual(1, actual);
}
[Test]
public void Product()
{
object actual = XLWorkbook.EvaluateExpr("Product(2,3,4)");
Assert.AreEqual(24.0, actual);
}
[Test]
public void Quotient()
{
object actual = XLWorkbook.EvaluateExpr("Quotient(5,2)");
Assert.AreEqual(2, actual);
actual = XLWorkbook.EvaluateExpr("Quotient(4.5,3.1)");
Assert.AreEqual(1, actual);
actual = XLWorkbook.EvaluateExpr("Quotient(-10,3)");
Assert.AreEqual(-3, actual);
}
[Test]
public void Radians()
{
object actual = XLWorkbook.EvaluateExpr("Radians(270)");
Assert.IsTrue(Math.Abs(4.71238898038469 - (double) actual) < XLHelper.Epsilon);
}
[Test]
public void Roman()
{
object actual = XLWorkbook.EvaluateExpr("Roman(3046, 1)");
Assert.AreEqual("MMMXLVI", actual);
actual = XLWorkbook.EvaluateExpr("Roman(270)");
Assert.AreEqual("CCLXX", actual);
actual = XLWorkbook.EvaluateExpr("Roman(3999, true)");
Assert.AreEqual("MMMCMXCIX", actual);
}
[Test]
public void Round()
{
object actual = XLWorkbook.EvaluateExpr("Round(2.15, 1)");
Assert.AreEqual(2.2, actual);
actual = XLWorkbook.EvaluateExpr("Round(2.149, 1)");
Assert.AreEqual(2.1, actual);
actual = XLWorkbook.EvaluateExpr("Round(-1.475, 2)");
Assert.AreEqual(-1.48, actual);
actual = XLWorkbook.EvaluateExpr("Round(21.5, -1)");
Assert.AreEqual(20.0, actual);
actual = XLWorkbook.EvaluateExpr("Round(626.3, -3)");
Assert.AreEqual(1000.0, actual);
actual = XLWorkbook.EvaluateExpr("Round(1.98, -1)");
Assert.AreEqual(0.0, actual);
actual = XLWorkbook.EvaluateExpr("Round(-50.55, -2)");
Assert.AreEqual(-100.0, actual);
actual = XLWorkbook.EvaluateExpr("ROUND(59 * 0.535, 2)"); // (59 * 0.535) = 31.565
Assert.AreEqual(31.57, actual);
actual = XLWorkbook.EvaluateExpr("ROUND(59 * -0.535, 2)"); // (59 * -0.535) = -31.565
Assert.AreEqual(-31.57, actual);
}
[Test]
public void RoundDown()
{
object actual = XLWorkbook.EvaluateExpr("RoundDown(3.2, 0)");
Assert.AreEqual(3.0, actual);
actual = XLWorkbook.EvaluateExpr("RoundDown(76.9, 0)");
Assert.AreEqual(76.0, actual);
actual = XLWorkbook.EvaluateExpr("RoundDown(3.14159, 3)");
Assert.AreEqual(3.141, actual);
actual = XLWorkbook.EvaluateExpr("RoundDown(-3.14159, 1)");
Assert.AreEqual(-3.1, actual);
actual = XLWorkbook.EvaluateExpr("RoundDown(31415.92654, -2)");
Assert.AreEqual(31400.0, actual);
actual = XLWorkbook.EvaluateExpr("RoundDown(0, 3)");
Assert.AreEqual(0.0, actual);
}
[Test]
public void RoundUp()
{
object actual = XLWorkbook.EvaluateExpr("RoundUp(3.2, 0)");
Assert.AreEqual(4.0, actual);
actual = XLWorkbook.EvaluateExpr("RoundUp(76.9, 0)");
Assert.AreEqual(77.0, actual);
actual = XLWorkbook.EvaluateExpr("RoundUp(3.14159, 3)");
Assert.AreEqual(3.142, actual);
actual = XLWorkbook.EvaluateExpr("RoundUp(-3.14159, 1)");
Assert.AreEqual(-3.2, actual);
actual = XLWorkbook.EvaluateExpr("RoundUp(31415.92654, -2)");
Assert.AreEqual(31500.0, actual);
actual = XLWorkbook.EvaluateExpr("RoundUp(0, 3)");
Assert.AreEqual(0.0, actual);
}
[Test]
public void SeriesSum()
{
object actual = XLWorkbook.EvaluateExpr("SERIESSUM(2,3,4,5)");
Assert.AreEqual(40.0, actual);
var wb = new XLWorkbook();
IXLWorksheet ws = wb.AddWorksheet("Sheet1");
ws.Cell("A2").FormulaA1 = "PI()/4";
ws.Cell("A3").Value = 1;
ws.Cell("A4").FormulaA1 = "-1/FACT(2)";
ws.Cell("A5").FormulaA1 = "1/FACT(4)";
ws.Cell("A6").FormulaA1 = "-1/FACT(6)";
actual = ws.Evaluate("SERIESSUM(A2,0,2,A3:A6)");
Assert.IsTrue(Math.Abs(0.70710321482284566 - (double) actual) < XLHelper.Epsilon);
}
[Test]
public void SqrtPi()
{
object actual = XLWorkbook.EvaluateExpr("SqrtPi(1)");
Assert.IsTrue(Math.Abs(1.7724538509055159 - (double) actual) < XLHelper.Epsilon);
actual = XLWorkbook.EvaluateExpr("SqrtPi(2)");
Assert.IsTrue(Math.Abs(2.5066282746310002 - (double) actual) < XLHelper.Epsilon);
}
[Test]
public void SubtotalAverage()
{
object actual = XLWorkbook.EvaluateExpr("Subtotal(1,2,3)");
Assert.AreEqual(2.5, actual);
actual = XLWorkbook.EvaluateExpr(@"Subtotal(1,""A"",3, 2)");
Assert.AreEqual(2.5, actual);
}
[Test]
public void SubtotalCount()
{
object actual = XLWorkbook.EvaluateExpr("Subtotal(2,2,3)");
Assert.AreEqual(2, actual);
actual = XLWorkbook.EvaluateExpr(@"Subtotal(2,""A"",3)");
Assert.AreEqual(1, actual);
}
[Test]
public void SubtotalCountA()
{
Object actual;
actual = XLWorkbook.EvaluateExpr("Subtotal(3,2,3)");
Assert.AreEqual(2.0, actual);
actual = XLWorkbook.EvaluateExpr(@"Subtotal(3,"""",3)");
Assert.AreEqual(1.0, actual);
}
[Test]
public void SubtotalMax()
{
Object actual;
actual = XLWorkbook.EvaluateExpr(@"Subtotal(4,2,3,""A"")");
Assert.AreEqual(3.0, actual);
}
[Test]
public void SubtotalMin()
{
Object actual;
actual = XLWorkbook.EvaluateExpr(@"Subtotal(5,2,3,""A"")");
Assert.AreEqual(2.0, actual);
}
[Test]
public void SubtotalProduct()
{
Object actual;
actual = XLWorkbook.EvaluateExpr(@"Subtotal(6,2,3,""A"")");
Assert.AreEqual(6.0, actual);
}
[Test]
public void SubtotalStDev()
{
Object actual;
actual = XLWorkbook.EvaluateExpr(@"Subtotal(7,2,3,""A"")");
Assert.IsTrue(Math.Abs(0.70710678118654757 - (double) actual) < XLHelper.Epsilon);
}
[Test]
public void SubtotalStDevP()
{
Object actual;
actual = XLWorkbook.EvaluateExpr(@"Subtotal(8,2,3,""A"")");
Assert.AreEqual(0.5, actual);
}
[Test]
public void SubtotalSum()
{
Object actual;
actual = XLWorkbook.EvaluateExpr(@"Subtotal(9,2,3,""A"")");
Assert.AreEqual(5.0, actual);
}
[Test]
public void SubtotalVar()
{
Object actual;
actual = XLWorkbook.EvaluateExpr(@"Subtotal(10,2,3,""A"")");
Assert.IsTrue(Math.Abs(0.5 - (double) actual) < XLHelper.Epsilon);
}
[Test]
public void SubtotalVarP()
{
Object actual;
actual = XLWorkbook.EvaluateExpr(@"Subtotal(11,2,3,""A"")");
Assert.AreEqual(0.25, actual);
}
[Test]
public void Sum()
{
IXLCell cell = new XLWorkbook().AddWorksheet("Sheet1").FirstCell();
IXLCell fCell = cell.SetValue(1).CellBelow().SetValue(2).CellBelow();
fCell.FormulaA1 = "sum(A1:A2)";
Assert.AreEqual(3.0, fCell.Value);
}
[Test]
public void SumDateTimeAndNumber()
{
using (var wb = new XLWorkbook())
{
var ws = wb.AddWorksheet("Sheet1");
ws.Cell("A1").Value = 1;
ws.Cell("A2").Value = new DateTime(2018, 1, 1);
Assert.AreEqual(43102, ws.Evaluate("SUM(A1:A2)"));
ws.Cell("A1").Value = 2;
ws.Cell("A2").FormulaA1 = "DATE(2018,1,1)";
Assert.AreEqual(43103, ws.Evaluate("SUM(A1:A2)"));
}
}
[Test]
public void SumSq()
{
Object actual;
actual = XLWorkbook.EvaluateExpr(@"SumSq(3,4)");
Assert.AreEqual(25.0, actual);
}
[Test]
public void TextConcat()
{
var wb = new XLWorkbook();
IXLWorksheet ws = wb.AddWorksheet("Sheet1");
ws.Cell("A1").Value = 1;
ws.Cell("A2").Value = 1;
ws.Cell("B1").Value = 1;
ws.Cell("B2").Value = 1;
ws.Cell("C1").FormulaA1 = "\"The total value is: \" & SUM(A1:B2)";
object r = ws.Cell("C1").Value;
Assert.AreEqual("The total value is: 4", r.ToString());
}
[Test]
public void Trim()
{
Assert.AreEqual("Test", XLWorkbook.EvaluateExpr("Trim(\"Test \")"));
//Should not trim non breaking space
//See http://office.microsoft.com/en-us/excel-help/trim-function-HP010062581.aspx
Assert.AreEqual("Test\u00A0", XLWorkbook.EvaluateExpr("Trim(\"Test\u00A0 \")"));
}
[Test]
public void TestEmptyTallyOperations()
{
//In these test no values have been set
XLWorkbook wb = new XLWorkbook();
wb.Worksheets.Add("TallyTests");
var cell = wb.Worksheet(1).Cell(1, 1).SetFormulaA1("=MAX(D1,D2)");
Assert.AreEqual(0, cell.Value);
cell = wb.Worksheet(1).Cell(2, 1).SetFormulaA1("=MIN(D1,D2)");
Assert.AreEqual(0, cell.Value);
cell = wb.Worksheet(1).Cell(3, 1).SetFormulaA1("=SUM(D1,D2)");
Assert.AreEqual(0, cell.Value);
Assert.That(() => wb.Worksheet(1).Cell(3, 1).SetFormulaA1("=AVERAGE(D1,D2)").Value, Throws.TypeOf<ApplicationException>());
}
[Test]
public void TestOmittedParameters()
{
using (var wb = new XLWorkbook())
{
object value;
value = wb.Evaluate("=IF(TRUE,1)");
Assert.AreEqual(1, value);
value = wb.Evaluate("=IF(TRUE,1,)");
Assert.AreEqual(1, value);
value = wb.Evaluate("=IF(FALSE,1,)");
Assert.AreEqual(false, value);
value = wb.Evaluate("=IF(FALSE,,2)");
Assert.AreEqual(2, value);
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.RecoveryServices.SiteRecovery
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.RecoveryServices;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for ReplicationNetworksOperations.
/// </summary>
public static partial class ReplicationNetworksOperationsExtensions
{
/// <summary>
/// Gets the list of networks. View-only API.
/// </summary>
/// <remarks>
/// Lists the networks available in a vault
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<Network> List(this IReplicationNetworksOperations operations)
{
return operations.ListAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Gets the list of networks. View-only API.
/// </summary>
/// <remarks>
/// Lists the networks available in a vault
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Network>> ListAsync(this IReplicationNetworksOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets the list of networks under a fabric.
/// </summary>
/// <remarks>
/// Lists the networks available for a fabric.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='fabricName'>
/// Fabric name
/// </param>
public static IPage<Network> ListByReplicationFabrics(this IReplicationNetworksOperations operations, string fabricName)
{
return operations.ListByReplicationFabricsAsync(fabricName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the list of networks under a fabric.
/// </summary>
/// <remarks>
/// Lists the networks available for a fabric.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='fabricName'>
/// Fabric name
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Network>> ListByReplicationFabricsAsync(this IReplicationNetworksOperations operations, string fabricName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByReplicationFabricsWithHttpMessagesAsync(fabricName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets a network with specified server id and network name.
/// </summary>
/// <remarks>
/// Gets the details of a network.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='fabricName'>
/// Server Id.
/// </param>
/// <param name='networkName'>
/// Primary network name.
/// </param>
public static Network Get(this IReplicationNetworksOperations operations, string fabricName, string networkName)
{
return operations.GetAsync(fabricName, networkName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets a network with specified server id and network name.
/// </summary>
/// <remarks>
/// Gets the details of a network.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='fabricName'>
/// Server Id.
/// </param>
/// <param name='networkName'>
/// Primary network name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Network> GetAsync(this IReplicationNetworksOperations operations, string fabricName, string networkName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(fabricName, networkName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets the list of networks. View-only API.
/// </summary>
/// <remarks>
/// Lists the networks available in a vault
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<Network> ListNext(this IReplicationNetworksOperations operations, string nextPageLink)
{
return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the list of networks. View-only API.
/// </summary>
/// <remarks>
/// Lists the networks available in a vault
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Network>> ListNextAsync(this IReplicationNetworksOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets the list of networks under a fabric.
/// </summary>
/// <remarks>
/// Lists the networks available for a fabric.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<Network> ListByReplicationFabricsNext(this IReplicationNetworksOperations operations, string nextPageLink)
{
return operations.ListByReplicationFabricsNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the list of networks under a fabric.
/// </summary>
/// <remarks>
/// Lists the networks available for a fabric.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Network>> ListByReplicationFabricsNextAsync(this IReplicationNetworksOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByReplicationFabricsNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2011 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using NUnit.Framework.Constraints;
using NUnit.Framework.Internal;
namespace NUnit.Framework
{
/// <summary>
/// The Assert class contains a collection of static methods that
/// implement the most common assertions used in NUnit.
/// </summary>
public partial class Assert
{
#region Assert.That
#region Boolean
/// <summary>
/// Asserts that a condition is true. If the condition is false the method throws
/// an <see cref="AssertionException"/>.
/// </summary>
/// <param name="condition">The evaluated condition</param>
/// <param name="message">The message to display if the condition is false</param>
/// <param name="args">Arguments to be used in formatting the message</param>
public static void That(bool condition, string message, params object[] args)
{
Assert.That(condition, Is.True, message, args);
}
/// <summary>
/// Asserts that a condition is true. If the condition is false the method throws
/// an <see cref="AssertionException"/>.
/// </summary>
/// <param name="condition">The evaluated condition</param>
public static void That(bool condition)
{
Assert.That(condition, Is.True, null, null);
}
#if !NET_2_0
/// <summary>
/// Asserts that a condition is true. If the condition is false the method throws
/// an <see cref="AssertionException"/>.
/// </summary>
/// <param name="condition">The evaluated condition</param>
/// <param name="getExceptionMessage">A function to build the message included with the Exception</param>
public static void That(bool condition, Func<string> getExceptionMessage)
{
Assert.That(condition, Is.True, getExceptionMessage);
}
#endif
#endregion
#region Lambda returning Boolean
#if !NET_2_0
/// <summary>
/// Asserts that a condition is true. If the condition is false the method throws
/// an <see cref="AssertionException"/>.
/// </summary>
/// <param name="condition">A lambda that returns a Boolean</param>
/// <param name="message">The message to display if the condition is false</param>
/// <param name="args">Arguments to be used in formatting the message</param>
public static void That(Func<bool> condition, string message, params object[] args)
{
Assert.That(condition.Invoke(), Is.True, message, args);
}
/// <summary>
/// Asserts that a condition is true. If the condition is false the method throws
/// an <see cref="AssertionException"/>.
/// </summary>
/// <param name="condition">A lambda that returns a Boolean</param>
public static void That(Func<bool> condition)
{
Assert.That(condition.Invoke(), Is.True, null, null);
}
/// <summary>
/// Asserts that a condition is true. If the condition is false the method throws
/// an <see cref="AssertionException"/>.
/// </summary>
/// <param name="condition">A lambda that returns a Boolean</param>
/// <param name="getExceptionMessage">A function to build the message included with the Exception</param>
public static void That(Func<bool> condition, Func<string> getExceptionMessage)
{
Assert.That(condition.Invoke(), Is.True, getExceptionMessage);
}
#endif
#endregion
#region ActualValueDelegate
/// <summary>
/// Apply a constraint to an actual value, succeeding if the constraint
/// is satisfied and throwing an assertion exception on failure.
/// </summary>
/// <typeparam name="TActual">The Type being compared.</typeparam>
/// <param name="del">An ActualValueDelegate returning the value to be tested</param>
/// <param name="expr">A Constraint expression to be applied</param>
public static void That<TActual>(ActualValueDelegate<TActual> del, IResolveConstraint expr)
{
Assert.That(del, expr.Resolve(), null, null);
}
/// <summary>
/// Apply a constraint to an actual value, succeeding if the constraint
/// is satisfied and throwing an assertion exception on failure.
/// </summary>
/// <typeparam name="TActual">The Type being compared.</typeparam>
/// <param name="del">An ActualValueDelegate returning the value to be tested</param>
/// <param name="expr">A Constraint expression to be applied</param>
/// <param name="message">The message that will be displayed on failure</param>
/// <param name="args">Arguments to be used in formatting the message</param>
public static void That<TActual>(ActualValueDelegate<TActual> del, IResolveConstraint expr, string message, params object[] args)
{
var constraint = expr.Resolve();
IncrementAssertCount();
var result = constraint.ApplyTo(del);
if (!result.IsSuccess)
ReportFailure(result, message, args);
}
#if !NET_2_0
/// <summary>
/// Apply a constraint to an actual value, succeeding if the constraint
/// is satisfied and throwing an assertion exception on failure.
/// </summary>
/// <typeparam name="TActual">The Type being compared.</typeparam>
/// <param name="del">An ActualValueDelegate returning the value to be tested</param>
/// <param name="expr">A Constraint expression to be applied</param>
/// <param name="getExceptionMessage">A function to build the message included with the Exception</param>
public static void That<TActual>(
ActualValueDelegate<TActual> del,
IResolveConstraint expr,
Func<string> getExceptionMessage)
{
var constraint = expr.Resolve();
IncrementAssertCount();
var result = constraint.ApplyTo(del);
if (!result.IsSuccess)
ReportFailure(result, getExceptionMessage());
}
#endif
#endregion
#region TestDelegate
/// <summary>
/// Asserts that the code represented by a delegate throws an exception
/// that satisfies the constraint provided.
/// </summary>
/// <param name="code">A TestDelegate to be executed</param>
/// <param name="constraint">A ThrowsConstraint used in the test</param>
public static void That(TestDelegate code, IResolveConstraint constraint)
{
Assert.That(code, constraint, null, null);
}
/// <summary>
/// Asserts that the code represented by a delegate throws an exception
/// that satisfies the constraint provided.
/// </summary>
/// <param name="code">A TestDelegate to be executed</param>
/// <param name="constraint">A ThrowsConstraint used in the test</param>
/// <param name="message">The message that will be displayed on failure</param>
/// <param name="args">Arguments to be used in formatting the message</param>
public static void That(TestDelegate code, IResolveConstraint constraint, string message, params object[] args)
{
Assert.That((object)code, constraint, message, args);
}
#if !NET_2_0
/// <summary>
/// Asserts that the code represented by a delegate throws an exception
/// that satisfies the constraint provided.
/// </summary>
/// <param name="code">A TestDelegate to be executed</param>
/// <param name="constraint">A ThrowsConstraint used in the test</param>
/// <param name="getExceptionMessage">A function to build the message included with the Exception</param>
public static void That(TestDelegate code, IResolveConstraint constraint, Func<string> getExceptionMessage)
{
Assert.That((object)code, constraint, getExceptionMessage);
}
#endif
#endregion
#endregion
#region Assert.That<TActual>
/// <summary>
/// Apply a constraint to an actual value, succeeding if the constraint
/// is satisfied and throwing an assertion exception on failure.
/// </summary>
/// <typeparam name="TActual">The Type being compared.</typeparam>
/// <param name="actual">The actual value to test</param>
/// <param name="expression">A Constraint to be applied</param>
public static void That<TActual>(TActual actual, IResolveConstraint expression)
{
Assert.That(actual, expression, null, null);
}
/// <summary>
/// Apply a constraint to an actual value, succeeding if the constraint
/// is satisfied and throwing an assertion exception on failure.
/// </summary>
/// <typeparam name="TActual">The Type being compared.</typeparam>
/// <param name="actual">The actual value to test</param>
/// <param name="expression">A Constraint expression to be applied</param>
/// <param name="message">The message that will be displayed on failure</param>
/// <param name="args">Arguments to be used in formatting the message</param>
public static void That<TActual>(TActual actual, IResolveConstraint expression, string message, params object[] args)
{
var constraint = expression.Resolve();
IncrementAssertCount();
var result = constraint.ApplyTo(actual);
if (!result.IsSuccess)
ReportFailure(result, message, args);
}
#if !NET_2_0
/// <summary>
/// Apply a constraint to an actual value, succeeding if the constraint
/// is satisfied and throwing an assertion exception on failure.
/// </summary>
/// <typeparam name="TActual">The Type being compared.</typeparam>
/// <param name="actual">The actual value to test</param>
/// <param name="expression">A Constraint expression to be applied</param>
/// <param name="getExceptionMessage">A function to build the message included with the Exception</param>
public static void That<TActual>(
TActual actual,
IResolveConstraint expression,
Func<string> getExceptionMessage)
{
var constraint = expression.Resolve();
IncrementAssertCount();
var result = constraint.ApplyTo(actual);
if (!result.IsSuccess)
ReportFailure(result, getExceptionMessage());
}
#endif
#endregion
#region Assert.ByVal
/// <summary>
/// Apply a constraint to an actual value, succeeding if the constraint
/// is satisfied and throwing an assertion exception on failure.
/// Used as a synonym for That in rare cases where a private setter
/// causes a Visual Basic compilation error.
/// </summary>
/// <param name="actual">The actual value to test</param>
/// <param name="expression">A Constraint to be applied</param>
public static void ByVal(object actual, IResolveConstraint expression)
{
Assert.That(actual, expression, null, null);
}
/// <summary>
/// Apply a constraint to an actual value, succeeding if the constraint
/// is satisfied and throwing an assertion exception on failure.
/// Used as a synonym for That in rare cases where a private setter
/// causes a Visual Basic compilation error.
/// </summary>
/// <remarks>
/// This method is provided for use by VB developers needing to test
/// the value of properties with private setters.
/// </remarks>
/// <param name="actual">The actual value to test</param>
/// <param name="expression">A Constraint expression to be applied</param>
/// <param name="message">The message that will be displayed on failure</param>
/// <param name="args">Arguments to be used in formatting the message</param>
public static void ByVal(object actual, IResolveConstraint expression, string message, params object[] args)
{
Assert.That(actual, expression, message, args);
}
#endregion
}
}
| |
#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
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
#if !(NET35 || NET20 || PORTABLE40)
using System.Dynamic;
#endif
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Security;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Utilities;
using System.Runtime.Serialization;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace Newtonsoft.Json.Serialization
{
internal class JsonSerializerInternalWriter : JsonSerializerInternalBase
{
private JsonContract _rootContract;
private int _rootLevel;
private readonly List<object> _serializeStack = new List<object>();
public JsonSerializerInternalWriter(JsonSerializer serializer)
: base(serializer)
{
}
public void Serialize(JsonWriter jsonWriter, object value, Type objectType)
{
if (jsonWriter == null)
throw new ArgumentNullException("jsonWriter");
_rootContract = (objectType != null) ? Serializer._contractResolver.ResolveContract(objectType) : null;
_rootLevel = _serializeStack.Count + 1;
JsonContract contract = GetContractSafe(value);
try
{
if (ShouldWriteReference(value, null, contract, null, null))
{
WriteReference(jsonWriter, value);
}
else
{
SerializeValue(jsonWriter, value, contract, null, null, null);
}
}
catch (Exception ex)
{
if (IsErrorHandled(null, contract, null, null, jsonWriter.Path, ex))
{
HandleError(jsonWriter, 0);
}
else
{
// clear context in case serializer is being used inside a converter
// if the converter wraps the error then not clearing the context will cause this error:
// "Current error context error is different to requested error."
ClearErrorContext();
throw;
}
}
finally
{
// clear root contract to ensure that if level was > 1 then it won't
// accidently be used for non root values
_rootContract = null;
}
}
private JsonSerializerProxy GetInternalSerializer()
{
if (InternalSerializer == null)
InternalSerializer = new JsonSerializerProxy(this);
return InternalSerializer;
}
private JsonContract GetContractSafe(object value)
{
if (value == null)
return null;
return Serializer._contractResolver.ResolveContract(value.GetType());
}
private void SerializePrimitive(JsonWriter writer, object value, JsonPrimitiveContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
{
if (contract.TypeCode == PrimitiveTypeCode.Bytes)
{
// if type name handling is enabled then wrap the base64 byte string in an object with the type name
bool includeTypeDetails = ShouldWriteType(TypeNameHandling.Objects, contract, member, containerContract, containerProperty);
if (includeTypeDetails)
{
writer.WriteStartObject();
WriteTypeProperty(writer, contract.CreatedType);
writer.WritePropertyName(JsonTypeReflector.ValuePropertyName, false);
JsonWriter.WriteValue(writer, contract.TypeCode, value);
writer.WriteEndObject();
return;
}
}
JsonWriter.WriteValue(writer, contract.TypeCode, value);
}
private void SerializeValue(JsonWriter writer, object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
{
if (value == null)
{
writer.WriteNull();
return;
}
JsonConverter converter =
((member != null) ? member.Converter : null) ??
((containerProperty != null) ? containerProperty.ItemConverter : null) ??
((containerContract != null) ? containerContract.ItemConverter : null) ??
valueContract.Converter ??
Serializer.GetMatchingConverter(valueContract.UnderlyingType) ??
valueContract.InternalConverter;
if (converter != null && converter.CanWrite)
{
SerializeConvertable(writer, converter, value, valueContract, containerContract, containerProperty);
return;
}
switch (valueContract.ContractType)
{
case JsonContractType.Object:
SerializeObject(writer, value, (JsonObjectContract)valueContract, member, containerContract, containerProperty);
break;
case JsonContractType.Array:
JsonArrayContract arrayContract = (JsonArrayContract)valueContract;
if (!arrayContract.IsMultidimensionalArray)
SerializeList(writer, (IEnumerable)value, arrayContract, member, containerContract, containerProperty);
else
SerializeMultidimensionalArray(writer, (Array)value, arrayContract, member, containerContract, containerProperty);
break;
case JsonContractType.Primitive:
SerializePrimitive(writer, value, (JsonPrimitiveContract)valueContract, member, containerContract, containerProperty);
break;
case JsonContractType.String:
SerializeString(writer, value, (JsonStringContract)valueContract);
break;
case JsonContractType.Dictionary:
JsonDictionaryContract dictionaryContract = (JsonDictionaryContract)valueContract;
SerializeDictionary(writer, (value is IDictionary) ? (IDictionary)value : dictionaryContract.CreateWrapper(value), dictionaryContract, member, containerContract, containerProperty);
break;
#if !(NET35 || NET20 || PORTABLE40)
case JsonContractType.Dynamic:
SerializeDynamic(writer, (IDynamicMetaObjectProvider)value, (JsonDynamicContract)valueContract, member, containerContract, containerProperty);
break;
#endif
#if !(DOTNET || PORTABLE40 || PORTABLE)
case JsonContractType.Serializable:
SerializeISerializable(writer, (ISerializable)value, (JsonISerializableContract)valueContract, member, containerContract, containerProperty);
break;
#endif
case JsonContractType.Linq:
((JToken)value).WriteTo(writer, Serializer.Converters.ToArray());
break;
}
}
private bool? ResolveIsReference(JsonContract contract, JsonProperty property, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
bool? isReference = null;
// value could be coming from a dictionary or array and not have a property
if (property != null)
isReference = property.IsReference;
if (isReference == null && containerProperty != null)
isReference = containerProperty.ItemIsReference;
if (isReference == null && collectionContract != null)
isReference = collectionContract.ItemIsReference;
if (isReference == null)
isReference = contract.IsReference;
return isReference;
}
private bool ShouldWriteReference(object value, JsonProperty property, JsonContract valueContract, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
if (value == null)
return false;
if (valueContract.ContractType == JsonContractType.Primitive || valueContract.ContractType == JsonContractType.String)
return false;
bool? isReference = ResolveIsReference(valueContract, property, collectionContract, containerProperty);
if (isReference == null)
{
if (valueContract.ContractType == JsonContractType.Array)
isReference = HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Arrays);
else
isReference = HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Objects);
}
if (!isReference.Value)
return false;
return Serializer.GetReferenceResolver().IsReferenced(this, value);
}
private bool ShouldWriteProperty(object memberValue, JsonProperty property)
{
if (property.NullValueHandling.GetValueOrDefault(Serializer._nullValueHandling) == NullValueHandling.Ignore &&
memberValue == null)
return false;
if (HasFlag(property.DefaultValueHandling.GetValueOrDefault(Serializer._defaultValueHandling), DefaultValueHandling.Ignore)
&& MiscellaneousUtils.ValueEquals(memberValue, property.GetResolvedDefaultValue()))
return false;
return true;
}
private bool CheckForCircularReference(JsonWriter writer, object value, JsonProperty property, JsonContract contract, JsonContainerContract containerContract, JsonProperty containerProperty)
{
if (value == null || contract.ContractType == JsonContractType.Primitive || contract.ContractType == JsonContractType.String)
return true;
ReferenceLoopHandling? referenceLoopHandling = null;
if (property != null)
referenceLoopHandling = property.ReferenceLoopHandling;
if (referenceLoopHandling == null && containerProperty != null)
referenceLoopHandling = containerProperty.ItemReferenceLoopHandling;
if (referenceLoopHandling == null && containerContract != null)
referenceLoopHandling = containerContract.ItemReferenceLoopHandling;
bool exists = (Serializer._equalityComparer != null)
? _serializeStack.Contains(value, Serializer._equalityComparer)
: _serializeStack.Contains(value);
if (exists)
{
string message = "Self referencing loop detected";
if (property != null)
message += " for property '{0}'".FormatWith(CultureInfo.InvariantCulture, property.PropertyName);
message += " with type '{0}'.".FormatWith(CultureInfo.InvariantCulture, value.GetType());
switch (referenceLoopHandling.GetValueOrDefault(Serializer._referenceLoopHandling))
{
case ReferenceLoopHandling.Error:
throw JsonSerializationException.Create(null, writer.ContainerPath, message, null);
case ReferenceLoopHandling.Ignore:
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, message + ". Skipping serializing self referenced value."), null);
return false;
case ReferenceLoopHandling.Serialize:
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, message + ". Serializing self referenced value."), null);
return true;
}
}
return true;
}
private void WriteReference(JsonWriter writer, object value)
{
string reference = GetReference(writer, value);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Writing object reference to Id '{0}' for {1}.".FormatWith(CultureInfo.InvariantCulture, reference, value.GetType())), null);
writer.WriteStartObject();
writer.WritePropertyName(JsonTypeReflector.RefPropertyName, false);
writer.WriteValue(reference);
writer.WriteEndObject();
}
private string GetReference(JsonWriter writer, object value)
{
try
{
string reference = Serializer.GetReferenceResolver().GetReference(this, value);
return reference;
}
catch (Exception ex)
{
throw JsonSerializationException.Create(null, writer.ContainerPath, "Error writing object reference for '{0}'.".FormatWith(CultureInfo.InvariantCulture, value.GetType()), ex);
}
}
internal static bool TryConvertToString(object value, Type type, out string s)
{
#if !(DOTNET || PORTABLE40 || PORTABLE)
TypeConverter converter = ConvertUtils.GetConverter(type);
// use the objectType's TypeConverter if it has one and can convert to a string
if (converter != null
&& !(converter is ComponentConverter)
&& converter.GetType() != typeof(TypeConverter))
{
if (converter.CanConvertTo(typeof(string)))
{
s = converter.ConvertToInvariantString(value);
return true;
}
}
#endif
#if (DOTNET || PORTABLE)
if (value is Guid || value is Uri || value is TimeSpan)
{
s = value.ToString();
return true;
}
#endif
if (value is Type)
{
s = ((Type)value).AssemblyQualifiedName;
return true;
}
s = null;
return false;
}
private void SerializeString(JsonWriter writer, object value, JsonStringContract contract)
{
OnSerializing(writer, contract, value);
string s;
TryConvertToString(value, contract.UnderlyingType, out s);
writer.WriteValue(s);
OnSerialized(writer, contract, value);
}
private void OnSerializing(JsonWriter writer, JsonContract contract, object value)
{
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Started serializing {0}".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)), null);
contract.InvokeOnSerializing(value, Serializer._context);
}
private void OnSerialized(JsonWriter writer, JsonContract contract, object value)
{
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Finished serializing {0}".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)), null);
contract.InvokeOnSerialized(value, Serializer._context);
}
private void SerializeObject(JsonWriter writer, object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
OnSerializing(writer, contract, value);
_serializeStack.Add(value);
WriteObjectStart(writer, value, contract, member, collectionContract, containerProperty);
int initialDepth = writer.Top;
for (int index = 0; index < contract.Properties.Count; index++)
{
JsonProperty property = contract.Properties[index];
try
{
object memberValue;
JsonContract memberContract;
if (!CalculatePropertyValues(writer, value, contract, member, property, out memberContract, out memberValue))
continue;
property.WritePropertyName(writer);
SerializeValue(writer, memberValue, memberContract, property, contract, member);
}
catch (Exception ex)
{
if (IsErrorHandled(value, contract, property.PropertyName, null, writer.ContainerPath, ex))
HandleError(writer, initialDepth);
else
throw;
}
}
if (contract.ExtensionDataGetter != null)
{
IEnumerable<KeyValuePair<object, object>> extensionData = contract.ExtensionDataGetter(value);
if (extensionData != null)
{
foreach (KeyValuePair<object, object> e in extensionData)
{
JsonContract keyContract = GetContractSafe(e.Key);
JsonContract valueContract = GetContractSafe(e.Value);
bool escape;
string propertyName = GetPropertyName(writer, e.Key, keyContract, out escape);
if (ShouldWriteReference(e.Value, null, valueContract, contract, member))
{
writer.WritePropertyName(propertyName);
WriteReference(writer, e.Value);
}
else
{
if (!CheckForCircularReference(writer, e.Value, null, valueContract, contract, member))
continue;
writer.WritePropertyName(propertyName);
SerializeValue(writer, e.Value, valueContract, null, contract, member);
}
}
}
}
writer.WriteEndObject();
_serializeStack.RemoveAt(_serializeStack.Count - 1);
OnSerialized(writer, contract, value);
}
private bool CalculatePropertyValues(JsonWriter writer, object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, out JsonContract memberContract, out object memberValue)
{
if (!property.Ignored && property.Readable && ShouldSerialize(writer, property, value) && IsSpecified(writer, property, value))
{
if (property.PropertyContract == null)
property.PropertyContract = Serializer._contractResolver.ResolveContract(property.PropertyType);
memberValue = property.ValueProvider.GetValue(value);
memberContract = (property.PropertyContract.IsSealed) ? property.PropertyContract : GetContractSafe(memberValue);
if (ShouldWriteProperty(memberValue, property))
{
if (ShouldWriteReference(memberValue, property, memberContract, contract, member))
{
property.WritePropertyName(writer);
WriteReference(writer, memberValue);
return false;
}
if (!CheckForCircularReference(writer, memberValue, property, memberContract, contract, member))
return false;
if (memberValue == null)
{
JsonObjectContract objectContract = contract as JsonObjectContract;
Required resolvedRequired = property._required ?? ((objectContract != null) ? objectContract.ItemRequired : null) ?? Required.Default;
if (resolvedRequired == Required.Always)
throw JsonSerializationException.Create(null, writer.ContainerPath, "Cannot write a null value for property '{0}'. Property requires a value.".FormatWith(CultureInfo.InvariantCulture, property.PropertyName), null);
}
return true;
}
}
memberContract = null;
memberValue = null;
return false;
}
private void WriteObjectStart(JsonWriter writer, object value, JsonContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
writer.WriteStartObject();
bool isReference = ResolveIsReference(contract, member, collectionContract, containerProperty) ?? HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Objects);
// don't make readonly fields the referenced value because they can't be deserialized to
if (isReference && (member == null || member.Writable))
{
WriteReferenceIdProperty(writer, contract.UnderlyingType, value);
}
if (ShouldWriteType(TypeNameHandling.Objects, contract, member, collectionContract, containerProperty))
{
WriteTypeProperty(writer, contract.UnderlyingType);
}
}
private void WriteReferenceIdProperty(JsonWriter writer, Type type, object value)
{
string reference = GetReference(writer, value);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "Writing object reference Id '{0}' for {1}.".FormatWith(CultureInfo.InvariantCulture, reference, type)), null);
writer.WritePropertyName(JsonTypeReflector.IdPropertyName, false);
writer.WriteValue(reference);
}
private void WriteTypeProperty(JsonWriter writer, Type type)
{
string typeName = ReflectionUtils.GetTypeName(type, Serializer._typeNameAssemblyFormat, Serializer._binder);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "Writing type name '{0}' for {1}.".FormatWith(CultureInfo.InvariantCulture, typeName, type)), null);
writer.WritePropertyName(JsonTypeReflector.TypePropertyName, false);
writer.WriteValue(typeName);
}
private bool HasFlag(DefaultValueHandling value, DefaultValueHandling flag)
{
return ((value & flag) == flag);
}
private bool HasFlag(PreserveReferencesHandling value, PreserveReferencesHandling flag)
{
return ((value & flag) == flag);
}
private bool HasFlag(TypeNameHandling value, TypeNameHandling flag)
{
return ((value & flag) == flag);
}
private void SerializeConvertable(JsonWriter writer, JsonConverter converter, object value, JsonContract contract, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
if (ShouldWriteReference(value, null, contract, collectionContract, containerProperty))
{
WriteReference(writer, value);
}
else
{
if (!CheckForCircularReference(writer, value, null, contract, collectionContract, containerProperty))
return;
_serializeStack.Add(value);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Started serializing {0} with converter {1}.".FormatWith(CultureInfo.InvariantCulture, value.GetType(), converter.GetType())), null);
converter.WriteJson(writer, value, GetInternalSerializer());
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Finished serializing {0} with converter {1}.".FormatWith(CultureInfo.InvariantCulture, value.GetType(), converter.GetType())), null);
_serializeStack.RemoveAt(_serializeStack.Count - 1);
}
}
private void SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
IWrappedCollection wrappedCollection = values as IWrappedCollection;
object underlyingList = wrappedCollection != null ? wrappedCollection.UnderlyingCollection : values;
OnSerializing(writer, contract, underlyingList);
_serializeStack.Add(underlyingList);
bool hasWrittenMetadataObject = WriteStartArray(writer, underlyingList, contract, member, collectionContract, containerProperty);
writer.WriteStartArray();
int initialDepth = writer.Top;
int index = 0;
// note that an error in the IEnumerable won't be caught
foreach (object value in values)
{
try
{
JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value);
if (ShouldWriteReference(value, null, valueContract, contract, member))
{
WriteReference(writer, value);
}
else
{
if (CheckForCircularReference(writer, value, null, valueContract, contract, member))
{
SerializeValue(writer, value, valueContract, null, contract, member);
}
}
}
catch (Exception ex)
{
if (IsErrorHandled(underlyingList, contract, index, null, writer.ContainerPath, ex))
HandleError(writer, initialDepth);
else
throw;
}
finally
{
index++;
}
}
writer.WriteEndArray();
if (hasWrittenMetadataObject)
writer.WriteEndObject();
_serializeStack.RemoveAt(_serializeStack.Count - 1);
OnSerialized(writer, contract, underlyingList);
}
private void SerializeMultidimensionalArray(JsonWriter writer, Array values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
OnSerializing(writer, contract, values);
_serializeStack.Add(values);
bool hasWrittenMetadataObject = WriteStartArray(writer, values, contract, member, collectionContract, containerProperty);
SerializeMultidimensionalArray(writer, values, contract, member, writer.Top, new int[0]);
if (hasWrittenMetadataObject)
writer.WriteEndObject();
_serializeStack.RemoveAt(_serializeStack.Count - 1);
OnSerialized(writer, contract, values);
}
private void SerializeMultidimensionalArray(JsonWriter writer, Array values, JsonArrayContract contract, JsonProperty member, int initialDepth, int[] indices)
{
int dimension = indices.Length;
int[] newIndices = new int[dimension + 1];
for (int i = 0; i < dimension; i++)
{
newIndices[i] = indices[i];
}
writer.WriteStartArray();
for (int i = values.GetLowerBound(dimension); i <= values.GetUpperBound(dimension); i++)
{
newIndices[dimension] = i;
bool isTopLevel = (newIndices.Length == values.Rank);
if (isTopLevel)
{
object value = values.GetValue(newIndices);
try
{
JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value);
if (ShouldWriteReference(value, null, valueContract, contract, member))
{
WriteReference(writer, value);
}
else
{
if (CheckForCircularReference(writer, value, null, valueContract, contract, member))
{
SerializeValue(writer, value, valueContract, null, contract, member);
}
}
}
catch (Exception ex)
{
if (IsErrorHandled(values, contract, i, null, writer.ContainerPath, ex))
HandleError(writer, initialDepth + 1);
else
throw;
}
}
else
{
SerializeMultidimensionalArray(writer, values, contract, member, initialDepth + 1, newIndices);
}
}
writer.WriteEndArray();
}
private bool WriteStartArray(JsonWriter writer, object values, JsonArrayContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
{
bool isReference = ResolveIsReference(contract, member, containerContract, containerProperty) ?? HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Arrays);
// don't make readonly fields the referenced value because they can't be deserialized to
isReference = (isReference && (member == null || member.Writable));
bool includeTypeDetails = ShouldWriteType(TypeNameHandling.Arrays, contract, member, containerContract, containerProperty);
bool writeMetadataObject = isReference || includeTypeDetails;
if (writeMetadataObject)
{
writer.WriteStartObject();
if (isReference)
{
WriteReferenceIdProperty(writer, contract.UnderlyingType, values);
}
if (includeTypeDetails)
{
WriteTypeProperty(writer, values.GetType());
}
writer.WritePropertyName(JsonTypeReflector.ArrayValuesPropertyName, false);
}
if (contract.ItemContract == null)
contract.ItemContract = Serializer._contractResolver.ResolveContract(contract.CollectionItemType ?? typeof(object));
return writeMetadataObject;
}
#if !(DOTNET || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35)
[SecuritySafeCritical]
#endif
private void SerializeISerializable(JsonWriter writer, ISerializable value, JsonISerializableContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
if (!JsonTypeReflector.FullyTrusted)
{
string message = @"Type '{0}' implements ISerializable but cannot be serialized using the ISerializable interface because the current application is not fully trusted and ISerializable can expose secure data." + Environment.NewLine +
@"To fix this error either change the environment to be fully trusted, change the application to not deserialize the type, add JsonObjectAttribute to the type or change the JsonSerializer setting ContractResolver to use a new DefaultContractResolver with IgnoreSerializableInterface set to true." + Environment.NewLine;
message = message.FormatWith(CultureInfo.InvariantCulture, value.GetType());
throw JsonSerializationException.Create(null, writer.ContainerPath, message, null);
}
OnSerializing(writer, contract, value);
_serializeStack.Add(value);
WriteObjectStart(writer, value, contract, member, collectionContract, containerProperty);
SerializationInfo serializationInfo = new SerializationInfo(contract.UnderlyingType, new FormatterConverter());
value.GetObjectData(serializationInfo, Serializer._context);
foreach (SerializationEntry serializationEntry in serializationInfo)
{
JsonContract valueContract = GetContractSafe(serializationEntry.Value);
if (ShouldWriteReference(serializationEntry.Value, null, valueContract, contract, member))
{
writer.WritePropertyName(serializationEntry.Name);
WriteReference(writer, serializationEntry.Value);
}
else if (CheckForCircularReference(writer, serializationEntry.Value, null, valueContract, contract, member))
{
writer.WritePropertyName(serializationEntry.Name);
SerializeValue(writer, serializationEntry.Value, valueContract, null, contract, member);
}
}
writer.WriteEndObject();
_serializeStack.RemoveAt(_serializeStack.Count - 1);
OnSerialized(writer, contract, value);
}
#endif
#if !(NET35 || NET20 || PORTABLE40)
private void SerializeDynamic(JsonWriter writer, IDynamicMetaObjectProvider value, JsonDynamicContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
OnSerializing(writer, contract, value);
_serializeStack.Add(value);
WriteObjectStart(writer, value, contract, member, collectionContract, containerProperty);
int initialDepth = writer.Top;
for (int index = 0; index < contract.Properties.Count; index++)
{
JsonProperty property = contract.Properties[index];
// only write non-dynamic properties that have an explicit attribute
if (property.HasMemberAttribute)
{
try
{
object memberValue;
JsonContract memberContract;
if (!CalculatePropertyValues(writer, value, contract, member, property, out memberContract, out memberValue))
continue;
property.WritePropertyName(writer);
SerializeValue(writer, memberValue, memberContract, property, contract, member);
}
catch (Exception ex)
{
if (IsErrorHandled(value, contract, property.PropertyName, null, writer.ContainerPath, ex))
HandleError(writer, initialDepth);
else
throw;
}
}
}
foreach (string memberName in value.GetDynamicMemberNames())
{
object memberValue;
if (contract.TryGetMember(value, memberName, out memberValue))
{
try
{
JsonContract valueContract = GetContractSafe(memberValue);
if (!ShouldWriteDynamicProperty(memberValue))
continue;
if (CheckForCircularReference(writer, memberValue, null, valueContract, contract, member))
{
string resolvedPropertyName = (contract.PropertyNameResolver != null)
? contract.PropertyNameResolver(memberName)
: memberName;
writer.WritePropertyName(resolvedPropertyName);
SerializeValue(writer, memberValue, valueContract, null, contract, member);
}
}
catch (Exception ex)
{
if (IsErrorHandled(value, contract, memberName, null, writer.ContainerPath, ex))
HandleError(writer, initialDepth);
else
throw;
}
}
}
writer.WriteEndObject();
_serializeStack.RemoveAt(_serializeStack.Count - 1);
OnSerialized(writer, contract, value);
}
#endif
private bool ShouldWriteDynamicProperty(object memberValue)
{
if (Serializer._nullValueHandling == NullValueHandling.Ignore && memberValue == null)
return false;
if (HasFlag(Serializer._defaultValueHandling, DefaultValueHandling.Ignore) &&
(memberValue == null || MiscellaneousUtils.ValueEquals(memberValue, ReflectionUtils.GetDefaultValue(memberValue.GetType()))))
return false;
return true;
}
private bool ShouldWriteType(TypeNameHandling typeNameHandlingFlag, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
{
TypeNameHandling resolvedTypeNameHandling =
((member != null) ? member.TypeNameHandling : null)
?? ((containerProperty != null) ? containerProperty.ItemTypeNameHandling : null)
?? ((containerContract != null) ? containerContract.ItemTypeNameHandling : null)
?? Serializer._typeNameHandling;
if (HasFlag(resolvedTypeNameHandling, typeNameHandlingFlag))
return true;
// instance type and the property's type's contract default type are different (no need to put the type in JSON because the type will be created by default)
if (HasFlag(resolvedTypeNameHandling, TypeNameHandling.Auto))
{
if (member != null)
{
if (contract.UnderlyingType != member.PropertyContract.CreatedType)
return true;
}
else if (containerContract != null)
{
if (containerContract.ItemContract == null || contract.UnderlyingType != containerContract.ItemContract.CreatedType)
return true;
}
else if (_rootContract != null && _serializeStack.Count == _rootLevel)
{
if (contract.UnderlyingType != _rootContract.CreatedType)
return true;
}
}
return false;
}
private void SerializeDictionary(JsonWriter writer, IDictionary values, JsonDictionaryContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
IWrappedDictionary wrappedDictionary = values as IWrappedDictionary;
object underlyingDictionary = wrappedDictionary != null ? wrappedDictionary.UnderlyingDictionary : values;
OnSerializing(writer, contract, underlyingDictionary);
_serializeStack.Add(underlyingDictionary);
WriteObjectStart(writer, underlyingDictionary, contract, member, collectionContract, containerProperty);
if (contract.ItemContract == null)
contract.ItemContract = Serializer._contractResolver.ResolveContract(contract.DictionaryValueType ?? typeof(object));
if (contract.KeyContract == null)
contract.KeyContract = Serializer._contractResolver.ResolveContract(contract.DictionaryKeyType ?? typeof(object));
int initialDepth = writer.Top;
foreach (DictionaryEntry entry in values)
{
bool escape;
string propertyName = GetPropertyName(writer, entry.Key, contract.KeyContract, out escape);
propertyName = (contract.DictionaryKeyResolver != null)
? contract.DictionaryKeyResolver(propertyName)
: propertyName;
try
{
object value = entry.Value;
JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value);
if (ShouldWriteReference(value, null, valueContract, contract, member))
{
writer.WritePropertyName(propertyName, escape);
WriteReference(writer, value);
}
else
{
if (!CheckForCircularReference(writer, value, null, valueContract, contract, member))
continue;
writer.WritePropertyName(propertyName, escape);
SerializeValue(writer, value, valueContract, null, contract, member);
}
}
catch (Exception ex)
{
if (IsErrorHandled(underlyingDictionary, contract, propertyName, null, writer.ContainerPath, ex))
HandleError(writer, initialDepth);
else
throw;
}
}
writer.WriteEndObject();
_serializeStack.RemoveAt(_serializeStack.Count - 1);
OnSerialized(writer, contract, underlyingDictionary);
}
private string GetPropertyName(JsonWriter writer, object name, JsonContract contract, out bool escape)
{
string propertyName;
if (contract.ContractType == JsonContractType.Primitive)
{
JsonPrimitiveContract primitiveContract = (JsonPrimitiveContract)contract;
if (primitiveContract.TypeCode == PrimitiveTypeCode.DateTime || primitiveContract.TypeCode == PrimitiveTypeCode.DateTimeNullable)
{
escape = false;
StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
DateTimeUtils.WriteDateTimeString(sw, (DateTime)name, writer.DateFormatHandling, writer.DateFormatString, writer.Culture);
return sw.ToString();
}
#if !NET20
else if (primitiveContract.TypeCode == PrimitiveTypeCode.DateTimeOffset || primitiveContract.TypeCode == PrimitiveTypeCode.DateTimeOffsetNullable)
{
escape = false;
StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
DateTimeUtils.WriteDateTimeOffsetString(sw, (DateTimeOffset)name, writer.DateFormatHandling, writer.DateFormatString, writer.Culture);
return sw.ToString();
}
#endif
else
{
escape = true;
return Convert.ToString(name, CultureInfo.InvariantCulture);
}
}
else if (TryConvertToString(name, name.GetType(), out propertyName))
{
escape = true;
return propertyName;
}
else
{
escape = true;
return name.ToString();
}
}
private void HandleError(JsonWriter writer, int initialDepth)
{
ClearErrorContext();
if (writer.WriteState == WriteState.Property)
writer.WriteNull();
while (writer.Top > initialDepth)
{
writer.WriteEnd();
}
}
private bool ShouldSerialize(JsonWriter writer, JsonProperty property, object target)
{
if (property.ShouldSerialize == null)
return true;
bool shouldSerialize = property.ShouldSerialize(target);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "ShouldSerialize result for property '{0}' on {1}: {2}".FormatWith(CultureInfo.InvariantCulture, property.PropertyName, property.DeclaringType, shouldSerialize)), null);
return shouldSerialize;
}
private bool IsSpecified(JsonWriter writer, JsonProperty property, object target)
{
if (property.GetIsSpecified == null)
return true;
bool isSpecified = property.GetIsSpecified(target);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "IsSpecified result for property '{0}' on {1}: {2}".FormatWith(CultureInfo.InvariantCulture, property.PropertyName, property.DeclaringType, isSpecified)), null);
return isSpecified;
}
}
}
| |
using System;
using System.Globalization;
using System.Xml;
using System.Xml.XPath;
namespace umbraco.presentation.xslt.Exslt
{
/// <summary>
/// This class implements the EXSLT functions in the http://exslt.org/dates-and-times namespace.
/// </summary>
public class ExsltDatesAndTimes
{
/// <summary>
/// Implements the following function
/// string date:date-time()
/// </summary>
/// <returns>The current time</returns>
public static string datetime(){
return DateTime.Now.ToString("s");
}
/// <summary>
/// Implements the following function
/// string date:date-time()
/// </summary>
/// <returns>The current date and time or the empty string if the
/// date is invalid </returns>
public static string datetime(string d){
try{
return DateTime.Parse(d).ToString("s");
}catch(FormatException){
return "";
}
}
/// <summary>
/// Implements the following function
/// string date:date()
/// </summary>
/// <returns>The current date</returns>
public static string date(){
string date = DateTime.Now.ToString("s");
string[] dateNtime = date.Split(new Char[]{'T'});
return dateNtime[0];
}
/// <summary>
/// Implements the following function
/// string date:date(string)
/// </summary>
/// <returns>The date part of the specified date or the empty string if the
/// date is invalid</returns>
public static string date(string d){
try{
string[] dateNtime = DateTime.Parse(d).ToString("s").Split(new Char[]{'T'});
return dateNtime[0];
}catch(FormatException){
return "";
}
}
/// <summary>
/// Implements the following function
/// string date:time()
/// </summary>
/// <returns>The current time</returns>
public static string time(){
string date = DateTime.Now.ToString("s");
string[] dateNtime = date.Split(new Char[]{'T'});
return dateNtime[1];
}
/// <summary>
/// Implements the following function
/// string date:time(string)
/// </summary>
/// <returns>The time part of the specified date or the empty string if the
/// date is invalid</returns>
public static string time(string d){
try{
string[] dateNtime = DateTime.Parse(d).ToString("s").Split(new Char[]{'T'});
return dateNtime[1];
}catch(FormatException){
return "";
}
}
/// <summary>
/// Implements the following function
/// number date:year()
/// </summary>
/// <returns>The current year</returns>
public static double year(){
return DateTime.Now.Year;
}
/// <summary>
/// Implements the following function
/// number date:year(string)
/// </summary>
/// <returns>The year part of the specified date or the empty string if the
/// date is invalid</returns>
/// <remarks>Does not support dates in the format of the xs:yearMonth or
/// xs:gYear types</remarks>
public static double year(string d){
try{
DateTime date = DateTime.Parse(d);
return date.Year;
}catch(FormatException){
return System.Double.NaN;
}
}
/// <summary>
/// Helper method for calculating whether a year is a leap year. Algorithm
/// obtained from http://mindprod.com/jglossleapyear.html
/// </summary>
private static bool IsLeapYear ( int year) {
return CultureInfo.CurrentCulture.Calendar.IsLeapYear(year);
}
/// <summary>
/// Implements the following function
/// boolean date:leap-year()
/// </summary>
/// <returns>True if the current year is a leap year</returns>
public static bool leapyear(){
return IsLeapYear(DateTime.Now.Year);
}
/// <summary>
/// Implements the following function
/// boolean date:leap-year(string)
/// </summary>
/// <returns>True if the specified year is a leap year</returns>
/// <remarks>Does not support dates in the format of the xs:yearMonth or
/// xs:gYear types</remarks>
public static bool leapyear(string d){
try{
DateTime date = DateTime.Parse(d);
return IsLeapYear(date.Year);
}catch(FormatException){
return false;
}
}
/// <summary>
/// Implements the following function
/// number date:month-in-year()
/// </summary>
/// <returns>The current month</returns>
public static double monthinyear(){
return DateTime.Now.Month;
}
/// <summary>
/// Implements the following function
/// number date:month-in-year(string)
/// </summary>
/// <returns>The month part of the specified date or the empty string if the
/// date is invalid</returns>
/// <remarks>Does not support dates in the format of the xs:yearMonth or
/// xs:gYear types</remarks>
public static double monthinyear(string d){
try{
DateTime date = DateTime.Parse(d);
return date.Month;
}catch(FormatException){
return System.Double.NaN;
}
}
/// <summary>
/// Helper method uses local culture information.
/// </summary>
/// <param name="d"></param>
/// <returns></returns>
private static double weekinyear(DateTime d){
Calendar calendar = CultureInfo.CurrentCulture.Calendar;
return calendar.GetWeekOfYear(d,CultureInfo.CurrentCulture.DateTimeFormat.CalendarWeekRule,
CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek);
}
/// <summary>
/// Implements the following function
/// number date:week-in-year()
/// </summary>
/// <returns>The current week. This method uses the Calendar.GetWeekOfYear() method
/// with the CalendarWeekRule and FirstDayOfWeek of the current culture.
/// THE RESULTS OF CALLING THIS FUNCTION VARIES ACROSS CULTURES</returns>
public static double weekinyear(){
return weekinyear(DateTime.Now);
}
/// <summary>
/// Implements the following function
/// number date:week-in-year(string)
/// </summary>
/// <returns>The week part of the specified date or the empty string if the
/// date is invalid</returns>
/// <remarks>Does not support dates in the format of the xs:yearMonth or
/// xs:gYear types. This method uses the Calendar.GetWeekOfYear() method
/// with the CalendarWeekRule and FirstDayOfWeek of the current culture.
/// THE RESULTS OF CALLING THIS FUNCTION VARIES ACROSS CULTURES</remarks>
public static double weekinyear(string d){
try{
DateTime date = DateTime.Parse(d);
return weekinyear(date);
}catch(FormatException){
return System.Double.NaN;
}
}
/// <summary>
/// Implements the following function
/// number date:day-in-year()
/// </summary>
/// <returns>The current day. </returns>
public static double dayinyear(){
return DateTime.Now.DayOfYear;
}
/// <summary>
/// Implements the following function
/// number date:day-in-year(string)
/// </summary>
/// <returns>The day part of the specified date or the empty string if the
/// date is invalid</returns>
public static double dayinyear(string d){
try{
DateTime date = DateTime.Parse(d);
return date.DayOfYear;
}catch(FormatException){
return System.Double.NaN;
}
}
/// <summary>
/// Implements the following function
/// number date:day-in-week()
/// </summary>
/// <returns>The current day in the week. 1=Sunday, 2=Monday,...,7=Saturday</returns>
public static double dayinweek(){
return ((int) DateTime.Now.DayOfWeek) + 1;
}
/// <summary>
/// Implements the following function
/// number date:day-in-week(string)
/// </summary>
/// <returns>The day in the week of the specified date or the empty string if the
/// date is invalid. <returns>The current day in the week. 1=Sunday, 2=Monday,...,7=Saturday
/// </returns>
public static double dayinweek(string d){
try{
DateTime date = DateTime.Parse(d);
return ((int)date.DayOfWeek) + 1;
}catch(FormatException){
return System.Double.NaN;
}
}
/// <summary>
/// Implements the following function
/// number date:day-in-month()
/// </summary>
/// <returns>The current day. </returns>
public static double dayinmonth(){
return DateTime.Now.Day;
}
/// <summary>
/// Implements the following function
/// number date:day-in-month(string)
/// </summary>
/// <returns>The day part of the specified date or the empty string if the
/// date is invalid</returns>
/// <remarks>Does not support dates in the format of the xs:MonthDay or
/// xs:gDay types</remarks>
public static double dayinmonth(string d){
try{
DateTime date = DateTime.Parse(d);
return date.Day;
}catch(FormatException){
return System.Double.NaN;
}
}
/// <summary>
/// Helper method.
/// </summary>
/// <param name="day"></param>
/// <returns></returns>
private static double dayofweekinmonth(int day){
int toReturn = 0;
do{
toReturn++;
day-= 7;
}while(day > 0);
return toReturn;
}
/// <summary>
/// Implements the following function
/// number date:day-of-week-in-month()
/// </summary>
/// <returns>The current day of week in the month as a number. For instance
/// the third Tuesday of the month returns 3</returns>
public static double dayofweekinmonth(){
return dayofweekinmonth(DateTime.Now.Day);
}
/// <summary>
/// Implements the following function
/// number date:day-of-week-in-month(string)
/// </summary>
/// <returns>The day part of the specified date or the empty string if the
/// date is invalid</returns>
public static double dayofweekinmonth(string d){
try{
DateTime date = DateTime.Parse(d);
return dayofweekinmonth(date.Day);
}catch(FormatException){
return System.Double.NaN;
}
}
/// <summary>
/// Implements the following function
/// number date:hour-in-day()
/// </summary>
/// <returns>The current hour of the day as a number.</returns>
public static double hourinday(){
return DateTime.Now.Hour;
}
/// <summary>
/// Implements the following function
/// number date:hour-in-day(string)
/// </summary>
/// <returns>The current hour of the specified time or the empty string if the
/// date is invalid</returns>
public static double hourinday(string d){
try{
DateTime date = DateTime.Parse(d);
return date.Hour;
}catch(FormatException){
return System.Double.NaN;
}
}
/// <summary>
/// Implements the following function
/// number date:minute-in-hour()
/// </summary>
/// <returns>The minute of the current hour as a number. </returns>
public static double minuteinhour(){
return DateTime.Now.Minute;
}
/// <summary>
/// Implements the following function
/// number date:minute-in-hour(string)
/// </summary>
/// <returns>The minute of the hour of the specified time or the empty string if the
/// date is invalid</returns>
public static double minuteinhour(string d){
try{
DateTime date = DateTime.Parse(d);
return date.Minute;
}catch(FormatException){
return System.Double.NaN;
}
}
/// <summary>
/// Implements the following function
/// number date:second-in-minute()
/// </summary>
/// <returns>The seconds of the current minute as a number. </returns>
public static double secondinminute(){
return DateTime.Now.Second;
}
/// <summary>
/// Implements the following function
/// number date:second-in-minute(string)
/// </summary>
/// <returns>The seconds of the minute of the specified time or the empty string if the
/// date is invalid</returns>
public static double secondinminute(string d){
try{
DateTime date = DateTime.Parse(d);
return date.Second;
}catch(FormatException){
return System.Double.NaN;
}
}
/// <summary>
/// Implements the following function
/// string date:day-name()
/// </summary>
/// <returns>The name of the current day</returns>
public static string dayname(){
return DateTime.Now.DayOfWeek.ToString();
}
/// <summary>
/// Implements the following function
/// string date:day-name(string)
/// </summary>
/// <returns>The name of the day of the specified date or the empty string if the
/// date is invalid</returns>
public static string dayname(string d){
try{
DateTime date = DateTime.Parse(d);
return date.DayOfWeek.ToString();
}catch(FormatException){
return "";
}
}
/// <summary>
/// Implements the following function
/// string date:day-abbreviation()
/// </summary>
/// <returns>The abbreviated name of the current day</returns>
public static string dayabbreviation(){
return DateTime.Now.DayOfWeek.ToString().Substring(0,3);
}
/// <summary>
/// Implements the following function
/// string date:day-abbreviation(string)
/// </summary>
/// <returns>The abbreviated name of the day of the specified date or the empty string if the
/// date is invalid</returns>
public static string dayabbreviation(string d){
try{
DateTime date = DateTime.Parse(d);
return date.DayOfWeek.ToString().Substring(0,3);
}catch(FormatException){
return "";
}
}
/// <summary>
/// Implements the following function
/// string date:month-name()
/// </summary>
/// <returns>The name of the current month</returns>
public static string monthname(){
string month = DateTime.Now.ToString("MMMM");
string[] splitmonth = month.Split(new Char[]{' '});
return splitmonth[0];
}
/// <summary>
/// Implements the following function
/// string date:month-name(string)
/// </summary>
/// <returns>The name of the month of the specified date or the empty string if the
/// date is invalid</returns>
/// <remarks>Does not support dates in the format of the xs:yearMonth or
/// xs:gYear types</remarks>
public static string monthname(string d){
try{
DateTime date = DateTime.Parse(d);
string month = date.ToString("MMMM");
string[] splitmonth = month.Split(new Char[]{' '});
return splitmonth[0];
}catch(FormatException){
return "";
}
}
/// <summary>
/// Implements the following function
/// string date:month-abbreviation()
/// </summary>
/// <returns>The abbreviated name of the current month</returns>
public static string monthabbreviation(){
string month = DateTime.Now.ToString("MMM");
string[] splitmonth = month.Split(new Char[]{' '});
return splitmonth[0].Substring(0,3);
}
/// <summary>
/// Implements the following function
/// string date:month-abbreviation(string)
/// </summary>
/// <returns>The abbreviated name of the month of the specified date or the empty string if the
/// date is invalid</returns>
/// <remarks>Does not support dates in the format of the xs:yearMonth or
/// xs:gYear types</remarks>
public static string monthabbreviation(string d){
try{
DateTime date = DateTime.Parse(d);
string month = date.ToString("MMM");
string[] splitmonth = month.Split(new Char[]{' '});
return splitmonth[0].Substring(0, 3);;
}catch(FormatException){
return "";
}
}
/// <summary>
/// Implements the following function
/// string date:format-date(string, string)
/// </summary>
/// <param name="date">The date to format</param>
/// <param name="format">One of the format strings understood by the
/// DateTime.ToString(string) method.</param>
/// <returns>The formated date</returns>
public static string formatdate(string d, string format){
try{
DateTime date = DateTime.Parse(d);
return date.ToString(format);
}catch(FormatException){
return "";
}
}
/// <summary>
/// Implements the following function
/// string date:parse-date(string, string)
/// </summary>
/// <param name="date">The date to parse</param>
/// <param name="format">One of the format strings understood by the
/// DateTime.ToString(string) method.</param>
/// <returns>The parsed date</returns>
public static string parsedate(string d, string format){
try{
DateTime date = DateTime.ParseExact(d, format, CultureInfo.CurrentCulture);
return XmlConvert.ToString(date, XmlDateTimeSerializationMode.Unspecified);
}catch(FormatException){
return "";
}
}
/// <summary>
/// Implements the following function
/// string:date:difference(string, string)
/// </summary>
/// <param name="start">The start date</param>
/// <param name="end">The end date</param>
/// <returns>A positive difference if start is before end otherwise a negative
/// difference. The difference is in the format [-][d.]hh:mm:ss[.ff]</returns>
public static string difference(string start, string end){
try{
DateTime startdate = DateTime.Parse(start);
DateTime enddate = DateTime.Parse(end);
return XmlConvert.ToString(enddate.Subtract(startdate));
}catch(FormatException){
return "";
}
}
/// <summary>
/// Implements the following function
/// string:date:add(string, string)
/// </summary>
/// <param name="datetime">A date/time</param>
/// <param name="duration">the duration to add</param>
/// <returns>The new time</returns>
public static string add(string datetime, string duration){
try{
DateTime date = DateTime.Parse(datetime);
TimeSpan timespan = System.Xml.XmlConvert.ToTimeSpan(duration);
return XmlConvert.ToString(date.Add(timespan), XmlDateTimeSerializationMode.Unspecified);
}catch(FormatException){
return "";
}
}
/// <summary>
/// Implements the following function
/// string:date:add-duration(string, string)
/// </summary>
/// <param name="datetime">A date/time</param>
/// <param name="duration">the duration to add</param>
/// <returns>The new time</returns>
public static string addduration(string duration1, string duration2){
try{
TimeSpan timespan1 = XmlConvert.ToTimeSpan(duration1);
TimeSpan timespan2 = XmlConvert.ToTimeSpan(duration2);
return XmlConvert.ToString(timespan1.Add(timespan2));
}catch(FormatException){
return "";
}
}
/// <summary>
/// Implements the following function
/// number date:seconds()
/// </summary>
/// <returns>The amount of seconds since the epoch (1970-01-01T00:00:00Z)</returns>
public static double seconds(){
try{
DateTime epoch = new DateTime(1970, 1, 1, 0,0,0,0, CultureInfo.CurrentCulture.Calendar);
TimeSpan duration = DateTime.Now.Subtract(epoch);
return duration.TotalSeconds;
}catch(Exception){
return System.Double.NaN;
}
}
/// <summary>
/// Implements the following function
/// number date:seconds(string)
/// </summary>
/// <returns>The amount of seconds between the specified date and the
/// epoch (1970-01-01T00:00:00Z)</returns>
public static double seconds(string datetime){
try{
DateTime epoch = new DateTime(1970, 1, 1, 0,0,0,0, CultureInfo.CurrentCulture.Calendar);
DateTime date = DateTime.Parse(datetime);;
return date.Subtract(epoch).TotalSeconds;
}catch(FormatException){ ; } //might be a duration
try{
TimeSpan duration = XmlConvert.ToTimeSpan(datetime);
return duration.TotalSeconds;
}catch(FormatException){
return System.Double.NaN;
}
}
/// <summary>
/// Implements the following function
/// string date:sum(node-set)
/// </summary>
/// <param name="iterator">The nodeset</param>
/// <returns>The sum of the values within the node set treated as </returns>
public static string sum(XPathNodeIterator iterator){
TimeSpan sum = new TimeSpan(0,0,0,0);
if(iterator.Count == 0){
return "";
}
try{
while(iterator.MoveNext()){
sum = XmlConvert.ToTimeSpan(iterator.Current.Value).Add(sum);
}
}catch(FormatException){
return "";
}
return XmlConvert.ToString(sum) ; //XmlConvert.ToString(sum);
}
/// <summary>
/// Implements the following function
/// string date:duration(number)
/// </summary>
/// <param name="seconds"></param>
/// <returns></returns>
public static string duration(double seconds){
return XmlConvert.ToString(new TimeSpan(0,0,(int)seconds));
}
/// <summary>
/// Implements the following function
/// string date:avg(node-set)
/// </summary>
/// <param name="iterator"></param>
/// <returns></returns>
/// <remarks>THIS FUNCTION IS NOT PART OF EXSLT!!!</remarks>
public static string avg(XPathNodeIterator iterator){
TimeSpan sum = new TimeSpan(0,0,0,0);
int count = iterator.Count;
if(count == 0){
return "";
}
try{
while(iterator.MoveNext()){
sum = XmlConvert.ToTimeSpan(iterator.Current.Value).Add(sum);
}
}catch(FormatException){
return "";
}
return duration(sum.TotalSeconds / count);
}
/// <summary>
/// Implements the following function
/// string date:min(node-set)
/// </summary>
/// <param name="iterator"></param>
/// <returns></returns>
/// <remarks>THIS FUNCTION IS NOT PART OF EXSLT!!!</remarks>
public static string min(XPathNodeIterator iterator){
TimeSpan min, t;
if(iterator.Count == 0){
return "";
}
try{
iterator.MoveNext();
min = XmlConvert.ToTimeSpan(iterator.Current.Value);
while(iterator.MoveNext()){
t = XmlConvert.ToTimeSpan(iterator.Current.Value);
min = (t < min)? t : min;
}
}catch(FormatException){
return "";
}
return XmlConvert.ToString(min);
}
/// <summary>
/// Implements the following function
/// string date:max(node-set)
/// </summary>
/// <param name="iterator"></param>
/// <returns></returns>
/// <remarks>THIS FUNCTION IS NOT PART OF EXSLT!!!</remarks>
public static string max(XPathNodeIterator iterator){
TimeSpan max, t;
if(iterator.Count == 0){
return "";
}
try{
iterator.MoveNext();
max = XmlConvert.ToTimeSpan(iterator.Current.Value);
while(iterator.MoveNext()){
t = XmlConvert.ToTimeSpan(iterator.Current.Value);
max = (t > max)? t : max;
}
}catch(FormatException){
return "";
}
return XmlConvert.ToString(max);
}
}
}
| |
using System;
using System.IO;
using System.Text;
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using ArchivePDF.csproj.Properties;
//using SolidworksBMPWrapper;
//using ImageMagickObject;
namespace Thumbnail {
class Thumbnailer {
private Frame swFrame;
private DrawingDoc swDraw;
private View swView;
private String sourcePath = String.Empty;
private String drawingPath = String.Empty;
public bool assmbly = true;
public Thumbnailer(SldWorks sw) {
swApp = sw;
APathSet.ShtFmtPath = @"\\AMSTORE-SVR-22\cad\Solid Works\AMSTORE_SHEET_FORMATS\zPostCard.slddrt";
swFrame = (Frame)swApp.Frame();
swModel = (ModelDoc2)swApp.ActiveDoc;
swDraw = (DrawingDoc)swModel;
if (swApp == null)
throw new ThumbnailerException("I know you gave me the SW Application Object, but I dropped it somewhere.");
if (swDraw == null)
throw new ThumbnailerException("You must having a drawing document open.");
swView = GetFirstView(swApp);
sourcePath = swView.GetReferencedModelName().ToUpper().Trim();
if (!sourcePath.Contains("SLDASM"))
assmbly = false;
drawingPath = swModel.GetPathName().ToUpper().Trim();
}
public Thumbnailer(SldWorks sw, ArchivePDF.csproj.PathSet ps) {
swApp = sw;
APathSet = ps;
swFrame = (Frame)swApp.Frame();
swModel = (ModelDoc2)swApp.ActiveDoc;
swDraw = (DrawingDoc)swModel;
if (swApp == null)
throw new ThumbnailerException("I know you gave me the SW Application Object, but I dropped it somewhere.");
if (swDraw == null)
throw new ThumbnailerException("You must having a drawing document open.");
swView = GetFirstView(swApp);
sourcePath = swView.GetReferencedModelName().ToUpper().Trim();
if (!sourcePath.Contains("SLDASM"))
assmbly = false;
drawingPath = swModel.GetPathName().ToUpper().Trim();
}
public void CreateThumbnail() {
if (assmbly) {
bool bRet;
double xSize = 2 * .0254;
double ySize = 2 * .0254;
double xCenter = (xSize / 2) - Settings.Default.WeirdArbitraryFactor;
double yCenter = (ySize / 2);
swDwgPaperSizes_e paperSize = swDwgPaperSizes_e.swDwgPapersUserDefined;
swDwgTemplates_e drwgTemplate = swDwgTemplates_e.swDwgTemplateNone;
swDisplayMode_e dispMode = swDisplayMode_e.swFACETED_HIDDEN;
//G:\\Solid Works\\AMSTORE_SHEET_FORMATS\\AM_PART.slddrt
//swModel = (ModelDoc2)swApp.NewDocument(@"\\AMSTORE-SVR-22\cad\Solid Works\AMSTORE_SHEET_FORMATS\zPostCard.slddrt", (int)paperSize, xSize, ySize);
swModel = (ModelDoc2)swApp.NewDocument(APathSet.ShtFmtPath, (int)paperSize, xSize, ySize);
swDraw = (DrawingDoc)swModel;
bRet = swDraw.SetupSheet5("AMS1", (int)paperSize, (int)drwgTemplate, 1, 1, false, "", xSize, ySize, "Default", false);
View view = swDraw.DropDrawingViewFromPalette(76, xSize, ySize, 0);
swDraw.ActivateView("Drawing View1");
bRet = swModel.Extension.SelectByID2("Drawing View1", "DRAWINGVIEW", xSize, ySize, 0, false, 0, null, 0);
view = swDraw.CreateDrawViewFromModelView3(sourcePath, "*Isometric", xCenter, yCenter, 0);
bRet = view.SetDisplayMode3(false, (int)dispMode, false, true);
System.Diagnostics.Debug.Print(view.ScaleDecimal.ToString());
ScaleAppropriately(swDraw, view, 0.8, 2);
System.Diagnostics.Debug.Print(view.ScaleDecimal.ToString());
swDraw.ActivateView(view.Name);
TurnOffSillyMarks();
}
}
/// <summary>
///
/// </summary>
/// <param name="formats">An array of paths to SolidWorks sheet templates.</param>
/// <param name="monochrome">A bool array indicating whether we ought to have ImageMagick convert to 2-bit.</param>
public void CreateThumbnails(string[] formats, bool[] monochrome) {
bool bRet;
double xSize = 2 * .0254;
double ySize = 2 * .0254;
double xCenter = (xSize / 2);
double yCenter = (ySize / 2);
string orientation = "*Isometric";
string template = string.Empty;
swDwgPaperSizes_e paperSize = swDwgPaperSizes_e.swDwgPapersUserDefined;
swDwgTemplates_e drwgTemplate = swDwgTemplates_e.swDwgTemplateCustom;
swDisplayMode_e dispMode = swDisplayMode_e.swHIDDEN;
for (int i = 0; i < formats.Length; i++) {
template = (new FileInfo(formats[i]).Name).Split(new char[] { '.' })[0];
switch (formats[i].ToUpper().Contains("POSTCARD")) {
case true:
xSize = 7 * 0.0254;
ySize = 5 * 0.0254;
xCenter = (xSize / 2);
yCenter = (ySize / 2);
orientation = "*Isometric";
break;
case false:
xSize = 2 * 0.0254;
ySize = 2 * 0.0254;
xCenter = (xSize / 2) - Settings.Default.WeirdArbitraryFactor;
yCenter = (ySize / 2);
orientation = "*Trimetric";
break;
default:
break;
}
swModel = (ModelDoc2)swApp.NewDocument(formats[i], (int)paperSize, xSize, ySize);
swDraw = (DrawingDoc)swModel;
bRet = swDraw.SetupSheet5("Sheet1", (int)paperSize, (int)drwgTemplate, 1, 1, false, template, xSize, ySize, "Default", false);
View view = swDraw.DropDrawingViewFromPalette(76, xSize, ySize, 0);
swDraw.ActivateView("Drawing View1");
bRet = swModel.Extension.SelectByID2("Drawing View1", "DRAWINGVIEW", xSize, ySize, 0, false, 0, null, 0);
view = swDraw.CreateDrawViewFromModelView3(sourcePath, orientation, xCenter, yCenter, 0);
bRet = view.SetDisplayMode3(false, (int)dispMode, false, true);
//view.ScaleDecimal = GetAppropriateScalingFactor(swDraw, view, 0.8, 2);
ScaleAppropriately(swDraw, view, 0.9, 2);
swDraw.ActivateView(view.Name);
TurnOffSillyMarks();
switch (monochrome[i]) {
case true:
SaveAribaLabel(Settings.Default.AribaPath);
break;
case false:
SaveAsJPG(Settings.Default.JPGPath);
break;
default:
break;
}
CloseThumbnail();
}
}
public void ScaleAppropriately(DrawingDoc dd, View vv, double resize_factor, double starting_factor) {
double[] sht_size = GetSheetSize(dd);
double new_factor = starting_factor;
vv.ScaleDecimal = starting_factor;
double[] view_size = GetBoundingBoxSize(vv);
while (view_size[0] > sht_size[0] || view_size[1] > sht_size[1]) {
vv.ScaleDecimal *= resize_factor;
view_size = GetBoundingBoxSize(vv);
}
}
public double GetAppropriateScalingFactor(DrawingDoc dd, View vv, double resize_factor, double starting_factor) {
double[] sht_size = GetSheetSize(dd);
double new_factor = starting_factor;
vv.ScaleDecimal = starting_factor;
double[] view_size = GetBoundingBoxSize(vv);
double[] tmp_view_size = view_size;
do {
tmp_view_size[0] *= resize_factor;
tmp_view_size[1] *= resize_factor;
new_factor *= resize_factor;
} while (tmp_view_size[0] > sht_size[0] || tmp_view_size[1] > sht_size[1]);
return new_factor;
}
public double[] GetSheetSize(DrawingDoc d) {
Sheet sht = (Sheet)d.GetCurrentSheet();
double[] sp = (double[])sht.GetProperties();
double[] s_size = { sp[5], sp[6] };
return s_size;
}
public double[] GetBoundingBoxSize(View v) {
double[] bb = (double[])v.GetOutline();
double[] bb_size = { (bb[2] - bb[0]), (bb[3] - bb[1]) };
return bb_size;
}
public double[] GetPosition(View v) {
return (double[])swView.Position;
}
public void TurnOffSillyMarks() {
// For some reason, the model imports with a bunch of ugly pointless stuff displayed. So, here's where we turn them off.
bool bRet = swModel.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swDisplayOrigins, false);
bRet &= swModel.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swDisplayPlanes, false);
bRet &= swModel.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swDisplayRoutePoints, false);
bRet &= swModel.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swDisplaySketches, false);
}
public View GetFirstView(SldWorks sw) {
ModelDoc2 swModel = (ModelDoc2)sw.ActiveDoc;
View v;
DrawingDoc d = (DrawingDoc)swModel;
string[] shtNames = (String[])swDraw.GetSheetNames();
string message = string.Empty;
//This should find the first page with something on it.
int x = 0;
do {
try {
d.ActivateSheet(shtNames[x]);
} catch (IndexOutOfRangeException e) {
throw new IndexOutOfRangeException("Went beyond the number of sheets.", e);
} catch (Exception e) {
throw e;
}
v = (View)d.GetFirstView();
v = (View)v.GetNextView();
x++;
} while ((v == null) && (x < d.GetSheetCount()));
message = (string)v.GetName2() + ":\n";
if (v == null) {
throw new Exception("I couldn't find a model anywhere in this document.");
}
return v;
}
public void SaveAsJPG(string targetPath) {
int saveVersion = (int)swSaveAsVersion_e.swSaveAsCurrentVersion;
int saveOptions = (int)swSaveAsOptions_e.swSaveAsOptions_Silent;
int refErrors = 0;
int refWarnings = 0;
bool bRet;
StringBuilder tp = new StringBuilder(targetPath);
StringBuilder targetFileName = new StringBuilder();
if (!targetPath.EndsWith("\\"))
tp.Append("\\");
targetFileName.AppendFormat("{0}{1}.jpg", tp.ToString(), Path.GetFileNameWithoutExtension(drawingPath));
string tempFileName = "" + targetFileName.ToString();
System.Diagnostics.Debug.Print("Saving " + tempFileName);
swFrame.SetStatusBarText("Saving '" + tempFileName + "'...");
bRet = swModel.SaveAs4(tempFileName, saveVersion, saveOptions, ref refErrors, ref refWarnings);
}
public void SaveAribaLabel(string targetPath) {
bool bRet;
string tmpPath = Path.GetTempPath();
StringBuilder tp = new StringBuilder(targetPath);
StringBuilder targetFilename = new StringBuilder();
if (!targetPath.EndsWith("\\"))
tp.Append("\\");
targetFilename.AppendFormat("{0}{1}.bmp", tmpPath, Path.GetFileNameWithoutExtension(drawingPath));
string tempFileName = "" + targetFilename.ToString();
System.Diagnostics.Debug.Print("Saving " + tempFileName);
swFrame.SetStatusBarText("Saving '" + tempFileName + "'...");
// Maybe this affects BMP. The "Export Options" screen says it'll affect TIF/PSD/JPG/PNG.
swApp.SetUserPreferenceIntegerValue((int)swUserPreferenceIntegerValue_e.swTiffPrintDPI, 600);
bRet = swModel.SaveBMP(tempFileName.ToString(), 96 * 2, 96 * 2);
string imPath = WheresImageMagick();
if (imPath.Length > 0) {
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.EnableRaisingEvents = false;
p.StartInfo.FileName = string.Format(@"{0}\convert.exe ", imPath);
// I'll just resize. ImageMagick can't mess this up, right?
p.StartInfo.Arguments = string.Format("\"{0}\" -resize 192x192! -colors 2 \"{1}{2}.jpg\"",
targetFilename.ToString(),
tp.ToString(),
Path.GetFileNameWithoutExtension(drawingPath));
p.Start();
p.WaitForExit();
} else {
swApp.SendMsgToUser2(ArchivePDF.csproj.Properties.Resources.WheresImageMagick,
(int)swMessageBoxIcon_e.swMbWarning,
(int)swMessageBoxBtn_e.swMbOk);
}
}
public string WheresImageMagick() {
Microsoft.Win32.RegistryKey rk = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Wow6432Node\ImageMagick\Current\");
if (rk != null) {
return (string)rk.GetValue("BinPath".ToUpper());
} else {
return string.Empty;
}
}
public void CloseThumbnail() {
//if (assmbly) {
swFrame.SetStatusBarText("Closing '" + swModel.GetPathName().ToUpper() + "'...");
System.Diagnostics.Debug.Print("Closing '" + swModel.GetPathName().ToUpper() + "'...");
swApp.CloseDoc(swModel.GetPathName().ToUpper());
//}
}
public void CloseFiles() {
if (assmbly) {
swFrame.SetStatusBarText("Closing everything...");
System.Diagnostics.Debug.Print("Closing everything...");
swApp.CloseAllDocuments(true);
}
}
private SldWorks swApp;
public SldWorks swApplication {
get { return swApp; }
set { swApp = value; }
}
private ModelDoc2 swModel;
public ModelDoc2 swDocument {
get { return swModel; }
set { swModel = value; }
}
private ArchivePDF.csproj.PathSet _ps;
public ArchivePDF.csproj.PathSet APathSet {
get { return _ps; }
set { _ps = value; }
}
}
}
| |
//
// ARC4ManagedTest.cs - NUnit Test Cases for Alleged RC4(tm)
// RC4 is a trademark of RSA Security
//
// Author:
// Sebastien Pouliot (spouliot@motus.com)
//
// (C) 2003 Motus Technologies Inc. (http://www.motus.com)
//
using NUnit.Framework;
using System;
using System.Security.Cryptography;
using Mono.Security.Cryptography;
namespace MonoTests.Mono.Security.Cryptography {
// References
// a. Usenet 1994 - RC4 Algorithm revealed
// http://www.qrst.de/html/dsds/rc4.htm
// b. Netscape SSL version 3 implementation details
// Export Client SSL Connection Details
// http://wp.netscape.com/eng/ssl3/traces/trc-clnt-ex.html
[TestFixture]
public class ARC4ManagedTest : Assertion {
// because most crypto stuff works with byte[] buffers
static public void AssertEquals (string msg, byte[] array1, byte[] array2)
{
if ((array1 == null) && (array2 == null))
return;
if (array1 == null)
Fail (msg + " -> First array is NULL");
if (array2 == null)
Fail (msg + " -> Second array is NULL");
bool a = (array1.Length == array2.Length);
if (a) {
for (int i = 0; i < array1.Length; i++) {
if (array1 [i] != array2 [i]) {
a = false;
break;
}
}
}
msg += " -> Expected " + BitConverter.ToString (array1, 0);
msg += " is different than " + BitConverter.ToString (array2, 0);
Assert (msg, a);
}
// from ref. a
[Test]
public void Vector0 ()
{
byte[] key = { 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef };
byte[] input = { 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef };
byte[] expected = { 0x75, 0xb7, 0x87, 0x80, 0x99, 0xe0, 0xc5, 0x96 };
ARC4Managed rc4 = new ARC4Managed ();
rc4.Key = key;
ICryptoTransform stream = rc4.CreateEncryptor ();
byte[] output = stream.TransformFinalBlock (input, 0, input.Length);
AssertEquals ("RC4 - Test Vector 0", expected, output);
}
// from ref. a
[Test]
public void Vector1 ()
{
byte[] key = { 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef };
byte[] input = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
byte[] expected = { 0x74, 0x94, 0xc2, 0xe7, 0x10, 0x4b, 0x08, 0x79 };
ARC4Managed rc4 = new ARC4Managed ();
rc4.Key = key;
ICryptoTransform stream = rc4.CreateEncryptor ();
byte[] output = stream.TransformFinalBlock (input, 0, input.Length);
AssertEquals ("RC4 - Test Vector 1", expected, output);
}
// from ref. a
[Test]
public void Vector2 ()
{
byte[] key = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
byte[] input = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
byte[] expected = { 0xde, 0x18, 0x89, 0x41, 0xa3, 0x37, 0x5d, 0x3a };
ARC4Managed rc4 = new ARC4Managed ();
rc4.Key = key;
ICryptoTransform stream = rc4.CreateEncryptor ();
byte[] output = stream.TransformFinalBlock (input, 0, input.Length);
AssertEquals ("RC4 - Test Vector 2", expected, output);
}
// from ref. a
[Test]
public void Vector3 ()
{
byte[] key = { 0xef, 0x01, 0x23, 0x45 };
byte[] input = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
byte[] expected = { 0xd6, 0xa1, 0x41, 0xa7, 0xec, 0x3c, 0x38, 0xdf, 0xbd, 0x61 };
ARC4Managed rc4 = new ARC4Managed ();
rc4.Key = key;
ICryptoTransform stream = rc4.CreateEncryptor ();
byte[] output = stream.TransformFinalBlock (input, 0, input.Length);
AssertEquals ("RC4 - Test Vector 3", expected, output);
}
// from ref. a
[Test]
public void Vector4 ()
{
byte[] key = { 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef };
byte[] input = new byte [512];
for (int i=0; i < input.Length; i++)
input [i] = 0x01;
byte[] expected = { 0x75, 0x95, 0xc3, 0xe6, 0x11, 0x4a, 0x09, 0x78, 0x0c, 0x4a, 0xd4,
0x52, 0x33, 0x8e, 0x1f, 0xfd, 0x9a, 0x1b, 0xe9, 0x49, 0x8f,
0x81, 0x3d, 0x76, 0x53, 0x34, 0x49, 0xb6, 0x77, 0x8d, 0xca,
0xd8, 0xc7, 0x8a, 0x8d, 0x2b, 0xa9, 0xac, 0x66, 0x08, 0x5d,
0x0e, 0x53, 0xd5, 0x9c, 0x26, 0xc2, 0xd1, 0xc4, 0x90, 0xc1,
0xeb, 0xbe, 0x0c, 0xe6, 0x6d, 0x1b, 0x6b, 0x1b, 0x13, 0xb6,
0xb9, 0x19, 0xb8, 0x47, 0xc2, 0x5a, 0x91, 0x44, 0x7a, 0x95,
0xe7, 0x5e, 0x4e, 0xf1, 0x67, 0x79, 0xcd, 0xe8, 0xbf, 0x0a,
0x95, 0x85, 0x0e, 0x32, 0xaf, 0x96, 0x89, 0x44, 0x4f, 0xd3,
0x77, 0x10, 0x8f, 0x98, 0xfd, 0xcb, 0xd4, 0xe7, 0x26, 0x56,
0x75, 0x00, 0x99, 0x0b, 0xcc, 0x7e, 0x0c, 0xa3, 0xc4, 0xaa,
0xa3, 0x04, 0xa3, 0x87, 0xd2, 0x0f, 0x3b, 0x8f, 0xbb, 0xcd,
0x42, 0xa1, 0xbd, 0x31, 0x1d, 0x7a, 0x43, 0x03, 0xdd, 0xa5,
0xab, 0x07, 0x88, 0x96, 0xae, 0x80, 0xc1, 0x8b, 0x0a, 0xf6,
0x6d, 0xff, 0x31, 0x96, 0x16, 0xeb, 0x78, 0x4e, 0x49, 0x5a,
0xd2, 0xce, 0x90, 0xd7, 0xf7, 0x72, 0xa8, 0x17, 0x47, 0xb6,
0x5f, 0x62, 0x09, 0x3b, 0x1e, 0x0d, 0xb9, 0xe5, 0xba, 0x53,
0x2f, 0xaf, 0xec, 0x47, 0x50, 0x83, 0x23, 0xe6, 0x71, 0x32,
0x7d, 0xf9, 0x44, 0x44, 0x32, 0xcb, 0x73, 0x67, 0xce, 0xc8,
0x2f, 0x5d, 0x44, 0xc0, 0xd0, 0x0b, 0x67, 0xd6, 0x50, 0xa0,
0x75, 0xcd, 0x4b, 0x70, 0xde, 0xdd, 0x77, 0xeb, 0x9b, 0x10,
0x23, 0x1b, 0x6b, 0x5b, 0x74, 0x13, 0x47, 0x39, 0x6d, 0x62,
0x89, 0x74, 0x21, 0xd4, 0x3d, 0xf9, 0xb4, 0x2e, 0x44, 0x6e,
0x35, 0x8e, 0x9c, 0x11, 0xa9, 0xb2, 0x18, 0x4e, 0xcb, 0xef,
0x0c, 0xd8, 0xe7, 0xa8, 0x77, 0xef, 0x96, 0x8f, 0x13, 0x90,
0xec, 0x9b, 0x3d, 0x35, 0xa5, 0x58, 0x5c, 0xb0, 0x09, 0x29,
0x0e, 0x2f, 0xcd, 0xe7, 0xb5, 0xec, 0x66, 0xd9, 0x08, 0x4b,
0xe4, 0x40, 0x55, 0xa6, 0x19, 0xd9, 0xdd, 0x7f, 0xc3, 0x16,
0x6f, 0x94, 0x87, 0xf7, 0xcb, 0x27, 0x29, 0x12, 0x42, 0x64,
0x45, 0x99, 0x85, 0x14, 0xc1, 0x5d, 0x53, 0xa1, 0x8c, 0x86,
0x4c, 0xe3, 0xa2, 0xb7, 0x55, 0x57, 0x93, 0x98, 0x81, 0x26,
0x52, 0x0e, 0xac, 0xf2, 0xe3, 0x06, 0x6e, 0x23, 0x0c, 0x91,
0xbe, 0xe4, 0xdd, 0x53, 0x04, 0xf5, 0xfd, 0x04, 0x05, 0xb3,
0x5b, 0xd9, 0x9c, 0x73, 0x13, 0x5d, 0x3d, 0x9b, 0xc3, 0x35,
0xee, 0x04, 0x9e, 0xf6, 0x9b, 0x38, 0x67, 0xbf, 0x2d, 0x7b,
0xd1, 0xea, 0xa5, 0x95, 0xd8, 0xbf, 0xc0, 0x06, 0x6f, 0xf8,
0xd3, 0x15, 0x09, 0xeb, 0x0c, 0x6c, 0xaa, 0x00, 0x6c, 0x80,
0x7a, 0x62, 0x3e, 0xf8, 0x4c, 0x3d, 0x33, 0xc1, 0x95, 0xd2,
0x3e, 0xe3, 0x20, 0xc4, 0x0d, 0xe0, 0x55, 0x81, 0x57, 0xc8,
0x22, 0xd4, 0xb8, 0xc5, 0x69, 0xd8, 0x49, 0xae, 0xd5, 0x9d,
0x4e, 0x0f, 0xd7, 0xf3, 0x79, 0x58, 0x6b, 0x4b, 0x7f, 0xf6,
0x84, 0xed, 0x6a, 0x18, 0x9f, 0x74, 0x86, 0xd4, 0x9b, 0x9c,
0x4b, 0xad, 0x9b, 0xa2, 0x4b, 0x96, 0xab, 0xf9, 0x24, 0x37,
0x2c, 0x8a, 0x8f, 0xff, 0xb1, 0x0d, 0x55, 0x35, 0x49, 0x00,
0xa7, 0x7a, 0x3d, 0xb5, 0xf2, 0x05, 0xe1, 0xb9, 0x9f, 0xcd,
0x86, 0x60, 0x86, 0x3a, 0x15, 0x9a, 0xd4, 0xab, 0xe4, 0x0f,
0xa4, 0x89, 0x34, 0x16, 0x3d, 0xdd, 0xe5, 0x42, 0xa6, 0x58,
0x55, 0x40, 0xfd, 0x68, 0x3c, 0xbf, 0xd8, 0xc0, 0x0f, 0x12,
0x12, 0x9a, 0x28, 0x4d, 0xea, 0xcc, 0x4c, 0xde, 0xfe, 0x58,
0xbe, 0x71, 0x37, 0x54, 0x1c, 0x04, 0x71, 0x26, 0xc8, 0xd4,
0x9e, 0x27, 0x55, 0xab, 0x18, 0x1a, 0xb7, 0xe9, 0x40, 0xb0,
0xc0 };
ARC4Managed rc4 = new ARC4Managed ();
rc4.Key = key;
ICryptoTransform stream = rc4.CreateEncryptor ();
byte[] output = stream.TransformFinalBlock (input, 0, input.Length);
AssertEquals ("RC4 - Test Vector 4", expected, output);
}
static byte[] clientWriteKey = { 0x32, 0x10, 0xcd, 0xe1, 0xd6, 0xdc, 0x07, 0x83, 0xf3, 0x75, 0x4c, 0x32, 0x2e, 0x59, 0x96, 0x61 };
static byte[] serverWriteKey = { 0xed, 0x0e, 0x56, 0xc8, 0x95, 0x12, 0x37, 0xb6, 0x21, 0x17, 0x1c, 0x72, 0x79, 0x91, 0x12, 0x1e };
// SSL3 Client's Finished Handshake (from ref. b)
[Test]
public void SSLClient ()
{
byte[] data = { 0x14, 0x00, 0x00, 0x24, 0xf2, 0x40, 0x10, 0x3f, 0x74, 0x63, 0xea, 0xe8, 0x7a, 0x27, 0x23, 0x56, 0x5f, 0x59, 0x07, 0xd2, 0xa3, 0x79, 0x5d, 0xb7, 0x8b, 0x94, 0xdb, 0xcf, 0xfa, 0xf5, 0x18, 0x22, 0x15, 0x7b, 0xf2, 0x4a, 0x96, 0x52, 0x9a, 0x0e, 0xd3, 0x09, 0xde, 0x28, 0x84, 0xa7, 0x07, 0x5c, 0x7c, 0x0c, 0x08, 0x85, 0x6b, 0x4f, 0x63, 0x04 };
ARC4Managed rc4 = new ARC4Managed ();
rc4.Key = clientWriteKey;
// encrypt inplace (in same buffer)
rc4.TransformBlock (data, 0, data.Length, data, 0);
byte[] expectedData = { 0xed, 0x37, 0x7f, 0x16, 0xd3, 0x11, 0xe8, 0xa3, 0xe1, 0x2a, 0x20, 0xb7, 0x88, 0xf6, 0x11, 0xf3, 0xa6, 0x7d, 0x37, 0xf7, 0x17, 0xac, 0x67, 0x20, 0xb8, 0x0e, 0x88, 0xd1, 0xa0, 0xc6, 0x83, 0xe4, 0x80, 0xe8, 0xc7, 0xe3, 0x0b, 0x91, 0x29, 0x30, 0x29, 0xe4, 0x28, 0x47, 0xb7, 0x40, 0xa4, 0xd1, 0x3c, 0xda, 0x82, 0xb7, 0xb3, 0x9f, 0x67, 0x10 };
AssertEquals ("RC4 - Client's Finished Handshake", expectedData, data);
}
// SSL3 Server Finished Handshake (from ref. b)
[Test]
public void SSLServer ()
{
byte[] encryptedData = { 0x54, 0x3c, 0xe1, 0xe7, 0x4d, 0x77, 0x76, 0x62, 0x86, 0xfa, 0x4e, 0x0a, 0x6f, 0x5f, 0x6a, 0x3d, 0x43, 0x26, 0xf4, 0xad, 0x8d, 0x3e, 0x09, 0x0b, 0x2b, 0xf7, 0x9f, 0x49, 0x44, 0x92, 0xfb, 0xa9, 0xa4, 0xb0, 0x5a, 0xd8, 0x72, 0x77, 0x6e, 0x8b, 0xb3, 0x78, 0xfb, 0xda, 0xe0, 0x25, 0xef, 0xb3, 0xf5, 0xa7, 0x90, 0x08, 0x6d, 0x60, 0xd5, 0x4e };
ARC4Managed rc4 = new ARC4Managed ();
rc4.Key = serverWriteKey;
// decrypt inplace (in same buffer)
rc4.TransformBlock (encryptedData, 0, encryptedData.Length, encryptedData, 0);
byte[] expectedData = { 0x14, 0x00, 0x00, 0x24, 0xb7, 0xcc, 0xd6, 0x05, 0x6b, 0xfc, 0xfa, 0x6d, 0xfa, 0xdd, 0x76, 0x81, 0x45, 0x36, 0xe4, 0xf4, 0x26, 0x35, 0x72, 0x2c, 0xec, 0x87, 0x62, 0x1f, 0x55, 0x08, 0x05, 0x4f, 0xc8, 0xf5, 0x7c, 0x49, 0xe2, 0xee, 0xc5, 0xba, 0xbd, 0x69, 0x27, 0x3b, 0xd0, 0x13, 0x23, 0x52, 0xed, 0xec, 0x11, 0x55, 0xd8, 0xb9, 0x90, 0x8c };
AssertEquals ("RC4 - Server's Finished Handshake", expectedData, encryptedData);
}
[Test]
public void DefaultProperties ()
{
ARC4Managed rc4 = new ARC4Managed ();
Assert ("CanReuseTransform", !rc4.CanReuseTransform);
Assert ("CanTransformMultipleBlocks", rc4.CanTransformMultipleBlocks);
AssertEquals ("InputBlockSize", 1, rc4.InputBlockSize);
AssertEquals ("OutputBlockSize", 1, rc4.OutputBlockSize);
}
[Test]
public void DefaultSizes ()
{
ARC4Managed rc4 = new ARC4Managed ();
rc4.GenerateKey ();
rc4.GenerateIV ();
AssertEquals ("Key.Length", 16, rc4.Key.Length);
AssertEquals ("KeySize", 128, rc4.KeySize);
AssertEquals ("IV.Length", 0, rc4.IV.Length);
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void TransformBlock_InputBuffer_Null ()
{
byte[] output = new byte [1];
ARC4Managed rc4 = new ARC4Managed ();
rc4.TransformBlock (null, 0, 1, output, 0);
}
[Test]
[ExpectedException (typeof (ArgumentOutOfRangeException))]
public void TransformBlock_InputOffset_Negative ()
{
byte[] input = new byte [1];
byte[] output = new byte [1];
ARC4Managed rc4 = new ARC4Managed ();
rc4.TransformBlock (input, -1, 1, output, 0);
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void TransformBlock_InputOffset_Overflow ()
{
byte[] input = new byte [1];
byte[] output = new byte [1];
ARC4Managed rc4 = new ARC4Managed ();
rc4.TransformBlock (input, Int32.MaxValue, 1, output, 0);
}
[Test]
[ExpectedException (typeof (ArgumentOutOfRangeException))]
public void TransformBlock_InputCount_Negative ()
{
byte[] input = new byte [1];
byte[] output = new byte [1];
ARC4Managed rc4 = new ARC4Managed ();
rc4.TransformBlock (input, 0, -1, output, 0);
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void TransformBlock_InputCount_Overflow ()
{
byte[] input = new byte [1];
byte[] output = new byte [1];
ARC4Managed rc4 = new ARC4Managed ();
rc4.TransformBlock (input, 1, Int32.MaxValue, output, 0);
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void TransformBlock_OutputBuffer_Null ()
{
byte[] input = new byte [1];
ARC4Managed rc4 = new ARC4Managed ();
rc4.TransformBlock (input, 0, 1, null, 0);
}
[Test]
[ExpectedException (typeof (ArgumentOutOfRangeException))]
public void TransformBlock_OutputOffset_Negative ()
{
byte[] input = new byte [1];
byte[] output = new byte [1];
ARC4Managed rc4 = new ARC4Managed ();
rc4.TransformBlock (input, 0, 1, output, -1);
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void TransformBlock_OutputOffset_Overflow ()
{
byte[] input = new byte [1];
byte[] output = new byte [1];
ARC4Managed rc4 = new ARC4Managed ();
rc4.TransformBlock (input, 0, 1, output, Int32.MaxValue);
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void TransformFinalBlock_InputBuffer_Null ()
{
ARC4Managed rc4 = new ARC4Managed ();
rc4.TransformFinalBlock (null, 0, 1);
}
[Test]
[ExpectedException (typeof (ArgumentOutOfRangeException))]
public void TransformFinalBlock_InputOffset_Negative ()
{
byte[] input = new byte [1];
ARC4Managed rc4 = new ARC4Managed ();
rc4.TransformFinalBlock (input, -1, 1);
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void TransformFinalBlock_InputOffset_Overflow ()
{
byte[] input = new byte [1];
ARC4Managed rc4 = new ARC4Managed ();
rc4.TransformFinalBlock (input, Int32.MaxValue, 1);
}
[Test]
[ExpectedException (typeof (ArgumentOutOfRangeException))]
public void TransformFinalBlock_InputCount_Negative ()
{
byte[] input = new byte [1];
ARC4Managed rc4 = new ARC4Managed ();
rc4.TransformFinalBlock (input, 0, -1);
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void TransformFinalBlock_InputCount_Overflow ()
{
byte[] input = new byte [1];
ARC4Managed rc4 = new ARC4Managed ();
rc4.TransformFinalBlock (input, 1, Int32.MaxValue);
}
}
}
| |
using System;
using System.Data;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.IO;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Windows.Forms;
using Belikov.GenuineChannels;
using Belikov.GenuineChannels.DotNetRemotingLayer;
using Belikov.GenuineChannels.GenuineTcp;
using Known;
namespace Server
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form : System.Windows.Forms.Form
{
private System.Windows.Forms.StatusBar statusBar;
private System.Windows.Forms.StatusBarPanel statusBarPanelConnect;
private System.Windows.Forms.MainMenu mainMenu;
private System.Windows.Forms.MenuItem menuItem1;
private System.Windows.Forms.MenuItem menuItem3;
private System.Windows.Forms.Panel panel;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button buttonStart;
private System.Windows.Forms.Button buttonStop;
private System.Windows.Forms.RichTextBox richTextBoxLog;
private System.Windows.Forms.MenuItem menuItemExit;
private System.Windows.Forms.MenuItem menuItemAbout;
private System.Windows.Forms.NumericUpDown numericUpDownPort;
private System.Windows.Forms.Timer timer;
private System.Windows.Forms.CheckBox checkBoxFireTheEvent;
private System.ComponentModel.IContainer components;
public Form()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.statusBar = new System.Windows.Forms.StatusBar();
this.statusBarPanelConnect = new System.Windows.Forms.StatusBarPanel();
this.mainMenu = new System.Windows.Forms.MainMenu();
this.menuItem1 = new System.Windows.Forms.MenuItem();
this.menuItemExit = new System.Windows.Forms.MenuItem();
this.menuItem3 = new System.Windows.Forms.MenuItem();
this.menuItemAbout = new System.Windows.Forms.MenuItem();
this.panel = new System.Windows.Forms.Panel();
this.label8 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.numericUpDownPort = new System.Windows.Forms.NumericUpDown();
this.buttonStart = new System.Windows.Forms.Button();
this.buttonStop = new System.Windows.Forms.Button();
this.richTextBoxLog = new System.Windows.Forms.RichTextBox();
this.timer = new System.Windows.Forms.Timer(this.components);
this.checkBoxFireTheEvent = new System.Windows.Forms.CheckBox();
((System.ComponentModel.ISupportInitialize)(this.statusBarPanelConnect)).BeginInit();
this.panel.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownPort)).BeginInit();
this.SuspendLayout();
//
// statusBar
//
this.statusBar.Location = new System.Drawing.Point(0, 296);
this.statusBar.Name = "statusBar";
this.statusBar.Panels.AddRange(new System.Windows.Forms.StatusBarPanel[] {
this.statusBarPanelConnect});
this.statusBar.ShowPanels = true;
this.statusBar.Size = new System.Drawing.Size(528, 22);
this.statusBar.TabIndex = 7;
//
// statusBarPanelConnect
//
this.statusBarPanelConnect.AutoSize = System.Windows.Forms.StatusBarPanelAutoSize.Spring;
this.statusBarPanelConnect.MinWidth = 150;
this.statusBarPanelConnect.Text = "Status:";
this.statusBarPanelConnect.Width = 512;
//
// mainMenu
//
this.mainMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItem1,
this.menuItem3});
//
// menuItem1
//
this.menuItem1.Index = 0;
this.menuItem1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItemExit});
this.menuItem1.Text = "&File";
//
// menuItemExit
//
this.menuItemExit.Index = 0;
this.menuItemExit.Text = "E&xit";
this.menuItemExit.Click += new System.EventHandler(this.menuItemExit_Click);
//
// menuItem3
//
this.menuItem3.Index = 1;
this.menuItem3.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItemAbout});
this.menuItem3.Text = "&Help";
//
// menuItemAbout
//
this.menuItemAbout.Index = 0;
this.menuItemAbout.Text = "&About";
this.menuItemAbout.Click += new System.EventHandler(this.menuItemAbout_Click);
//
// panel
//
this.panel.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right);
this.panel.BackColor = System.Drawing.SystemColors.ControlLight;
this.panel.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.panel.Controls.AddRange(new System.Windows.Forms.Control[] {
this.label8});
this.panel.Location = new System.Drawing.Point(8, 8);
this.panel.Name = "panel";
this.panel.Size = new System.Drawing.Size(512, 56);
this.panel.TabIndex = 0;
//
// label8
//
this.label8.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right);
this.label8.BackColor = System.Drawing.SystemColors.ControlLight;
this.label8.Font = new System.Drawing.Font("Arial", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.label8.Location = new System.Drawing.Point(8, 8);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(496, 40);
this.label8.TabIndex = 0;
this.label8.Text = "Enter the server port and press the Start button to start accepting clients. Pres" +
"s the Stop button to stop accepting clients.";
//
// label1
//
this.label1.Location = new System.Drawing.Point(8, 72);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(100, 20);
this.label1.TabIndex = 1;
this.label1.Text = "Port:";
this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// numericUpDownPort
//
this.numericUpDownPort.Location = new System.Drawing.Point(112, 72);
this.numericUpDownPort.Maximum = new System.Decimal(new int[] {
65535,
0,
0,
0});
this.numericUpDownPort.Minimum = new System.Decimal(new int[] {
1,
0,
0,
0});
this.numericUpDownPort.Name = "numericUpDownPort";
this.numericUpDownPort.TabIndex = 2;
this.numericUpDownPort.Value = new System.Decimal(new int[] {
8737,
0,
0,
0});
//
// buttonStart
//
this.buttonStart.Location = new System.Drawing.Point(8, 96);
this.buttonStart.Name = "buttonStart";
this.buttonStart.TabIndex = 3;
this.buttonStart.Text = "&Start";
this.buttonStart.Click += new System.EventHandler(this.buttonStart_Click);
//
// buttonStop
//
this.buttonStop.Location = new System.Drawing.Point(88, 96);
this.buttonStop.Name = "buttonStop";
this.buttonStop.TabIndex = 4;
this.buttonStop.Text = "&Stop";
this.buttonStop.Click += new System.EventHandler(this.buttonStop_Click);
//
// richTextBoxLog
//
this.richTextBoxLog.Anchor = (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right);
this.richTextBoxLog.Location = new System.Drawing.Point(8, 128);
this.richTextBoxLog.Name = "richTextBoxLog";
this.richTextBoxLog.ReadOnly = true;
this.richTextBoxLog.Size = new System.Drawing.Size(512, 160);
this.richTextBoxLog.TabIndex = 6;
this.richTextBoxLog.Text = "";
//
// timer
//
this.timer.Interval = 333;
this.timer.Tick += new System.EventHandler(this.timer_Tick);
//
// checkBoxFireTheEvent
//
this.checkBoxFireTheEvent.Checked = true;
this.checkBoxFireTheEvent.CheckState = System.Windows.Forms.CheckState.Checked;
this.checkBoxFireTheEvent.Location = new System.Drawing.Point(280, 96);
this.checkBoxFireTheEvent.Name = "checkBoxFireTheEvent";
this.checkBoxFireTheEvent.Size = new System.Drawing.Size(216, 24);
this.checkBoxFireTheEvent.TabIndex = 5;
this.checkBoxFireTheEvent.Text = "Fire the event three times per second";
this.checkBoxFireTheEvent.CheckedChanged += new System.EventHandler(this.checkBoxFireTheEvent_CheckedChanged);
//
// Form
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(528, 318);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.checkBoxFireTheEvent,
this.richTextBoxLog,
this.statusBar,
this.buttonStart,
this.buttonStop,
this.label1,
this.numericUpDownPort,
this.panel});
this.Menu = this.mainMenu;
this.Name = "Form";
this.Text = "Security Session Demo Server";
this.Load += new System.EventHandler(this.Form_Load);
((System.ComponentModel.ISupportInitialize)(this.statusBarPanelConnect)).EndInit();
this.panel.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.numericUpDownPort)).EndInit();
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form());
}
#region GUI events
private void menuItemExit_Click(object sender, System.EventArgs e)
{
this.Close();
}
private void menuItemAbout_Click(object sender, System.EventArgs e)
{
About about = new About();
about.ShowDialog(this);
}
private void Form_Load(object sender, System.EventArgs e)
{
this.EstablishSecuritySession = new EstablishSecuritySession();
this.ServerEventProvider = new ServerEventProvider(this);
this.CreateFile = new CreateFile();
RemotingServices.Marshal(this.ServerEventProvider, "ServerEventProvider.rem");
RemotingServices.Marshal(this.EstablishSecuritySession, "EstablishSecuritySession.rem");
RemotingServices.Marshal(this.CreateFile, "CreateFile.rem");
GenuineGlobalEventProvider.GenuineChannelsGlobalEvent += new GenuineChannelsGlobalEventHandler(this.GenuineChannelsEventHandler);
this.buttonStartEnabled = true;
this.buttonStart_Click(sender, e);
this.timer.Start();
}
private void buttonStart_Click(object sender, System.EventArgs e)
{
try
{
if (this.GenuineTcpChannel == null)
{
Hashtable properties = new Hashtable();
properties["port"] = this.numericUpDownPort.Value.ToString();
properties["port"] = this.numericUpDownPort.Value.ToString();
this.GenuineTcpChannel = new GenuineTcpChannel(properties, null, null);
ChannelServices.RegisterChannel(this.GenuineTcpChannel);
}
else
{
this.GenuineTcpChannel["port"] = this.numericUpDownPort.Value.ToString();
this.GenuineTcpChannel.StartListening(null);
}
this.UpdateLog("Server has been successfully started.");
this.buttonStartEnabled = false;
}
catch(Exception ex)
{
if (ex is OperationException)
{
OperationException operationException = (OperationException) ex;
MessageBox.Show(this, operationException.OperationErrorMessage.UserFriendlyMessage, operationException.OperationErrorMessage.ErrorIdentifier, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
MessageBox.Show(this, ex.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonStop_Click(object sender, System.EventArgs e)
{
try
{
this.GenuineTcpChannel.StopListening(null);
}
catch(Exception)
{
}
this.buttonStartEnabled = true;
}
private void timer_Tick(object sender, System.EventArgs e)
{
this.ServerEventProvider.FireEvent();
}
private void checkBoxFireTheEvent_CheckedChanged(object sender, System.EventArgs e)
{
this.IsEventFired = this.checkBoxFireTheEvent.Checked;
}
#endregion
/// <summary>
/// Sets values of connect and disconnect buttons.
/// </summary>
public bool buttonStartEnabled
{
set
{
this.buttonStart.Enabled = value;
this.buttonStop.Enabled = ! value;
this.statusBarPanelConnect.Text = "Status: " + (!value ? "Accepting clients." : "Stopped.");
}
}
public bool IsEventFired = true;
public ServerEventProvider ServerEventProvider;
public EstablishSecuritySession EstablishSecuritySession;
public CreateFile CreateFile;
private GenuineTcpChannel GenuineTcpChannel;
/// <summary>
/// Processes events thrown by Genuine Channels.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void GenuineChannelsEventHandler(object sender, GenuineEventArgs e)
{
string remoteHostInfo = e.HostInformation == null ? "<not specified>" : e.HostInformation.ToString();
switch (e.EventType)
{
case GenuineEventType.GeneralConnectionEstablished:
this.UpdateLog("Connection is established by {0}.", remoteHostInfo);
break;
case GenuineEventType.GeneralConnectionClosed:
if (e.SourceException != null)
this.UpdateLog("Connection to the host {0} is closed due to the exception: {1}.", remoteHostInfo, e.SourceException);
else
this.UpdateLog("Connection to the host {0} is closed.", remoteHostInfo, e.SourceException);
break;
case GenuineEventType.GeneralConnectionReestablishing:
if (e.SourceException != null)
this.UpdateLog("Connection to the host {0} has been broken due to the exception: {1} but will probably be restored.", remoteHostInfo, e.SourceException);
else
this.UpdateLog("Connection to the host {0} has been broken but will probably be restored.", remoteHostInfo);
break;
}
}
private delegate void RichTextBoxAppendTextDelegate(string str);
/// <summary>
/// Appends a log.
/// </summary>
/// <param name="format">String.</param>
/// <param name="args">String arguments.</param>
public void UpdateLog(string format, params object[] args)
{
string str = string.Format(format, args);
str = string.Format("\r\n------- {0} \r\n{1}", DateTime.Now, str);
RichTextBoxAppendTextDelegate richTextBoxAppendTextDelegate = new RichTextBoxAppendTextDelegate(this.richTextBoxLog.AppendText);
this.richTextBoxLog.Invoke(richTextBoxAppendTextDelegate, new object[] { str });
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Windows;
using Microsoft.Practices.Prism.Events;
using Microsoft.Practices.Prism.Properties;
using Microsoft.Practices.Prism.Regions.Behaviors;
using Microsoft.Practices.ServiceLocation;
namespace Microsoft.Practices.Prism.Regions
{
/// <summary>
/// This class is responsible for maintaining a collection of regions and attaching regions to controls.
/// </summary>
/// <remarks>
/// This class supplies the attached properties that can be used for simple region creation from XAML.
/// </remarks>
public class RegionManager : IRegionManager
{
#region Static members (for XAML support)
private static readonly WeakDelegatesManager updatingRegionsListeners = new WeakDelegatesManager();
/// <summary>
/// Identifies the RegionName attached property.
/// </summary>
/// <remarks>
/// When a control has both the <see cref="RegionNameProperty"/> and
/// <see cref="RegionManagerProperty"/> attached properties set to
/// a value different than <see langword="null" /> and there is a
/// <see cref="IRegionAdapter"/> mapping registered for the control, it
/// will create and adapt a new region for that control, and register it
/// in the <see cref="IRegionManager"/> with the specified region name.
/// </remarks>
public static readonly DependencyProperty RegionNameProperty = DependencyProperty.RegisterAttached(
"RegionName",
typeof(string),
typeof(RegionManager),
new PropertyMetadata(OnSetRegionNameCallback));
/// <summary>
/// Sets the <see cref="RegionNameProperty"/> attached property.
/// </summary>
/// <param name="regionTarget">The object to adapt. This is typically a container (i.e a control).</param>
/// <param name="regionName">The name of the region to register.</param>
public static void SetRegionName(DependencyObject regionTarget, string regionName)
{
if (regionTarget == null) throw new ArgumentNullException("regionTarget");
regionTarget.SetValue(RegionNameProperty, regionName);
}
/// <summary>
/// Gets the value for the <see cref="RegionNameProperty"/> attached property.
/// </summary>
/// <param name="regionTarget">The object to adapt. This is typically a container (i.e a control).</param>
/// <returns>The name of the region that should be created when
/// <see cref="RegionManagerProperty"/> is also set in this element.</returns>
public static string GetRegionName(DependencyObject regionTarget)
{
if (regionTarget == null) throw new ArgumentNullException("regionTarget");
return regionTarget.GetValue(RegionNameProperty) as string;
}
private static readonly DependencyProperty ObservableRegionProperty =
DependencyProperty.RegisterAttached("ObservableRegion", typeof(ObservableObject<IRegion>), typeof(RegionManager), null);
/// <summary>
/// Returns an <see cref="ObservableObject{T}"/> wrapper that can hold an <see cref="IRegion"/>. Using this wrapper
/// you can detect when an <see cref="IRegion"/> has been created by the <see cref="RegionAdapterBase{T}"/>.
///
/// If the <see cref="ObservableObject{T}"/> wrapper does not yet exist, a new wrapper will be created. When the region
/// gets created and assigned to the wrapper, you can use the <see cref="ObservableObject{T}.PropertyChanged"/> event
/// to get notified of that change.
/// </summary>
/// <param name="view">The view that will host the region. </param>
/// <returns>Wrapper that can hold an <see cref="IRegion"/> value and can notify when the <see cref="IRegion"/> value changes. </returns>
public static ObservableObject<IRegion> GetObservableRegion(DependencyObject view)
{
if (view == null) throw new ArgumentNullException("view");
ObservableObject<IRegion> regionWrapper = view.GetValue(ObservableRegionProperty) as ObservableObject<IRegion>;
if (regionWrapper == null)
{
regionWrapper = new ObservableObject<IRegion>();
view.SetValue(ObservableRegionProperty, regionWrapper);
}
return regionWrapper;
}
private static void OnSetRegionNameCallback(DependencyObject element, DependencyPropertyChangedEventArgs args)
{
if (!IsInDesignMode(element))
{
CreateRegion(element);
}
}
private static void CreateRegion(DependencyObject element)
{
IServiceLocator locator = ServiceLocator.Current;
DelayedRegionCreationBehavior regionCreationBehavior = locator.GetInstance<DelayedRegionCreationBehavior>();
regionCreationBehavior.TargetElement = element;
regionCreationBehavior.Attach();
}
/// <summary>
/// Identifies the RegionManager attached property.
/// </summary>
/// <remarks>
/// When a control has both the <see cref="RegionNameProperty"/> and
/// <see cref="RegionManagerProperty"/> attached properties set to
/// a value different than <see langword="null" /> and there is a
/// <see cref="IRegionAdapter"/> mapping registered for the control, it
/// will create and adapt a new region for that control, and register it
/// in the <see cref="IRegionManager"/> with the specified region name.
/// </remarks>
public static readonly DependencyProperty RegionManagerProperty =
DependencyProperty.RegisterAttached("RegionManager", typeof(IRegionManager), typeof(RegionManager), null);
/// <summary>
/// Gets the value of the <see cref="RegionNameProperty"/> attached property.
/// </summary>
/// <param name="target">The target element.</param>
/// <returns>The <see cref="IRegionManager"/> attached to the <paramref name="target"/> element.</returns>
public static IRegionManager GetRegionManager(DependencyObject target)
{
if (target == null) throw new ArgumentNullException("target");
return (IRegionManager)target.GetValue(RegionManagerProperty);
}
/// <summary>
/// Sets the <see cref="RegionManagerProperty"/> attached property.
/// </summary>
/// <param name="target">The target element.</param>
/// <param name="value">The value.</param>
public static void SetRegionManager(DependencyObject target, IRegionManager value)
{
if (target == null) throw new ArgumentNullException("target");
target.SetValue(RegionManagerProperty, value);
}
/// <summary>
/// Identifies the RegionContext attached property.
/// </summary>
public static readonly DependencyProperty RegionContextProperty =
DependencyProperty.RegisterAttached("RegionContext", typeof(object), typeof(RegionManager), new PropertyMetadata(OnRegionContextChanged));
private static void OnRegionContextChanged(DependencyObject depObj, DependencyPropertyChangedEventArgs e)
{
if (RegionContext.GetObservableContext(depObj).Value != e.NewValue)
{
RegionContext.GetObservableContext(depObj).Value = e.NewValue;
}
}
/// <summary>
/// Gets the value of the <see cref="RegionContextProperty"/> attached property.
/// </summary>
/// <param name="target">The target element.</param>
/// <returns>The region context to pass to the contained views.</returns>
public static object GetRegionContext(DependencyObject target)
{
if (target == null) throw new ArgumentNullException("target");
return target.GetValue(RegionContextProperty);
}
/// <summary>
/// Sets the <see cref="RegionContextProperty"/> attached property.
/// </summary>
/// <param name="target">The target element.</param>
/// <param name="value">The value.</param>
public static void SetRegionContext(DependencyObject target, object value)
{
if (target == null) throw new ArgumentNullException("target");
target.SetValue(RegionContextProperty, value);
}
/// <summary>
/// Notification used by attached behaviors to update the region managers appropriatelly if needed to.
/// </summary>
/// <remarks>This event uses weak references to the event handler to prevent this static event of keeping the
/// target element longer than expected.</remarks>
public static event EventHandler UpdatingRegions
{
add { updatingRegionsListeners.AddListener(value); }
remove { updatingRegionsListeners.RemoveListener(value); }
}
/// <summary>
/// Notifies attached behaviors to update the region managers appropriatelly if needed to.
/// </summary>
/// <remarks>
/// This method is normally called internally, and there is usually no need to call this from user code.
/// </remarks>
public static void UpdateRegions()
{
try
{
updatingRegionsListeners.Raise(null, EventArgs.Empty);
}
catch (TargetInvocationException ex)
{
Exception rootException = ex.GetRootException();
throw new UpdateRegionsException(string.Format(CultureInfo.CurrentCulture,
Resources.UpdateRegionException, rootException), ex.InnerException);
}
}
private static bool IsInDesignMode(DependencyObject element)
{
return DesignerProperties.GetIsInDesignMode(element);
}
#endregion
private readonly RegionCollection regionCollection;
/// <summary>
/// Initializes a new instance of <see cref="RegionManager"/>.
/// </summary>
public RegionManager()
{
regionCollection = new RegionCollection(this);
}
/// <summary>
/// Gets a collection of <see cref="IRegion"/> that identify each region by name. You can use this collection to add or remove regions to the current region manager.
/// </summary>
/// <value>A <see cref="IRegionCollection"/> with all the registered regions.</value>
public IRegionCollection Regions
{
get { return regionCollection; }
}
/// <summary>
/// Creates a new region manager.
/// </summary>
/// <returns>A new region manager that can be used as a different scope from the current region manager.</returns>
public IRegionManager CreateRegionManager()
{
return new RegionManager();
}
private class RegionCollection : IRegionCollection
{
private readonly IRegionManager regionManager;
private readonly List<IRegion> regions;
public RegionCollection(IRegionManager regionManager)
{
this.regionManager = regionManager;
this.regions = new List<IRegion>();
}
public event NotifyCollectionChangedEventHandler CollectionChanged;
public IEnumerator<IRegion> GetEnumerator()
{
UpdateRegions();
return this.regions.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public IRegion this[string regionName]
{
get
{
UpdateRegions();
IRegion region = GetRegionByName(regionName);
if (region == null)
{
throw new KeyNotFoundException(string.Format(CultureInfo.CurrentUICulture, Resources.RegionNotInRegionManagerException, regionName));
}
return region;
}
}
public void Add(IRegion region)
{
if (region == null) throw new ArgumentNullException("region");
UpdateRegions();
if (region.Name == null)
{
throw new InvalidOperationException(Resources.RegionNameCannotBeEmptyException);
}
if (this.GetRegionByName(region.Name) != null)
{
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
Resources.RegionNameExistsException, region.Name));
}
this.regions.Add(region);
region.RegionManager = this.regionManager;
this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, region, 0));
}
public bool Remove(string regionName)
{
UpdateRegions();
bool removed = false;
IRegion region = GetRegionByName(regionName);
if (region != null)
{
removed = true;
this.regions.Remove(region);
region.RegionManager = null;
this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, region, 0));
}
return removed;
}
public bool ContainsRegionWithName(string regionName)
{
UpdateRegions();
return GetRegionByName(regionName) != null;
}
private IRegion GetRegionByName(string regionName)
{
return this.regions.FirstOrDefault(r => r.Name == regionName);
}
private void OnCollectionChanged(NotifyCollectionChangedEventArgs notifyCollectionChangedEventArgs)
{
var handler = this.CollectionChanged;
if (handler != null)
{
handler(this, notifyCollectionChangedEventArgs);
}
}
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// Material.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
#endregion
namespace MultipassLightingSample
{
public class Material
{
//graphics and Game references
Effect effectInstance;
EffectParameter lightsParameterValue;
ContentManager content;
GraphicsDevice device;
private Texture diffuseTexture = null;
private Texture specularTexture = null;
private ModelMesh currentMesh = null;
private ModelMeshPart currentMeshPart = null;
//shadow parameters
private float textureURepsValue = 2f;
private float textureVRepsValue = 2f;
private float specularPowerValue = 4f;
private float specularIntensityValue = 200f;
private string diffuseTextureNameValue = null;
private string specularTextureNameValue = null;
private Color colorValue = Color.White;
#region Initialization
public Material(ContentManager contentManager, GraphicsDevice graphicsDevice,
Effect baseEffect)
{
if (graphicsDevice == null)
{
throw new ArgumentNullException("graphicsDevice");
}
device = graphicsDevice;
if (contentManager == null)
{
throw new ArgumentNullException("contentManager");
}
content = contentManager;
if (baseEffect == null)
{
throw new ArgumentNullException("baseEffect");
}
//clone the material effect instances
//see the MaterialsAndLights sample for more details
effectInstance = baseEffect.Clone(device);
effectInstance.CurrentTechnique =
effectInstance.Techniques[0];
device = graphicsDevice;
// Set the defaults for the effect
effectInstance.Parameters["specularPower"].SetValue(specularPowerValue);
effectInstance.Parameters["specularIntensity"].SetValue(
specularIntensityValue);
effectInstance.Parameters["materialColor"].SetValue(colorValue.ToVector4());
effectInstance.Parameters["textureUReps"].SetValue(textureURepsValue);
effectInstance.Parameters["textureVReps"].SetValue(textureVRepsValue);
lightsParameterValue = effectInstance.Parameters["lights"];
}
public void SetTexturedMaterial(Color color, float specularPower,
float specularIntensity, string diffuseTextureName,
string specularTextureName, float textureUReps, float textureVReps)
{
Color = color;
SpecularIntensity = specularIntensity;
SpecularPower = specularPower;
DiffuseTexture = diffuseTextureName;
SpecularTexture = specularTextureName;
TextureVReps = textureVReps;
TextureUReps = textureUReps;
}
public void SetBasicProperties(Color color, float specularPower, float
specularIntensity)
{
Color = color;
SpecularIntensity = specularIntensity;
SpecularPower = specularPower;
}
#endregion
#region Material Properties
public string SpecularTexture
{
set
{
specularTextureNameValue = value;
if (specularTextureNameValue == null)
{
specularTexture = null;
effectInstance.Parameters["specularTexture"].SetValue(
(Texture)null);
effectInstance.Parameters["specularTexEnabled"].SetValue(false);
}
else
{
specularTexture = content.Load<Texture>("Textures\\" +
specularTextureNameValue);
effectInstance.Parameters["specularTexture"].SetValue(
specularTexture);
effectInstance.Parameters["specularTexEnabled"].SetValue(true);
}
}
get
{
return specularTextureNameValue;
}
}
public string DiffuseTexture
{
set
{
diffuseTextureNameValue = value;
if (diffuseTextureNameValue == null)
{
diffuseTexture = null;
effectInstance.Parameters["diffuseTexture"].SetValue((Texture)null);
effectInstance.Parameters["diffuseTexEnabled"].SetValue(false);
}
else
{
diffuseTexture = content.Load<Texture>("Textures\\" +
diffuseTextureNameValue);
effectInstance.Parameters["diffuseTexture"].SetValue(
diffuseTexture);
effectInstance.Parameters["diffuseTexEnabled"].SetValue(true);
}
}
get
{
return diffuseTextureNameValue;
}
}
public Color Color
{
set
{
colorValue = value;
effectInstance.Parameters["materialColor"].SetValue(
colorValue.ToVector4());
}
get
{
return colorValue;
}
}
public float SpecularIntensity
{
set
{
specularIntensityValue = value;
effectInstance.Parameters["specularIntensity"].SetValue(
specularIntensityValue);
}
get
{
return specularIntensityValue;
}
}
public float SpecularPower
{
set
{
specularPowerValue = value;
effectInstance.Parameters["specularPower"].SetValue(specularPowerValue);
}
get
{
return specularPowerValue;
}
}
public float TextureUReps
{
set
{
textureURepsValue = value;
effectInstance.Parameters["textureUReps"].SetValue(textureURepsValue);
}
get
{
return textureURepsValue;
}
}
public float TextureVReps
{
set
{
textureVRepsValue = value;
effectInstance.Parameters["textureVReps"].SetValue(textureVRepsValue);
}
get
{
return textureVRepsValue;
}
}
public EffectParameter LightsParameter
{
get
{
return lightsParameterValue;
}
}
#endregion
#region Draw Function
/// <summary>
/// This function sets up the material shader for a batch of draws
/// performed over multiple lights. It also renders an ambient
/// light pass on the geometry.
/// </summary>
/// <param name="model">The model that will be drawn in this batch.</param>
/// <param name="world">
/// The world matrix for this particular peice of geometry.
/// </param>
public void BeginBatch(Model model, ref Matrix world)
{
if (model == null)
{
throw new ArgumentNullException("model");
}
// our sample meshes only contain a single part, so we don't need to bother
// looping over the ModelMesh and ModelMeshPart collections. If the meshes
// were more complex, we would repeat all the following code for each part
currentMesh = model.Meshes[0];
currentMeshPart = currentMesh.MeshParts[0];
// set the vertex source to the mesh's vertex buffer
device.Vertices[0].SetSource(
currentMesh.VertexBuffer, currentMeshPart.StreamOffset,
currentMeshPart.VertexStride);
// set the vertex declaration
device.VertexDeclaration = currentMeshPart.VertexDeclaration;
// set the current index buffer to the sample mesh's index buffer
device.Indices = currentMesh.IndexBuffer;
//set the world parameter of this instance of the model
effectInstance.Parameters["world"].SetValue(world);
effectInstance.Begin(SaveStateMode.None);
//////////////////////////////////////////////////////////////
// Example 2.1: State Batching //
// //
// In this sample, the BeginBatch() function is responsible //
// for the one-time drawing of an ambient pass. This is a //
// simplification for the sake of sample code. The ambient //
// pass has the dual role of adding an ambient light effect //
// to the backbuffer, as well as pre-populating the depth //
// buffer for the subsequent additive alpha draws. Also, //
// notice that depth is written on this opaque pass, but //
// disabled for subsequent passes, as it is unnecessary //
// as the geometry does not change. //
//////////////////////////////////////////////////////////////
device.RenderState.DepthBufferWriteEnable = true;
device.RenderState.AlphaBlendEnable = false;
effectInstance.CurrentTechnique.Passes["Ambient"].Begin();
device.DrawIndexedPrimitives(
PrimitiveType.TriangleList, currentMeshPart.BaseVertex, 0,
currentMeshPart.NumVertices, currentMeshPart.StartIndex,
currentMeshPart.PrimitiveCount);
effectInstance.CurrentTechnique.Passes["Ambient"].End();
//Set up renderstates for point-light contributions
device.RenderState.AlphaBlendEnable = true;
device.RenderState.DepthBufferWriteEnable = false;
effectInstance.CurrentTechnique.Passes["PointLight"].Begin();
}
/// <summary>
/// The draw function for the material has been moved off to
/// the material. Sorting draws on the material is generally a
/// good way to reduce state switching and thusly CPU performance
/// overhead.
/// </summary>
public void DrawModel()
{
if (currentMesh == null)
{
throw new InvalidOperationException(
"DrawModel may only be called between begin/end pairs.");
}
//////////////////////////////////////////////////////////////
// Example 2.2: CommitChanges() //
// //
// In this draw function, we're assuming that the light //
// states have been changed. Therefore, CommitChanges() //
// is called implicitly to get the latest updates to the //
// "dirty" effect paramters before submitting the draw. //
//////////////////////////////////////////////////////////////
effectInstance.CommitChanges();
// sampleMesh contains all of the information required to draw
// the current mesh
device.DrawIndexedPrimitives(
PrimitiveType.TriangleList, currentMeshPart.BaseVertex, 0,
currentMeshPart.NumVertices, currentMeshPart.StartIndex,
currentMeshPart.PrimitiveCount);
}
public void EndBatch()
{
// EffectPass.End must be called when the effect is no longer needed
effectInstance.CurrentTechnique.Passes["PointLight"].End();
// likewise, Effect.End will end the current technique
effectInstance.End();
currentMeshPart = null;
currentMesh = null;
}
#endregion
}
}
| |
#region Licence...
/*
The MIT License (MIT)
Copyright (c) 2015 Oleg Shilo
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 Licence...
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Xml.Linq;
using Microsoft.Deployment.WindowsInstaller;
using WixSharp.Bootstrapper;
using IO = System.IO;
namespace WixSharp
{
//This code requires heavy optimization and refactoring. Toady it serves the purpose of refining the API.
public partial class Compiler
{
/// <summary>
/// Builds WiX Bootstrapper application from the specified <see cref="Bundle"/> project instance.
/// </summary>
/// <param name="project">The project.</param>
/// <param name="path">The path.</param>
/// <exception cref="System.ApplicationException">Wix compiler/linker cannot be found</exception>
public static string Build(Bundle project, string path)
{
path = path.ExpandEnvVars();
string oldCurrDir = Environment.CurrentDirectory;
try
{
//System.Diagnostics.Debug.Assert(false);
Compiler.TempFiles.Clear();
string compiler = Utils.PathCombine(WixLocation, "candle.exe");
string linker = Utils.PathCombine(WixLocation, "light.exe");
if (!IO.File.Exists(compiler) || !IO.File.Exists(linker))
{
Compiler.OutputWriteLine("Wix binaries cannot be found. Expected location is " + compiler.PathGetDirName());
throw new ApplicationException("Wix compiler/linker cannot be found");
}
else
{
if (!project.SourceBaseDir.IsEmpty())
Environment.CurrentDirectory = project.SourceBaseDir;
string wxsFile = BuildWxs(project);
string objFile = IO.Path.ChangeExtension(wxsFile, ".wixobj");
string pdbFile = IO.Path.ChangeExtension(wxsFile, ".wixpdb");
string extensionDlls = "";
// note we need to avoid possible duplications cause by non expanded envars
// %wix_location%\ext.dll vs c:\Program Files\...\ext.dll
foreach (string dll in project.WixExtensions.DistinctBy(x => x.ExpandEnvVars()))
extensionDlls += " -ext \"" + dll + "\"";
string wxsFiles = "";
foreach (string file in project.WxsFiles.Distinct())
wxsFiles += " \"" + file + "\"";
var candleOptions = CandleOptions + " " + project.CandleOptions;
string command = candleOptions + " " + extensionDlls + " \"" + wxsFile + "\" ";
string outDir = null;
if (wxsFiles.IsNotEmpty())
{
command += wxsFiles;
outDir = IO.Path.GetDirectoryName(wxsFile);
// if multiple files are specified candle expect a path for the -out switch
// or no path at all (use current directory)
// note the '\' character must be escaped twice: as a C# string and as a CMD char
if (outDir.IsNotEmpty())
command += $" -out \"{outDir}\\\\\"";
}
else
command += $" -out \"{objFile}\"";
command = command.ExpandEnvVars();
Run(compiler, command);
if (IO.File.Exists(objFile))
{
string outFile = wxsFile.PathChangeExtension(".exe");
if (path.IsNotEmpty())
outFile = path.PathGetFullPath().PathEnsureExtension(".exe");
outFile.DeleteIfExists();
string fragmentObjectFiles = project.WxsFiles
.Distinct()
.JoinBy(" ", file => "\"" + outDir.PathCombine(IO.Path.GetFileNameWithoutExtension(file)) + ".wixobj\"");
string lightOptions = LightOptions + " " + project.LightOptions;
if (fragmentObjectFiles.IsNotEmpty())
lightOptions += " " + fragmentObjectFiles;
Run(linker, lightOptions + " \"" + objFile + "\" -out \"" + outFile + "\"" + extensionDlls + " -cultures:" + project.Language);
if (IO.File.Exists(outFile))
{
Compiler.TempFiles.Add(wxsFile);
Compiler.OutputWriteLine("\n----------------------------------------------------------\n");
Compiler.OutputWriteLine("Bootstrapper file has been built: " + outFile + "\n");
Compiler.OutputWriteLine(" Name : " + project.Name);
Compiler.OutputWriteLine(" Version : " + project.Version);
Compiler.OutputWriteLine(" UpgradeCode: {" + project.UpgradeCode + "}\n");
if (!PreserveDbgFiles && !project.PreserveDbgFiles)
{
objFile.DeleteIfExists();
pdbFile.DeleteIfExists();
}
project.DigitalSignature?.Apply(outFile);
}
}
else
{
Compiler.OutputWriteLine("Cannot build " + wxsFile);
Trace.WriteLine("Cannot build " + wxsFile);
}
}
if (!PreserveTempFiles && !project.PreserveTempFiles)
foreach (var file in Compiler.TempFiles)
try
{
if (IO.File.Exists(file))
IO.File.Delete(file);
}
catch { }
}
finally
{
Environment.CurrentDirectory = oldCurrDir;
}
return path;
}
/// <summary>
/// Builds the WiX source file and generates batch file capable of building
/// WiX/MSI bootstrapper with WiX toolset.
/// </summary>
/// <param name="project">The project.</param>
/// <param name="path">The path to the batch file to be created.</param>
/// <exception cref="System.ApplicationException">Wix compiler/linker cannot be found</exception>
public static string BuildCmd(Bundle project, string path = null)
{
if (path == null)
path = IO.Path.GetFullPath(IO.Path.Combine(project.OutDir, "Build_" + project.OutFileName) + ".cmd");
path = path.ExpandEnvVars();
//System.Diagnostics.Debug.Assert(false);
string wixLocationEnvVar = $"set WixLocation={WixLocation}" + Environment.NewLine;
string compiler = Utils.PathCombine(WixLocation, "candle.exe");
string linker = Utils.PathCombine(WixLocation, "light.exe");
string batchFile = path;
if (!IO.File.Exists(compiler) || !IO.File.Exists(linker))
{
Compiler.OutputWriteLine("Wix binaries cannot be found. Expected location is " + IO.Path.GetDirectoryName(compiler));
throw new ApplicationException("Wix compiler/linker cannot be found");
}
else
{
string wxsFile = BuildWxs(project);
if (!project.SourceBaseDir.IsEmpty())
Environment.CurrentDirectory = project.SourceBaseDir;
string objFile = IO.Path.ChangeExtension(wxsFile, ".wixobj");
string pdbFile = IO.Path.ChangeExtension(wxsFile, ".wixpdb");
string extensionDlls = "";
// note we need to avoid possible duplications cause by non expanded envars
// %wix_location%\ext.dll vs c:\Program Files\...\ext.dll
foreach (string dll in project.WixExtensions.DistinctBy(x => x.ExpandEnvVars()))
extensionDlls += " -ext \"" + dll + "\"";
string wxsFiles = "";
foreach (string file in project.WxsFiles.Distinct())
wxsFiles += " \"" + file + "\"";
var candleOptions = CandleOptions + " " + project.CandleOptions;
string batchFileContent = wixLocationEnvVar + "\"" + compiler + "\" " + candleOptions + " " + extensionDlls +
" \"" + IO.Path.GetFileName(wxsFile) + "\" ";
string outDir = null;
if (wxsFiles.IsNotEmpty())
{
batchFileContent += wxsFiles;
outDir = IO.Path.GetDirectoryName(wxsFile);
// if multiple files are specified candle expect a path for the -out switch
// or no path at all (use current directory)
// note the '\' character must be escaped twice: as a C# string and as a CMD char
if (outDir.IsNotEmpty())
batchFileContent += $" -out \"{outDir}\\\\\"";
}
else
batchFileContent += $" -out \"{objFile}\"";
batchFileContent += "\r\n";
string fragmentObjectFiles = project.WxsFiles
.Distinct()
.JoinBy(" ", file => "\"" + outDir.PathCombine(IO.Path.GetFileNameWithoutExtension(file)) + ".wixobj\"");
string lightOptions = LightOptions + " " + project.LightOptions;
if (fragmentObjectFiles.IsNotEmpty())
lightOptions += " " + fragmentObjectFiles;
if (path.IsNotEmpty())
lightOptions += " -out \"" + IO.Path.ChangeExtension(objFile, ".exe") + "\"";
batchFileContent += "\"" + linker + "\" " + lightOptions + " \"" + objFile + "\" " + extensionDlls + " -cultures:" + project.Language + "\r\npause";
batchFileContent = batchFileContent.ExpandEnvVars();
using (var sw = new IO.StreamWriter(batchFile))
sw.Write(batchFileContent);
}
return path;
}
/// <summary>
/// Builds the WiX source file (*.wxs) from the specified <see cref="Bundle"/> instance.
/// </summary>
/// <param name="project">The project.</param>
/// <returns></returns>
public static string BuildWxs(Bundle project)
{
lock (typeof(Compiler))
{
if (Compiler.ClientAssembly.IsEmpty())
Compiler.ClientAssembly = Compiler.FindClientAssemblyInCallStack();
project.Validate();
lock (Compiler.AutoGeneration.WxsGenerationSynchObject)
{
var oldAlgorithm = AutoGeneration.CustomIdAlgorithm;
try
{
project.ResetAutoIdGeneration(supressWarning: false);
AutoGeneration.CustomIdAlgorithm = project.CustomIdAlgorithm ?? AutoGeneration.CustomIdAlgorithm;
string file = IO.Path.GetFullPath(IO.Path.Combine(project.OutDir, project.OutFileName) + ".wxs");
if (IO.File.Exists(file))
IO.File.Delete(file);
string extraNamespaces = project.WixNamespaces.Distinct()
.Select(x => x.StartsWith("xmlns:") ? x : "xmlns:" + x)
.ConcatItems(" ");
var wix3Namespace = "http://schemas.microsoft.com/wix/2006/wi";
var wix4Namespace = "http://wixtoolset.org/schemas/v4/wxs";
var wixNamespace = Compiler.IsWix4 ? wix4Namespace : wix3Namespace;
var doc = XDocument.Parse(
@"<?xml version=""1.0"" encoding=""utf-8""?>
" + $"<Wix xmlns=\"{wixNamespace}\" {extraNamespaces} " + @" >
</Wix>");
doc.Root.Add(project.ToXml());
AutoElements.NormalizeFilePaths(doc, project.SourceBaseDir, EmitRelativePaths);
project.InvokeWixSourceGenerated(doc);
AutoElements.ExpandCustomAttributes(doc, project);
if (WixSourceGenerated != null)
WixSourceGenerated(doc);
string xml = "";
using (IO.StringWriter sw = new StringWriterWithEncoding(Encoding.Default))
{
doc.Save(sw, SaveOptions.None);
xml = sw.ToString();
}
//of course you can use XmlTextWriter.WriteRaw but this is just a temporary quick'n'dirty solution
//http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2657663&SiteID=1
xml = xml.Replace("xmlns=\"\"", "");
DefaultWixSourceFormatedHandler(ref xml);
project.InvokeWixSourceFormated(ref xml);
if (WixSourceFormated != null)
WixSourceFormated(ref xml);
using (var sw = new IO.StreamWriter(file, false, Encoding.Default))
sw.WriteLine(xml);
Compiler.OutputWriteLine("\n----------------------------------------------------------\n");
Compiler.OutputWriteLine("Wix project file has been built: " + file + "\n");
project.InvokeWixSourceSaved(file);
if (WixSourceSaved != null)
WixSourceSaved(file);
return file;
}
finally
{
AutoGeneration.CustomIdAlgorithm = oldAlgorithm;
project.ResetAutoIdGeneration(supressWarning: true);
}
}
}
}
/// <summary>
/// Builds WiX Bootstrapper application from the specified <see cref="Bundle"/> project instance.
/// </summary>
/// <param name="project">The project.</param>
/// <returns></returns>
public static string Build(Bundle project)
{
string outFile = IO.Path.GetFullPath(IO.Path.Combine(project.OutDir, project.OutFileName) + ".exe");
Utils.EnsureFileDir(outFile);
if (IO.File.Exists(outFile))
IO.File.Delete(outFile);
Build(project, outFile);
return IO.File.Exists(outFile) ? outFile : null;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#if FEATURE_APPDOMAIN
using System;
using System.Collections.Generic;
// TYPELIBATTR clashes with the one in InteropServices.
using TYPELIBATTR = System.Runtime.InteropServices.ComTypes.TYPELIBATTR;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Microsoft.Build.Tasks;
using Xunit;
using Microsoft.Build.Shared;
using System.IO;
using Microsoft.Build.BackEnd;
using Shouldly;
namespace Microsoft.Build.UnitTests
{
sealed public class ResolveComReference_Tests
{
/// <summary>
/// Creates a valid task item that's modified later
/// </summary>
private TaskItem SetupTaskItem()
{
var item = new TaskItem();
item.SetMetadata(ComReferenceItemMetadataNames.guid, "{5C6D0C4D-D530-4B08-B22F-307CA6BFCB65}");
item.SetMetadata(ComReferenceItemMetadataNames.versionMajor, "1");
item.SetMetadata(ComReferenceItemMetadataNames.versionMinor, "0");
item.SetMetadata(ComReferenceItemMetadataNames.lcid, "0");
item.SetMetadata(ComReferenceItemMetadataNames.wrapperTool, "tlbimp");
return item;
}
private void AssertReference(ITaskItem item, bool valid, string attribute)
{
string missingOrInvalidAttribute;
Assert.Equal(ResolveComReference.VerifyReferenceMetadataForNameItem(item, out missingOrInvalidAttribute), valid);
Assert.Equal(missingOrInvalidAttribute, attribute);
}
private void AssertMetadataInitialized(ITaskItem item, string metadataName, string metadataValue)
{
Assert.Equal(item.GetMetadata(metadataName), metadataValue);
}
/// <summary>
/// Issue in this bug was an ArgumentNullException when ResolvedAssemblyReferences was null
/// </summary>
[Fact]
public void GetResolvedASsemblyReferenceSpecNotNull()
{
var task = new ResolveComReference();
Assert.NotNull(task.GetResolvedAssemblyReferenceItemSpecs());
}
[Fact]
public void TestSerializationAndDeserialization()
{
ResolveComReferenceCache cache = new("path1", "path2");
cache.componentTimestamps = new()
{
{ "first", DateTime.Now },
{ "second", DateTime.FromBinary(10000) },
};
ResolveComReferenceCache cache2 = null;
using (TestEnvironment env = TestEnvironment.Create())
{
TransientTestFile file = env.CreateFile();
cache.SerializeCache(file.Path, null);
cache2 = StateFileBase.DeserializeCache(file.Path, null, typeof(ResolveComReferenceCache)) as ResolveComReferenceCache;
}
cache2.tlbImpLocation.ShouldBe(cache.tlbImpLocation);
cache2.axImpLocation.ShouldBe(cache.axImpLocation);
cache2.componentTimestamps.Count.ShouldBe(cache.componentTimestamps.Count);
cache2.componentTimestamps["second"].ShouldBe(cache.componentTimestamps["second"]);
}
/*
* Method: CheckComReferenceAttributeVerificationForNameItems
*
* Checks if verification of Com reference item metadata works properly
*/
[Fact]
public void CheckComReferenceMetadataVerificationForNameItems()
{
// valid item
TaskItem item = SetupTaskItem();
AssertReference(item, true, "");
// invalid guid
item = SetupTaskItem();
item.SetMetadata(ComReferenceItemMetadataNames.guid, "{I'm pretty sure this is not a valid guid}");
AssertReference(item, false, ComReferenceItemMetadataNames.guid);
// missing guid
item = SetupTaskItem();
item.RemoveMetadata(ComReferenceItemMetadataNames.guid);
AssertReference(item, false, ComReferenceItemMetadataNames.guid);
// invalid verMajor
item = SetupTaskItem();
item.SetMetadata(ComReferenceItemMetadataNames.versionMajor, "eleventy one");
AssertReference(item, false, ComReferenceItemMetadataNames.versionMajor);
// missing verMajor
item = SetupTaskItem();
item.RemoveMetadata(ComReferenceItemMetadataNames.versionMajor);
AssertReference(item, false, ComReferenceItemMetadataNames.versionMajor);
// invalid verMinor
item = SetupTaskItem();
item.SetMetadata(ComReferenceItemMetadataNames.versionMinor, "eleventy one");
AssertReference(item, false, ComReferenceItemMetadataNames.versionMinor);
// missing verMinor
item = SetupTaskItem();
item.RemoveMetadata(ComReferenceItemMetadataNames.versionMinor);
AssertReference(item, false, ComReferenceItemMetadataNames.versionMinor);
// invalid lcid
item = SetupTaskItem();
item.SetMetadata(ComReferenceItemMetadataNames.lcid, "Mars-us");
AssertReference(item, false, ComReferenceItemMetadataNames.lcid);
// missing lcid - it's optional, so this should work ok
item = SetupTaskItem();
item.RemoveMetadata(ComReferenceItemMetadataNames.lcid);
AssertReference(item, true, String.Empty);
// invalid tool
item = SetupTaskItem();
item.SetMetadata(ComReferenceItemMetadataNames.wrapperTool, "crowbar");
AssertReference(item, false, ComReferenceItemMetadataNames.wrapperTool);
// missing tool - it's optional, so this should work ok
item = SetupTaskItem();
item.RemoveMetadata(ComReferenceItemMetadataNames.wrapperTool);
AssertReference(item, true, String.Empty);
}
/*
* Method: CheckComReferenceAttributeInitializationForNameItems
*
* Checks if missing optional attributes for COM name references get initialized correctly
*/
[Fact]
public void CheckComReferenceMetadataInitializationForNameItems()
{
// missing lcid - should get initialized to 0
TaskItem item = SetupTaskItem();
item.RemoveMetadata(ComReferenceItemMetadataNames.lcid);
ResolveComReference.InitializeDefaultMetadataForNameItem(item);
AssertMetadataInitialized(item, ComReferenceItemMetadataNames.lcid, "0");
// existing lcid - should not get modified
item = SetupTaskItem();
item.SetMetadata(ComReferenceItemMetadataNames.lcid, "1033");
ResolveComReference.InitializeDefaultMetadataForNameItem(item);
AssertMetadataInitialized(item, ComReferenceItemMetadataNames.lcid, "1033");
// missing wrapperTool - should get initialized to tlbimp
item = SetupTaskItem();
item.RemoveMetadata(ComReferenceItemMetadataNames.wrapperTool);
ResolveComReference.InitializeDefaultMetadataForNameItem(item);
AssertMetadataInitialized(item, ComReferenceItemMetadataNames.wrapperTool, ComReferenceTypes.tlbimp);
// existing wrapperTool - should not get modified
item = SetupTaskItem();
item.SetMetadata(ComReferenceItemMetadataNames.wrapperTool, ComReferenceTypes.aximp);
ResolveComReference.InitializeDefaultMetadataForNameItem(item);
AssertMetadataInitialized(item, ComReferenceItemMetadataNames.wrapperTool, ComReferenceTypes.aximp);
}
/*
* Method: CheckComReferenceAttributeInitializationForFileItems
*
* Checks if missing optional attributes for COM file references get initialized correctly
*/
[Fact]
public void CheckComReferenceMetadataInitializationForFileItems()
{
// missing wrapperTool - should get initialized to tlbimp
TaskItem item = SetupTaskItem();
item.RemoveMetadata(ComReferenceItemMetadataNames.wrapperTool);
ResolveComReference.InitializeDefaultMetadataForFileItem(item);
AssertMetadataInitialized(item, ComReferenceItemMetadataNames.wrapperTool, ComReferenceTypes.tlbimp);
// existing wrapperTool - should not get modified
item = SetupTaskItem();
item.SetMetadata(ComReferenceItemMetadataNames.wrapperTool, ComReferenceTypes.aximp);
ResolveComReference.InitializeDefaultMetadataForFileItem(item);
AssertMetadataInitialized(item, ComReferenceItemMetadataNames.wrapperTool, ComReferenceTypes.aximp);
}
/// <summary>
/// Helper function for creating a COM reference task item instance
/// </summary>
private TaskItem CreateComReferenceTaskItem(string itemSpec, string guid, string vMajor, string vMinor, string lcid, string wrapperType, string embedInteropTypes)
{
var item = new TaskItem(itemSpec);
item.SetMetadata(ComReferenceItemMetadataNames.guid, guid);
item.SetMetadata(ComReferenceItemMetadataNames.versionMajor, vMajor);
item.SetMetadata(ComReferenceItemMetadataNames.versionMinor, vMinor);
item.SetMetadata(ComReferenceItemMetadataNames.lcid, lcid);
item.SetMetadata(ComReferenceItemMetadataNames.wrapperTool, wrapperType);
item.SetMetadata(ItemMetadataNames.embedInteropTypes, embedInteropTypes);
return item;
}
/// <summary>
/// Helper function for creating a COM reference task item instance
/// </summary>
private TaskItem CreateComReferenceTaskItem(string itemSpec, string guid, string vMajor, string vMinor, string lcid, string wrapperType)
{
return CreateComReferenceTaskItem(itemSpec, guid, vMajor, vMinor, lcid, wrapperType, String.Empty);
}
/// <summary>
/// Test the ResolveComReference.TaskItemToTypeLibAttr method
/// </summary>
[Fact]
public void CheckTaskItemToTypeLibAttr()
{
Guid refGuid = Guid.NewGuid();
TaskItem reference = CreateComReferenceTaskItem("ref", refGuid.ToString(), "11", "0", "1033", ComReferenceTypes.tlbimp);
TYPELIBATTR refAttr = ResolveComReference.TaskItemToTypeLibAttr(reference);
Assert.Equal(refGuid, refAttr.guid); // "incorrect guid"
Assert.Equal(11, refAttr.wMajorVerNum); // "incorrect version major"
Assert.Equal(0, refAttr.wMinorVerNum); // "incorrect version minor"
Assert.Equal(1033, refAttr.lcid); // "incorrect lcid"
}
/// <summary>
/// Helper function for creating a ComReferenceInfo object using an existing TaskInfo object and
/// typelib name/path. The type lib pointer will obviously not be initialized, so this object cannot
/// be used in any code that uses it.
/// </summary>
private ComReferenceInfo CreateComReferenceInfo(ITaskItem taskItem, string typeLibName, string typeLibPath)
{
var referenceInfo = new ComReferenceInfo();
referenceInfo.taskItem = taskItem;
referenceInfo.attr = ResolveComReference.TaskItemToTypeLibAttr(taskItem);
referenceInfo.typeLibName = typeLibName;
referenceInfo.fullTypeLibPath = typeLibPath;
referenceInfo.strippedTypeLibPath = typeLibPath;
referenceInfo.typeLibPointer = null;
return referenceInfo;
}
/// <summary>
/// Create a few test references for unit tests
/// </summary>
private void CreateTestReferences(
out ComReferenceInfo axRefInfo, out ComReferenceInfo tlbRefInfo, out ComReferenceInfo piaRefInfo,
out TYPELIBATTR axAttr, out TYPELIBATTR tlbAttr, out TYPELIBATTR piaAttr, out TYPELIBATTR notInProjectAttr)
{
// doing my part to deplete the worldwide guid reserves...
Guid axGuid = Guid.NewGuid();
Guid tlbGuid = Guid.NewGuid();
Guid piaGuid = Guid.NewGuid();
// create reference task items
TaskItem axTaskItem = CreateComReferenceTaskItem("axref", axGuid.ToString(), "1", "0", "1033", ComReferenceTypes.aximp);
TaskItem tlbTaskItem = CreateComReferenceTaskItem("tlbref", tlbGuid.ToString(), "5", "1", "0", ComReferenceTypes.tlbimp);
TaskItem piaTaskItem = CreateComReferenceTaskItem("piaref", piaGuid.ToString(), "999", "444", "123", ComReferenceTypes.primary);
// create reference infos
axRefInfo = CreateComReferenceInfo(axTaskItem, "AxRefLibName", "AxRefLibPath");
tlbRefInfo = CreateComReferenceInfo(tlbTaskItem, "TlbRefLibName", "TlbRefLibPath");
piaRefInfo = CreateComReferenceInfo(piaTaskItem, "PiaRefLibName", "PiaRefLibPath");
// get the references' typelib attributes
axAttr = ResolveComReference.TaskItemToTypeLibAttr(axTaskItem);
tlbAttr = ResolveComReference.TaskItemToTypeLibAttr(tlbTaskItem);
piaAttr = ResolveComReference.TaskItemToTypeLibAttr(piaTaskItem);
// create typelib attributes not matching any of the project refs
notInProjectAttr = new TYPELIBATTR();
notInProjectAttr.guid = tlbGuid;
notInProjectAttr.wMajorVerNum = 5;
notInProjectAttr.wMinorVerNum = 1;
notInProjectAttr.lcid = 1033;
}
/// <summary>
/// Unit test for the ResolveComReference.IsExistingProjectReference() method
/// </summary>
[Fact]
public void CheckIsExistingProjectReference()
{
TYPELIBATTR axAttr, tlbAttr, piaAttr, notInProjectAttr;
ComReferenceInfo axRefInfo, tlbRefInfo, piaRefInfo;
CreateTestReferences(out axRefInfo, out tlbRefInfo, out piaRefInfo,
out axAttr, out tlbAttr, out piaAttr, out notInProjectAttr);
var rcr = new ResolveComReference();
// populate the ResolveComReference's list of project references
rcr.allProjectRefs = new List<ComReferenceInfo>();
rcr.allProjectRefs.Add(axRefInfo);
rcr.allProjectRefs.Add(tlbRefInfo);
rcr.allProjectRefs.Add(piaRefInfo);
// find the Ax ref, matching with any type of reference - should NOT find it
bool retValue = rcr.IsExistingProjectReference(axAttr, null, out ComReferenceInfo referenceInfo);
Assert.True(!retValue && referenceInfo == null); // "ActiveX ref should NOT be found for any type of ref"
// find the Ax ref, matching with aximp types - should find it
retValue = rcr.IsExistingProjectReference(axAttr, ComReferenceTypes.aximp, out referenceInfo);
Assert.True(retValue && referenceInfo == axRefInfo); // "ActiveX ref should be found for aximp ref types"
// find the Ax ref, matching with tlbimp types - should NOT find it
retValue = rcr.IsExistingProjectReference(axAttr, ComReferenceTypes.tlbimp, out referenceInfo);
Assert.True(!retValue && referenceInfo == null); // "ActiveX ref should NOT be found for tlbimp ref types"
// find the Tlb ref, matching with any type of reference - should find it
retValue = rcr.IsExistingProjectReference(tlbAttr, null, out referenceInfo);
Assert.True(retValue && referenceInfo == tlbRefInfo); // "Tlb ref should be found for any type of ref"
// find the Tlb ref, matching with tlbimp types - should find it
retValue = rcr.IsExistingProjectReference(tlbAttr, ComReferenceTypes.tlbimp, out referenceInfo);
Assert.True(retValue && referenceInfo == tlbRefInfo); // "Tlb ref should be found for tlbimp ref types"
// find the Tlb ref, matching with pia types - should NOT find it
retValue = rcr.IsExistingProjectReference(tlbAttr, ComReferenceTypes.primary, out referenceInfo);
Assert.True(!retValue && referenceInfo == null); // "Tlb ref should NOT be found for primary ref types"
// find the Pia ref, matching with any type of reference - should find it
retValue = rcr.IsExistingProjectReference(piaAttr, null, out referenceInfo);
Assert.True(retValue && referenceInfo == piaRefInfo); // "Pia ref should be found for any type of ref"
// find the Pia ref, matching with pia types - should find it
retValue = rcr.IsExistingProjectReference(piaAttr, ComReferenceTypes.primary, out referenceInfo);
Assert.True(retValue && referenceInfo == piaRefInfo); // "Pia ref should be found for pia ref types"
// find the Pia ref, matching with pia types - should NOT find it
retValue = rcr.IsExistingProjectReference(piaAttr, ComReferenceTypes.aximp, out referenceInfo);
Assert.True(!retValue && referenceInfo == null); // "Pia ref should NOT be found for aximp ref types"
// try to find a non existing reference
retValue = rcr.IsExistingProjectReference(notInProjectAttr, null, out referenceInfo);
Assert.True(!retValue && referenceInfo == null); // "not in project ref should not be found"
}
/// <summary>
/// Unit test for the ResolveComReference.IsExistingDependencyReference() method
/// </summary>
[Fact]
public void CheckIsExistingDependencyReference()
{
TYPELIBATTR axAttr, tlbAttr, piaAttr, notInProjectAttr;
ComReferenceInfo axRefInfo, tlbRefInfo, piaRefInfo;
CreateTestReferences(out axRefInfo, out tlbRefInfo, out piaRefInfo,
out axAttr, out tlbAttr, out piaAttr, out notInProjectAttr);
var rcr = new ResolveComReference();
// populate the ResolveComReference's list of project references
rcr.allDependencyRefs = new List<ComReferenceInfo>();
rcr.allDependencyRefs.Add(axRefInfo);
rcr.allDependencyRefs.Add(tlbRefInfo);
rcr.allDependencyRefs.Add(piaRefInfo);
// find the Ax ref - should find it
bool retValue = rcr.IsExistingDependencyReference(axAttr, out ComReferenceInfo referenceInfo);
Assert.True(retValue && referenceInfo == axRefInfo); // "ActiveX ref should be found"
// find the Tlb ref - should find it
retValue = rcr.IsExistingDependencyReference(tlbAttr, out referenceInfo);
Assert.True(retValue && referenceInfo == tlbRefInfo); // "Tlb ref should be found"
// find the Pia ref - should find it
retValue = rcr.IsExistingDependencyReference(piaAttr, out referenceInfo);
Assert.True(retValue && referenceInfo == piaRefInfo); // "Pia ref should be found"
// try to find a non existing reference - should not find it
retValue = rcr.IsExistingDependencyReference(notInProjectAttr, out referenceInfo);
Assert.True(!retValue && referenceInfo == null); // "not in project ref should not be found"
// Now, try to resolve a non-existent ComAssemblyReference.
string path;
IComReferenceResolver resolver = (IComReferenceResolver)rcr;
Assert.False(resolver.ResolveComAssemblyReference("MyAssembly", out path));
Assert.Null(path);
}
/// <summary>
/// ResolveComReference automatically adds missing tlbimp references for aximp references.
/// This test verifies we actually create the missing references.
/// </summary>
[Fact]
public void CheckAddMissingTlbReference()
{
TYPELIBATTR axAttr, tlbAttr, piaAttr, notInProjectAttr;
ComReferenceInfo axRefInfo, tlbRefInfo, piaRefInfo;
CreateTestReferences(out axRefInfo, out tlbRefInfo, out piaRefInfo,
out axAttr, out tlbAttr, out piaAttr, out notInProjectAttr);
var rcr = new ResolveComReference();
rcr.BuildEngine = new MockEngine();
// populate the ResolveComReference's list of project references
rcr.allProjectRefs = new List<ComReferenceInfo>();
rcr.allProjectRefs.Add(axRefInfo);
rcr.allProjectRefs.Add(tlbRefInfo);
rcr.allProjectRefs.Add(piaRefInfo);
rcr.AddMissingTlbReferences();
Assert.Equal(4, rcr.allProjectRefs.Count); // "There should be four references now"
ComReferenceInfo newTlbInfo = (ComReferenceInfo)rcr.allProjectRefs[3];
Assert.Equal(axRefInfo.primaryOfAxImpRef, newTlbInfo); // "axRefInfo should hold back reference to tlbRefInfo"
Assert.True(ComReference.AreTypeLibAttrEqual(newTlbInfo.attr, axRefInfo.attr)); // "The added reference should have the same attributes as the Ax reference"
Assert.Equal(newTlbInfo.typeLibName, axRefInfo.typeLibName); // "The added reference should have the same type lib name as the Ax reference"
Assert.Equal(newTlbInfo.strippedTypeLibPath, axRefInfo.strippedTypeLibPath); // "The added reference should have the same type lib path as the Ax reference"
Assert.Equal(newTlbInfo.taskItem.ItemSpec, axRefInfo.taskItem.ItemSpec); // "The added reference should have the same task item spec as the Ax reference"
Assert.Equal(newTlbInfo.taskItem.GetMetadata(ComReferenceItemMetadataNames.wrapperTool), ComReferenceTypes.primaryortlbimp); // "The added reference should have the tlbimp/primary wrapper tool"
rcr.AddMissingTlbReferences();
Assert.Equal(4, rcr.allProjectRefs.Count); // "There should still be four references"
}
[Fact]
public void BothKeyFileAndKeyContainer()
{
var rcr = new ResolveComReference();
var e = new MockEngine();
rcr.BuildEngine = e;
rcr.KeyFile = "foo";
rcr.KeyContainer = "bar";
Assert.False(rcr.Execute());
e.AssertLogContains("MSB3300");
}
[Fact]
public void DelaySignWithoutEitherKeyFileOrKeyContainer()
{
var rcr = new ResolveComReference();
var e = new MockEngine();
rcr.BuildEngine = e;
rcr.DelaySign = true;
Assert.False(rcr.Execute());
e.AssertLogContains("MSB3301");
}
/// <summary>
/// Test if assemblies located in the gac get their CopyLocal attribute set to False
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void CheckSetCopyLocalToFalseOnEmbedInteropTypesAssemblies()
{
string gacPath = @"C:\windows\gac";
ResolveComReference rcr = new ResolveComReference();
rcr.BuildEngine = new MockEngine();
// the matrix of TargetFrameworkVersion values we are testing
string[] fxVersions =
{
"v2.0",
"v3.0",
"v3.5",
"v4.0"
};
for (int i = 0; i < fxVersions.Length; i++)
{
string fxVersion = fxVersions[i];
var taskItems = new List<ITaskItem>();
var nonGacNoPrivate = new TaskItem(@"C:\windows\gar\test1.dll");
nonGacNoPrivate.SetMetadata(ItemMetadataNames.embedInteropTypes, "true");
var gacNoPrivate = new TaskItem(@"C:\windows\gac\assembly1.dll");
gacNoPrivate.SetMetadata(ItemMetadataNames.embedInteropTypes, "true");
var nonGacPrivateFalse = new TaskItem(@"C:\windows\gar\test1.dll");
nonGacPrivateFalse.SetMetadata(ItemMetadataNames.privateMetadata, "false");
nonGacPrivateFalse.SetMetadata(ItemMetadataNames.embedInteropTypes, "true");
var gacPrivateFalse = new TaskItem(@"C:\windows\gac\assembly1.dll");
gacPrivateFalse.SetMetadata(ItemMetadataNames.privateMetadata, "false");
gacPrivateFalse.SetMetadata(ItemMetadataNames.embedInteropTypes, "true");
var nonGacPrivateTrue = new TaskItem(@"C:\windows\gar\test1.dll");
nonGacPrivateTrue.SetMetadata(ItemMetadataNames.privateMetadata, "true");
nonGacPrivateTrue.SetMetadata(ItemMetadataNames.embedInteropTypes, "true");
var gacPrivateTrue = new TaskItem(@"C:\windows\gac\assembly1.dll");
gacPrivateTrue.SetMetadata(ItemMetadataNames.privateMetadata, "true");
gacPrivateTrue.SetMetadata(ItemMetadataNames.embedInteropTypes, "true");
taskItems.Add(nonGacNoPrivate);
taskItems.Add(gacNoPrivate);
taskItems.Add(nonGacPrivateFalse);
taskItems.Add(gacPrivateFalse);
taskItems.Add(nonGacPrivateTrue);
taskItems.Add(gacPrivateTrue);
rcr.TargetFrameworkVersion = fxVersion;
rcr.SetFrameworkVersionFromString(rcr.TargetFrameworkVersion);
rcr.SetCopyLocalToFalseOnGacOrNoPIAAssemblies(taskItems, gacPath);
bool enabledNoPIA = false;
switch (fxVersion)
{
case "v4.0":
enabledNoPIA = true;
break;
default:
break;
}
// if Private is missing, by default GAC items are CopyLocal=false, non GAC CopyLocal=true
Assert.Equal(nonGacNoPrivate.GetMetadata(ItemMetadataNames.copyLocal), enabledNoPIA ? "false" : "true");
Assert.Equal(gacNoPrivate.GetMetadata(ItemMetadataNames.copyLocal), enabledNoPIA ? "false" : "false");
// if Private is set, it takes precedence
Assert.Equal(nonGacPrivateFalse.GetMetadata(ItemMetadataNames.copyLocal), enabledNoPIA ? "false" : "false");
Assert.Equal(gacPrivateFalse.GetMetadata(ItemMetadataNames.copyLocal), enabledNoPIA ? "false" : "false");
Assert.Equal(nonGacPrivateTrue.GetMetadata(ItemMetadataNames.copyLocal), enabledNoPIA ? "false" : "true");
Assert.Equal(gacPrivateTrue.GetMetadata(ItemMetadataNames.copyLocal), enabledNoPIA ? "false" : "true");
}
}
/// <summary>
/// Test if assemblies located in the gac get their CopyLocal attribute set to False
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void CheckSetCopyLocalToFalseOnGacAssemblies()
{
string gacPath = @"C:\windows\gac";
var rcr = new ResolveComReference();
rcr.BuildEngine = new MockEngine();
var taskItems = new List<ITaskItem>();
TaskItem nonGacNoPrivate = new TaskItem(@"C:\windows\gar\test1.dll");
TaskItem gacNoPrivate = new TaskItem(@"C:\windows\gac\assembly1.dll");
TaskItem nonGacPrivateFalse = new TaskItem(@"C:\windows\gar\test1.dll");
nonGacPrivateFalse.SetMetadata(ItemMetadataNames.privateMetadata, "false");
TaskItem gacPrivateFalse = new TaskItem(@"C:\windows\gac\assembly1.dll");
gacPrivateFalse.SetMetadata(ItemMetadataNames.privateMetadata, "false");
TaskItem nonGacPrivateTrue = new TaskItem(@"C:\windows\gar\test1.dll");
nonGacPrivateTrue.SetMetadata(ItemMetadataNames.privateMetadata, "true");
TaskItem gacPrivateTrue = new TaskItem(@"C:\windows\gac\assembly1.dll");
gacPrivateTrue.SetMetadata(ItemMetadataNames.privateMetadata, "true");
taskItems.Add(nonGacNoPrivate);
taskItems.Add(gacNoPrivate);
taskItems.Add(nonGacPrivateFalse);
taskItems.Add(gacPrivateFalse);
taskItems.Add(nonGacPrivateTrue);
taskItems.Add(gacPrivateTrue);
rcr.SetCopyLocalToFalseOnGacOrNoPIAAssemblies(taskItems, gacPath);
// if Private is missing, by default GAC items are CopyLocal=false, non GAC CopyLocal=true
Assert.Equal("true", nonGacNoPrivate.GetMetadata(ItemMetadataNames.copyLocal)); // "Non Gac assembly, missing Private, should be TRUE"
Assert.Equal("false", gacNoPrivate.GetMetadata(ItemMetadataNames.copyLocal)); // "Gac assembly, missing Private, should be FALSE"
// if Private is set, it takes precedence
Assert.Equal("false", nonGacPrivateFalse.GetMetadata(ItemMetadataNames.copyLocal)); // "Non Gac assembly, Private false, should be FALSE"
Assert.Equal("false", gacPrivateFalse.GetMetadata(ItemMetadataNames.copyLocal)); // "Gac assembly, Private false, should be FALSE"
Assert.Equal("true", nonGacPrivateTrue.GetMetadata(ItemMetadataNames.copyLocal)); // "Non Gac assembly, Private true, should be TRUE"
Assert.Equal("true", gacPrivateTrue.GetMetadata(ItemMetadataNames.copyLocal)); // "Gac assembly, Private true, should be TRUE"
}
/// <summary>
/// Make sure the conflicting references are detected correctly
/// </summary>
[Fact]
public void TestCheckForConflictingReferences()
{
TYPELIBATTR axAttr, tlbAttr, piaAttr, notInProjectAttr;
ComReferenceInfo axRefInfo, tlbRefInfo, piaRefInfo;
CreateTestReferences(out axRefInfo, out tlbRefInfo, out piaRefInfo,
out axAttr, out tlbAttr, out piaAttr, out notInProjectAttr);
var rcr = new ResolveComReference();
rcr.BuildEngine = new MockEngine();
// populate the ResolveComReference's list of project references
rcr.allProjectRefs = new List<ComReferenceInfo>();
rcr.allProjectRefs.Add(axRefInfo);
rcr.allProjectRefs.Add(tlbRefInfo);
rcr.allProjectRefs.Add(piaRefInfo);
// no conflicts should be found with just the three initial refs
Assert.True(rcr.CheckForConflictingReferences());
Assert.Equal(3, rcr.allProjectRefs.Count);
// duplicate refs should not be treated as conflicts
ComReferenceInfo referenceInfo = new ComReferenceInfo(tlbRefInfo);
rcr.allProjectRefs.Add(referenceInfo);
referenceInfo = new ComReferenceInfo(axRefInfo);
rcr.allProjectRefs.Add(referenceInfo);
referenceInfo = new ComReferenceInfo(piaRefInfo);
rcr.allProjectRefs.Add(referenceInfo);
Assert.True(rcr.CheckForConflictingReferences());
Assert.Equal(6, rcr.allProjectRefs.Count);
// tlb and ax refs with same lib name but different attributes should be considered conflicting
// We don't care about typelib name conflicts for PIA refs, because we don't have to create wrappers for them
var conflictTlb = new ComReferenceInfo(tlbRefInfo);
conflictTlb.attr = notInProjectAttr;
rcr.allProjectRefs.Add(conflictTlb);
var conflictAx = new ComReferenceInfo(axRefInfo);
conflictAx.attr = notInProjectAttr;
rcr.allProjectRefs.Add(conflictAx);
var piaRef = new ComReferenceInfo(piaRefInfo);
piaRef.attr = notInProjectAttr;
rcr.allProjectRefs.Add(piaRef);
Assert.False(rcr.CheckForConflictingReferences());
// ... and conflicting references should have been removed
Assert.Equal(7, rcr.allProjectRefs.Count);
Assert.DoesNotContain(conflictTlb, rcr.allProjectRefs);
Assert.DoesNotContain(conflictAx, rcr.allProjectRefs);
Assert.Contains(piaRef, rcr.allProjectRefs);
}
/// <summary>
/// In order to make ResolveComReferences multitargetable, two properties, ExecuteAsTool
/// and SdkToolsPath were added. In order to have correct behavior when using pre-4.0
/// toolsversions, ExecuteAsTool must default to true, and the paths to the tools will be the
/// v3.5 path. It is difficult to verify the tool paths in a unit test, however, so
/// this was done by ad hoc testing and will be maintained by the dev suites.
/// </summary>
[Fact]
public void MultiTargetingDefaultSetCorrectly()
{
ResolveComReference t = new ResolveComReference();
Assert.True(t.ExecuteAsTool); // "ExecuteAsTool should default to true"
}
/// <summary>
/// When calling AxImp.exe directly, the runtime-callable wrapper needs to be
/// passed via the /rcw switch, so RCR needs to make sure that the ax reference knows about
/// its corresponding TLB wrapper.
/// </summary>
[Fact]
public void AxReferenceKnowsItsRCWCreateTlb()
{
CheckAxReferenceRCWTlbExists(RcwStyle.GenerateTlb /* have RCR create the TLB reference */, false /* don't include TLB version in the interop name */);
}
/// <summary>
/// When calling AxImp.exe directly, the runtime-callable wrapper needs to be
/// passed via the /rcw switch, so RCR needs to make sure that the ax reference knows about
/// its corresponding TLB wrapper.
/// </summary>
[Fact]
public void AxReferenceKnowsItsRCWCreateTlb_IncludeVersion()
{
CheckAxReferenceRCWTlbExists(RcwStyle.GenerateTlb /* have RCR create the TLB reference */, true /* include TLB version in the interop name */);
}
/// <summary>
/// When calling AxImp.exe directly, the runtime-callable wrapper needs to be
/// passed via the /rcw switch, so RCR needs to make sure that the ax reference knows about
/// its corresponding TLB wrapper.
/// </summary>
[Fact]
public void AxReferenceKnowsItsRCWTlbExists()
{
CheckAxReferenceRCWTlbExists(RcwStyle.PreexistingTlb /* pass in the TLB reference */, false /* don't include TLB version in the interop name */);
}
/// <summary>
/// When calling AxImp.exe directly, the runtime-callable wrapper needs to be
/// passed via the /rcw switch, so RCR needs to make sure that the ax reference knows about
/// its corresponding TLB wrapper.
///
/// Tests that still works when IncludeVersionInInteropName = true
/// </summary>
[Fact]
public void AxReferenceKnowsItsRCWTlbExists_IncludeVersion()
{
CheckAxReferenceRCWTlbExists(RcwStyle.PreexistingTlb /* pass in the TLB reference */, true /* include TLB version in the interop name */);
}
/// <summary>
/// When calling AxImp.exe directly, the runtime-callable wrapper needs to be
/// passed via the /rcw switch, so RCR needs to make sure that the ax reference knows about
/// its corresponding TLB wrapper.
/// </summary>
[Fact]
public void AxReferenceKnowsItsRCWPiaExists()
{
CheckAxReferenceRCWTlbExists(RcwStyle.PreexistingPia /* pass in the TLB reference */, false /* don't include version in the interop name */);
}
/// <summary>
/// When calling AxImp.exe directly, the runtime-callable wrapper needs to be
/// passed via the /rcw switch, so RCR needs to make sure that the ax reference knows about
/// its corresponding TLB wrapper.
///
/// Tests that still works when IncludeVersionInInteropName = true
/// </summary>
[Fact]
public void AxReferenceKnowsItsRCWPiaExists_IncludeVersion()
{
CheckAxReferenceRCWTlbExists(RcwStyle.PreexistingPia /* pass in the PIA reference */, true /* include version in the interop name */);
}
private enum RcwStyle { GenerateTlb, PreexistingTlb, PreexistingPia };
/// <summary>
/// Helper method that will new up an AX and matching TLB reference, and verify that the AX reference
/// sets its RCW appropriately.
/// </summary>
private void CheckAxReferenceRCWTlbExists(RcwStyle rcwStyle, bool includeVersionInInteropName)
{
Guid axGuid = Guid.NewGuid();
ComReferenceInfo tlbRefInfo;
var rcr = new ResolveComReference();
rcr.BuildEngine = new MockEngine();
rcr.IncludeVersionInInteropName = includeVersionInInteropName;
rcr.allProjectRefs = new List<ComReferenceInfo>();
TaskItem axTaskItem = CreateComReferenceTaskItem("ref", axGuid.ToString(), "1", "2", "1033", ComReferenceTypes.aximp);
ComReferenceInfo axRefInfo = CreateComReferenceInfo(axTaskItem, "RefLibName", "RefLibPath");
rcr.allProjectRefs.Add(axRefInfo);
switch (rcwStyle)
{
case RcwStyle.GenerateTlb: break;
case RcwStyle.PreexistingTlb:
{
TaskItem tlbTaskItem = CreateComReferenceTaskItem("ref", axGuid.ToString(), "1", "2", "1033", ComReferenceTypes.tlbimp, "true");
tlbRefInfo = CreateComReferenceInfo(tlbTaskItem, "RefLibName", "RefLibPath");
rcr.allProjectRefs.Add(tlbRefInfo);
break;
}
case RcwStyle.PreexistingPia:
{
TaskItem tlbTaskItem = CreateComReferenceTaskItem("ref", axGuid.ToString(), "1", "2", "1033", ComReferenceTypes.primary, "true");
tlbRefInfo = CreateComReferenceInfo(tlbTaskItem, "RefLibName", "RefLibPath");
rcr.allProjectRefs.Add(tlbRefInfo);
break;
}
}
rcr.AddMissingTlbReferences();
Assert.Equal(2, rcr.allProjectRefs.Count); // "Should be two references"
tlbRefInfo = rcr.allProjectRefs[1];
var embedInteropTypes = tlbRefInfo.taskItem.GetMetadata(ItemMetadataNames.embedInteropTypes);
Assert.Equal("false", embedInteropTypes); // "The tlb wrapper for the activex control should have EmbedInteropTypes=false not " + embedInteropTypes);
Assert.True(ComReference.AreTypeLibAttrEqual(tlbRefInfo.attr, axRefInfo.attr)); // "reference information should be the same"
Assert.Equal(TlbReference.GetWrapperFileName
(
axRefInfo.taskItem.GetMetadata(ComReferenceItemMetadataNames.tlbReferenceName),
includeVersionInInteropName,
axRefInfo.attr.wMajorVerNum,
axRefInfo.attr.wMinorVerNum
),
TlbReference.GetWrapperFileName
(
tlbRefInfo.typeLibName,
includeVersionInInteropName,
tlbRefInfo.attr.wMajorVerNum,
tlbRefInfo.attr.wMinorVerNum
)); // "Expected Ax reference's RCW name to match the new TLB"
}
}
}
#endif
| |
/*
* Yeppp! library implementation
*
* This file is part of Yeppp! library and licensed under the New BSD license.
* See LICENSE.txt for the full text of the license.
*/
using System;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
namespace Spreads {
internal interface INativeLibraryLoader {
IntPtr LoadLibrary(string path);
bool UnloadLibrary(IntPtr library);
IntPtr FindFunction(IntPtr library, string function);
}
internal sealed class WindowsLibraryLoader : INativeLibraryLoader {
IntPtr INativeLibraryLoader.LoadLibrary(string path) {
return WindowsLibraryLoader.LoadLibraryW(path);
}
bool INativeLibraryLoader.UnloadLibrary(IntPtr library) {
return WindowsLibraryLoader.FreeLibrary(library);
}
IntPtr INativeLibraryLoader.FindFunction(IntPtr library, string function) {
return WindowsLibraryLoader.GetProcAddress(library, function);
}
[DllImport("kernel32", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true)]
private static extern IntPtr LoadLibraryW(string path);
[DllImport("kernel32", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool FreeLibrary(IntPtr library);
[DllImport("kernel32", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true)]
private static extern IntPtr GetProcAddress(IntPtr library, string function);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool SetDllDirectory(string lpPathName);
}
internal abstract class UnixLibraryLoader : INativeLibraryLoader {
IntPtr INativeLibraryLoader.LoadLibrary(string path) {
int flags = GetDLOpenFlags();
return UnixLibraryLoader.dlopen(path, flags);
}
bool INativeLibraryLoader.UnloadLibrary(IntPtr library) {
return UnixLibraryLoader.dlclose(library) == 0;
}
IntPtr INativeLibraryLoader.FindFunction(IntPtr library, string function) {
return UnixLibraryLoader.dlsym(library, function);
}
protected abstract int GetDLOpenFlags();
[DllImport("dl", CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr dlopen([MarshalAs(UnmanagedType.LPStr)] string path, int flags);
[DllImport("dl", CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr dlsym(IntPtr library, [MarshalAs(UnmanagedType.LPStr)] string function);
[DllImport("dl", CallingConvention = CallingConvention.Cdecl)]
private static extern int dlclose(IntPtr library);
}
internal sealed class AndroidLibraryLoader : UnixLibraryLoader {
protected override int GetDLOpenFlags() {
return RTLD_NOW | RTLD_LOCAL;
}
private const int RTLD_NOW = 0x00000000;
private const int RTLD_LOCAL = 0x00000000;
}
internal sealed class LinuxLibraryLoader : UnixLibraryLoader {
protected override int GetDLOpenFlags() {
return RTLD_NOW | RTLD_LOCAL;
}
private const int RTLD_NOW = 0x00000002;
private const int RTLD_LOCAL = 0x00000000;
}
internal sealed class OSXLibraryLoader : UnixLibraryLoader {
protected override int GetDLOpenFlags() {
return RTLD_NOW | RTLD_LOCAL;
}
private const int RTLD_NOW = 0x00000002;
private const int RTLD_LOCAL = 0x00000004;
}
internal class Loader {
public static NativeLibrary LoadNativeLibrary<T>(string libname) {
ABI abi = Process.DetectABI();
if (abi.Equals(ABI.Unknown))
return null;
INativeLibraryLoader loader = GetNativeLibraryLoader(abi);
if (loader == null)
return null;
string resource = GetNativeLibraryResource(abi, libname);
if (resource == null)
return null;
string path = ExtractResource<T>(resource);
if (path == null)
return null;
return new NativeLibrary(path, loader);
}
internal static Assembly ResolveManagedAssembly(object sender,
ResolveEventArgs args) {
var assemblyname = new AssemblyName(args.Name).Name;
var assemblyFileName = Path.Combine(Bootstrapper.Instance.AppFolder, assemblyname + ".dll");
var assembly = Assembly.LoadFrom(assemblyFileName);
return assembly;
}
public static INativeLibraryLoader GetNativeLibraryLoader(ABI abi) {
if (abi.IsWindows())
return new WindowsLibraryLoader();
else if (abi.IsLinux())
return new LinuxLibraryLoader();
else if (abi.IsOSX())
return new OSXLibraryLoader();
else
return null;
}
private static string GetNativeLibraryResource(ABI abi, string libname) {
if (abi.Equals(ABI.Windows_X86))
return "win/x32/" + libname + ".dll";
else if (abi.Equals(ABI.Windows_X86_64))
return "win/x64/" + libname + ".dll";
else if (abi.Equals(ABI.OSX_X86))
return "osx/x32/" + libname + ".dylib";
else if (abi.Equals(ABI.OSX_X86_64))
return "osx/x64/" + libname + ".dylib";
else if (abi.Equals(ABI.Linux_X86))
return "lin/x32/" + libname + ".so";
else if (abi.Equals(ABI.Linux_X86_64))
return "lin/x64/" + libname + ".so";
else if (abi.Equals(ABI.Linux_ARMEL))
return "lin/armel/" + libname + ".so";
else if (abi.Equals(ABI.Linux_ARMHF))
return "lin/armhf/" + libname + ".so";
else
return null;
}
public static string ExtractNativeResource<T>(string resource) {
var split = resource.Split('/');
// each process will have its own temp folder
string path = Path.Combine(Bootstrapper.Instance.TempFolder, split.Last());
try {
Assembly assembly = typeof(T).Assembly;
using (Stream resourceStream = assembly.GetManifestResourceStream(resource)) {
using (DeflateStream deflateStream = new DeflateStream(resourceStream, CompressionMode.Decompress)) {
using (
FileStream fileStream = new FileStream(path, FileMode.Create, FileAccess.Write,
FileShare.ReadWrite)) {
byte[] buffer = new byte[1048576];
int bytesRead;
do {
bytesRead = deflateStream.Read(buffer, 0, buffer.Length);
if (bytesRead != 0)
fileStream.Write(buffer, 0, bytesRead);
}
while (bytesRead != 0);
}
}
}
return path;
} catch {
File.Delete(path);
return null;
}
}
public static string ExtractResource<T>(string resource) {
// [os/][arch/]name.extension
var split = resource.Split('/');
string path = null;
if (split.Length == 1) {
// name.extension
path = Path.Combine(Bootstrapper.Instance.AppFolder, split[0]);
} else if (split.Length == 2 && (split[0].StartsWith("x") || split[0].StartsWith("ar"))) {
// arch.name.extension
path = Path.Combine(Bootstrapper.Instance.AppFolder, split[0], split[1]);
} else if (split.Length == 2) {
// os.name.extension
path = Path.Combine(Bootstrapper.Instance.AppFolder, split[1]);
} else if (split.Length == 3) {
// os.arch.name.extension, ignore os
path = Path.Combine(Bootstrapper.Instance.AppFolder, split[1], split[2]);
} else {
throw new ArgumentException("wrong resource name");
}
try {
Assembly assembly = typeof(T).Assembly;
using (Stream resourceStream = assembly.GetManifestResourceStream(resource)) {
using (DeflateStream deflateStream = new DeflateStream(resourceStream, CompressionMode.Decompress)) {
using (
FileStream fileStream = new FileStream(path, FileMode.Create, FileAccess.Write,
FileShare.ReadWrite)) {
byte[] buffer = new byte[1048576];
int bytesRead;
do {
bytesRead = deflateStream.Read(buffer, 0, buffer.Length);
if (bytesRead != 0)
fileStream.Write(buffer, 0, bytesRead);
}
while (bytesRead != 0);
}
}
}
} catch {
}
return path;
}
public static Assembly LoadManagedDll<T>(string name) {
// [os/][arch/]name.extension
var split = name.Split('/');
string path = null;
if (split.Length == 1) {
// name.extension
path = Path.Combine(Bootstrapper.Instance.AppFolder, split[0]);
} else {
throw new ArgumentException("wrong resource name");
}
Assembly assembly = typeof(T).Assembly;
using (Stream resourceStream = assembly.GetManifestResourceStream(name)) {
using (DeflateStream deflateStream = new DeflateStream(resourceStream, CompressionMode.Decompress)) {
using (
MemoryStream ms = new MemoryStream()) {
byte[] buffer = new byte[1048576];
int bytesRead;
do {
bytesRead = deflateStream.Read(buffer, 0, buffer.Length);
if (bytesRead != 0)
ms.Write(buffer, 0, bytesRead);
}
while (bytesRead != 0);
var bytes = ms.ToArray();
return Assembly.Load(bytes);
}
}
}
}
public static void CompressResource(string path) {
using (FileStream inFileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) {
using (
FileStream outFileStream = new FileStream(path + ".compressed", FileMode.Create, FileAccess.Write,
FileShare.ReadWrite)) {
using (DeflateStream deflateStream = new DeflateStream(outFileStream, CompressionMode.Compress)) {
byte[] buffer = new byte[1048576];
int bytesRead;
do {
bytesRead = inFileStream.Read(buffer, 0, buffer.Length);
if (bytesRead != 0)
deflateStream.Write(buffer, 0, bytesRead);
}
while (bytesRead != 0);
}
}
}
}
public static void CompressFolder(string path) {
//if (File.Exists(path + ".zip")) {
// //throw new ApplicationException("File already exists: " + path + ".zip");
//}
//else {
//}
try {
ZipFile.CreateFromDirectory(path, path + ".zip", CompressionLevel.Optimal, false);
} catch (IOException e) {
Console.WriteLine(e.ToString());
}
}
public static void ExtractFolder(string path, string targetPath) {
//var arch = ZipFile.OpenRead(path);
//foreach (var entry in arch.Entries) {
// entry.ExtractToFile(Path.Combine(targetPath, entry.FullName), true);
//}
try {
ZipFile.ExtractToDirectory(path, targetPath);
} catch (IOException e) {
Console.WriteLine(e.ToString());
}
}
}
}
| |
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using DocoptNet;
using Microsoft.Xtc.Common.Cli.Commands;
using Microsoft.Xtc.Common.Services;
using Microsoft.Xtc.TestCloud.Commands;
using Xunit;
namespace Microsoft.Xtc.TestCloud.Tests.Commands
{
public class UploadTestsCommandOptionsTests
{
[Fact]
public void AllOptionsShouldBeCorrectlyParsed()
{
var args = new[]
{
"test",
"testApp.apk",
"testApiKey",
"--user", "testUser@xamarin.com",
"--workspace", "c:\\TestWorkspace",
"--app-name", "testApp",
"--devices", "testDevices",
"--async",
"--async-json",
"--locale", "pl_PL",
"--series", "testSeries",
"--dsym-directory", "c:\\TestDSymDirectory",
"--test-parameters", "testKey1:testValue1:complex,testKey2:testValue2",
"--debug"
};
var uploadOptions = ParseOptions(args);
Assert.Equal("testApp.apk", uploadOptions.AppFile);
Assert.Equal("testApiKey", uploadOptions.ApiKey);
Assert.Equal("testUser@xamarin.com", uploadOptions.User);
Assert.Equal("c:\\TestWorkspace", uploadOptions.Workspace);
Assert.Equal("testApp", uploadOptions.AppName);
Assert.Equal("testDevices", uploadOptions.Devices);
Assert.True(uploadOptions.Async);
Assert.True(uploadOptions.AsyncJson);
Assert.Equal("pl_PL", uploadOptions.Locale);
Assert.Equal("testSeries", uploadOptions.Series);
Assert.Equal("c:\\TestDSymDirectory", uploadOptions.DSymDirectory);
Assert.True(uploadOptions.Debug);
Assert.Equal(
new[]
{
new KeyValuePair<string, string>("testKey1", "testValue1:complex"),
new KeyValuePair<string, string>("testKey2", "testValue2")
},
uploadOptions.TestParameters.ToArray());
}
[Fact]
public void DefaultValuesShouldBeCorrect()
{
var platformService = new PlatformService();
string apkPath;
if (platformService.CurrentPlatform == OSPlatform.Windows)
{
apkPath = "c:\\Temp\\TestApp.apk";
}
else
{
apkPath = "/tmp/app/TestApp.apk";
}
var args = new[]
{
"test",
apkPath,
"testApiKey",
"--user", "testUser@xamarin.com",
"--devices", "testDevices",
"--workspace", "."
};
var uploadOptions = ParseOptions(args);
Assert.Equal("en_US", uploadOptions.Locale);
Assert.False(uploadOptions.Async);
Assert.False(uploadOptions.AsyncJson);
Assert.False(uploadOptions.Debug);
Assert.Null(uploadOptions.Series);
Assert.Null(uploadOptions.DSymDirectory);
Assert.Null(uploadOptions.AppName);
}
[Fact]
public void ValidationShouldFailWhenAppFileDoesntExist()
{
var args = new[]
{
"test",
"z:\\not_existing_app.apk",
"testApiKey",
"--user", "testUser@xamarin.com",
"--workspace", ".",
"--devices", "testDevices"
};
var uploadOptions = ParseOptions(args);
Assert.Throws<CommandException>(() => uploadOptions.Validate());
}
[Fact]
public void ValidationShouldFailWhenWorkspaceDoesntExist()
{
var args = new[]
{
"test",
Assembly.GetEntryAssembly().Location,
"testApiKey",
"--user", "testUser@xamarin.com",
"--devices", "testDevices",
"--workspace", "z:\\not_existing_workspace_directory"
};
var uploadOptions = ParseOptions(args);
Assert.Throws<CommandException>(() => uploadOptions.Validate());
}
[Fact]
public void ValidationShouldFailWhenDSymDirectoryDoesntExist()
{
var args = new[]
{
"test",
Assembly.GetEntryAssembly().Location,
"testApiKey",
"--user", "testUser@xamarin.com",
"--devices", "testDevices",
"--workspace", ".",
"--dsym-directory", "z:\\not_existing_dSym_directory"
};
var uploadOptions = ParseOptions(args);
Assert.Throws<CommandException>(() => uploadOptions.Validate());
}
[Fact]
public void ParsingShouldFailWhenUserIsMissing()
{
var args = new[]
{
"test",
Assembly.GetEntryAssembly().Location,
"testApiKey",
"--devices", "testDevices",
};
Assert.Throws<DocoptInputErrorException>(() => ParseOptions(args));
}
[Fact]
public void ParsingShouldFailWhenDeviceSelectionIsMissing()
{
var args = new[]
{
"test",
Assembly.GetEntryAssembly().Location,
"testApiKey",
"--user", "testUser@xamarin.com@xamarin.com"
};
Assert.Throws<DocoptInputErrorException>(() => ParseOptions(args));
}
[Fact]
public void ParsingShouldFailWhenWorkspaceIsMissing()
{
var args = new[]
{
"test",
Assembly.GetEntryAssembly().Location,
"testApiKey",
"--user", "testUser@xamarin.com@xamarin.com",
"--devices", "testDevices",
};
Assert.Throws<DocoptInputErrorException>(() => ParseOptions(args));
}
[Fact]
public void ValidationShouldFailWhenTestParametersAreIncorrect()
{
var args = new[]
{
"test",
Assembly.GetEntryAssembly().Location,
"testApiKey",
"--user", "testUser@xamarin.com",
"--devices", "testDevices",
"--workspace", ".",
"--test-parameters", "testKey testValue"
};
var uploadOptions = ParseOptions(args);
Assert.Throws<CommandException>(() => uploadOptions.Validate());
}
[Fact]
public void ValidationShouldPassWhenAllRequiredOptionsAreCorrect()
{
var args = new[]
{
"test",
Assembly.GetEntryAssembly().Location,
"testApiKey",
"--user", "testUser@xamarin.com",
"--devices", "testDevices",
"--workspace", ".",
"--test-parameters", "testKey:testValue"
};
var uploadOptions = ParseOptions(args);
uploadOptions.Validate();
}
[Fact]
public void ValidationShouldFailWhenThereAreUnrecognizedOptions()
{
var args = new[]
{
"test",
"c:\\Temp\\testApp.apk",
"testApiKey",
"--user", "testUser@xamarin.com",
"--devices", "testDevices",
"--unrecognized-option"
};
var command = new UploadTestsCommand();
Assert.Throws<DocoptInputErrorException>(() => new Docopt().Apply(command.Syntax, args));
}
private UploadTestsCommandOptions ParseOptions(string[] args)
{
ICommand command = new UploadTestsCommand();
var docoptOptions = new Docopt().Apply(command.Syntax, args);
return new UploadTestsCommandOptions(docoptOptions);
}
}
}
| |
#region License
/* **********************************************************************************
* Copyright (c) Roman Ivantsov
* This source code is subject to terms and conditions of the MIT License
* for Irony. A copy of the license can be found in the License.txt file
* at the root of this distribution.
* By using this source code in any fashion, you are agreeing to be bound by the terms of the
* MIT License.
* You must not remove this notice from this software.
* **********************************************************************************/
#endregion License
using System;
namespace Irony.Parsing
{
public class SourceStream : ISourceStream
{
private readonly char[] chars;
private readonly int tabWidth;
private StringComparison stringComparison;
private int textLength;
public SourceStream(string text, bool caseSensitive, int tabWidth) : this(text, caseSensitive, tabWidth, new SourceLocation())
{
}
public SourceStream(string text, bool caseSensitive, int tabWidth, SourceLocation initialLocation)
{
this.text = text;
this.textLength = this.text.Length;
this.chars = this.text.ToCharArray();
this.stringComparison = caseSensitive ? StringComparison.InvariantCulture : StringComparison.InvariantCultureIgnoreCase;
this.tabWidth = tabWidth;
this.location = initialLocation;
this.previewPosition = this.location.Position;
if (this.tabWidth <= 1)
this.tabWidth = 8;
}
#region ISourceStream Members
private SourceLocation location;
private int previewPosition;
private string text;
public SourceLocation Location
{
[System.Diagnostics.DebuggerStepThrough]
get { return this.location; }
set { this.location = value; }
}
public char NextPreviewChar
{
[System.Diagnostics.DebuggerStepThrough]
get
{
if (this.previewPosition + 1 >= this.textLength)
return '\0';
return this.chars[this.previewPosition + 1];
}
}
public int Position
{
get
{
return this.location.Position;
}
set
{
if (this.location.Position != value)
this.SetNewPosition(value);
}
}
public char PreviewChar
{
[System.Diagnostics.DebuggerStepThrough]
get
{
if (this.previewPosition >= this.textLength)
return '\0';
return this.chars[this.previewPosition];
}
}
public int PreviewPosition
{
get { return this.previewPosition; }
set { this.previewPosition = value; }
}
public string Text
{
get { return this.text; }
}
public Token CreateToken(Terminal terminal)
{
var tokenText = this.GetPreviewText();
return new Token(terminal, this.Location, tokenText, tokenText);
}
public Token CreateToken(Terminal terminal, object value)
{
var tokenText = this.GetPreviewText();
return new Token(terminal, this.Location, tokenText, value);
}
[System.Diagnostics.DebuggerStepThrough]
public bool EOF()
{
return this.previewPosition >= this.textLength;
}
public bool MatchSymbol(string symbol)
{
try
{
int cmp = string.Compare(this.text, this.PreviewPosition, symbol, 0, symbol.Length, this.stringComparison);
return cmp == 0;
}
catch
{
// Exception may be thrown if Position + symbol.length > text.Length;
// this happens not often, only at the very end of the file, so we don't check this explicitly
// but simply catch the exception and return false. Again, try/catch block has no overhead
// if exception is not thrown.
return false;
}
}
#endregion ISourceStream Members
/// <summary>
/// To make debugging easier: show 20 chars from current position
/// </summary>
/// <returns></returns>
public override string ToString()
{
string result;
try
{
var p = this.Location.Position;
if (p + 20 < this.textLength)
// " ..."
result = this.text.Substring(p, 20) + Resources.LabelSrcHaveMore;
else
// "(EOF)"
result = this.text.Substring(p) + Resources.LabelEofMark;
}
catch (Exception)
{
result = this.PreviewChar + Resources.LabelSrcHaveMore;
}
// "[{0}], at {1}"
return string.Format(Resources.MsgSrcPosToString, result, this.Location);
}
/// <summary>
/// returns substring from Location.Position till (PreviewPosition - 1)
/// </summary>
/// <returns></returns>
private string GetPreviewText()
{
var until = this.previewPosition;
if (until > this.textLength)
until = this.textLength;
var p = this.location.Position;
return this.text.Substring(p, until - p);
}
/// <summary>
/// Computes the Location info (line, col) for a new source position.
/// </summary>
/// <param name="newPosition"></param>
private void SetNewPosition(int newPosition)
{
if (newPosition < Position)
throw new Exception(Resources.ErrCannotMoveBackInSource);
int p = this.Position;
int col = this.Location.Column;
int line = this.Location.Line;
while (p < newPosition)
{
var curr = this.chars[p];
switch (curr)
{
case '\n': line++; col = 0; break;
case '\r': break;
case '\t': col = (col / this.tabWidth + 1) * this.tabWidth; break;
default: col++; break;
}
p++;
}
this.Location = new SourceLocation(p, line, col);
}
}
}
| |
using System;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using Encog.Util;
using aXon.Rover.Annotations;
using aXon.Rover.Enumerations;
using aXon.Rover.Models;
using aXon.Rover.Utilities;
namespace aXon.Rover
{
public class RobotSimulator : INotifyPropertyChanged
{
private static readonly Random _random = new Random();
private double[] _position;
private double[] _destination;
private double[] _startPosition;
private double _startDistance;
private double _fuel;
private int _seconds;
private double _altitude;
private double _turns;
private double _rests;
private double _success;
private double _lastDistance;
private double _previousDistance;
private double _distanceToDestination;
private double _heading;
private CommandDirection _currentDirection;
public event OnPositionChanged PositionChanged;
protected virtual void OnPositionChanged1(Position args)
{
OnPositionChanged handler = PositionChanged;
if (handler != null) handler(this, args);
}
public RobotSimulator(Position source, Position destination)
{
Success = -10000;
Fuel = 9000;
Seconds = 0;
Altitude = 100000;
Rests = 0;
Turns = 0;
Position = new double[2] {source.X, source.Y};
Destination = new double[2] {destination.X, destination.Y};
StartPosition = new double[2] {source.X, source.Y};
CurrentDirection = CommandDirection.MoveForward;
DistanceToDestination = CalculateDistance();
LastDistance = DistanceToDestination;
PreviousDistance = LastDistance;
StartDistance = DistanceToDestination;
UpdateHeading();
}
public double[] Position
{
get { return _position; }
set
{
if (Equals(value, _position)) return;
_position = value;
OnPropertyChanged();
OnPropertyChanged("LeftDistance");
OnPropertyChanged("FrontDistance");
OnPropertyChanged("RightDistance");
OnPropertyChanged("BackDistance");
}
}
public double[] Destination
{
get { return _destination; }
set
{
if (Equals(value, _destination)) return;
_destination = value;
OnPropertyChanged();
OnPropertyChanged("Score");
OnPropertyChanged("Traveling");
}
}
public double[] StartPosition
{
get { return _startPosition; }
set
{
if (Equals(value, _startPosition)) return;
_startPosition = value;
OnPropertyChanged();
OnPropertyChanged("Score");
OnPropertyChanged("Traveling");
}
}
public double StartDistance
{
get { return _startDistance; }
set { _startDistance = value; }
}
public double Fuel
{
get { return _fuel; }
set
{
if (value.Equals(_fuel)) return;
_fuel = value;
OnPropertyChanged();
OnPropertyChanged("Score");
OnPropertyChanged("ShoudRest");
OnPropertyChanged("Traveling");
}
}
public int Seconds
{
get { return _seconds; }
set
{
if (value == _seconds) return;
_seconds = value;
OnPropertyChanged();
OnPropertyChanged("Score");
OnPropertyChanged("Traveling");
}
}
public double Altitude
{
get { return _altitude; }
set
{
if (value.Equals(_altitude)) return;
_altitude = value;
OnPropertyChanged();
}
}
public double Turns
{
get { return _turns; }
set
{
if (value.Equals(_turns)) return;
_turns = value;
OnPropertyChanged();
}
}
public double Rests
{
get { return _rests; }
set
{
if (value.Equals(_rests)) return;
_rests = value;
OnPropertyChanged();
OnPropertyChanged("Score");
}
}
public CommandDirection CurrentDirection
{
get { return _currentDirection; }
set
{
if (value == _currentDirection) return;
_currentDirection = value;
OnPropertyChanged();
}
}
public int Score
{
get
{
//double startdist = CalculateDistance(StartPosition, Destination);
//double lastdist = CalculateDistance();
////double closeness = startdist - lastdist;
////double traveled = startdist - closeness;
////double perctraverced = (startdist/traveled);
//if (Success > 0)
// perctraverced = 10;
return (int) ( Success + (Seconds*-1));
}
}
public double ShoudRest
{
get { return Fuel/200; }
}
public bool Traveling
{
get
{
if (DistanceToDestination == 0)
{
Success = 1000000;
return false;
}
double startdist = CalculateDistance(StartPosition, Destination);
double lastdist = CalculateDistance();
double perdist = 100000/startdist;
double closeness = lastdist*perdist;
if (PreviousDistance < DistanceToDestination)
{
Seconds *= 100;
Success = closeness*-1;
return false;
}
else
{
PreviousDistance = LastDistance;
LastDistance = DistanceToDestination;
}
if (Seconds >= 2000)
{
Seconds *= 100;
Success = closeness*-1;
return false;
}
if (Fuel == 0 && Seconds >= 2000 && DistanceToDestination > 0)
{
Seconds *= 100;
Success = closeness*-1;
return false;
}
return true;
}
}
public double Success
{
get { return _success; }
set
{
if (value.Equals(_success)) return;
_success = value;
OnPropertyChanged();
OnPropertyChanged("Score");
}
}
public double LastDistance
{
get { return _lastDistance; }
set
{
if (value.Equals(_lastDistance)) return;
_lastDistance = value;
OnPropertyChanged();
OnPropertyChanged("Traveling");
}
}
public double PreviousDistance
{
get { return _previousDistance; }
set
{
if (value.Equals(_previousDistance)) return;
_previousDistance = value;
OnPropertyChanged();
OnPropertyChanged("Traveling");
}
}
public double DistanceToDestination
{
get { return _distanceToDestination; }
set
{
if (value.Equals(_distanceToDestination)) return;
_distanceToDestination = value;
OnPropertyChanged();
OnPropertyChanged("Traveling");
}
}
public double LeftDistance
{
get
{
double col = Position[1];
return col;
}
}
public double FrontDistance
{
get
{
double row = Position[0];
double col = Position[1];
return row;
}
}
public double RightDistance
{
get
{
double row = Position[0];
double col = Position[1];
return col;
}
}
public double BackDistance
{
get
{
double row = Position[0];
return -row;
}
}
public double Heading
{
get { return _heading; }
set
{
if (value.Equals(_heading)) return;
_heading = value;
OnPropertyChanged();
}
}
private double CalculateDistance()
{
double xdist = Position[0] - Destination[0];
double ydist = Position[1] - Destination[1];
if (xdist < 0)
xdist = xdist*-1;
if (ydist < 0)
ydist = ydist*-1;
return xdist + ydist;
}
private double CalculateDistance(double[] source, double[] dest)
{
double xdist = source[0] - dest[0];
double ydist = source[1] - dest[1];
if (xdist < 0)
xdist = xdist*-1;
if (ydist < 0)
ydist = ydist*-1;
return xdist + ydist;
}
public void Turn(CommandDirection newDirection)
{
CurrentDirection = newDirection;
Seconds++;
//if (newDirection == RobotDirection.Rest)
//{
// Rests++;
// Fuel = 200;
// return;
//}
//if (Fuel > 0)
//{
// Fuel -= 1;
//}
if (!CanGoInDirection(newDirection))
{
return;
}
MoveToNewPostion(newDirection);
OnPositionChanged1(new Position(Position[0],Position[1]));
DistanceToDestination = CalculateDistance();
if (Altitude < 0)
Altitude = 0;
}
private void MoveToNewPostion(CommandDirection newDirection)
{
switch (newDirection)
{
case CommandDirection.MoveForward:
Position[0] = Position[0] - 1;
break;
case CommandDirection.TurnLeft:
Position[1] = Position[1] - 1;
break;
case CommandDirection.TurnRight:
Position[1] = Position[1] + 1;
break;
case CommandDirection.MoveInReverse:
Position[0] = Position[0] + 1;
break;
}
if (Position[0] < 0)
Position[0] = 0;
if (Position[1] < 0)
Position[1] = 0;
Position = new double[2]{Position[0],Position[1]};
try
{
lock (RobotContol.ConsoleLock)
{
//Console.SetCursorPosition((int) Position[0], (int) Position[1]);
//Console.Write('.');
}
}
catch
{
}
UpdateHeading();
}
private void UpdateHeading()
{
var src = new Position(Position[0], Position[1]);
var dest = new Position(Destination[0], Destination[1]);
var calc = new PositionBearingCalculator(new AngleConverter());
Heading = calc.CalculateBearing(src, dest);
}
public bool CanGoInDirection(CommandDirection newDirection)
{
var pos = new double[2]{Position[0],Position[1]};
switch (newDirection)
{
case CommandDirection.MoveForward:
pos[0] = pos[0] - 1;
break;
case CommandDirection.TurnLeft:
pos[1] = pos[1] - 1;
break;
case CommandDirection.TurnRight:
pos[1] = pos[1] + 1;
break;
case CommandDirection.MoveInReverse:
pos[0] = pos[0] + 1;
break;
}
if (pos[0] < 0)
pos[0] = 0;
if (pos[1] < 0)
pos[1] = 0;
var warpos =(from p in RobotContol.Warehouse.Positions where p.X == pos[0] && p.Y == pos[1] select p).FirstOrDefault();
if (warpos == null)
return false;
switch (warpos.MapMode)
{
case MapMode.ObstructionMode:
return false;
case MapMode.PersonMode:
return false;
case MapMode.StorageMode:
if (Destination[0] == pos[0] && Destination[1] == pos[1])
return true;
if (StartPosition[0] == pos[0] && StartPosition[1] == pos[1])
return true;
return false;
case MapMode.PickupMode:
if (Destination[0] == pos[0] && Destination[1] == pos[1])
return true;
if (StartPosition[0] == pos[0] && StartPosition[1] == pos[1])
return true;
return false;
case MapMode.ShipMode:
if (Destination[0] == pos[0] && Destination[1] == pos[1])
return true;
if (StartPosition[0] == pos[0] && StartPosition[1] == pos[1])
return true;
return false;
default:
return true;
}
}
public String Telemetry()
{
return string
.Format(
"time: {0} s, Fuel: {1} l, dist: {2} ft, dir: {3}, x: {4}, y: {5}, Score: {6}, Should Rest: {7}",
Seconds,
Fuel,
Format.FormatDouble(DistanceToDestination, 4),
CurrentDirection.ToString(), Position[0], Position[1], Score, ShoudRest);
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
public delegate void OnPositionChanged(object sender, Position args);
}
| |
// 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.
//
// Description:
// class for the main TypeConverterContext object passed to type converters
//
using System;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Xml;
using MS.Utility;
using System.Diagnostics;
using MS.Internal.Xaml.Parser;
#if PBTCOMPILER
namespace MS.Internal.Markup
#else
using System.Windows;
using System.Security;
using MS.Internal;
namespace System.Windows.Markup
#endif
{
#if PBTCOMPILER
///<summary>
/// The IUriContext interface allows elements (like Frame, PageViewer) and type converters
/// (like BitmapImage TypeConverters) a way to ensure that base uri is set on them by the
/// parser, codegen for xaml, baml and caml cases. The elements can then use this base uri
/// to navigate.
///</summary>
internal interface IUriContext
{
/// <summary>
/// Provides the base uri of the current context.
/// </summary>
Uri BaseUri
{
get;
set;
}
}
#endif
/// <summary>
/// Provides all the context information required by Parser
/// </summary>
#if PBTCOMPILER
internal class ParserContext : IUriContext
#else
public class ParserContext : IUriContext
#endif
{
#region Public Methods
/// <summary>
/// Constructor
/// </summary>
public ParserContext()
{
Initialize();
}
// Initialize the ParserContext to a known, default state. DO NOT wipe out
// data that may be able to be shared between seperate parses, such as the
// xamlTypeMapper and the map table.
internal void Initialize()
{
_xmlnsDictionary = null; // created on its first use
#if !PBTCOMPILER
_nameScopeStack = null;
#endif
_xmlLang = String.Empty;
_xmlSpace = String.Empty;
}
#if !PBTCOMPILER
/// <summary>
/// Constructor that takes the XmlParserContext.
/// A parserContext object will be built based on this.
/// </summary>
/// <param name="xmlParserContext">xmlParserContext to use</param>
public ParserContext(XmlParserContext xmlParserContext)
{
if (xmlParserContext == null)
{
throw new ArgumentNullException( "xmlParserContext" );
}
_xmlLang = xmlParserContext.XmlLang;
TypeConverter typeConverter = TypeDescriptor.GetConverter(typeof(XmlSpace));
if (typeConverter != null)
_xmlSpace = (string) typeConverter.ConvertToString(null, TypeConverterHelper.InvariantEnglishUS, xmlParserContext.XmlSpace);
else
_xmlSpace = String.Empty;
_xmlnsDictionary = new XmlnsDictionary() ;
if (xmlParserContext.BaseURI != null && xmlParserContext.BaseURI.Length > 0)
{
_baseUri = new Uri(xmlParserContext.BaseURI, UriKind.RelativeOrAbsolute);
}
XmlNamespaceManager xmlnsManager = xmlParserContext.NamespaceManager;
if (null != xmlnsManager)
{
foreach (string key in xmlnsManager)
{
_xmlnsDictionary.Add(key, xmlnsManager.LookupNamespace(key));
}
}
}
#endif
#if !PBTCOMPILER
/// <summary>
/// Constructor overload that takes an XmlReader, in order to
/// pull the BaseURI, Lang, and Space from it.
/// </summary>
internal ParserContext( XmlReader xmlReader )
{
if( xmlReader.BaseURI != null && xmlReader.BaseURI.Length != 0 )
{
BaseUri = new Uri( xmlReader.BaseURI );
}
XmlLang = xmlReader.XmlLang;
if( xmlReader.XmlSpace != System.Xml.XmlSpace.None )
{
XmlSpace = xmlReader.XmlSpace.ToString();
}
}
#endif
#if !PBTCOMPILER
/// <summary>
/// Constructor that takes the ParserContext.
/// A parserContext object will be built based on this.
/// </summary>
/// <param name="parserContext">xmlParserContext to use</param>
internal ParserContext(ParserContext parserContext)
{
_xmlLang = parserContext.XmlLang;
_xmlSpace = parserContext.XmlSpace;
_xamlTypeMapper = parserContext.XamlTypeMapper;
_mapTable = parserContext.MapTable;
_baseUri = parserContext.BaseUri;
_masterBracketCharacterCache = parserContext.MasterBracketCharacterCache;
_rootElement = parserContext._rootElement;
if (parserContext._nameScopeStack != null)
_nameScopeStack = (Stack)parserContext._nameScopeStack.Clone();
else
_nameScopeStack = null;
// Don't want to force the lazy init so we just set privates
_skipJournaledProperties = parserContext._skipJournaledProperties;
_xmlnsDictionary = null;
// when there are no namespace prefix mappings in incoming ParserContext,
// we are not going to create an empty XmlnsDictionary.
if (parserContext._xmlnsDictionary != null &&
parserContext._xmlnsDictionary.Count > 0)
{
_xmlnsDictionary = new XmlnsDictionary();
XmlnsDictionary xmlDictionaryFrom = parserContext.XmlnsDictionary;
if (null != xmlDictionaryFrom)
{
foreach (string key in xmlDictionaryFrom.Keys)
{
_xmlnsDictionary[key] = xmlDictionaryFrom[key];
}
}
}
}
#endif
/// <summary>
/// Constructs a cache of all the members in this particular type that have
/// MarkupExtensionBracketCharactersAttribute set on them. This cache is added to a master
/// cache which stores the BracketCharacter cache for each type.
/// </summary>
internal Dictionary<string, SpecialBracketCharacters> InitBracketCharacterCacheForType(Type type)
{
if (!MasterBracketCharacterCache.ContainsKey(type))
{
Dictionary<string, SpecialBracketCharacters> map = BuildBracketCharacterCacheForType(type);
MasterBracketCharacterCache.Add(type, map);
}
return MasterBracketCharacterCache[type];
}
/// <summary>
/// Pushes the context scope stack (modifications to the ParserContext only apply to levels below
/// the modification in the stack, except for the XamlTypeMapper property)
/// </summary>
internal void PushScope()
{
_repeat++;
_currentFreezeStackFrame.IncrementRepeatCount();
// Wait till the context needs XmlnsDictionary, create on first use.
if (_xmlnsDictionary != null)
_xmlnsDictionary.PushScope();
}
/// <summary>
/// Pops the context scope stack
/// </summary>
internal void PopScope()
{
// Pop state off of the _langSpaceStack
if (_repeat > 0)
{
_repeat--;
}
else
{
if (null != _langSpaceStack && _langSpaceStack.Count > 0)
{
_repeat = (int) _langSpaceStack.Pop();
_targetType = (Type) _langSpaceStack.Pop();
_xmlSpace = (string) _langSpaceStack.Pop();
_xmlLang = (string) _langSpaceStack.Pop();
}
}
// Pop state off of _currentFreezeStackFrame
if (!_currentFreezeStackFrame.DecrementRepeatCount())
{
// If the end of the current frame has been reached, pop
// the next frame off the freeze stack
_currentFreezeStackFrame = (FreezeStackFrame) _freezeStack.Pop();
}
// Wait till the context needs XmlnsDictionary, create on first use.
if (_xmlnsDictionary != null)
_xmlnsDictionary.PopScope();
}
/// <summary>
/// XmlNamespaceDictionary
/// </summary>
public XmlnsDictionary XmlnsDictionary
{
get
{
// Entry Point to others, initialize if null.
if (_xmlnsDictionary == null)
_xmlnsDictionary = new XmlnsDictionary();
return _xmlnsDictionary;
}
}
/// <summary>
/// XmlLang property
/// </summary>
public string XmlLang
{
get
{
return _xmlLang;
}
set
{
EndRepeat();
_xmlLang = (null == value ? String.Empty : value);
}
}
/// <summary>
/// XmlSpace property
/// </summary>
// (Why isn't this of type XmlSpace?)
public string XmlSpace
{
get
{
return _xmlSpace;
}
set
{
EndRepeat();
_xmlSpace = value;
}
}
//
// TargetType
//
// Keep track of the Style/Template TargetType's in the current context. This allows Setters etc
// to interpret properties without walking up the reader stack to see it. This is internal and
// hard-coded to target type, but the intent in the future is to generalize this so that we don't
// have to have the custom parser, and so that the designer can provide the same contextual information.
//
internal Type TargetType
{
get
{
return _targetType;
}
#if !PBTCOMPILER
set
{
EndRepeat();
_targetType = value;
}
#endif
}
// Items specific to XAML
/// <summary>
/// XamlTypeMapper that should be used when resolving XML
/// </summary>
public XamlTypeMapper XamlTypeMapper
{
get
{
return _xamlTypeMapper ;
}
set
{
// The BamlMapTable must always be kept in sync with the XamlTypeMapper. If
// the XamlTypeMapper changes, then the map table must also be reset.
if (_xamlTypeMapper != value)
{
_xamlTypeMapper = value;
_mapTable = new BamlMapTable(value);
_xamlTypeMapper.MapTable = _mapTable;
}
}
}
#if !PBTCOMPILER
/// <summary>
/// Gets or sets the list of INameScopes in parent chain
/// </summary>
internal Stack NameScopeStack
{
get
{
if (_nameScopeStack == null)
_nameScopeStack = new Stack(2);
return _nameScopeStack;
}
}
#endif
/// <summary>
/// Gets or sets the base Uri
/// </summary>
public Uri BaseUri
{
get
{
return _baseUri ;
}
set
{
_baseUri = value;
}
}
#if !PBTCOMPILER
/// <summary>
/// Should DependencyProperties marked with the Journal metadata flag be set or skipped?
/// </summary>
/// <value></value>
internal bool SkipJournaledProperties
{
get { return _skipJournaledProperties; }
set { _skipJournaledProperties = value; }
}
//
// The Assembly which hosts the Baml stream.
//
internal Assembly StreamCreatedAssembly
{
get { return _streamCreatedAssembly.Value; }
set { _streamCreatedAssembly.Value = value; }
}
#endif
/// <summary>
/// Operator for Converting a ParserContext to an XmlParserContext
/// </summary>
/// <param name="parserContext">ParserContext to Convert</param>
/// <returns>XmlParserContext</returns>
public static implicit operator XmlParserContext(ParserContext parserContext)
{
return ParserContext.ToXmlParserContext(parserContext);
}
/// <summary>
/// Operator for Converting a ParserContext to an XmlParserContext
/// </summary>
/// <param name="parserContext">ParserContext to Convert</param>
/// <returns>XmlParserContext</returns>
public static XmlParserContext ToXmlParserContext(ParserContext parserContext)
{
if (parserContext == null)
{
throw new ArgumentNullException( "parserContext" );
}
XmlNamespaceManager xmlnsMgr = new XmlNamespaceManager(new NameTable());
XmlSpace xmlSpace = System.Xml.XmlSpace.None;
if (parserContext.XmlSpace != null && parserContext.XmlSpace.Length != 0)
{
TypeConverter typeConverter = TypeDescriptor.GetConverter(typeof(System.Xml.XmlSpace));
if (null != typeConverter)
{
try
{
xmlSpace = (System.Xml.XmlSpace)typeConverter.ConvertFromString(null, TypeConverterHelper.InvariantEnglishUS, parserContext.XmlSpace);
}
catch (System.FormatException) // If it's not a valid space value, ignore it
{
xmlSpace = System.Xml.XmlSpace.None;
}
}
}
// We start getting Keys list only if we have non-empty dictionary
if (parserContext._xmlnsDictionary != null)
{
foreach (string key in parserContext._xmlnsDictionary.Keys)
{
xmlnsMgr.AddNamespace(key, parserContext._xmlnsDictionary[key]);
}
}
XmlParserContext xmlParserContext = new XmlParserContext(null, xmlnsMgr, parserContext.XmlLang, xmlSpace);
if( parserContext.BaseUri == null)
{
xmlParserContext.BaseURI = null;
}
else
{
string serializedSafe = parserContext.BaseUri.GetComponents(UriComponents.SerializationInfoString, UriFormat.SafeUnescaped);
Uri sameUri = new Uri(serializedSafe);
string cannonicalString = sameUri.GetComponents(UriComponents.SerializationInfoString, UriFormat.UriEscaped);
xmlParserContext.BaseURI = cannonicalString;
}
return xmlParserContext;
}
#endregion Public Methods
#region Internal
// Reset stack to default state
private void EndRepeat()
{
if (_repeat > 0)
{
if (null == _langSpaceStack)
{
_langSpaceStack = new Stack(1);
}
_langSpaceStack.Push(XmlLang);
_langSpaceStack.Push(XmlSpace);
_langSpaceStack.Push(TargetType);
_langSpaceStack.Push(_repeat);
_repeat = 0;
}
}
/// <summary>
/// LineNumber for the first character in the given
/// stream. This is used when parsing a section of a larger file so
/// that proper line number in the overall file can be calculated.
/// </summary>
internal int LineNumber
{
get { return _lineNumber; }
#if !PBTCOMPILER
set { _lineNumber = value; }
#endif
}
/// <summary>
/// LinePosition for the first character in the given
/// stream. This is used when parsing a section of a larger file so
/// that proper line positions in the overall file can be calculated.
/// </summary>
internal int LinePosition
{
get { return _linePosition; }
#if !PBTCOMPILER
set { _linePosition = value; }
#endif
}
#if !PBTCOMPILER
internal bool IsDebugBamlStream
{
get { return _isDebugBamlStream; }
set { _isDebugBamlStream = value; }
}
/// <summary>
/// Gets or sets the object at the root of the portion of the tree
/// currently being parsed. Note that this may not be the very top of the tree
/// if the parsing operation is scoped to a specific subtree, such as in Style
/// parsing.
/// </summary>
internal object RootElement
{
get { return _rootElement; }
set { _rootElement = value; }
}
// If this is false (default), then the parser does not own the stream and so if
// it has any defer loaded content, it needs to copy it into a byte array since
// the owner\caller will close the stream when parsing is complete. Currently, this
// is set to true only by the theme engine since the stream is a system-wide resource
// an dso will always be open for teh lifetime of the process laoding the theme and so
// it can be re-used for perf reasons.
internal bool OwnsBamlStream
{
get { return _ownsBamlStream; }
set { _ownsBamlStream = value; }
}
#endif
/// <summary>
/// Allows sharing a map table between instances of BamlReaders and Writers.
/// </summary>
internal BamlMapTable MapTable
{
get { return _mapTable; }
#if !PBTCOMPILER
set
{
// The XamlTypeMapper and the map table must always be kept in sync. If the
// map table changes, update the XamlTypeMapper also
if (_mapTable != value)
{
_mapTable = value;
_xamlTypeMapper = _mapTable.XamlTypeMapper;
_xamlTypeMapper.MapTable = _mapTable;
}
}
#endif
}
#if !PBTCOMPILER
internal IStyleConnector StyleConnector
{
get { return _styleConnector; }
set { _styleConnector = value; }
}
// Keep a cached ProvideValueProvider so that we don't have to keep re-creating one.
internal ProvideValueServiceProvider ProvideValueProvider
{
get
{
if (_provideValueServiceProvider == null)
{
_provideValueServiceProvider = new ProvideValueServiceProvider(this);
}
return _provideValueServiceProvider;
}
}
/// <summary>
/// This is used to resolve a StaticResourceId record within a deferred content
/// section against a StaticResourceExtension on the parent dictionary.
/// </summary>
internal List<object[]> StaticResourcesStack
{
get
{
if (_staticResourcesStack == null)
{
_staticResourcesStack = new List<object[]>();
}
return _staticResourcesStack;
}
}
/// <summary>
/// Says if we are we currently loading deferred content
/// </summary>
internal bool InDeferredSection
{
get { return (_staticResourcesStack != null && _staticResourcesStack.Count > 0); }
}
#endif
// Return a new Parser context that has the same instance variables as this instance, with
// only scope dependent variables deep copied. Variables that are not dependent on scope
// (such as the baml map table) are not deep copied.
#if !PBTCOMPILER
internal ParserContext ScopedCopy()
{
return ScopedCopy( true /* copyNameScopeStack */ );
}
#endif
#if !PBTCOMPILER
internal ParserContext ScopedCopy(bool copyNameScopeStack)
{
ParserContext context = new ParserContext();
context._baseUri = _baseUri;
context._skipJournaledProperties = _skipJournaledProperties;
context._xmlLang = _xmlLang;
context._xmlSpace = _xmlSpace;
context._repeat = _repeat;
context._lineNumber = _lineNumber;
context._linePosition = _linePosition;
context._isDebugBamlStream = _isDebugBamlStream;
context._mapTable = _mapTable;
context._xamlTypeMapper = _xamlTypeMapper;
context._targetType = _targetType;
context._streamCreatedAssembly.Value = _streamCreatedAssembly.Value;
context._rootElement = _rootElement;
context._styleConnector = _styleConnector;
// Copy the name scope stack, if necessary.
if (_nameScopeStack != null && copyNameScopeStack)
context._nameScopeStack = (_nameScopeStack != null) ? (Stack)_nameScopeStack.Clone() : null;
else
context._nameScopeStack = null;
// Deep copy only selected scope dependent instance variables
context._langSpaceStack = (_langSpaceStack != null) ? (Stack)_langSpaceStack.Clone() : null;
if (_xmlnsDictionary != null)
context._xmlnsDictionary = new XmlnsDictionary(_xmlnsDictionary);
else
context._xmlnsDictionary = null;
context._currentFreezeStackFrame = _currentFreezeStackFrame;
context._freezeStack = (_freezeStack != null) ? (Stack) _freezeStack.Clone() : null;
return context;
}
#endif
//
// This is called by a user of a parser context when it is a good time to drop unnecessary
// references (today, just an empty stack).
//
#if !PBTCOMPILER
internal void TrimState()
{
if( _nameScopeStack != null && _nameScopeStack.Count == 0 )
{
_nameScopeStack = null;
}
}
#endif
/// <summary>
/// Master cache of Bracket Characters which stores the BracketCharacter cache for each Type.
/// </summary>
internal Dictionary<Type, Dictionary<string, SpecialBracketCharacters>> MasterBracketCharacterCache
{
get
{
if (_masterBracketCharacterCache == null)
{
_masterBracketCharacterCache = new Dictionary<Type, Dictionary<string, SpecialBracketCharacters>>();
}
return _masterBracketCharacterCache;
}
}
// Return a new Parser context that has the same instance variables as this instance,
// will all scoped and non-scoped complex properties deep copied.
#if !PBTCOMPILER
internal ParserContext Clone()
{
ParserContext context = ScopedCopy();
// Deep copy only selected instance variables
context._mapTable = (_mapTable != null) ? _mapTable.Clone() : null;
context._xamlTypeMapper = (_xamlTypeMapper != null) ? _xamlTypeMapper.Clone() : null;
// Connect the XamlTypeMapper and bamlmaptable
context._xamlTypeMapper.MapTable = context._mapTable;
context._mapTable.XamlTypeMapper = context._xamlTypeMapper;
return context;
}
#endif
#if !PBTCOMPILER
// Set/Get whether or not Freezables within the current scope
// should be Frozen.
internal bool FreezeFreezables
{
get
{
return _currentFreezeStackFrame.FreezeFreezables;
}
set
{
// If the freeze flag isn't actually changing, we don't need to
// register a change
if (value != _currentFreezeStackFrame.FreezeFreezables)
{
// When this scope was entered the repeat count was initially incremented,
// indicating no _freezeFreezables state changes within this scope.
//
// Now that a state change has been found, we need to replace that no-op with
// a directive to restore the old state by un-doing the increment
// and pushing the stack frame
#if DEBUG
bool canDecrement =
#endif
_currentFreezeStackFrame.DecrementRepeatCount();
#if DEBUG
// We're replacing a no-op with a state change. Detect if we accidently
// start replacing actual state changes. This might happen if we allowed
// FreezeFreezable to be set twice within the same scope, for
// example.
Debug.Assert(canDecrement);
#endif
if (_freezeStack == null)
{
// Lazily allocate a _freezeStack if this is the first
// state change.
_freezeStack = new Stack();
}
// Save the old frame
_freezeStack.Push(_currentFreezeStackFrame);
// Set the new frame
_currentFreezeStackFrame.Reset(value);
}
}
}
internal bool TryCacheFreezable(string value, Freezable freezable)
{
if (FreezeFreezables)
{
if (freezable.CanFreeze)
{
if (!freezable.IsFrozen)
{
freezable.Freeze();
}
if (_freezeCache == null)
{
_freezeCache = new Dictionary<string, Freezable>();
}
_freezeCache.Add(value, freezable);
return true;
}
}
return false;
}
internal Freezable TryGetFreezable(string value)
{
Freezable freezable = null;
if (_freezeCache != null)
{
_freezeCache.TryGetValue(value, out freezable);
}
return freezable;
}
#endif
#endregion Internal
#region Date
private XamlTypeMapper _xamlTypeMapper;
private Uri _baseUri;
private XmlnsDictionary _xmlnsDictionary;
private String _xmlLang = String.Empty;
private String _xmlSpace = String.Empty;
private Stack _langSpaceStack;
private int _repeat;
private Type _targetType;
private Dictionary<Type, Dictionary<string, SpecialBracketCharacters>> _masterBracketCharacterCache;
#if !PBTCOMPILER
private bool _skipJournaledProperties;
private SecurityCriticalDataForSet<Assembly> _streamCreatedAssembly;
private bool _ownsBamlStream;
private ProvideValueServiceProvider _provideValueServiceProvider;
private IStyleConnector _styleConnector;
private Stack _nameScopeStack;
private List<object[]> _staticResourcesStack;
object _rootElement; // RootElement for the Page scoping [temporary, should be
// something like page name or baseUri]
#endif
/// <summary>
/// Looks up all properties via reflection on the given type, and scans through the attributes on all of them
/// to build a cache of properties which have MarkupExtensionBracketCharactersAttribute set on them.
/// </summary>
private Dictionary<string, SpecialBracketCharacters> BuildBracketCharacterCacheForType(Type extensionType)
{
Dictionary<string, SpecialBracketCharacters> cache = new Dictionary<string, SpecialBracketCharacters>(StringComparer.OrdinalIgnoreCase);
PropertyInfo[] propertyInfo = extensionType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
Type constructorArgumentType = null;
Type markupExtensionBracketCharacterType = null;
foreach (PropertyInfo property in propertyInfo)
{
string propertyName = property.Name;
string constructorArgumentName = null;
IList<CustomAttributeData> customAttributes = CustomAttributeData.GetCustomAttributes(property);
SpecialBracketCharacters bracketCharacters = null;
foreach (CustomAttributeData attributeData in customAttributes)
{
Type attributeType = attributeData.AttributeType;
Assembly xamlAssembly = attributeType.Assembly;
if (constructorArgumentType == null || markupExtensionBracketCharacterType == null)
{
constructorArgumentType =
xamlAssembly.GetType("System.Windows.Markup.ConstructorArgumentAttribute");
markupExtensionBracketCharacterType =
xamlAssembly.GetType("System.Windows.Markup.MarkupExtensionBracketCharactersAttribute");
}
if (attributeType.IsAssignableFrom(constructorArgumentType))
{
constructorArgumentName = attributeData.ConstructorArguments[0].Value as string;
}
else if (attributeType.IsAssignableFrom(markupExtensionBracketCharacterType))
{
if (bracketCharacters == null)
{
bracketCharacters = new SpecialBracketCharacters();
}
bracketCharacters.AddBracketCharacters((char)attributeData.ConstructorArguments[0].Value, (char)attributeData.ConstructorArguments[1].Value);
}
}
if (bracketCharacters != null)
{
bracketCharacters.EndInit();
cache.Add(propertyName, bracketCharacters);
if (constructorArgumentName != null)
{
cache.Add(constructorArgumentName, bracketCharacters);
}
}
}
return cache.Count == 0 ? null : cache;
}
// Struct that maintains both the freezeFreezable state & stack depth
// between freezeFreezable state changes
private struct FreezeStackFrame
{
internal void IncrementRepeatCount() { _repeatCount++; }
// Returns false when the count reaches 0 such that the decrement can not occur
internal bool DecrementRepeatCount()
{
if (_repeatCount > 0)
{
_repeatCount--;
return true;
}
else
{
return false;
}
}
#if !PBTCOMPILER
// Accessors for private state
internal bool FreezeFreezables
{
get { return _freezeFreezables; }
}
// Reset's this frame to a new scope. Only used with _currentFreezeStackFrame.
internal void Reset(bool freezeFreezables)
{
_freezeFreezables = freezeFreezables;
_repeatCount = 0;
}
// Whether or not Freezeables with the current scope should be Frozen
private bool _freezeFreezables;
#endif
// The number of frames until the next state change.
// We need to know how many times PopScope() is called until the
// state changes. That information is tracked by _repeatCount.
private int _repeatCount;
}
// First frame is maintained off of the _freezeStack to avoid allocating
// a Stack<FreezeStackFlag> for the common case where Freeze isn't specified.
FreezeStackFrame _currentFreezeStackFrame;
#if !PBTCOMPILER
// When cloning, it isn't necessary to copy this cache of freezables.
// This cache allows frozen freezables to use a shared instance and save on memory.
private Dictionary<string, Freezable> _freezeCache;
#endif
private Stack _freezeStack = null;
private int _lineNumber = 0; // number of lines between the start of the file and
// our starting point (the starting point of this context)
private int _linePosition=0; // default start ot left of first character which is a zero
private BamlMapTable _mapTable;
#if !PBTCOMPILER
private bool _isDebugBamlStream = false;
#endif
#endregion Data
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Globalization;
using System.Xml;
using System.Xml.Linq;
//using System.Xml.XPath;
using System.Text;
using System.IO;
using Microsoft.Test.ModuleCore;
namespace CoreXml.Test.XLinq
{
public partial class FunctionalTests : TestModule
{
public partial class XNodeBuilderTests : XLinqTestCase
{
public partial class TCCheckChars : BridgeHelpers
{
//[Variation(Id = 1, Desc = "CheckChars=true, invalid XML test WriteEntityRef", Priority = 1, Param = "EntityRef")]
//[Variation(Id = 2, Desc = "CheckChars=true, invalid XML test WriteSurrogateCharEntity", Priority = 1, Param = "SurrogateCharEntity")]
//[Variation(Id = 3, Desc = "CheckChars=true, invalid XML test WriteWhitespace", Priority = 1, Param = "Whitespace")]
//[Variation(Id = 4, Desc = "CheckChars=true, invalid name chars WriteDocType(name)", Priority = 1, Param = "WriteDocTypeName")]
public void checkChars_1()
{
char[] invalidXML = { '\u0000', '\u0008', '\u000B', '\u000C', '\u000E', '\u001F', '\uFFFE', '\uFFFF' };
XElement d = new XElement("a");
XmlWriter w = d.CreateWriter();
try
{
switch (Variation.Param.ToString())
{
case "WriteDocTypeName":
w.WriteDocType(":badname", "sysid", "pubid", "subset");
break;
case "WriteDocTypeSysid":
w.WriteDocType("name", invalidXML[1].ToString(), "pubid", "subset");
break;
case "WriteDocTypePubid":
w.WriteDocType("name", "sysid", invalidXML[1].ToString(), "subset");
break;
case "String":
w.WriteString(invalidXML[0].ToString());
break;
case "CData":
w.WriteCData(invalidXML[1].ToString());
break;
case "Comment":
w.WriteComment(invalidXML[2].ToString());
break;
case "CharEntity":
w.WriteCharEntity(invalidXML[3]);
break;
case "EntityRef":
w.WriteEntityRef(invalidXML[4].ToString());
break;
case "SurrogateCharEntity":
w.WriteSurrogateCharEntity(invalidXML[5], invalidXML[1]);
break;
case "PI":
w.WriteProcessingInstruction("pi", invalidXML[6].ToString());
break;
case "Whitespace":
w.WriteWhitespace(invalidXML[7].ToString());
break;
case "Chars":
w.WriteChars(invalidXML, 1, 5);
break;
case "RawString":
w.WriteRaw(invalidXML[4].ToString());
break;
case "RawChars":
w.WriteRaw(invalidXML, 6, 2);
break;
case "WriteValue":
w.WriteValue(invalidXML[3].ToString());
break;
default:
TestLog.Compare(false, "Invalid param value");
break;
}
}
catch (XmlException)
{
TestLog.Compare(w.WriteState, WriteState.Error, "WriteState should be Error");
return;
}
catch (ArgumentException)
{
TestLog.Compare(w.WriteState, WriteState.Error, "WriteState should be Error");
return;
}
finally
{
w.Dispose();
}
throw new TestException(TestResult.Failed, "");
}
//[Variation(Id = 40, Desc = "CheckChars=false, invalid XML characters in WriteWhitespace should error", Priority = 1, Params = new object[] { "Whitespace", false })]
//[Variation(Id = 41, Desc = "CheckChars=false, invalid XML characters in WriteSurrogateCharEntity should error", Priority = 1, Params = new object[] { "Surrogate", false })]
//[Variation(Id = 42, Desc = "CheckChars=false, invalid XML characters in WriteEntityRef should error", Priority = 1, Params = new object[] { "EntityRef", false })]
//[Variation(Id = 43, Desc = "CheckChars=false, invalid XML characters in WriteQualifiedName should error", Priority = 1, Params = new object[] { "QName", false })]
//[Variation(Id = 44, Desc = "CheckChars=true, invalid XML characters in WriteWhitespace should error", Priority = 1, Params = new object[] { "Whitespace", true })]
//[Variation(Id = 45, Desc = "CheckChars=true, invalid XML characters in WriteSurrogateCharEntity should error", Priority = 1, Params = new object[] { "Surrogate", true })]
//[Variation(Id = 46, Desc = "CheckChars=true, invalid XML characters in WriteEntityRef should error", Priority = 1, Params = new object[] { "EntityRef", true })]
//[Variation(Id = 47, Desc = "CheckChars=true, invalid XML characters in WriteQualifiedName should error", Priority = 1, Params = new object[] { "QName", true })]
public void checkChars_4()
{
char[] invalidXML = { '\u0000', '\u0008', '\u000B', '\u000C', '\u000E', '\u001F', '\uFFFE', '\uFFFF' };
XElement d = new XElement("a");
XmlWriter w = d.CreateWriter();
try
{
w.WriteStartElement("Root");
switch (Variation.Params[0].ToString())
{
case "Whitespace":
w.WriteWhitespace(invalidXML[7].ToString());
break;
case "Surrogate":
w.WriteSurrogateCharEntity(invalidXML[7], invalidXML[0]);
break;
case "EntityRef":
w.WriteEntityRef(invalidXML[4].ToString());
break;
case "Name":
w.WriteName(invalidXML[6].ToString());
break;
case "NmToken":
w.WriteNmToken(invalidXML[5].ToString());
break;
case "QName":
w.WriteQualifiedName(invalidXML[3].ToString(), "");
break;
default:
TestLog.Compare(false, "Invalid param value");
break;
}
}
catch (ArgumentException)
{
TestLog.Compare(w.WriteState, WriteState.Error, "WriteState should be Error");
return;
}
finally
{
w.Dispose();
}
throw new TestException(TestResult.Failed, "");
}
}
public partial class TCNewLineHandling : BridgeHelpers
{
//[Variation(Id = 7, Desc = "Test for CR (xD) inside attr when NewLineHandling = Replace", Priority = 0)]
public void NewLineHandling_7()
{
XDocument d = new XDocument();
XmlWriter w = d.CreateWriter();
w.WriteStartElement("root");
w.WriteAttributeString("attr", "\r");
w.WriteEndElement();
w.Dispose();
if (!CompareReader(d.CreateReader(), "<root attr=\"
\" />"))
throw new TestException(TestResult.Failed, "");
}
//[Variation(Id = 8, Desc = "Test for LF (xA) inside attr when NewLineHandling = Replace", Priority = 0)]
public void NewLineHandling_8()
{
XDocument d = new XDocument();
XmlWriter w = d.CreateWriter();
w.WriteStartElement("root");
w.WriteAttributeString("attr", "\n");
w.WriteEndElement();
w.Dispose();
if (!CompareReader(d.CreateReader(), "<root attr=\"
\" />"))
throw new TestException(TestResult.Failed, "");
}
//[Variation(Id = 9, Desc = "Test for CR LF (xD xA) inside attr when NewLineHandling = Replace", Priority = 0)]
public void NewLineHandling_9()
{
XDocument d = new XDocument();
XmlWriter w = d.CreateWriter();
w.WriteStartElement("root");
w.WriteAttributeString("attr", "\r\n");
w.WriteEndElement();
w.Dispose();
if (!CompareReader(d.CreateReader(), "<root attr=\"
\" />"))
throw new TestException(TestResult.Failed, "");
}
//[Variation(Id = 10, Desc = "Test for CR (xD) inside attr when NewLineHandling = Entitize", Priority = 0)]
public void NewLineHandling_10()
{
XDocument d = new XDocument();
XmlWriter w = d.CreateWriter();
w.WriteStartElement("root");
w.WriteAttributeString("attr", "\r");
w.WriteEndElement();
w.Dispose();
if (!CompareReader(d.CreateReader(), "<root attr=\"
\" />"))
throw new TestException(TestResult.Failed, "");
}
//[Variation(Id = 11, Desc = "Test for LF (xA) inside attr when NewLineHandling = Entitize", Priority = 0)]
public void NewLineHandling_11()
{
XDocument d = new XDocument();
XmlWriter w = d.CreateWriter();
w.WriteStartElement("root");
w.WriteAttributeString("attr", "\n");
w.WriteEndElement();
w.Dispose();
if (!CompareReader(d.CreateReader(), "<root attr=\"
\" />"))
throw new TestException(TestResult.Failed, "");
}
//[Variation(Id = 12, Desc = "Test for CR LF (xD xA) inside attr when NewLineHandling = Entitize", Priority = 0)]
public void NewLineHandling_12()
{
XDocument d = new XDocument();
XmlWriter w = d.CreateWriter();
w.WriteStartElement("root");
w.WriteAttributeString("attr", "\r\n");
w.WriteEndElement();
w.Dispose();
if (!CompareReader(d.CreateReader(), "<root attr=\"
\" />"))
throw new TestException(TestResult.Failed, "");
}
//[Variation(Id = 13, Desc = "Factory-created writers do not entitize 0xD character in text content when NewLineHandling=Entitize")]
public void NewLineHandling_13()
{
XDocument d = new XDocument();
XmlWriter w = d.CreateWriter();
w.WriteStartElement("a");
w.WriteString("A \r\n \r \n B");
w.WriteEndElement();
w.Dispose();
if (!CompareReader(d.CreateReader(), "<a>A 
\xA 
 \xA B</a>"))
throw new TestException(TestResult.Failed, "");
}
}
public partial class TCIndent : BridgeHelpers
{
//[Variation(Id = 1, Desc = "Simple test when false", Priority = 0)]
public void indent_1()
{
XDocument d = new XDocument();
XmlWriter w = d.CreateWriter();
TestLog.Compare(w.Settings.Indent, false, "Mismatch in Indent");
w.WriteStartElement("Root");
w.WriteStartElement("child");
w.WriteEndElement();
w.WriteEndElement();
w.Dispose();
if (!CompareReader(d.CreateReader(), "<Root><child /></Root>"))
throw new TestException(TestResult.Failed, "");
}
//[Variation(Id = 2, Desc = "Simple test when true", Priority = 0)]
public void indent_2()
{
XDocument d = new XDocument();
XmlWriter w = d.CreateWriter();
w.WriteStartElement("Root");
w.WriteStartElement("child");
w.WriteEndElement();
w.WriteEndElement();
w.Dispose();
if (!CompareReader(d.CreateReader(), "<Root>\xD\xA <child />\xD\xA</Root>"))
throw new TestException(TestResult.Failed, "");
}
//[Variation(Id = 3, Desc = "Indent = false, element content is empty", Priority = 0)]
public void indent_3()
{
XDocument d = new XDocument();
XmlWriter w = d.CreateWriter();
w.WriteStartElement("Root");
w.WriteString("");
w.WriteEndElement();
w.Dispose();
if (!CompareReader(d.CreateReader(), "<Root></Root>"))
throw new TestException(TestResult.Failed, "");
}
//[Variation(Id = 5, Desc = "Indent = false, element content is empty, FullEndElement", Priority = 0)]
public void indent_5()
{
XDocument d = new XDocument();
XmlWriter w = d.CreateWriter();
w.WriteStartElement("Root");
w.WriteString("");
w.WriteFullEndElement();
w.Dispose();
if (!CompareReader(d.CreateReader(), "<Root></Root>"))
throw new TestException(TestResult.Failed, "");
}
//[Variation(Id = 6, Desc = "Indent = true, element content is empty, FullEndElement", Priority = 0)]
public void indent_6()
{
XDocument d = new XDocument();
XmlWriter w = d.CreateWriter();
w.WriteStartElement("Root");
w.WriteString("");
w.WriteFullEndElement();
w.Dispose();
if (!CompareReader(d.CreateReader(), "<Root></Root>"))
throw new TestException(TestResult.Failed, "");
}
//[Variation(Id = 7, Desc = "Indent = true, mixed content", Priority = 0)]
public void indent_7()
{
XDocument d = new XDocument();
XmlWriter w = d.CreateWriter();
w.WriteStartElement("Root");
w.WriteString("test");
w.WriteStartElement("child");
w.WriteEndElement();
w.WriteEndElement();
w.Dispose();
if (!CompareReader(d.CreateReader(), "<Root>test<child /></Root>"))
throw new TestException(TestResult.Failed, "");
}
//[Variation(Id = 8, Desc = "Indent = true, mixed content, FullEndElement", Priority = 0)]
public void indent_8()
{
XDocument d = new XDocument();
XmlWriter w = d.CreateWriter();
w.WriteStartElement("Root");
w.WriteString("test");
w.WriteStartElement("child");
w.WriteFullEndElement();
w.WriteFullEndElement();
w.Dispose();
if (!CompareReader(d.CreateReader(), "<Root>test<child></child></Root>"))
throw new TestException(TestResult.Failed, "");
}
}
public partial class TCNewLineOnAttributes : BridgeHelpers
{
//[Variation(Id = 1, Desc = "Make sure the setting has no effect when Indent is false", Priority = 0)]
public void NewLineOnAttributes_1()
{
XDocument d = new XDocument();
XmlWriter w = d.CreateWriter();
TestLog.Compare(w.Settings.NewLineOnAttributes, false, "Mismatch in NewLineOnAttributes");
w.WriteStartElement("root");
w.WriteAttributeString("attr1", "value1");
w.WriteAttributeString("attr2", "value2");
w.WriteEndElement();
w.Dispose();
if (!CompareReader(d.CreateReader(), "<root attr1=\"value1\" attr2=\"value2\" />"))
throw new TestException(TestResult.Failed, "");
}
//[Variation(Id = 3, Desc = "Attributes of nested elements", Priority = 1)]
public void NewLineOnAttributes_3()
{
XDocument d = new XDocument();
XmlWriter w = d.CreateWriter();
w.WriteStartElement("level1");
w.WriteAttributeString("attr1", "value1");
w.WriteAttributeString("attr2", "value2");
w.WriteStartElement("level2");
w.WriteAttributeString("attr1", "value1");
w.WriteAttributeString("attr2", "value2");
w.WriteEndElement();
w.WriteEndElement();
w.Dispose();
if (!CompareBaseline(d, "NewLineOnAttributes3.txt"))
throw new TestException(TestResult.Failed, "");
}
}
public partial class TCStandAlone : BridgeHelpers
{
//[Variation(Id = 1, Desc = "StartDocument(bool standalone = true)", Priority = 0)]
public void standalone_1()
{
XDocument d = new XDocument();
XmlWriter w = d.CreateWriter();
w.WriteStartDocument(true);
w.WriteStartElement("Root");
w.WriteEndElement();
w.WriteEndDocument();
w.Dispose();
if (!CompareReader(d.CreateReader(), "<?xml version=\"1.0\" encoding=\"utf8\" standalone=\"yes\"?><Root />"))
throw new TestException(TestResult.Failed, "");
}
//[Variation(Id = 2, Desc = "StartDocument(bool standalone = false)", Priority = 0)]
public void standalone_2()
{
XDocument d = new XDocument();
XmlWriter w = d.CreateWriter();
w.WriteStartDocument(false);
w.WriteStartElement("Root");
w.WriteEndElement();
w.WriteEndDocument();
w.Dispose();
if (!CompareReader(d.CreateReader(), "<?xml version=\"1.0\" encoding=\"utf8\" standalone=\"no\"?><Root />"))
throw new TestException(TestResult.Failed, "");
}
}
public partial class TCFragmentCL : BridgeHelpers
{
//[Variation(Id = 1, Desc = "WriteDocType should error when CL=fragment", Priority = 1)]
public void frag_1()
{
XElement d = new XElement("a");
using (XmlWriter w = d.CreateWriter())
{
try
{
w.WriteDocType("ROOT", "publicid", "sysid", "<!ENTITY e 'abc'>");
}
catch (InvalidOperationException)
{
TestLog.Compare(w.WriteState, WriteState.Error, "WriteState should be Error");
return;
}
}
TestLog.WriteLine("Did not throw exception");
throw new TestException(TestResult.Failed, "");
}
//[Variation(Id = 2, Desc = "WriteStartDocument() should error when CL=fragment", Priority = 1)]
public void frag_2()
{
XElement d = new XElement("a");
using (XmlWriter w = d.CreateWriter())
{
try
{
w.WriteStartDocument();
}
catch (InvalidOperationException)
{
TestLog.Compare(w.WriteState, WriteState.Error, "WriteState should be Error");
return;
}
}
TestLog.WriteLine("Did not throw exception");
throw new TestException(TestResult.Failed, "");
}
}
public partial class TCAutoCL : BridgeHelpers
{
//[Variation(Id = 1, Desc = "Change to CL Document after WriteStartDocument()", Priority = 0)]
public void auto_1()
{
XDocument d = new XDocument();
XmlWriter w = d.CreateWriter();
w.WriteStartDocument();
// PROLOG
TestLog.Compare(w.Settings.ConformanceLevel, ConformanceLevel.Document, "Error");
w.WriteStartElement("root");
w.WriteEndElement();
// Try writing another root element, should error
try
{
w.WriteStartElement("root");
}
catch (InvalidOperationException)
{
return;
}
finally
{
w.Dispose();
}
TestLog.WriteLine("Conformance level = Document did not take effect");
throw new TestException(TestResult.Failed, "");
}
//[Variation(Id = 2, Desc = "Change to CL Document after WriteStartDocument(standalone = true)", Priority = 0, Param = "true")]
//[Variation(Id = 3, Desc = "Change to CL Document after WriteStartDocument(standalone = false)", Priority = 0, Param = "false")]
public void auto_2()
{
XDocument d = new XDocument();
XmlWriter w = d.CreateWriter();
switch (Variation.Param.ToString())
{
case "true":
w.WriteStartDocument(true);
break;
case "false":
w.WriteStartDocument(false);
break;
}
// PROLOG
TestLog.Compare(w.Settings.ConformanceLevel, ConformanceLevel.Document, "Error");
w.WriteStartElement("root");
// ELEMENT CONTENT
TestLog.Compare(w.Settings.ConformanceLevel, ConformanceLevel.Document, "Error");
// Inside Attribute
w.WriteStartAttribute("attr");
TestLog.Compare(w.Settings.ConformanceLevel, ConformanceLevel.Document, "Error");
w.WriteEndElement();
// Try writing another root element, should error
try
{
w.WriteStartElement("root");
}
catch (InvalidOperationException)
{
return;
}
finally
{
w.Dispose();
}
TestLog.WriteLine("Conformance level = Document did not take effect");
throw new TestException(TestResult.Failed, "");
}
//[Variation(Id = 4, Desc = "Change to CL Document when you write DocType decl", Priority = 0)]
public void auto_3()
{
XDocument d = new XDocument();
XmlWriter w = d.CreateWriter();
w.WriteDocType("ROOT", "publicid", "sysid", "<!ENTITY e 'abc'>");
// PROLOG
TestLog.Compare(w.Settings.ConformanceLevel, ConformanceLevel.Document, "Should switch to Document from Auto when you write top level DTD");
w.WriteStartElement("Root");
w.WriteEndElement();
// Try writing text at root level, should error
try
{
w.WriteString("text");
}
catch (InvalidOperationException)
{
return;
}
finally
{
w.Dispose();
}
TestLog.WriteLine("Conformance level = Document did not take effect");
throw new TestException(TestResult.Failed, "");
}
//[Variation(Id = 5, Desc = "Change to CL Fragment when you write a root element", Priority = 1)]
public void auto_4()
{
XElement d = new XElement("a");
XmlWriter w = d.CreateWriter();
w.WriteStartElement("root");
TestLog.Compare(w.Settings.ConformanceLevel, ConformanceLevel.Fragment, "Error");
w.WriteEndElement();
TestLog.Compare(w.Settings.ConformanceLevel, ConformanceLevel.Fragment, "Error");
w.WriteStartElement("root");
w.WriteEndElement();
w.Dispose();
}
//[Variation(Id = 6, Desc = "Change to CL Fragment for WriteString at top level", Priority = 1, Param = "String")]
//[Variation(Id = 7, Desc = "Change to CL Fragment for WriteCData at top level", Priority = 1, Param = "CData")]
//[Variation(Id = 9, Desc = "Change to CL Fragment for WriteCharEntity at top level", Priority = 1, Param = "CharEntity")]
//[Variation(Id = 10, Desc = "Change to CL Fragment for WriteSurrogateCharEntity at top level", Priority = 1, Param = "SurrogateCharEntity")]
//[Variation(Id = 11, Desc = "Change to CL Fragment for WriteChars at top level", Priority = 1, Param = "Chars")]
//[Variation(Id = 12, Desc = "Change to CL Fragment for WriteRaw at top level", Priority = 1, Param = "Raw")]
//[Variation(Id = 14, Desc = "Change to CL Fragment for WriteBinHex at top level", Priority = 1, Param = "BinHex")]
public void auto_5()
{
XElement d = new XElement("a");
XmlWriter w = d.CreateWriter();
byte[] buffer = new byte[10];
switch (Variation.Param.ToString())
{
case "String":
w.WriteString("text");
break;
case "CData":
w.WriteCData("cdata text");
break;
case "CharEntity":
w.WriteCharEntity('\uD23E');
break;
case "SurrogateCharEntity":
w.WriteSurrogateCharEntity('\uDF41', '\uD920');
break;
case "Chars":
string s = "test";
char[] buf = s.ToCharArray();
w.WriteChars(buf, 0, 1);
break;
case "Raw":
w.WriteRaw("<Root />");
break;
case "BinHex":
w.WriteBinHex(buffer, 0, 1);
break;
default:
TestLog.Compare(false, "Invalid param in testcase");
break;
}
TestLog.Compare(w.Settings.ConformanceLevel, ConformanceLevel.Fragment, "Error");
w.Dispose();
}
//[Variation(Id = 15, Desc = "WritePI at top level, followed by DTD, expected CL = Document", Priority = 2, Param = "PI")]
//[Variation(Id = 16, Desc = "WriteComment at top level, followed by DTD, expected CL = Document", Priority = 2, Param = "Comment")]
//[Variation(Id = 17, Desc = "WriteWhitespace at top level, followed by DTD, expected CL = Document", Priority = 2, Param = "WS")]
public void auto_6()
{
XDocument d = new XDocument();
XmlWriter w = d.CreateWriter();
switch (Variation.Param.ToString())
{
case "PI":
w.WriteProcessingInstruction("pi", "text");
break;
case "Comment":
w.WriteComment("text");
break;
case "WS":
w.WriteWhitespace(" ");
break;
default:
TestLog.Compare(false, "Invalid param in testcase");
break;
}
w.WriteDocType("ROOT", "publicid", "sysid", "<!ENTITY e 'abc'>");
TestLog.Compare(w.Settings.ConformanceLevel, ConformanceLevel.Document, "Error");
w.Dispose();
}
//[Variation(Id = 18, Desc = "WritePI at top level, followed by text, expected CL = Fragment", Priority = 2, Param = "PI")]
//[Variation(Id = 19, Desc = "WriteComment at top level, followed by text, expected CL = Fragment", Priority = 2, Param = "Comment")]
//[Variation(Id = 20, Desc = "WriteWhitespace at top level, followed by text, expected CL = Fragment", Priority = 2, Param = "WS")]
public void auto_7()
{
XElement d = new XElement("a");
XmlWriter w = d.CreateWriter();
w.WriteProcessingInstruction("pi", "text");
w.WriteString("text");
TestLog.Compare(w.Settings.ConformanceLevel, ConformanceLevel.Fragment, "Error");
w.Dispose();
}
//[Variation(Id = 21, Desc = "WriteNode(XmlReader) when reader positioned on DocType node, expected CL = Document", Priority = 2)]
public void auto_8()
{
XDocument d = new XDocument();
XmlWriter w = d.CreateWriter();
string strxml = "<!DOCTYPE test [<!ENTITY e 'abc'>]><Root />";
XmlReader xr = GetReaderStr(strxml);
xr.Read();
w.WriteNode(xr, false);
TestLog.Compare(w.Settings.ConformanceLevel, ConformanceLevel.Document, "Error");
w.Dispose();
xr.Dispose();
}
//[Variation(Id = 22, Desc = "WriteNode(XmlReader) when reader positioned on text node, expected CL = Fragment", Priority = 2)]
public void auto_10()
{
XElement d = new XElement("a");
XmlWriter w = d.CreateWriter();
string strxml = "<Root>text</Root>";
XmlReader xr = GetReaderStr(strxml);
xr.Read(); xr.Read();
TestLog.Compare(xr.NodeType.ToString(), "Text", "Error");
w.WriteNode(xr, false);
TestLog.Compare(w.Settings.ConformanceLevel, ConformanceLevel.Fragment, "Error");
w.Dispose();
xr.Dispose();
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using Windows.System;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace DncShowcaseHub.Common
{
/// <summary>
/// NavigationManager aids in navigation between pages. It provides commands used to
/// navigate back and forward as well as registers for standard mouse and keyboard
/// shortcuts used to go back and forward. In addition it integrates SuspensionManger
/// to handle process lifetime management and state management when navigating between
/// pages.
/// </summary>
/// <example>
/// To make use of NavigationManager, follow these two steps or
/// start with a BasicPage or any other Page item template other than BlankPage.
///
/// 1) Create an instance of the NaivgationHelper somewhere such as in the
/// constructor for the page and register a callback for the LoadState and
/// SaveState events.
/// <code>
/// public MyPage()
/// {
/// this.InitializeComponent();
/// var navigationHelper = new NavigationHelper(this);
/// this.navigationHelper.LoadState += navigationHelper_LoadState;
/// this.navigationHelper.SaveState += navigationHelper_SaveState;
/// }
///
/// private async void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
/// { }
/// private async void navigationHelper_SaveState(object sender, LoadStateEventArgs e)
/// { }
/// </code>
///
/// 2) Register the page to call into the NavigationManager whenever the page participates
/// in navigation by overriding the <see cref="Windows.UI.Xaml.Controls.Page.OnNavigatedTo"/>
/// and <see cref="Windows.UI.Xaml.Controls.Page.OnNavigatedFrom"/> events.
/// <code>
/// protected override void OnNavigatedTo(NavigationEventArgs e)
/// {
/// navigationHelper.OnNavigatedTo(e);
/// }
///
/// protected override void OnNavigatedFrom(NavigationEventArgs e)
/// {
/// navigationHelper.OnNavigatedFrom(e);
/// }
/// </code>
/// </example>
[Windows.Foundation.Metadata.WebHostHidden]
public class NavigationHelper : DependencyObject
{
private Page Page { get; set; }
private Frame Frame { get { return this.Page.Frame; } }
/// <summary>
/// Initializes a new instance of the <see cref="NavigationHelper"/> class.
/// </summary>
/// <param name="page">A reference to the current page used for navigation.
/// This reference allows for frame manipulation and to ensure that keyboard
/// navigation requests only occur when the page is occupying the entire window.</param>
public NavigationHelper(Page page)
{
this.Page = page;
// When this page is part of the visual tree make two changes:
// 1) Map application view state to visual state for the page
// 2) Handle keyboard and mouse navigation requests
this.Page.Loaded += (sender, e) =>
{
// Keyboard and mouse navigation only apply when occupying the entire window
if (this.Page.ActualHeight == Window.Current.Bounds.Height &&
this.Page.ActualWidth == Window.Current.Bounds.Width)
{
// Listen to the window directly so focus isn't required
Window.Current.CoreWindow.Dispatcher.AcceleratorKeyActivated +=
CoreDispatcher_AcceleratorKeyActivated;
Window.Current.CoreWindow.PointerPressed +=
this.CoreWindow_PointerPressed;
}
};
// Undo the same changes when the page is no longer visible
this.Page.Unloaded += (sender, e) =>
{
Window.Current.CoreWindow.Dispatcher.AcceleratorKeyActivated -=
CoreDispatcher_AcceleratorKeyActivated;
Window.Current.CoreWindow.PointerPressed -=
this.CoreWindow_PointerPressed;
};
}
#region Navigation support
RelayCommand _goBackCommand;
RelayCommand _goForwardCommand;
/// <summary>
/// <see cref="RelayCommand"/> used to bind to the back Button's Command property
/// for navigating to the most recent item in back navigation history, if a Frame
/// manages its own navigation history.
///
/// The <see cref="RelayCommand"/> is set up to use the virtual method <see cref="GoBack"/>
/// as the Execute Action and <see cref="CanGoBack"/> for CanExecute.
/// </summary>
public RelayCommand GoBackCommand
{
get
{
if (_goBackCommand == null)
{
_goBackCommand = new RelayCommand(
() => this.GoBack(),
() => this.CanGoBack());
}
return _goBackCommand;
}
set
{
_goBackCommand = value;
}
}
/// <summary>
/// <see cref="RelayCommand"/> used for navigating to the most recent item in
/// the forward navigation history, if a Frame manages its own navigation history.
///
/// The <see cref="RelayCommand"/> is set up to use the virtual method <see cref="GoForward"/>
/// as the Execute Action and <see cref="CanGoForward"/> for CanExecute.
/// </summary>
public RelayCommand GoForwardCommand
{
get
{
if (_goForwardCommand == null)
{
_goForwardCommand = new RelayCommand(
() => this.GoForward(),
() => this.CanGoForward());
}
return _goForwardCommand;
}
}
/// <summary>
/// Virtual method used by the <see cref="GoBackCommand"/> property
/// to determine if the <see cref="Frame"/> can go back.
/// </summary>
/// <returns>
/// true if the <see cref="Frame"/> has at least one entry
/// in the back navigation history.
/// </returns>
public virtual bool CanGoBack()
{
return this.Frame != null && this.Frame.CanGoBack;
}
/// <summary>
/// Virtual method used by the <see cref="GoForwardCommand"/> property
/// to determine if the <see cref="Frame"/> can go forward.
/// </summary>
/// <returns>
/// true if the <see cref="Frame"/> has at least one entry
/// in the forward navigation history.
/// </returns>
public virtual bool CanGoForward()
{
return this.Frame != null && this.Frame.CanGoForward;
}
/// <summary>
/// Virtual method used by the <see cref="GoBackCommand"/> property
/// to invoke the <see cref="Windows.UI.Xaml.Controls.Frame.GoBack"/> method.
/// </summary>
public virtual void GoBack()
{
if (this.Frame != null && this.Frame.CanGoBack) this.Frame.GoBack();
}
/// <summary>
/// Virtual method used by the <see cref="GoForwardCommand"/> property
/// to invoke the <see cref="Windows.UI.Xaml.Controls.Frame.GoForward"/> method.
/// </summary>
public virtual void GoForward()
{
if (this.Frame != null && this.Frame.CanGoForward) this.Frame.GoForward();
}
/// <summary>
/// Invoked on every keystroke, including system keys such as Alt key combinations, when
/// this page is active and occupies the entire window. Used to detect keyboard navigation
/// between pages even when the page itself doesn't have focus.
/// </summary>
/// <param name="sender">Instance that triggered the event.</param>
/// <param name="e">Event data describing the conditions that led to the event.</param>
private void CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher sender,
AcceleratorKeyEventArgs e)
{
var virtualKey = e.VirtualKey;
// Only investigate further when Left, Right, or the dedicated Previous or Next keys
// are pressed
if ((e.EventType == CoreAcceleratorKeyEventType.SystemKeyDown ||
e.EventType == CoreAcceleratorKeyEventType.KeyDown) &&
(virtualKey == VirtualKey.Left || virtualKey == VirtualKey.Right ||
(int)virtualKey == 166 || (int)virtualKey == 167))
{
var coreWindow = Window.Current.CoreWindow;
var downState = CoreVirtualKeyStates.Down;
bool menuKey = (coreWindow.GetKeyState(VirtualKey.Menu) & downState) == downState;
bool controlKey = (coreWindow.GetKeyState(VirtualKey.Control) & downState) == downState;
bool shiftKey = (coreWindow.GetKeyState(VirtualKey.Shift) & downState) == downState;
bool noModifiers = !menuKey && !controlKey && !shiftKey;
bool onlyAlt = menuKey && !controlKey && !shiftKey;
if (((int)virtualKey == 166 && noModifiers) ||
(virtualKey == VirtualKey.Left && onlyAlt))
{
// When the previous key or Alt+Left are pressed navigate back
e.Handled = true;
this.GoBackCommand.Execute(null);
}
else if (((int)virtualKey == 167 && noModifiers) ||
(virtualKey == VirtualKey.Right && onlyAlt))
{
// When the next key or Alt+Right are pressed navigate forward
e.Handled = true;
this.GoForwardCommand.Execute(null);
}
}
}
/// <summary>
/// Invoked on every mouse click, touch screen tap, or equivalent interaction when this
/// page is active and occupies the entire window. Used to detect browser-style next and
/// previous mouse button clicks to navigate between pages.
/// </summary>
/// <param name="sender">Instance that triggered the event.</param>
/// <param name="e">Event data describing the conditions that led to the event.</param>
private void CoreWindow_PointerPressed(CoreWindow sender,
PointerEventArgs e)
{
var properties = e.CurrentPoint.Properties;
// Ignore button chords with the left, right, and middle buttons
if (properties.IsLeftButtonPressed || properties.IsRightButtonPressed ||
properties.IsMiddleButtonPressed) return;
// If back or foward are pressed (but not both) navigate appropriately
bool backPressed = properties.IsXButton1Pressed;
bool forwardPressed = properties.IsXButton2Pressed;
if (backPressed ^ forwardPressed)
{
e.Handled = true;
if (backPressed) this.GoBackCommand.Execute(null);
if (forwardPressed) this.GoForwardCommand.Execute(null);
}
}
#endregion
#region Process lifetime management
private String _pageKey;
/// <summary>
/// Register this event on the current page to populate the page
/// with content passed during navigation as well as any saved
/// state provided when recreating a page from a prior session.
/// </summary>
public event LoadStateEventHandler LoadState;
/// <summary>
/// Register this event on the current page to preserve
/// state associated with the current page in case the
/// application is suspended or the page is discarded from
/// the navigaqtion cache.
/// </summary>
public event SaveStateEventHandler SaveState;
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// This method calls <see cref="LoadState"/>, where all page specific
/// navigation and process lifetime management logic should be placed.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property provides the group to be displayed.</param>
public void OnNavigatedTo(NavigationEventArgs e)
{
var frameState = SuspensionManager.SessionStateForFrame(this.Frame);
this._pageKey = "Page-" + this.Frame.BackStackDepth;
if (e.NavigationMode == NavigationMode.New)
{
// Clear existing state for forward navigation when adding a new page to the
// navigation stack
var nextPageKey = this._pageKey;
int nextPageIndex = this.Frame.BackStackDepth;
while (frameState.Remove(nextPageKey))
{
nextPageIndex++;
nextPageKey = "Page-" + nextPageIndex;
}
// Pass the navigation parameter to the new page
if (this.LoadState != null)
{
this.LoadState(this, new LoadStateEventArgs(e.Parameter, null));
}
}
else
{
// Pass the navigation parameter and preserved page state to the page, using
// the same strategy for loading suspended state and recreating pages discarded
// from cache
if (this.LoadState != null)
{
this.LoadState(this, new LoadStateEventArgs(e.Parameter, (Dictionary<String, Object>)frameState[this._pageKey]));
}
}
}
/// <summary>
/// Invoked when this page will no longer be displayed in a Frame.
/// This method calls <see cref="SaveState"/>, where all page specific
/// navigation and process lifetime management logic should be placed.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property provides the group to be displayed.</param>
public void OnNavigatedFrom(NavigationEventArgs e)
{
var frameState = SuspensionManager.SessionStateForFrame(this.Frame);
var pageState = new Dictionary<String, Object>();
if (this.SaveState != null)
{
this.SaveState(this, new SaveStateEventArgs(pageState));
}
frameState[_pageKey] = pageState;
}
#endregion
}
/// <summary>
/// Represents the method that will handle the <see cref="NavigationHelper.LoadState"/>event
/// </summary>
public delegate void LoadStateEventHandler(object sender, LoadStateEventArgs e);
/// <summary>
/// Represents the method that will handle the <see cref="NavigationHelper.SaveState"/>event
/// </summary>
public delegate void SaveStateEventHandler(object sender, SaveStateEventArgs e);
/// <summary>
/// Class used to hold the event data required when a page attempts to load state.
/// </summary>
public class LoadStateEventArgs : EventArgs
{
/// <summary>
/// The parameter value passed to <see cref="Frame.Navigate(Type, Object)"/>
/// when this page was initially requested.
/// </summary>
public Object NavigationParameter { get; private set; }
/// <summary>
/// A dictionary of state preserved by this page during an earlier
/// session. This will be null the first time a page is visited.
/// </summary>
public Dictionary<string, Object> PageState { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="LoadStateEventArgs"/> class.
/// </summary>
/// <param name="navigationParameter">
/// The parameter value passed to <see cref="Frame.Navigate(Type, Object)"/>
/// when this page was initially requested.
/// </param>
/// <param name="pageState">
/// A dictionary of state preserved by this page during an earlier
/// session. This will be null the first time a page is visited.
/// </param>
public LoadStateEventArgs(Object navigationParameter, Dictionary<string, Object> pageState)
: base()
{
this.NavigationParameter = navigationParameter;
this.PageState = pageState;
}
}
/// <summary>
/// Class used to hold the event data required when a page attempts to save state.
/// </summary>
public class SaveStateEventArgs : EventArgs
{
/// <summary>
/// An empty dictionary to be populated with serializable state.
/// </summary>
public Dictionary<string, Object> PageState { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="SaveStateEventArgs"/> class.
/// </summary>
/// <param name="pageState">An empty dictionary to be populated with serializable state.</param>
public SaveStateEventArgs(Dictionary<string, Object> pageState)
: base()
{
this.PageState = pageState;
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Classes: Security Descriptor family of classes
**
**
===========================================================*/
using Microsoft.Win32;
using System;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Globalization;
using System.Diagnostics.Contracts;
namespace System.Security.AccessControl
{
[Flags]
public enum ControlFlags
{
None = 0x0000,
OwnerDefaulted = 0x0001, // set by RM only
GroupDefaulted = 0x0002, // set by RM only
DiscretionaryAclPresent = 0x0004, // set by RM or user, 'off' means DACL is null
DiscretionaryAclDefaulted = 0x0008, // set by RM only
SystemAclPresent = 0x0010, // same as DiscretionaryAclPresent
SystemAclDefaulted = 0x0020, // sams as DiscretionaryAclDefaulted
DiscretionaryAclUntrusted = 0x0040, // ignore this one
ServerSecurity = 0x0080, // ignore this one
DiscretionaryAclAutoInheritRequired = 0x0100, // ignore this one
SystemAclAutoInheritRequired = 0x0200, // ignore this one
DiscretionaryAclAutoInherited = 0x0400, // set by RM only
SystemAclAutoInherited = 0x0800, // set by RM only
DiscretionaryAclProtected = 0x1000, // when set, RM will stop inheriting
SystemAclProtected = 0x2000, // when set, RM will stop inheriting
RMControlValid = 0x4000, // the reserved 8 bits have some meaning
SelfRelative = 0x8000, // must always be on
}
public abstract class GenericSecurityDescriptor
{
#region Protected Members
//
// Pictorially the structure of a security descriptor is as follows:
//
// 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1
// 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
// +---------------------------------------------------------------+
// | Control |Reserved1 (SBZ)| Revision |
// +---------------------------------------------------------------+
// | Owner |
// +---------------------------------------------------------------+
// | Group |
// +---------------------------------------------------------------+
// | Sacl |
// +---------------------------------------------------------------+
// | Dacl |
// +---------------------------------------------------------------+
//
internal const int HeaderLength = 20;
internal const int OwnerFoundAt = 4;
internal const int GroupFoundAt = 8;
internal const int SaclFoundAt = 12;
internal const int DaclFoundAt = 16;
#endregion
#region Private Methods
//
// Stores an integer in big-endian format into an array at a given offset
//
private static void MarshalInt( byte[] binaryForm, int offset, int number )
{
binaryForm[offset + 0] = ( byte )( number >> 0 );
binaryForm[offset + 1] = ( byte )( number >> 8 );
binaryForm[offset + 2] = ( byte )( number >> 16 );
binaryForm[offset + 3] = ( byte )( number >> 24 );
}
//
// Retrieves an integer stored in big-endian format at a given offset in an array
//
internal static int UnmarshalInt( byte[] binaryForm, int offset )
{
return (int)(
( binaryForm[offset + 0] << 0 ) +
( binaryForm[offset + 1] << 8 ) +
( binaryForm[offset + 2] << 16 ) +
( binaryForm[offset + 3] << 24 ));
}
#endregion
#region Constructors
protected GenericSecurityDescriptor()
{ }
#endregion
#region Protected Properties
//
// Marshaling logic requires calling into the derived
// class to obtain pointers to SACL and DACL
//
internal abstract GenericAcl GenericSacl { get; }
internal abstract GenericAcl GenericDacl { get; }
private bool IsCraftedAefaDacl
{
get
{
return (GenericDacl is DiscretionaryAcl) && (GenericDacl as DiscretionaryAcl).EveryOneFullAccessForNullDacl;
}
}
#endregion
#region Public Properties
public static bool IsSddlConversionSupported()
{
return true; // SDDL to binary conversions are supported on Windows 2000 and higher
}
public static byte Revision
{
get { return 1; }
}
//
// Allows retrieving and setting the control bits for this security descriptor
//
public abstract ControlFlags ControlFlags { get; }
//
// Allows retrieving and setting the owner SID for this security descriptor
//
public abstract SecurityIdentifier Owner { get; set; }
//
// Allows retrieving and setting the group SID for this security descriptor
//
public abstract SecurityIdentifier Group { get; set; }
//
// Retrieves the length of the binary representation
// of the security descriptor
//
public int BinaryLength
{
get
{
int result = HeaderLength;
if ( Owner != null )
{
result += Owner.BinaryLength;
}
if ( Group != null )
{
result += Group.BinaryLength;
}
if (( ControlFlags & ControlFlags.SystemAclPresent ) != 0 &&
GenericSacl != null )
{
result += GenericSacl.BinaryLength;
}
if (( ControlFlags & ControlFlags.DiscretionaryAclPresent ) != 0 &&
GenericDacl != null && !IsCraftedAefaDacl)
{
result += GenericDacl.BinaryLength;
}
return result;
}
}
#endregion
#region Public Methods
//
// Converts the security descriptor to its SDDL form
//
[System.Security.SecuritySafeCritical] // auto-generated
public string GetSddlForm( AccessControlSections includeSections )
{
byte[] binaryForm = new byte[BinaryLength];
string resultSddl;
int error;
GetBinaryForm( binaryForm, 0 );
SecurityInfos flags = 0;
if (( includeSections & AccessControlSections.Owner ) != 0 )
{
flags |= SecurityInfos.Owner;
}
if (( includeSections & AccessControlSections.Group ) != 0 )
{
flags |= SecurityInfos.Group;
}
if (( includeSections & AccessControlSections.Audit ) != 0 )
{
flags |= SecurityInfos.SystemAcl;
}
if (( includeSections & AccessControlSections.Access ) != 0 )
{
flags |= SecurityInfos.DiscretionaryAcl;
}
error = Win32.ConvertSdToSddl( binaryForm, 1, flags, out resultSddl );
if ( error == Win32Native.ERROR_INVALID_PARAMETER ||
error == Win32Native.ERROR_UNKNOWN_REVISION )
{
//
// Indicates that the marshaling logic in GetBinaryForm is busted
//
Contract.Assert( false, "binaryForm produced invalid output" );
throw new InvalidOperationException();
}
else if ( error != Win32Native.ERROR_SUCCESS )
{
Contract.Assert( false, string.Format( CultureInfo.InvariantCulture, "Win32.ConvertSdToSddl returned {0}", error ));
throw new InvalidOperationException();
}
return resultSddl;
}
//
// Converts the security descriptor to its binary form
//
public void GetBinaryForm( byte[] binaryForm, int offset )
{
if ( binaryForm == null )
{
throw new ArgumentNullException( "binaryForm" );
}
if ( offset < 0 )
{
throw new ArgumentOutOfRangeException("offset",
Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ));
}
if ( binaryForm.Length - offset < BinaryLength )
{
throw new ArgumentOutOfRangeException(
"binaryForm",
Environment.GetResourceString( "ArgumentOutOfRange_ArrayTooSmall" ));
}
Contract.EndContractBlock();
//
// the offset will grow as we go for each additional field (owner, group,
// acl, etc) being written. But for each of such fields, we must use the
// original offset as passed in, not the growing offset
//
int originalOffset = offset;
//
// Populate the header
//
int length = BinaryLength;
byte rmControl =
(( this is RawSecurityDescriptor ) &&
(( ControlFlags & ControlFlags.RMControlValid ) != 0 )) ? (( this as RawSecurityDescriptor ).ResourceManagerControl ) : ( byte )0;
// if the DACL is our internally crafted NULL replacement, then let us turn off this control
int materializedControlFlags = ( int )ControlFlags;
if (IsCraftedAefaDacl)
{
unchecked {materializedControlFlags &= ~((int)ControlFlags.DiscretionaryAclPresent);}
}
binaryForm[offset + 0] = Revision;
binaryForm[offset + 1] = rmControl;
binaryForm[offset + 2] = ( byte )(( int )materializedControlFlags >> 0 );
binaryForm[offset + 3] = ( byte )(( int )materializedControlFlags >> 8 );
//
// Compute offsets at which owner, group, SACL and DACL are stored
//
int ownerOffset, groupOffset, saclOffset, daclOffset;
ownerOffset = offset + OwnerFoundAt;
groupOffset = offset + GroupFoundAt;
saclOffset = offset + SaclFoundAt;
daclOffset = offset + DaclFoundAt;
offset += HeaderLength;
//
// Marhsal the Owner SID into place
//
if ( Owner != null )
{
MarshalInt( binaryForm, ownerOffset, offset - originalOffset );
Owner.GetBinaryForm( binaryForm, offset );
offset += Owner.BinaryLength;
}
else
{
//
// If Owner SID is null, store 0 in the offset field
//
MarshalInt( binaryForm, ownerOffset, 0 );
}
//
// Marshal the Group SID into place
//
if ( Group != null )
{
MarshalInt( binaryForm, groupOffset, offset - originalOffset );
Group.GetBinaryForm( binaryForm, offset );
offset += Group.BinaryLength;
}
else
{
//
// If Group SID is null, store 0 in the offset field
//
MarshalInt( binaryForm, groupOffset, 0 );
}
//
// Marshal the SACL into place, if present
//
if (( ControlFlags & ControlFlags.SystemAclPresent ) != 0 &&
GenericSacl != null )
{
MarshalInt( binaryForm, saclOffset, offset - originalOffset );
GenericSacl.GetBinaryForm( binaryForm, offset );
offset += GenericSacl.BinaryLength;
}
else
{
//
// If SACL is null or not present, store 0 in the offset field
//
MarshalInt( binaryForm, saclOffset, 0 );
}
//
// Marshal the DACL into place, if present
//
if (( ControlFlags & ControlFlags.DiscretionaryAclPresent ) != 0 &&
GenericDacl != null && !IsCraftedAefaDacl )
{
MarshalInt( binaryForm, daclOffset, offset - originalOffset );
GenericDacl.GetBinaryForm( binaryForm, offset );
offset += GenericDacl.BinaryLength;
}
else
{
//
// If DACL is null or not present, store 0 in the offset field
//
MarshalInt( binaryForm, daclOffset, 0 );
}
}
#endregion
}
public sealed class RawSecurityDescriptor : GenericSecurityDescriptor
{
#region Private Members
private SecurityIdentifier _owner;
private SecurityIdentifier _group;
private ControlFlags _flags;
private RawAcl _sacl;
private RawAcl _dacl;
private byte _rmControl; // the not-so-reserved SBZ1 field
#endregion
#region Protected Properties
internal override GenericAcl GenericSacl
{
get { return _sacl; }
}
internal override GenericAcl GenericDacl
{
get { return _dacl; }
}
#endregion
#region Private methods
private void CreateFromParts( ControlFlags flags, SecurityIdentifier owner, SecurityIdentifier group, RawAcl systemAcl, RawAcl discretionaryAcl )
{
SetFlags( flags );
Owner = owner;
Group = group;
SystemAcl = systemAcl;
DiscretionaryAcl = discretionaryAcl;
ResourceManagerControl = 0;
}
#endregion
#region Constructors
//
// Creates a security descriptor explicitly
//
public RawSecurityDescriptor( ControlFlags flags, SecurityIdentifier owner, SecurityIdentifier group, RawAcl systemAcl, RawAcl discretionaryAcl )
: base()
{
CreateFromParts( flags, owner, group, systemAcl, discretionaryAcl );
}
//
// Creates a security descriptor from an SDDL string
//
[System.Security.SecuritySafeCritical] // auto-generated
public RawSecurityDescriptor( string sddlForm )
: this( BinaryFormFromSddlForm( sddlForm ), 0 )
{
}
//
// Creates a security descriptor from its binary representation
// Important: the representation must be in self-relative format
//
public RawSecurityDescriptor( byte[] binaryForm, int offset )
: base()
{
//
// The array passed in must be valid
//
if ( binaryForm == null )
{
throw new ArgumentNullException( "binaryForm" );
}
if ( offset < 0 )
{
//
// Offset must not be negative
//
throw new ArgumentOutOfRangeException("offset",
Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ));
}
//
// At least make sure the header is in place
//
if ( binaryForm.Length - offset < HeaderLength )
{
throw new ArgumentOutOfRangeException(
"binaryForm",
Environment.GetResourceString( "ArgumentOutOfRange_ArrayTooSmall" ));
}
//
// We only understand revision-1 security descriptors
//
if ( binaryForm[offset + 0] != Revision )
{
throw new ArgumentOutOfRangeException("binaryForm",
Environment.GetResourceString( "AccessControl_InvalidSecurityDescriptorRevision" ));
}
Contract.EndContractBlock();
ControlFlags flags;
SecurityIdentifier owner, group;
RawAcl sacl, dacl;
byte rmControl;
//
// Extract the ResourceManagerControl field
//
rmControl = binaryForm[offset + 1];
//
// Extract the control flags
//
flags = ( ControlFlags )(( binaryForm[offset + 2] << 0 ) + ( binaryForm[offset + 3] << 8 ));
//
// Make sure that the input is in self-relative format
//
if (( flags & ControlFlags.SelfRelative ) == 0 )
{
throw new ArgumentException(
Environment.GetResourceString( "AccessControl_InvalidSecurityDescriptorSelfRelativeForm" ),
"binaryForm" );
}
//
// Extract the owner SID
//
int ownerOffset = UnmarshalInt( binaryForm, offset + OwnerFoundAt );
if ( ownerOffset != 0 )
{
owner = new SecurityIdentifier( binaryForm, offset + ownerOffset );
}
else
{
owner = null;
}
//
// Extract the group SID
//
int groupOffset = UnmarshalInt( binaryForm, offset + GroupFoundAt );
if ( groupOffset != 0 )
{
group = new SecurityIdentifier( binaryForm, offset + groupOffset );
}
else
{
group = null;
}
//
// Extract the SACL
//
int saclOffset = UnmarshalInt( binaryForm, offset + SaclFoundAt );
if ((( flags & ControlFlags.SystemAclPresent ) != 0 ) &&
saclOffset != 0 )
{
sacl = new RawAcl( binaryForm, offset + saclOffset );
}
else
{
sacl = null;
}
//
// Extract the DACL
//
int daclOffset = UnmarshalInt( binaryForm, offset + DaclFoundAt );
if ((( flags & ControlFlags.DiscretionaryAclPresent ) != 0 ) &&
daclOffset != 0 )
{
dacl = new RawAcl( binaryForm, offset + daclOffset );
}
else
{
dacl = null;
}
//
// Create the resulting security descriptor
//
CreateFromParts( flags, owner, group, sacl, dacl );
//
// In the offchance that the flags indicate that the rmControl
// field is meaningful, remember what was there.
//
if (( flags & ControlFlags.RMControlValid ) != 0 )
{
ResourceManagerControl = rmControl;
}
}
#endregion
#region Static Methods
[System.Security.SecurityCritical] // auto-generated
private static byte[] BinaryFormFromSddlForm( string sddlForm )
{
if ( sddlForm == null )
{
throw new ArgumentNullException( "sddlForm" );
}
Contract.EndContractBlock();
int error;
IntPtr byteArray = IntPtr.Zero;
uint byteArraySize = 0;
const System.Int32 TRUE = 1;
byte[] binaryForm = null;
try
{
if ( TRUE != Win32Native.ConvertStringSdToSd(
sddlForm,
GenericSecurityDescriptor.Revision,
out byteArray,
ref byteArraySize ))
{
error = Marshal.GetLastWin32Error();
if ( error == Win32Native.ERROR_INVALID_PARAMETER ||
error == Win32Native.ERROR_INVALID_ACL ||
error == Win32Native.ERROR_INVALID_SECURITY_DESCR ||
error == Win32Native.ERROR_UNKNOWN_REVISION )
{
throw new ArgumentException(
Environment.GetResourceString( "ArgumentException_InvalidSDSddlForm" ),
"sddlForm" );
}
else if ( error == Win32Native.ERROR_NOT_ENOUGH_MEMORY )
{
throw new OutOfMemoryException();
}
else if ( error == Win32Native.ERROR_INVALID_SID )
{
throw new ArgumentException(
Environment.GetResourceString( "AccessControl_InvalidSidInSDDLString" ),
"sddlForm" );
}
else if ( error != Win32Native.ERROR_SUCCESS )
{
Contract.Assert( false, string.Format( CultureInfo.InvariantCulture, "Unexpected error out of Win32.ConvertStringSdToSd: {0}", error ));
throw new SystemException();
}
}
binaryForm = new byte[byteArraySize];
//
// Extract the data from the returned pointer
//
Marshal.Copy( byteArray, binaryForm, 0, ( int )byteArraySize );
}
finally
{
//
// Now is a good time to get rid of the returned pointer
//
if (byteArray != IntPtr.Zero)
{
Win32Native.LocalFree( byteArray );
}
}
return binaryForm;
}
#endregion
#region Public Properties
//
// Allows retrieving the control bits for this security descriptor
// Important: Special checks must be applied when setting flags and not
// all flags can be set (for instance, we only deal with self-relative
// security descriptors), thus flags can be set through other methods.
//
public override ControlFlags ControlFlags
{
get
{
return _flags;
}
}
//
// Allows retrieving and setting the owner SID for this security descriptor
//
public override SecurityIdentifier Owner
{
get
{
return _owner;
}
set
{
_owner = value;
}
}
//
// Allows retrieving and setting the group SID for this security descriptor
//
public override SecurityIdentifier Group
{
get
{
return _group;
}
set
{
_group = value;
}
}
//
// Allows retrieving and setting the SACL for this security descriptor
//
public RawAcl SystemAcl
{
get
{
return _sacl;
}
set
{
_sacl = value;
}
}
//
// Allows retrieving and setting the DACL for this security descriptor
//
public RawAcl DiscretionaryAcl
{
get
{
return _dacl;
}
set
{
_dacl = value;
}
}
//
// CORNER CASE (LEGACY)
// The ostensibly "reserved" field in the Security Descriptor header
// can in fact be used by obscure resource managers which in this
// case must set the RMControlValid flag.
//
public byte ResourceManagerControl
{
get
{
return _rmControl;
}
set
{
_rmControl = value;
}
}
#endregion
#region Public Methods
public void SetFlags( ControlFlags flags )
{
//
// We can not deal with non-self-relative descriptors
// so just forget about it
//
_flags = ( flags | ControlFlags.SelfRelative );
}
#endregion
}
public sealed class CommonSecurityDescriptor : GenericSecurityDescriptor
{
#region Private Members
bool _isContainer;
bool _isDS;
private RawSecurityDescriptor _rawSd;
private SystemAcl _sacl;
private DiscretionaryAcl _dacl;
#endregion
#region Private Methods
private void CreateFromParts( bool isContainer, bool isDS, ControlFlags flags, SecurityIdentifier owner, SecurityIdentifier group, SystemAcl systemAcl, DiscretionaryAcl discretionaryAcl )
{
if ( systemAcl != null &&
systemAcl.IsContainer != isContainer )
{
throw new ArgumentException(
Environment.GetResourceString( isContainer ?
"AccessControl_MustSpecifyContainerAcl" :
"AccessControl_MustSpecifyLeafObjectAcl" ),
"systemAcl" );
}
if ( discretionaryAcl != null &&
discretionaryAcl.IsContainer != isContainer )
{
throw new ArgumentException(
Environment.GetResourceString( isContainer ?
"AccessControl_MustSpecifyContainerAcl" :
"AccessControl_MustSpecifyLeafObjectAcl" ),
"discretionaryAcl" );
}
_isContainer = isContainer;
if ( systemAcl != null &&
systemAcl.IsDS != isDS )
{
throw new ArgumentException(
Environment.GetResourceString( isDS ?
"AccessControl_MustSpecifyDirectoryObjectAcl" :
"AccessControl_MustSpecifyNonDirectoryObjectAcl"),
"systemAcl");
}
if ( discretionaryAcl != null &&
discretionaryAcl.IsDS != isDS )
{
throw new ArgumentException(
Environment.GetResourceString( isDS ?
"AccessControl_MustSpecifyDirectoryObjectAcl" :
"AccessControl_MustSpecifyNonDirectoryObjectAcl"),
"discretionaryAcl");
}
_isDS = isDS;
_sacl = systemAcl;
//
// Replace null DACL with an allow-all for everyone DACL
//
if ( discretionaryAcl == null )
{
//
// to conform to native behavior, we will add allow everyone ace for DACL
//
discretionaryAcl = DiscretionaryAcl.CreateAllowEveryoneFullAccess(_isDS, _isContainer);
}
_dacl = discretionaryAcl;
//
// DACL is never null. So always set the flag bit on
//
ControlFlags actualFlags = flags | ControlFlags.DiscretionaryAclPresent;
//
// Keep SACL and the flag bit in [....].
//
if (systemAcl == null)
{
unchecked { actualFlags &= ~(ControlFlags.SystemAclPresent); }
}
else
{
actualFlags |= (ControlFlags.SystemAclPresent);
}
_rawSd = new RawSecurityDescriptor( actualFlags, owner, group, systemAcl == null ? null : systemAcl.RawAcl, discretionaryAcl.RawAcl );
}
#endregion
#region Constructors
//
// Creates a security descriptor explicitly
//
public CommonSecurityDescriptor( bool isContainer, bool isDS, ControlFlags flags, SecurityIdentifier owner, SecurityIdentifier group, SystemAcl systemAcl, DiscretionaryAcl discretionaryAcl )
{
CreateFromParts( isContainer, isDS, flags, owner, group, systemAcl, discretionaryAcl );
}
private CommonSecurityDescriptor( bool isContainer, bool isDS, ControlFlags flags, SecurityIdentifier owner, SecurityIdentifier group, RawAcl systemAcl, RawAcl discretionaryAcl )
: this( isContainer, isDS, flags, owner, group, systemAcl == null ? null : new SystemAcl( isContainer, isDS, systemAcl ), discretionaryAcl == null ? null : new DiscretionaryAcl( isContainer, isDS, discretionaryAcl ))
{
}
public CommonSecurityDescriptor( bool isContainer, bool isDS, RawSecurityDescriptor rawSecurityDescriptor )
: this( isContainer, isDS, rawSecurityDescriptor, false )
{
}
internal CommonSecurityDescriptor( bool isContainer, bool isDS, RawSecurityDescriptor rawSecurityDescriptor, bool trusted )
{
if ( rawSecurityDescriptor == null )
{
throw new ArgumentNullException( "rawSecurityDescriptor" );
}
Contract.EndContractBlock();
CreateFromParts(
isContainer,
isDS,
rawSecurityDescriptor.ControlFlags,
rawSecurityDescriptor.Owner,
rawSecurityDescriptor.Group,
rawSecurityDescriptor.SystemAcl == null ? null : new SystemAcl( isContainer, isDS, rawSecurityDescriptor.SystemAcl, trusted ),
rawSecurityDescriptor.DiscretionaryAcl == null ? null : new DiscretionaryAcl( isContainer, isDS, rawSecurityDescriptor.DiscretionaryAcl, trusted ));
}
//
// Create a security descriptor from an SDDL string
//
public CommonSecurityDescriptor( bool isContainer, bool isDS, string sddlForm )
: this( isContainer, isDS, new RawSecurityDescriptor( sddlForm ), true )
{
}
//
// Create a security descriptor from its binary representation
//
public CommonSecurityDescriptor( bool isContainer, bool isDS, byte[] binaryForm, int offset )
: this( isContainer, isDS, new RawSecurityDescriptor( binaryForm, offset ), true )
{
}
#endregion
#region Protected Properties
internal sealed override GenericAcl GenericSacl
{
get { return _sacl; }
}
internal sealed override GenericAcl GenericDacl
{
get { return _dacl; }
}
#endregion
#region Public Properties
public bool IsContainer
{
get { return _isContainer; }
}
public bool IsDS
{
get { return _isDS; }
}
//
// Allows retrieving the control bits for this security descriptor
//
public override ControlFlags ControlFlags
{
get
{
return _rawSd.ControlFlags;
}
}
//
// Allows retrieving and setting the owner SID for this security descriptor
//
public override SecurityIdentifier Owner
{
get
{
return _rawSd.Owner;
}
set
{
_rawSd.Owner = value;
}
}
//
// Allows retrieving and setting the group SID for this security descriptor
//
public override SecurityIdentifier Group
{
get
{
return _rawSd.Group;
}
set
{
_rawSd.Group = value;
}
}
public SystemAcl SystemAcl
{
get
{
return _sacl;
}
set
{
if ( value != null )
{
if ( value.IsContainer != this.IsContainer )
{
throw new ArgumentException(
Environment.GetResourceString( this.IsContainer ?
"AccessControl_MustSpecifyContainerAcl" :
"AccessControl_MustSpecifyLeafObjectAcl" ),
"value" );
}
if ( value.IsDS != this.IsDS )
{
throw new ArgumentException(
Environment.GetResourceString(this.IsDS ?
"AccessControl_MustSpecifyDirectoryObjectAcl" :
"AccessControl_MustSpecifyNonDirectoryObjectAcl"),
"value");
}
}
_sacl = value;
if ( _sacl != null )
{
_rawSd.SystemAcl = _sacl.RawAcl;
AddControlFlags( ControlFlags.SystemAclPresent );
}
else
{
_rawSd.SystemAcl = null;
RemoveControlFlags( ControlFlags.SystemAclPresent );
}
}
}
//
// Allows retrieving and setting the DACL for this security descriptor
//
public DiscretionaryAcl DiscretionaryAcl
{
get
{
return _dacl;
}
set
{
if ( value != null )
{
if ( value.IsContainer != this.IsContainer )
{
throw new ArgumentException(
Environment.GetResourceString( this.IsContainer ?
"AccessControl_MustSpecifyContainerAcl" :
"AccessControl_MustSpecifyLeafObjectAcl" ),
"value" );
}
if ( value.IsDS != this.IsDS )
{
throw new ArgumentException(
Environment.GetResourceString( this.IsDS ?
"AccessControl_MustSpecifyDirectoryObjectAcl" :
"AccessControl_MustSpecifyNonDirectoryObjectAcl"),
"value");
}
}
//
// NULL DACLs are replaced with allow everyone full access DACLs.
//
if ( value == null )
{
_dacl = DiscretionaryAcl.CreateAllowEveryoneFullAccess(IsDS, IsContainer);
}
else
{
_dacl = value;
}
_rawSd.DiscretionaryAcl = _dacl.RawAcl;
AddControlFlags( ControlFlags.DiscretionaryAclPresent );
}
}
public bool IsSystemAclCanonical
{
get { return ( SystemAcl == null || SystemAcl.IsCanonical ); }
}
public bool IsDiscretionaryAclCanonical
{
get { return ( DiscretionaryAcl == null || DiscretionaryAcl.IsCanonical ); }
}
#endregion
#region Public Methods
public void SetSystemAclProtection( bool isProtected, bool preserveInheritance )
{
if ( !isProtected )
{
RemoveControlFlags( ControlFlags.SystemAclProtected );
}
else
{
if ( !preserveInheritance && SystemAcl != null )
{
SystemAcl.RemoveInheritedAces();
}
AddControlFlags( ControlFlags.SystemAclProtected );
}
}
public void SetDiscretionaryAclProtection( bool isProtected, bool preserveInheritance )
{
if ( !isProtected )
{
RemoveControlFlags( ControlFlags.DiscretionaryAclProtected );
}
else
{
if ( !preserveInheritance && DiscretionaryAcl != null )
{
DiscretionaryAcl.RemoveInheritedAces();
}
AddControlFlags( ControlFlags.DiscretionaryAclProtected );
}
if (DiscretionaryAcl != null && DiscretionaryAcl.EveryOneFullAccessForNullDacl)
{
DiscretionaryAcl.EveryOneFullAccessForNullDacl = false;
}
}
public void PurgeAccessControl( SecurityIdentifier sid )
{
if ( sid == null )
{
throw new ArgumentNullException( "sid" );
}
Contract.EndContractBlock();
if ( DiscretionaryAcl != null )
{
DiscretionaryAcl.Purge( sid );
}
}
public void PurgeAudit( SecurityIdentifier sid )
{
if ( sid == null )
{
throw new ArgumentNullException( "sid" );
}
Contract.EndContractBlock();
if ( SystemAcl != null )
{
SystemAcl.Purge( sid );
}
}
#endregion
#region internal Methods
internal void UpdateControlFlags(ControlFlags flagsToUpdate, ControlFlags newFlags)
{
ControlFlags finalFlags = newFlags | (_rawSd.ControlFlags & (~flagsToUpdate));
_rawSd.SetFlags(finalFlags);
}
//
// These two add/remove method must be called with great care (and thus it is internal)
// The caller is responsible for keeping the SaclPresent and DaclPresent bits in [....]
// with the actual SACL and DACL.
//
internal void AddControlFlags(ControlFlags flags)
{
_rawSd.SetFlags(_rawSd.ControlFlags | flags);
}
internal void RemoveControlFlags(ControlFlags flags)
{
unchecked
{
_rawSd.SetFlags(_rawSd.ControlFlags & ~flags);
}
}
internal bool IsSystemAclPresent
{
get
{
return (_rawSd.ControlFlags & ControlFlags.SystemAclPresent) != 0;
}
}
internal bool IsDiscretionaryAclPresent
{
get
{
return (_rawSd.ControlFlags & ControlFlags.DiscretionaryAclPresent) != 0;
}
}
#endregion
}
}
| |
/*
Copyright 2019 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ArcGIS.Desktop.Framework;
using ArcGIS.Desktop.Framework.Contracts;
using ArcGIS.Desktop.Framework.Threading.Tasks;
using ArcGIS.Core.Data;
using ArcGIS.Desktop.Framework.Dialogs;
using ArcGIS.Desktop.Mapping;
using System.Windows.Input;
using System.Windows;
using ArcGIS.Desktop.Editing;
using System.Windows.Media;
namespace CrowdPlannerTool
{
#region Showbutton
/// <summary>
/// Button implementation to show the DockPane.
/// </summary>
internal class CPDockpane_ShowButton : Button
{
protected override void OnClick()
{
CPDockpaneViewModel.Show();
}
}
#endregion
#region DockPane Activate
internal class CPDockpaneViewModel : DockPane
{
private const string _dockPaneID = "CrowdPlannerTool_CPDockpane";
private KeyValuePair<string, int>[] _piechartResult;
private KeyValuePair<string, int>[] _piechartResultMedium;
private KeyValuePair<string, int>[] _piechartResultLow;
private string textboxBackground;
/// <summary>
/// Show the DockPane
/// </summary>
internal static void Show()
{
CPDockpaneViewModel pane = FrameworkApplication.DockPaneManager.Find(_dockPaneID) as CPDockpaneViewModel;
if (pane == null)
return;
pane.Activate();
}
protected CPDockpaneViewModel()
{
_updateSettingsCmd = new RelayCommand(() => GetTotalValues(), () => true);
_updateSettingsOnlyCmd = new RelayCommand(() => EnableSettings(), () => true);
_updateSettingsAllCurrentCmd = new RelayCommand(() => ResetValues("current"), () => true);
_updateSettingsAllDefaultCmd = new RelayCommand(() => ResetValues("default"), () => true);
_setDefaultSettingsCmd = new RelayCommand(() => SetDefaultSettings(), () => true);
//string textboxBackground;
if (FrameworkApplication.ApplicationTheme == ApplicationTheme.Dark ||
FrameworkApplication.ApplicationTheme == ApplicationTheme.HighContrast)
textboxBackground = "#323232";
else textboxBackground = "#FFFFFF";
//set background value for textboxes
_highBackground = textboxBackground;
_mediumBackground = textboxBackground;
_lowBackground = textboxBackground;
}
#endregion
#region Commands
// ** COMMANDS **
private RelayCommand _updateSettingsCmd;
public ICommand UpdateSettingsCmd
{
get
{
return _updateSettingsCmd;
}
}
private RelayCommand _updateSettingsOnlyCmd;
public ICommand UpdateSettingsOnlyCmd
{
get
{
return _updateSettingsOnlyCmd;
}
}
private RelayCommand _updateSettingsAllCurrentCmd;
public ICommand UpdateSettingsAllCurrentCmd
{
get
{
return _updateSettingsAllCurrentCmd;
}
}
private RelayCommand _updateSettingsAllDefaultCmd;
public ICommand UpdateSettingsAllDefaultCmd
{
get
{
return _updateSettingsAllDefaultCmd;
}
}
private RelayCommand _setDefaultSettingsCmd;
public ICommand SetDefaultSettingsCmd
{
get
{
return _setDefaultSettingsCmd;
}
}
#endregion
#region Properties
/// <summary>
/// Text shown near the top of the DockPane.
/// </summary>
//private string _heading = "Crowd Estimate Summary";
//public string Heading
//{
// get { return _heading; }
// set
// {
// SetProperty(ref _heading, value, () => Heading);
// }
//}
private long _totalHigh = 0;
public long TotalHigh
{
get
{
return _totalHigh;
}
set
{
_totalHigh = value;
NotifyPropertyChanged();
}
}
private double _highSetting = 0;
public double HighSetting
{
get
{
return _highSetting;
}
set
{
_highSetting = value;
NotifyPropertyChanged();
}
}
private double _mediumSetting = 0;
public double MediumSetting
{
get
{
return _mediumSetting;
}
set
{
_mediumSetting = value;
NotifyPropertyChanged();
}
}
private double _lowSetting = 0;
public double LowSetting
{
get
{
return _lowSetting;
}
set
{
_lowSetting = value;
NotifyPropertyChanged();
}
}
private long _targetSetting = 0;
public long TargetSetting
{
get
{
return _targetSetting;
}
set
{
_targetSetting = value;
NotifyPropertyChanged();
}
}
private long _totalMedium = 0;
public long TotalMedium
{
get
{
return _totalMedium;
}
set
{
_totalMedium = value;
NotifyPropertyChanged();
}
}
private long _totalLow = 0;
public long TotalLow
{
get
{
return _totalLow;
}
set
{
_totalLow = value;
NotifyPropertyChanged();
}
}
// High total background
private string _highBackground; // "#FFFFFF";
public string HighBackground
{
get
{
return _highBackground;
}
set
{
_highBackground = value;
NotifyPropertyChanged("ColorBrush");
}
}
public Brush ColorBrush => new SolidColorBrush((Color)ColorConverter.ConvertFromString(_highBackground));
// Medium total background
private string _mediumBackground; // = "#FFFFFF";
public string MediumBackground
{
get
{
return _mediumBackground;
}
set
{
_mediumBackground = value;
NotifyPropertyChanged("ColorBrushMedium");
}
}
public Brush ColorBrushMedium => new SolidColorBrush((Color)ColorConverter.ConvertFromString(_mediumBackground));
// Low total background
private string _lowBackground; // = "#FFFFFF";
public string LowBackground
{
get
{
return _lowBackground;
}
set
{
_lowBackground = value;
NotifyPropertyChanged("ColorBrushLow");
}
}
public Brush ColorBrushLow => new SolidColorBrush((Color)ColorConverter.ConvertFromString(_lowBackground));
// High Estimate Chart
public KeyValuePair<string, int>[] PieChartResult
{
get
{
return _piechartResult;
}
set
{
SetProperty(ref _piechartResult, value, () => PieChartResult);
}
}
// Medium Estimate Chart
public KeyValuePair<string, int>[] PieChartResultMedium
{
get
{
return _piechartResultMedium;
}
set
{
SetProperty(ref _piechartResultMedium, value, () => PieChartResultMedium);
}
}
// Low Estimate Chart
public KeyValuePair<string, int>[] PieChartResultLow
{
get
{
return _piechartResultLow;
}
set
{
SetProperty(ref _piechartResultLow, value, () => PieChartResultLow);
}
}
#endregion
#region EnableSettings
private bool _canEdit = false;
public void EnableSettings()
{
_canEdit = !_canEdit;
NotifyPropertyChanged("CanEdit");
}
public bool CanEdit => _canEdit;
#endregion
#region SetDefaultSettings
public void SetDefaultSettings()
{
HighSetting = 2.5;
MediumSetting = 4.5;
LowSetting = 10;
ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Default settings set for current editing only. Use Reset to Defaults to reset all polygons.", "Settings");
}
#endregion
#region ResetValues
// Reset Settings Based on Current Settings
public async void ResetValues(string settingsValue)
{
if (MapView.Active == null)
{
ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("CrowdPlanning Layer is not found. Please open the map view of the Crowd Planner data project.", "Error", MessageBoxButton.OK, MessageBoxImage.Exclamation);
return;
}
// Check for CrowdPlanning layer, exit if not present in current Map.
var CrowdLayerTest = MapView.Active.Map.FindLayers("CrowdPlanning").FirstOrDefault() as BasicFeatureLayer;
if (CrowdLayerTest == null)
{
ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("CrowdPlanning Layer is not found. Please use with the Crowd Planner data project.", "Error", MessageBoxButton.OK, MessageBoxImage.Exclamation);
return;
}
// *** Check to ensure the densitysettings are set. If not, show a warning and deactivate tool.
if (HighSetting == 0 || MediumSetting == 0 || LowSetting == 0 || TargetSetting == 0)
{
ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("An empty setting value exists. All settings are required to use this tool.", "Warning!");
// ** End if there are not complete settings
return;
}
// else proceed with confirming a reset is desired.
else
{
if (settingsValue == "current")
{
// Prompt for confirmation, and if answer is no, return.
var result = ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Reset all values to CURRENT settings?", "RESET VALUES", MessageBoxButton.OKCancel, MessageBoxImage.Asterisk);
// Return if cancel value is chosen
if (Convert.ToString(result) == "Cancel")
return;
}
else if (settingsValue == "default")
{
// Prompt for confirmation, and if answer is no, return.
var result = ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Reset all values to DEFAULT settings?", "RESET VALUES", MessageBoxButton.OKCancel, MessageBoxImage.Asterisk);
// Return if cancel value is chosen
if (Convert.ToString(result) == "Cancel")
return;
}
}
FeatureLayer CrowdLayer = MapView.Active.Map.Layers.First(layer => layer.Name.Equals("CrowdPlanning")) as FeatureLayer;
if (CrowdLayer == null)
{
ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("CrowdPlanning Layer is not found");
return;
}
ArcGIS.Core.Data.Table CrowdTable = await QueuedTask.Run(() => CrowdLayer.GetTable());
await QueuedTask.Run(() =>
{
var editOperation = new EditOperation();
editOperation.Callback(context =>
{
QueryFilter QF = new QueryFilter
{
WhereClause = "LOW > 0"
};
RowCursor CrowdRow = CrowdTable.Search(QF, false);
while (CrowdRow.MoveNext())
{
using (Row currentRow = CrowdRow.Current)
{
var squarefeetValue = currentRow["Shape_Area"];
long squarefeetValueLong;
squarefeetValueLong = Convert.ToInt64(squarefeetValue);
if (settingsValue == "current")
{
currentRow["High"] = (squarefeetValueLong / HighSetting);
currentRow["Medium"] = (squarefeetValueLong / MediumSetting);
currentRow["Low"] = (squarefeetValueLong / LowSetting);
currentRow["TargetSetting"] = TargetSetting;
currentRow["HighSetting"] = HighSetting;
currentRow["MediumSetting"] = MediumSetting;
currentRow["LowSetting"] = LowSetting;
}
else if (settingsValue == "default")
{
currentRow["High"] = squarefeetValueLong / 2.5;
currentRow["Medium"] = squarefeetValueLong / 4.5;
currentRow["Low"] = squarefeetValueLong / 10;
currentRow["TargetSetting"] = TargetSetting;
currentRow["HighSetting"] = 2.5;
currentRow["MediumSetting"] = 4.5;
currentRow["LowSetting"] = 10;
}
// Store the values
currentRow.Store();
// Has to be called after the store too.
context.Invalidate(currentRow);
}
}
CrowdTable.Dispose();
// close the editOperation.Callback(context
}, CrowdTable);
editOperation.ExecuteAsync();
}); // new closing QueuedTask
GetTotalValues();
}
#endregion
#region GetTotalValues
//public async void GetTotalValues()
public async void GetTotalValues()
{
long TotalValueLow = 0;
long TotalValueMedium = 0;
long TotalValueHigh = 0;
long targetSettingValue = 0;
double lowSettingValue = 0;
double mediumSettingValue = 0;
double highSettingValue = 0;
double targetRemaining = 0;
// Check for CrowdPlanning layer, exit if not present in current Map.
if (MapView.Active == null)
{
ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("CrowdPlanning Layer is not found. Please open the map view of the Crowd Planner data project.", "Error", MessageBoxButton.OK, MessageBoxImage.Exclamation);
return;
}
var CrowdLayerTest = MapView.Active.Map.FindLayers("CrowdPlanning").FirstOrDefault() as BasicFeatureLayer;
if (CrowdLayerTest == null)
{
ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("CrowdPlanning Layer is not found. Please use with the Crowd Planner data project.", "Error", MessageBoxButton.OK, MessageBoxImage.Exclamation);
return;
}
await QueuedTask.Run(() =>
{
// FeatureLayer CrowdLayer = MapView.Active.Map.FindLayer("CrowdPlanning") as FeatureLayer;
FeatureLayer CrowdLayer = MapView.Active.Map.GetLayersAsFlattenedList().FirstOrDefault(layer => layer.Name.Equals("CrowdPlanning")) as FeatureLayer;
//CrowdLayer.Search(null)
ArcGIS.Core.Data.Table CrowdTable = CrowdLayer.GetTable();
QueryFilter QF = new QueryFilter
{
WhereClause = "LOW > 0"
};
RowCursor CrowdRow = CrowdTable.Search(QF, false);
long lowValue;
long mediumValue;
long highValue;
while (CrowdRow.MoveNext())
{
lowValue = 0;
mediumValue = 0;
highValue = 0;
using (Row currentRow = CrowdRow.Current)
{
lowValue = Convert.ToInt32(currentRow["Low"]);
TotalValueLow = TotalValueLow + lowValue;
mediumValue = Convert.ToInt32(currentRow["Medium"]);
TotalValueMedium = TotalValueMedium + mediumValue;
highValue = Convert.ToInt32(currentRow["High"]);
TotalValueHigh = TotalValueHigh + highValue;
targetSettingValue = Convert.ToInt32(currentRow["TargetSetting"]);
lowSettingValue = Convert.ToDouble(currentRow["LowSetting"]);
mediumSettingValue = Convert.ToDouble(currentRow["MediumSetting"]);
highSettingValue = Convert.ToDouble(currentRow["HighSetting"]);
}
}
});
// Assign total values
TotalHigh = TotalValueHigh;
TotalMedium = TotalValueMedium;
TotalLow = TotalValueLow;
// Assign setting values
TargetSetting = targetSettingValue;
LowSetting = lowSettingValue;
MediumSetting = mediumSettingValue;
HighSetting = highSettingValue;
// UPDATE PIE CHARTS
// Chart 1 - High Estimate
if (TotalValueHigh > TargetSetting)
{
targetRemaining = 0;
_highBackground = "#9BBB59";
NotifyPropertyChanged(() => ColorBrush);
}
else
{
targetRemaining = (TargetSetting - TotalValueHigh);
_highBackground = textboxBackground;
NotifyPropertyChanged(() => ColorBrush);
}
KeyValuePair<string, int>[] myKeyValuePairHigh = new KeyValuePair<string, int>[]
{
new KeyValuePair<string,int>("High Estimate Allocated", Convert.ToInt32(TotalValueHigh)),
new KeyValuePair<string,int>("Remaining to Estimate", Convert.ToInt32(targetRemaining))
};
PieChartResult = myKeyValuePairHigh;
NotifyPropertyChanged(() => PieChartResult);
// Chart 2 - Medium Estimate
if (TotalValueMedium > TargetSetting)
{
targetRemaining = 0;
_mediumBackground = "#9BBB59";
NotifyPropertyChanged(() => ColorBrushMedium);
}
else
{
targetRemaining = (TargetSetting - TotalValueMedium);
_mediumBackground = textboxBackground;
NotifyPropertyChanged(() => ColorBrushMedium);
}
KeyValuePair<string, int>[] myKeyValuePairMedium = new KeyValuePair<string, int>[]
{
new KeyValuePair<string,int>("Medium Estimate Allocated", Convert.ToInt32(TotalValueMedium)),
new KeyValuePair<string,int>("Remaining to Estimate", Convert.ToInt32(targetRemaining))
};
PieChartResultMedium = myKeyValuePairMedium;
NotifyPropertyChanged(() => PieChartResultMedium);
// Chart 3 - Low Estimate
if (TotalValueLow > TargetSetting)
{
targetRemaining = 0;
_lowBackground = "#9BBB59";
NotifyPropertyChanged(() => ColorBrushLow);
}
else
{
targetRemaining = (TargetSetting - TotalValueLow);
_lowBackground = textboxBackground;
NotifyPropertyChanged(() => ColorBrushLow);
}
KeyValuePair<string, int>[] myKeyValuePairLow = new KeyValuePair<string, int>[]
{
new KeyValuePair<string,int>("Low Estimate Allocated", Convert.ToInt32(TotalValueLow)),
new KeyValuePair<string,int>("Remaining to Estimate", Convert.ToInt32(targetRemaining))
};
PieChartResultLow = myKeyValuePairLow;
NotifyPropertyChanged(() => PieChartResultLow);
//end of GetTotalValues
}
#endregion
}
}
| |
/*
* DISCLAIMER
*
* Copyright 2016 ArangoDB GmbH, Cologne, Germany
*
* 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.
*
* Copyright holder is ArangoDB GmbH, Cologne, Germany
*/
namespace ArangoDB.Internal.VelocyPack
{
using global::ArangoDB.Entity;
using global::ArangoDB.Internal.VelocyStream;
using global::ArangoDB.Model;
using global::ArangoDB.Velocypack;
using global::ArangoDB.Velocypack.Exceptions;
using global::ArangoDB.Velocystream;
/// <author>Mark - mark at arangodb.com</author>
public class VPackSerializers
{
private sealed class _VPackSerializer_48 : VPackSerializer
<Request>
{
public _VPackSerializer_48()
{
}
/// <exception cref="VPackException"/>
public void serialize(VPackBuilder builder, string attribute
, Request value, VPackSerializationContext
context)
{
builder.Add(attribute, ValueType.ARRAY);
builder.Add(value.getVersion());
builder.Add(value.getType());
builder.Add(value.getDatabase());
builder.Add(value.getRequestType().getType());
builder.Add(value.getRequest());
builder.Add(ValueType.OBJECT);
foreach (System.Collections.Generic.KeyValuePair<string, string> entry in value.getQueryParam
())
{
builder.Add(entry.Key, entry.Value);
}
builder.Close();
builder.Add(ValueType.OBJECT);
foreach (System.Collections.Generic.KeyValuePair<string, string> entry_1 in value
.getHeaderParam())
{
builder.Add(entry_1.Key, entry_1.Value);
}
builder.Close();
builder.Close();
}
}
public static readonly VPackSerializer<Request
> REQUEST = new _VPackSerializer_48();
private sealed class _VPackSerializer_75 : VPackSerializer
<AuthenticationRequest>
{
public _VPackSerializer_75()
{
}
/// <exception cref="VPackException"/>
public void serialize(VPackBuilder builder, string attribute
, AuthenticationRequest value, VPackSerializationContext
context)
{
builder.Add(attribute, ValueType.ARRAY);
builder.Add(value.getVersion());
builder.Add(value.getType());
builder.Add(value.getEncryption());
builder.Add(value.getUser());
builder.Add(value.getPassword());
builder.Close();
}
}
public static readonly VPackSerializer<AuthenticationRequest
> AUTH_REQUEST = new _VPackSerializer_75();
private sealed class _VPackSerializer_92 : VPackSerializer
<CollectionType>
{
public _VPackSerializer_92()
{
}
/// <exception cref="VPackException"/>
public void serialize(VPackBuilder builder, string attribute
, CollectionType value, VPackSerializationContext
context)
{
builder.Add(attribute, value.getType());
}
}
public static readonly VPackSerializer<CollectionType
> COLLECTION_TYPE = new _VPackSerializer_92();
private sealed class _VPackSerializer_103 : VPackSerializer
<BaseDocument>
{
public _VPackSerializer_103()
{
}
/// <exception cref="VPackException"/>
public void serialize(VPackBuilder builder, string attribute
, BaseDocument value, VPackSerializationContext
context)
{
System.Collections.Generic.IDictionary<string, object> doc = new System.Collections.Generic.Dictionary
<string, object>();
doc.putAll(value.getProperties());
doc[com.arangodb.entity.DocumentFieldAttribute.Type.ID.getSerializeName()] = value.getId();
doc[com.arangodb.entity.DocumentFieldAttribute.Type.KEY.getSerializeName()] = value.getKey
();
doc[com.arangodb.entity.DocumentFieldAttribute.Type.REV.getSerializeName()] = value.getRevision
();
context.serialize(builder, attribute, doc);
}
}
public static readonly VPackSerializer<BaseDocument
> BASE_DOCUMENT = new _VPackSerializer_103();
private sealed class _VPackSerializer_119 : VPackSerializer
<BaseEdgeDocument>
{
public _VPackSerializer_119()
{
}
/// <exception cref="VPackException"/>
public void serialize(VPackBuilder builder, string attribute
, BaseEdgeDocument value, VPackSerializationContext
context)
{
System.Collections.Generic.IDictionary<string, object> doc = new System.Collections.Generic.Dictionary
<string, object>();
doc.putAll(value.getProperties());
doc[com.arangodb.entity.DocumentFieldAttribute.Type.ID.getSerializeName()] = value.getId();
doc[com.arangodb.entity.DocumentFieldAttribute.Type.KEY.getSerializeName()] = value.getKey
();
doc[com.arangodb.entity.DocumentFieldAttribute.Type.REV.getSerializeName()] = value.getRevision
();
doc[com.arangodb.entity.DocumentFieldAttribute.Type.FROM.getSerializeName()] = value.getFrom
();
doc[com.arangodb.entity.DocumentFieldAttribute.Type.TO.getSerializeName()] = value.getTo();
context.serialize(builder, attribute, doc);
}
}
public static readonly VPackSerializer<BaseEdgeDocument
> BASE_EDGE_DOCUMENT = new _VPackSerializer_119();
private sealed class _VPackSerializer_137 : VPackSerializer
<TraversalOptions.Order>
{
public _VPackSerializer_137()
{
}
/// <exception cref="VPackException"/>
public void serialize(VPackBuilder builder, string attribute
, TraversalOptions.Order value, VPackSerializationContext
context)
{
if (TraversalOptions.Order.preorder_expander == value)
{
builder.Add(attribute, "preorder-expander");
}
else
{
builder.Add(attribute, value.ToString());
}
}
}
public static readonly VPackSerializer<TraversalOptions.Order
> TRAVERSAL_ORDER = new _VPackSerializer_137();
private sealed class _VPackSerializer_152 : VPackSerializer
<LogLevel>
{
public _VPackSerializer_152()
{
}
/// <exception cref="VPackException"/>
public void serialize(VPackBuilder builder, string attribute
, LogLevel value, VPackSerializationContext
context)
{
builder.Add(attribute, value.getLevel());
}
}
public static readonly VPackSerializer<LogLevel
> LOG_LEVEL = new _VPackSerializer_152();
}
}
| |
// 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.Diagnostics.Contracts;
using System;
namespace System.Text
{
public class Encoding
{
public int WindowsCodePage
{
get;
}
public bool IsMailNewsDisplay
{
get;
}
public static Encoding! UTF8
{
get;
}
public static Encoding! Default
{
get;
}
public bool IsMailNewsSave
{
get;
}
public string EncodingName
{
get;
}
public string BodyName
{
get;
}
public static Encoding! UTF7
{
get;
}
public string HeaderName
{
get;
}
public int CodePage
{
get;
}
public bool IsBrowserSave
{
get;
}
public static Encoding! Unicode
{
get;
}
public string WebName
{
get;
}
public static Encoding! BigEndianUnicode
{
get;
}
public static Encoding! ASCII
{
get;
}
public bool IsBrowserDisplay
{
get;
}
public string GetString (byte[] bytes, int index, int count) {
return default(string);
}
public string GetString (byte[]! bytes) {
CodeContract.Requires(bytes != null);
return default(string);
}
public int GetMaxCharCount (int arg0) {
return default(int);
}
public int GetMaxByteCount (int arg0) {
return default(int);
}
public Encoder GetEncoder () {
return default(Encoder);
}
public Decoder GetDecoder () {
return default(Decoder);
}
public int GetChars (byte[] arg0, int arg1, int arg2, char[] arg3, int arg4) {
return default(int);
}
public char[] GetChars (byte[] bytes, int index, int count) {
return default(char[]);
}
public char[] GetChars (byte[]! bytes) {
CodeContract.Requires(bytes != null);
return default(char[]);
}
public int GetCharCount (byte[] arg0, int arg1, int arg2) {
return default(int);
}
public int GetCharCount (byte[]! bytes) {
CodeContract.Requires(bytes != null);
return default(int);
}
public int GetBytes (string! s, int charIndex, int charCount, byte[] bytes, int byteIndex) {
CodeContract.Requires(s != null);
return default(int);
}
public byte[] GetBytes (string! s) {
CodeContract.Requires(s != null);
return default(byte[]);
}
public int GetBytes (char[] arg0, int arg1, int arg2, byte[] arg3, int arg4) {
return default(int);
}
public byte[] GetBytes (char[] chars, int index, int count) {
return default(byte[]);
}
public byte[] GetBytes (char[]! chars) {
CodeContract.Requires(chars != null);
return default(byte[]);
}
public int GetByteCount (char[] arg0, int arg1, int arg2) {
return default(int);
}
public int GetByteCount (string! s) {
CodeContract.Requires(s != null);
return default(int);
}
public int GetByteCount (char[]! chars) {
CodeContract.Requires(chars != null);
return default(int);
}
public byte[] GetPreamble () {
return default(byte[]);
}
public static Encoding GetEncoding (string name) {
CodeContract.Ensures(CodeContract.Result<Encoding>() != null);
return default(Encoding);
}
public static Encoding GetEncoding (int codepage) {
CodeContract.Requires(codepage >= 0);
CodeContract.Requires(codepage <= 65535);
CodeContract.Ensures(CodeContract.Result<Encoding>() != null);
return default(Encoding);
}
public static byte[] Convert (Encoding! srcEncoding, Encoding! dstEncoding, byte[]! bytes, int index, int count) {
CodeContract.Requires(srcEncoding != null);
CodeContract.Requires(dstEncoding != null);
CodeContract.Requires(bytes != null);
return default(byte[]);
}
public static byte[] Convert (Encoding srcEncoding, Encoding dstEncoding, byte[]! bytes) {
CodeContract.Requires(bytes != null);
return default(byte[]);
}
}
}
| |
using J2N.Collections.Generic.Extensions;
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
namespace Lucene.Net.Util
{
/*
* 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.
*/
/// <summary>
/// Methods for manipulating (sorting) collections.
/// Sort methods work directly on the supplied lists and don't copy to/from arrays
/// before/after. For medium size collections as used in the Lucene indexer that is
/// much more efficient.
/// <para/>
/// @lucene.internal
/// </summary>
public static class CollectionUtil // LUCENENET specific - made static
{
private sealed class ListIntroSorter<T> : IntroSorter
{
internal T pivot;
internal IList<T> list;
internal readonly IComparer<T> comp;
internal ListIntroSorter(IList<T> list, IComparer<T> comp)
: base()
{
// LUCENENET NOTE: All ILists in .NET are random access (only IEnumerable is forward-only)
//if (!(list is RandomAccess))
//{
// throw new ArgumentException("CollectionUtil can only sort random access lists in-place.");
//}
this.list = list;
this.comp = comp;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected override void SetPivot(int i)
{
pivot = (i < list.Count) ? list[i] : default;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected override void Swap(int i, int j)
{
list.Swap(i, j);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected override int Compare(int i, int j)
{
return comp.Compare(list[i], list[j]);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected override int ComparePivot(int j)
{
return comp.Compare(pivot, list[j]);
}
}
private sealed class ListTimSorter<T> : TimSorter
{
internal IList<T> list;
internal readonly IComparer<T> comp;
internal readonly T[] tmp;
internal ListTimSorter(IList<T> list, IComparer<T> comp, int maxTempSlots)
: base(maxTempSlots)
{
// LUCENENET NOTE: All ILists in .NET are random access (only IEnumerable is forward-only)
//if (!(list is RandomAccess))
//{
// throw new ArgumentException("CollectionUtil can only sort random access lists in-place.");
//}
this.list = list;
this.comp = comp;
if (maxTempSlots > 0)
{
this.tmp = new T[maxTempSlots];
}
else
{
this.tmp = null;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected override void Swap(int i, int j)
{
list.Swap(i, j);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected override void Copy(int src, int dest)
{
list[dest] = list[src];
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected override void Save(int i, int len)
{
for (int j = 0; j < len; ++j)
{
tmp[j] = list[i + j];
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected override void Restore(int i, int j)
{
list[j] = tmp[i];
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected override int Compare(int i, int j)
{
return comp.Compare(list[i], list[j]);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected override int CompareSaved(int i, int j)
{
return comp.Compare(tmp[i], list[j]);
}
}
/// <summary>
/// Sorts the given <see cref="IList{T}"/> using the <see cref="IComparer{T}"/>.
/// This method uses the intro sort
/// algorithm, but falls back to insertion sort for small lists.
/// </summary>
/// <param name="list">This <see cref="IList{T}"/></param>
/// <param name="comp">The <see cref="IComparer{T}"/> to use for the sort.</param>
public static void IntroSort<T>(IList<T> list, IComparer<T> comp)
{
int size = list.Count;
if (size <= 1)
{
return;
}
(new ListIntroSorter<T>(list, comp)).Sort(0, size);
}
/// <summary>
/// Sorts the given random access <see cref="IList{T}"/> in natural order.
/// This method uses the intro sort
/// algorithm, but falls back to insertion sort for small lists.
/// </summary>
/// <param name="list">This <see cref="IList{T}"/></param>
public static void IntroSort<T>(IList<T> list)
//where T : IComparable<T> // LUCENENET specific: removing constraint because in .NET, it is not needed
{
int size = list.Count;
if (size <= 1)
{
return;
}
IntroSort(list, ArrayUtil.GetNaturalComparer<T>());
}
// Tim sorts:
/// <summary>
/// Sorts the given <see cref="IList{T}"/> using the <see cref="IComparer{T}"/>.
/// This method uses the Tim sort
/// algorithm, but falls back to binary sort for small lists.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list">this <see cref="IList{T}"/></param>
/// <param name="comp">The <see cref="IComparer{T}"/> to use for the sort.</param>
public static void TimSort<T>(IList<T> list, IComparer<T> comp)
{
int size = list.Count;
if (size <= 1)
{
return;
}
(new ListTimSorter<T>(list, comp, list.Count / 64)).Sort(0, size);
}
/// <summary>
/// Sorts the given <see cref="IList{T}"/> in natural order.
/// This method uses the Tim sort
/// algorithm, but falls back to binary sort for small lists. </summary>
/// <param name="list">This <see cref="IList{T}"/></param>
public static void TimSort<T>(IList<T> list)
//where T : IComparable<T> // LUCENENET specific: removing constraint because in .NET, it is not needed
{
int size = list.Count;
if (size <= 1)
{
return;
}
TimSort(list, ArrayUtil.GetNaturalComparer<T>());
}
}
}
| |
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using SR = System.Reflection;
using Mono.Cecil.Cil;
using Mono.Cecil.Metadata;
using Mono.Cecil.PE;
using Mono.Collections.Generic;
namespace Mono.Cecil {
public enum ReadingMode {
Immediate = 1,
Deferred = 2,
}
public sealed class ReaderParameters {
ReadingMode reading_mode;
IAssemblyResolver assembly_resolver;
IMetadataResolver metadata_resolver;
Stream symbol_stream;
ISymbolReaderProvider symbol_reader_provider;
bool read_symbols;
public ReadingMode ReadingMode {
get { return reading_mode; }
set { reading_mode = value; }
}
public IAssemblyResolver AssemblyResolver {
get { return assembly_resolver; }
set { assembly_resolver = value; }
}
public IMetadataResolver MetadataResolver {
get { return metadata_resolver; }
set { metadata_resolver = value; }
}
public Stream SymbolStream {
get { return symbol_stream; }
set { symbol_stream = value; }
}
public ISymbolReaderProvider SymbolReaderProvider {
get { return symbol_reader_provider; }
set { symbol_reader_provider = value; }
}
public bool ReadSymbols {
get { return read_symbols; }
set { read_symbols = value; }
}
public ReaderParameters ()
: this (ReadingMode.Deferred)
{
}
public ReaderParameters (ReadingMode readingMode)
{
this.reading_mode = readingMode;
}
}
#if !READ_ONLY
public sealed class ModuleParameters {
ModuleKind kind;
TargetRuntime runtime;
TargetArchitecture architecture;
IAssemblyResolver assembly_resolver;
IMetadataResolver metadata_resolver;
public ModuleKind Kind {
get { return kind; }
set { kind = value; }
}
public TargetRuntime Runtime {
get { return runtime; }
set { runtime = value; }
}
public TargetArchitecture Architecture {
get { return architecture; }
set { architecture = value; }
}
public IAssemblyResolver AssemblyResolver {
get { return assembly_resolver; }
set { assembly_resolver = value; }
}
public IMetadataResolver MetadataResolver {
get { return metadata_resolver; }
set { metadata_resolver = value; }
}
public ModuleParameters ()
{
this.kind = ModuleKind.Dll;
this.Runtime = GetCurrentRuntime ();
this.architecture = TargetArchitecture.I386;
}
static TargetRuntime GetCurrentRuntime ()
{
#if !CF
return typeof (object).Assembly.ImageRuntimeVersion.ParseRuntime ();
#else
var corlib_version = typeof (object).Assembly.GetName ().Version;
switch (corlib_version.Major) {
case 1:
return corlib_version.Minor == 0
? TargetRuntime.Net_1_0
: TargetRuntime.Net_1_1;
case 2:
return TargetRuntime.Net_2_0;
case 4:
return TargetRuntime.Net_4_0;
default:
throw new NotSupportedException ();
}
#endif
}
}
public sealed class WriterParameters {
Stream symbol_stream;
ISymbolWriterProvider symbol_writer_provider;
bool write_symbols;
#if !SILVERLIGHT && !CF
SR.StrongNameKeyPair key_pair;
#endif
public Stream SymbolStream {
get { return symbol_stream; }
set { symbol_stream = value; }
}
public ISymbolWriterProvider SymbolWriterProvider {
get { return symbol_writer_provider; }
set { symbol_writer_provider = value; }
}
public bool WriteSymbols {
get { return write_symbols; }
set { write_symbols = value; }
}
#if !SILVERLIGHT && !CF
public SR.StrongNameKeyPair StrongNameKeyPair {
get { return key_pair; }
set { key_pair = value; }
}
#endif
}
#endif
public sealed class ModuleDefinition : ModuleReference, ICustomAttributeProvider {
internal Image Image;
internal MetadataSystem MetadataSystem;
internal ReadingMode ReadingMode;
internal ISymbolReaderProvider SymbolReaderProvider;
internal ISymbolReader symbol_reader;
internal IAssemblyResolver assembly_resolver;
internal IMetadataResolver metadata_resolver;
internal TypeSystem type_system;
readonly MetadataReader reader;
readonly string fq_name;
internal string runtime_version;
internal ModuleKind kind;
TargetRuntime runtime;
TargetArchitecture architecture;
ModuleAttributes attributes;
ModuleCharacteristics characteristics;
Guid mvid;
internal AssemblyDefinition assembly;
MethodDefinition entry_point;
#if !READ_ONLY
MetadataImporter importer;
#endif
Collection<CustomAttribute> custom_attributes;
Collection<AssemblyNameReference> references;
Collection<ModuleReference> modules;
Collection<Resource> resources;
Collection<ExportedType> exported_types;
TypeDefinitionCollection types;
public bool IsMain {
get { return kind != ModuleKind.NetModule; }
}
public ModuleKind Kind {
get { return kind; }
set { kind = value; }
}
public TargetRuntime Runtime {
get { return runtime; }
set {
runtime = value;
runtime_version = runtime.RuntimeVersionString ();
}
}
public string RuntimeVersion {
get { return runtime_version; }
set {
runtime_version = value;
runtime = runtime_version.ParseRuntime ();
}
}
public TargetArchitecture Architecture {
get { return architecture; }
set { architecture = value; }
}
public ModuleAttributes Attributes {
get { return attributes; }
set { attributes = value; }
}
public ModuleCharacteristics Characteristics {
get { return characteristics; }
set { characteristics = value; }
}
public string FullyQualifiedName {
get { return fq_name; }
}
public Guid Mvid {
get { return mvid; }
set { mvid = value; }
}
internal bool HasImage {
get { return Image != null; }
}
public bool HasSymbols {
get { return symbol_reader != null; }
}
public ISymbolReader SymbolReader {
get { return symbol_reader; }
}
public override MetadataScopeType MetadataScopeType {
get { return MetadataScopeType.ModuleDefinition; }
}
public AssemblyDefinition Assembly {
get { return assembly; }
}
#if !READ_ONLY
internal MetadataImporter MetadataImporter {
get {
if (importer == null)
Interlocked.CompareExchange (ref importer, new MetadataImporter (this), null);
return importer;
}
}
#endif
public IAssemblyResolver AssemblyResolver {
get {
if (assembly_resolver == null)
Interlocked.CompareExchange (ref assembly_resolver, new DefaultAssemblyResolver (), null);
return assembly_resolver;
}
}
public IMetadataResolver MetadataResolver {
get {
if (metadata_resolver == null)
Interlocked.CompareExchange (ref metadata_resolver, new MetadataResolver (this.AssemblyResolver), null);
return metadata_resolver;
}
}
public TypeSystem TypeSystem {
get {
if (type_system == null)
Interlocked.CompareExchange (ref type_system, TypeSystem.CreateTypeSystem (this), null);
return type_system;
}
}
public bool HasAssemblyReferences {
get {
if (references != null)
return references.Count > 0;
return HasImage && Image.HasTable (Table.AssemblyRef);
}
}
public Collection<AssemblyNameReference> AssemblyReferences {
get {
if (references != null)
return references;
if (HasImage)
return Read (ref references, this, (_, reader) => reader.ReadAssemblyReferences ());
return references = new Collection<AssemblyNameReference> ();
}
}
public bool HasModuleReferences {
get {
if (modules != null)
return modules.Count > 0;
return HasImage && Image.HasTable (Table.ModuleRef);
}
}
public Collection<ModuleReference> ModuleReferences {
get {
if (modules != null)
return modules;
if (HasImage)
return Read (ref modules, this, (_, reader) => reader.ReadModuleReferences ());
return modules = new Collection<ModuleReference> ();
}
}
public bool HasResources {
get {
if (resources != null)
return resources.Count > 0;
if (HasImage)
return Image.HasTable (Table.ManifestResource) || Read (this, (_, reader) => reader.HasFileResource ());
return false;
}
}
public Collection<Resource> Resources {
get {
if (resources != null)
return resources;
if (HasImage)
return Read (ref resources, this, (_, reader) => reader.ReadResources ());
return resources = new Collection<Resource> ();
}
}
public bool HasCustomAttributes {
get {
if (custom_attributes != null)
return custom_attributes.Count > 0;
return this.GetHasCustomAttributes (this);
}
}
public Collection<CustomAttribute> CustomAttributes {
get { return custom_attributes ?? (this.GetCustomAttributes (ref custom_attributes, this)); }
}
public bool HasTypes {
get {
if (types != null)
return types.Count > 0;
return HasImage && Image.HasTable (Table.TypeDef);
}
}
public Collection<TypeDefinition> Types {
get {
if (types != null)
return types;
if (HasImage)
return Read (ref types, this, (_, reader) => reader.ReadTypes ());
return types = new TypeDefinitionCollection (this);
}
}
public bool HasExportedTypes {
get {
if (exported_types != null)
return exported_types.Count > 0;
return HasImage && Image.HasTable (Table.ExportedType);
}
}
public Collection<ExportedType> ExportedTypes {
get {
if (exported_types != null)
return exported_types;
if (HasImage)
return Read (ref exported_types, this, (_, reader) => reader.ReadExportedTypes ());
return exported_types = new Collection<ExportedType> ();
}
}
public MethodDefinition EntryPoint {
get {
if (entry_point != null)
return entry_point;
if (HasImage)
return Read (ref entry_point, this, (_, reader) => reader.ReadEntryPoint ());
return entry_point = null;
}
set { entry_point = value; }
}
internal ModuleDefinition ()
{
this.MetadataSystem = new MetadataSystem ();
this.token = new MetadataToken (TokenType.Module, 1);
}
internal ModuleDefinition (Image image)
: this ()
{
this.Image = image;
this.kind = image.Kind;
this.RuntimeVersion = image.RuntimeVersion;
this.architecture = image.Architecture;
this.attributes = image.Attributes;
this.characteristics = image.Characteristics;
this.fq_name = image.FileName;
this.reader = new MetadataReader (this);
}
public bool HasTypeReference (string fullName)
{
return HasTypeReference (string.Empty, fullName);
}
public bool HasTypeReference (string scope, string fullName)
{
CheckFullName (fullName);
if (!HasImage)
return false;
return GetTypeReference (scope, fullName) != null;
}
public bool TryGetTypeReference (string fullName, out TypeReference type)
{
return TryGetTypeReference (string.Empty, fullName, out type);
}
public bool TryGetTypeReference (string scope, string fullName, out TypeReference type)
{
CheckFullName (fullName);
if (!HasImage) {
type = null;
return false;
}
return (type = GetTypeReference (scope, fullName)) != null;
}
TypeReference GetTypeReference (string scope, string fullname)
{
return Read (new Row<string, string> (scope, fullname), (row, reader) => reader.GetTypeReference (row.Col1, row.Col2));
}
public IEnumerable<TypeReference> GetTypeReferences ()
{
if (!HasImage)
return Empty<TypeReference>.Array;
return Read (this, (_, reader) => reader.GetTypeReferences ());
}
public IEnumerable<MemberReference> GetMemberReferences ()
{
if (!HasImage)
return Empty<MemberReference>.Array;
return Read (this, (_, reader) => reader.GetMemberReferences ());
}
public TypeReference GetType (string fullName, bool runtimeName)
{
return runtimeName
? TypeParser.ParseType (this, fullName)
: GetType (fullName);
}
public TypeDefinition GetType (string fullName)
{
CheckFullName (fullName);
var position = fullName.IndexOf ('/');
if (position > 0)
return GetNestedType (fullName);
return ((TypeDefinitionCollection) this.Types).GetType (fullName);
}
public TypeDefinition GetType (string @namespace, string name)
{
Mixin.CheckName (name);
return ((TypeDefinitionCollection) this.Types).GetType (@namespace ?? string.Empty, name);
}
public IEnumerable<TypeDefinition> GetTypes ()
{
return GetTypes (Types);
}
static IEnumerable<TypeDefinition> GetTypes (Collection<TypeDefinition> types)
{
for (int i = 0; i < types.Count; i++) {
var type = types [i];
yield return type;
if (!type.HasNestedTypes)
continue;
foreach (var nested in GetTypes (type.NestedTypes))
yield return nested;
}
}
static void CheckFullName (string fullName)
{
if (fullName == null)
throw new ArgumentNullException ("fullName");
if (fullName.Length == 0)
throw new ArgumentException ();
}
TypeDefinition GetNestedType (string fullname)
{
var names = fullname.Split ('/');
var type = GetType (names [0]);
if (type == null)
return null;
for (int i = 1; i < names.Length; i++) {
var nested_type = type.GetNestedType (names [i]);
if (nested_type == null)
return null;
type = nested_type;
}
return type;
}
internal FieldDefinition Resolve (FieldReference field)
{
return MetadataResolver.Resolve (field);
}
internal MethodDefinition Resolve (MethodReference method)
{
return MetadataResolver.Resolve (method);
}
internal TypeDefinition Resolve (TypeReference type)
{
return MetadataResolver.Resolve (type);
}
#if !READ_ONLY
static void CheckType (object type)
{
if (type == null)
throw new ArgumentNullException ("type");
}
static void CheckField (object field)
{
if (field == null)
throw new ArgumentNullException ("field");
}
static void CheckMethod (object method)
{
if (method == null)
throw new ArgumentNullException ("method");
}
static void CheckContext (IGenericParameterProvider context, ModuleDefinition module)
{
if (context == null)
return;
if (context.Module != module)
throw new ArgumentException ();
}
static ImportGenericContext GenericContextFor (IGenericParameterProvider context)
{
return context != null ? new ImportGenericContext (context) : default (ImportGenericContext);
}
#if !CF
public TypeReference Import (Type type)
{
return Import (type, null);
}
public TypeReference Import (Type type, IGenericParameterProvider context)
{
CheckType (type);
CheckContext (context, this);
return MetadataImporter.ImportType (
type,
GenericContextFor (context),
context != null ? ImportGenericKind.Open : ImportGenericKind.Definition);
}
public FieldReference Import (SR.FieldInfo field)
{
return Import (field, null);
}
public FieldReference Import (SR.FieldInfo field, IGenericParameterProvider context)
{
CheckField (field);
CheckContext (context, this);
return MetadataImporter.ImportField (field, GenericContextFor (context));
}
public MethodReference Import (SR.MethodBase method)
{
CheckMethod (method);
return MetadataImporter.ImportMethod (method, default (ImportGenericContext), ImportGenericKind.Definition);
}
public MethodReference Import (SR.MethodBase method, IGenericParameterProvider context)
{
CheckMethod (method);
CheckContext (context, this);
return MetadataImporter.ImportMethod (method,
GenericContextFor (context),
context != null ? ImportGenericKind.Open : ImportGenericKind.Definition);
}
#endif
public TypeReference Import (TypeReference type)
{
CheckType (type);
if (type.Module == this)
return type;
return MetadataImporter.ImportType (type, default (ImportGenericContext));
}
public TypeReference Import (TypeReference type, IGenericParameterProvider context)
{
CheckType (type);
if (type.Module == this)
return type;
CheckContext (context, this);
return MetadataImporter.ImportType (type, GenericContextFor (context));
}
public FieldReference Import (FieldReference field)
{
CheckField (field);
if (field.Module == this)
return field;
return MetadataImporter.ImportField (field, default (ImportGenericContext));
}
public FieldReference Import (FieldReference field, IGenericParameterProvider context)
{
CheckField (field);
if (field.Module == this)
return field;
CheckContext (context, this);
return MetadataImporter.ImportField (field, GenericContextFor (context));
}
public MethodReference Import (MethodReference method)
{
return Import (method, null);
}
public MethodReference Import (MethodReference method, IGenericParameterProvider context)
{
CheckMethod (method);
if (method.Module == this)
return method;
CheckContext (context, this);
return MetadataImporter.ImportMethod (method, GenericContextFor (context));
}
#endif
public IMetadataTokenProvider LookupToken (int token)
{
return LookupToken (new MetadataToken ((uint) token));
}
public IMetadataTokenProvider LookupToken (MetadataToken token)
{
return Read (token, (t, reader) => reader.LookupToken (t));
}
readonly object module_lock = new object();
internal object SyncRoot {
get { return module_lock; }
}
internal TRet Read<TItem, TRet> (TItem item, Func<TItem, MetadataReader, TRet> read)
{
lock (module_lock) {
var position = reader.position;
var context = reader.context;
var ret = read (item, reader);
reader.position = position;
reader.context = context;
return ret;
}
}
internal TRet Read<TItem, TRet> (ref TRet variable, TItem item, Func<TItem, MetadataReader, TRet> read) where TRet : class
{
lock (module_lock) {
if (variable != null)
return variable;
var position = reader.position;
var context = reader.context;
var ret = read (item, reader);
reader.position = position;
reader.context = context;
return variable = ret;
}
}
public bool HasDebugHeader {
get { return Image != null && !Image.Debug.IsZero; }
}
public ImageDebugDirectory GetDebugHeader (out byte [] header)
{
if (!HasDebugHeader)
throw new InvalidOperationException ();
return Image.GetDebugHeader (out header);
}
void ProcessDebugHeader ()
{
if (!HasDebugHeader)
return;
byte [] header;
var directory = GetDebugHeader (out header);
if (!symbol_reader.ProcessDebugHeader (directory, header))
throw new InvalidOperationException ();
}
#if !READ_ONLY
public static ModuleDefinition CreateModule (string name, ModuleKind kind)
{
return CreateModule (name, new ModuleParameters { Kind = kind });
}
public static ModuleDefinition CreateModule (string name, ModuleParameters parameters)
{
Mixin.CheckName (name);
Mixin.CheckParameters (parameters);
var module = new ModuleDefinition {
Name = name,
kind = parameters.Kind,
Runtime = parameters.Runtime,
architecture = parameters.Architecture,
mvid = Guid.NewGuid (),
Attributes = ModuleAttributes.ILOnly,
Characteristics = (ModuleCharacteristics) 0x8540,
};
if (parameters.AssemblyResolver != null)
module.assembly_resolver = parameters.AssemblyResolver;
if (parameters.MetadataResolver != null)
module.metadata_resolver = parameters.MetadataResolver;
if (parameters.Kind != ModuleKind.NetModule) {
var assembly = new AssemblyDefinition ();
module.assembly = assembly;
module.assembly.Name = CreateAssemblyName (name);
assembly.main_module = module;
}
module.Types.Add (new TypeDefinition (string.Empty, "<Module>", TypeAttributes.NotPublic));
return module;
}
static AssemblyNameDefinition CreateAssemblyName (string name)
{
if (name.EndsWith (".dll") || name.EndsWith (".exe"))
name = name.Substring (0, name.Length - 4);
return new AssemblyNameDefinition (name, new Version (0, 0, 0, 0));
}
#endif
public void ReadSymbols ()
{
if (string.IsNullOrEmpty (fq_name))
throw new InvalidOperationException ();
var provider = SymbolProvider.GetPlatformReaderProvider ();
if (provider == null)
throw new InvalidOperationException ();
ReadSymbols (provider.GetSymbolReader (this, fq_name));
}
public void ReadSymbols (ISymbolReader reader)
{
if (reader == null)
throw new ArgumentNullException ("reader");
symbol_reader = reader;
ProcessDebugHeader ();
}
public static ModuleDefinition ReadModule (string fileName)
{
return ReadModule (fileName, new ReaderParameters (ReadingMode.Deferred));
}
public static ModuleDefinition ReadModule (Stream stream)
{
return ReadModule (stream, new ReaderParameters (ReadingMode.Deferred));
}
public static ModuleDefinition ReadModule (string fileName, ReaderParameters parameters)
{
using (var stream = GetFileStream (fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) {
return ReadModule (stream, parameters);
}
}
static void CheckStream (object stream)
{
if (stream == null)
throw new ArgumentNullException ("stream");
}
public static ModuleDefinition ReadModule (Stream stream, ReaderParameters parameters)
{
CheckStream (stream);
if (!stream.CanRead || !stream.CanSeek)
throw new ArgumentException ();
Mixin.CheckParameters (parameters);
return ModuleReader.CreateModuleFrom (
ImageReader.ReadImageFrom (stream),
parameters);
}
static Stream GetFileStream (string fileName, FileMode mode, FileAccess access, FileShare share)
{
if (fileName == null)
throw new ArgumentNullException ("fileName");
if (fileName.Length == 0)
throw new ArgumentException ();
return new FileStream (fileName, mode, access, share);
}
#if !READ_ONLY
public void Write (string fileName)
{
Write (fileName, new WriterParameters ());
}
public void Write (Stream stream)
{
Write (stream, new WriterParameters ());
}
public void Write (string fileName, WriterParameters parameters)
{
using (var stream = GetFileStream (fileName, FileMode.Create, FileAccess.ReadWrite, FileShare.None)) {
Write (stream, parameters);
}
}
public void Write (Stream stream, WriterParameters parameters)
{
CheckStream (stream);
if (!stream.CanWrite || !stream.CanSeek)
throw new ArgumentException ();
Mixin.CheckParameters (parameters);
ModuleWriter.WriteModuleTo (this, stream, parameters);
}
#endif
}
static partial class Mixin {
public static void CheckParameters (object parameters)
{
if (parameters == null)
throw new ArgumentNullException ("parameters");
}
public static bool HasImage (this ModuleDefinition self)
{
return self != null && self.HasImage;
}
public static bool IsCorlib (this ModuleDefinition module)
{
if (module.Assembly == null)
return false;
return module.Assembly.Name.Name == "mscorlib";
}
public static string GetFullyQualifiedName (this Stream self)
{
#if !SILVERLIGHT
var file_stream = self as FileStream;
if (file_stream == null)
return string.Empty;
return Path.GetFullPath (file_stream.Name);
#else
return string.Empty;
#endif
}
public static TargetRuntime ParseRuntime (this string self)
{
switch (self [1]) {
case '1':
return self [3] == '0'
? TargetRuntime.Net_1_0
: TargetRuntime.Net_1_1;
case '2':
return TargetRuntime.Net_2_0;
case '4':
default:
return TargetRuntime.Net_4_0;
}
}
public static string RuntimeVersionString (this TargetRuntime runtime)
{
switch (runtime) {
case TargetRuntime.Net_1_0:
return "v1.0.3705";
case TargetRuntime.Net_1_1:
return "v1.1.4322";
case TargetRuntime.Net_2_0:
return "v2.0.50727";
case TargetRuntime.Net_4_0:
default:
return "v4.0.30319";
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using Microsoft.AspNetCore.Http;
using Microsoft.Net.Http.Headers;
using Xunit;
namespace Microsoft.AspNetCore.Internal
{
public class CookieChunkingTests
{
[Fact]
public void AppendLargeCookie_Appended()
{
HttpContext context = new DefaultHttpContext();
string testString = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
new ChunkingCookieManager() { ChunkSize = null }.AppendResponseCookie(context, "TestCookie", testString, new CookieOptions());
var values = context.Response.Headers["Set-Cookie"];
Assert.Single(values);
Assert.Equal("TestCookie=" + testString + "; path=/", values[0]);
}
[Fact]
public void AppendLargeCookie_WithOptions_Appended()
{
HttpContext context = new DefaultHttpContext();
var now = DateTimeOffset.UtcNow;
var options = new CookieOptions
{
Domain = "foo.com",
HttpOnly = true,
SameSite = Http.SameSiteMode.Strict,
Path = "/bar",
Secure = true,
Expires = now.AddMinutes(5),
MaxAge = TimeSpan.FromMinutes(5)
};
var testString = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
new ChunkingCookieManager() { ChunkSize = null }.AppendResponseCookie(context, "TestCookie", testString, options);
var values = context.Response.Headers["Set-Cookie"];
Assert.Single(values);
Assert.Equal($"TestCookie={testString}; expires={now.AddMinutes(5).ToString("R")}; max-age=300; domain=foo.com; path=/bar; secure; samesite=strict; httponly", values[0]);
}
[Fact]
public void AppendLargeCookieWithLimit_Chunked()
{
HttpContext context = new DefaultHttpContext();
string testString = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
new ChunkingCookieManager() { ChunkSize = 44 }.AppendResponseCookie(context, "TestCookie", testString, new CookieOptions());
var values = context.Response.Headers["Set-Cookie"];
Assert.Equal(4, values.Count);
Assert.Equal<string[]>(new[]
{
"TestCookie=chunks-3; path=/",
"TestCookieC1=abcdefghijklmnopqrstuv; path=/",
"TestCookieC2=wxyz0123456789ABCDEFGH; path=/",
"TestCookieC3=IJKLMNOPQRSTUVWXYZ; path=/",
}, values);
}
[Fact]
public void GetLargeChunkedCookie_Reassembled()
{
HttpContext context = new DefaultHttpContext();
context.Request.Headers["Cookie"] = new[]
{
"TestCookie=chunks-7",
"TestCookieC1=abcdefghi",
"TestCookieC2=jklmnopqr",
"TestCookieC3=stuvwxyz0",
"TestCookieC4=123456789",
"TestCookieC5=ABCDEFGHI",
"TestCookieC6=JKLMNOPQR",
"TestCookieC7=STUVWXYZ"
};
string result = new ChunkingCookieManager().GetRequestCookie(context, "TestCookie");
string testString = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Assert.Equal(testString, result);
}
[Fact]
public void GetLargeChunkedCookieWithMissingChunk_ThrowingEnabled_Throws()
{
HttpContext context = new DefaultHttpContext();
context.Request.Headers["Cookie"] = new[]
{
"TestCookie=chunks-7",
"TestCookieC1=abcdefghi",
// Missing chunk "TestCookieC2=jklmnopqr",
"TestCookieC3=stuvwxyz0",
"TestCookieC4=123456789",
"TestCookieC5=ABCDEFGHI",
"TestCookieC6=JKLMNOPQR",
"TestCookieC7=STUVWXYZ"
};
Assert.Throws<FormatException>(() => new ChunkingCookieManager() { ThrowForPartialCookies = true }
.GetRequestCookie(context, "TestCookie"));
}
[Fact]
public void GetLargeChunkedCookieWithMissingChunk_ThrowingDisabled_NotReassembled()
{
HttpContext context = new DefaultHttpContext();
context.Request.Headers["Cookie"] = new[]
{
"TestCookie=chunks-7",
"TestCookieC1=abcdefghi",
// Missing chunk "TestCookieC2=jklmnopqr",
"TestCookieC3=stuvwxyz0",
"TestCookieC4=123456789",
"TestCookieC5=ABCDEFGHI",
"TestCookieC6=JKLMNOPQR",
"TestCookieC7=STUVWXYZ"
};
string result = new ChunkingCookieManager() { ThrowForPartialCookies = false }.GetRequestCookie(context, "TestCookie");
string testString = "chunks-7";
Assert.Equal(testString, result);
}
[Fact]
public void DeleteChunkedCookieWithOptions_AllDeleted()
{
HttpContext context = new DefaultHttpContext();
context.Request.Headers.Append("Cookie", "TestCookie=chunks-7");
new ChunkingCookieManager().DeleteCookie(context, "TestCookie", new CookieOptions() { Domain = "foo.com", Secure = true });
var cookies = context.Response.Headers["Set-Cookie"];
Assert.Equal(8, cookies.Count);
Assert.Equal(new[]
{
"TestCookie=; expires=Thu, 01 Jan 1970 00:00:00 GMT; domain=foo.com; path=/; secure",
"TestCookieC1=; expires=Thu, 01 Jan 1970 00:00:00 GMT; domain=foo.com; path=/; secure",
"TestCookieC2=; expires=Thu, 01 Jan 1970 00:00:00 GMT; domain=foo.com; path=/; secure",
"TestCookieC3=; expires=Thu, 01 Jan 1970 00:00:00 GMT; domain=foo.com; path=/; secure",
"TestCookieC4=; expires=Thu, 01 Jan 1970 00:00:00 GMT; domain=foo.com; path=/; secure",
"TestCookieC5=; expires=Thu, 01 Jan 1970 00:00:00 GMT; domain=foo.com; path=/; secure",
"TestCookieC6=; expires=Thu, 01 Jan 1970 00:00:00 GMT; domain=foo.com; path=/; secure",
"TestCookieC7=; expires=Thu, 01 Jan 1970 00:00:00 GMT; domain=foo.com; path=/; secure",
}, cookies);
}
[Fact]
public void DeleteChunkedCookieWithOptionsAndResponseCookies_AllDeleted()
{
var chunkingCookieManager = new ChunkingCookieManager();
HttpContext httpContext = new DefaultHttpContext();
httpContext.Request.Headers["Cookie"] = new[]
{
"TestCookie=chunks-7",
"TestCookieC1=abcdefghi",
"TestCookieC2=jklmnopqr",
"TestCookieC3=stuvwxyz0",
"TestCookieC4=123456789",
"TestCookieC5=ABCDEFGHI",
"TestCookieC6=JKLMNOPQR",
"TestCookieC7=STUVWXYZ"
};
var cookieOptions = new CookieOptions()
{
Domain = "foo.com",
Path = "/",
Secure = true
};
httpContext.Response.Headers[HeaderNames.SetCookie] = new[]
{
"TestCookie=chunks-7; domain=foo.com; path=/; secure",
"TestCookieC1=STUVWXYZ; domain=foo.com; path=/; secure",
"TestCookieC2=123456789; domain=foo.com; path=/; secure",
"TestCookieC3=stuvwxyz0; domain=foo.com; path=/; secure",
"TestCookieC4=123456789; domain=foo.com; path=/; secure",
"TestCookieC5=ABCDEFGHI; domain=foo.com; path=/; secure",
"TestCookieC6=JKLMNOPQR; domain=foo.com; path=/; secure",
"TestCookieC7=STUVWXYZ; domain=foo.com; path=/; secure"
};
chunkingCookieManager.DeleteCookie(httpContext, "TestCookie", cookieOptions);
Assert.Equal(8, httpContext.Response.Headers[HeaderNames.SetCookie].Count);
Assert.Equal(new[]
{
"TestCookie=; expires=Thu, 01 Jan 1970 00:00:00 GMT; domain=foo.com; path=/; secure",
"TestCookieC1=; expires=Thu, 01 Jan 1970 00:00:00 GMT; domain=foo.com; path=/; secure",
"TestCookieC2=; expires=Thu, 01 Jan 1970 00:00:00 GMT; domain=foo.com; path=/; secure",
"TestCookieC3=; expires=Thu, 01 Jan 1970 00:00:00 GMT; domain=foo.com; path=/; secure",
"TestCookieC4=; expires=Thu, 01 Jan 1970 00:00:00 GMT; domain=foo.com; path=/; secure",
"TestCookieC5=; expires=Thu, 01 Jan 1970 00:00:00 GMT; domain=foo.com; path=/; secure",
"TestCookieC6=; expires=Thu, 01 Jan 1970 00:00:00 GMT; domain=foo.com; path=/; secure",
"TestCookieC7=; expires=Thu, 01 Jan 1970 00:00:00 GMT; domain=foo.com; path=/; secure"
}, httpContext.Response.Headers[HeaderNames.SetCookie]);
}
}
}
| |
// MIT License
//
// Copyright (c) 2009-2017 Luca Piccioni
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// This file is automatically generated
#pragma warning disable 649, 1572, 1573
// ReSharper disable RedundantUsingDirective
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using Khronos;
// ReSharper disable CheckNamespace
// ReSharper disable InconsistentNaming
// ReSharper disable JoinDeclarationAndInitializer
namespace OpenGL
{
public partial class Glx
{
/// <summary>
/// [GLX] Value of GLX_BUFFER_CLOBBER_MASK_SGIX symbol.
/// </summary>
[RequiredByFeature("GLX_SGIX_pbuffer")]
[Log(BitmaskName = "GLXEventMask")]
public const uint BUFFER_CLOBBER_MASK_SGIX = 0x08000000;
/// <summary>
/// [GLX] Value of GLX_SAMPLE_BUFFERS_BIT_SGIX symbol.
/// </summary>
[RequiredByFeature("GLX_SGIX_pbuffer")]
[Log(BitmaskName = "GLXPbufferClobberMask")]
public const uint SAMPLE_BUFFERS_BIT_SGIX = 0x00000100;
/// <summary>
/// [GLX] Value of GLX_OPTIMAL_PBUFFER_WIDTH_SGIX symbol.
/// </summary>
[RequiredByFeature("GLX_SGIX_pbuffer")]
public const int OPTIMAL_PBUFFER_WIDTH_SGIX = 0x8019;
/// <summary>
/// [GLX] Value of GLX_OPTIMAL_PBUFFER_HEIGHT_SGIX symbol.
/// </summary>
[RequiredByFeature("GLX_SGIX_pbuffer")]
public const int OPTIMAL_PBUFFER_HEIGHT_SGIX = 0x801A;
/// <summary>
/// [GLX] glXCreateGLXPbufferSGIX: Binding for glXCreateGLXPbufferSGIX.
/// </summary>
/// <param name="dpy">
/// A <see cref="T:IntPtr"/>.
/// </param>
/// <param name="config">
/// A <see cref="T:IntPtr"/>.
/// </param>
/// <param name="width">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="height">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="attrib_list">
/// A <see cref="T:int[]"/>.
/// </param>
[RequiredByFeature("GLX_SGIX_pbuffer")]
public static IntPtr CreateGLXPbufferSGIX(IntPtr dpy, IntPtr config, uint width, uint height, int[] attrib_list)
{
IntPtr retValue;
unsafe {
fixed (int* p_attrib_list = attrib_list)
{
Debug.Assert(Delegates.pglXCreateGLXPbufferSGIX != null, "pglXCreateGLXPbufferSGIX not implemented");
retValue = Delegates.pglXCreateGLXPbufferSGIX(dpy, config, width, height, p_attrib_list);
LogCommand("glXCreateGLXPbufferSGIX", retValue, dpy, config, width, height, attrib_list );
}
}
DebugCheckErrors(retValue);
return (retValue);
}
/// <summary>
/// [GLX] glXDestroyGLXPbufferSGIX: Binding for glXDestroyGLXPbufferSGIX.
/// </summary>
/// <param name="dpy">
/// A <see cref="T:IntPtr"/>.
/// </param>
/// <param name="pbuf">
/// A <see cref="T:IntPtr"/>.
/// </param>
[RequiredByFeature("GLX_SGIX_pbuffer")]
public static void DestroyGLXPbufferSGIX(IntPtr dpy, IntPtr pbuf)
{
Debug.Assert(Delegates.pglXDestroyGLXPbufferSGIX != null, "pglXDestroyGLXPbufferSGIX not implemented");
Delegates.pglXDestroyGLXPbufferSGIX(dpy, pbuf);
LogCommand("glXDestroyGLXPbufferSGIX", null, dpy, pbuf );
DebugCheckErrors(null);
}
/// <summary>
/// [GLX] glXQueryGLXPbufferSGIX: Binding for glXQueryGLXPbufferSGIX.
/// </summary>
/// <param name="dpy">
/// A <see cref="T:IntPtr"/>.
/// </param>
/// <param name="pbuf">
/// A <see cref="T:IntPtr"/>.
/// </param>
/// <param name="attribute">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="value">
/// A <see cref="T:uint[]"/>.
/// </param>
[RequiredByFeature("GLX_SGIX_pbuffer")]
public static int QueryGLXPbufferSGIX(IntPtr dpy, IntPtr pbuf, int attribute, uint[] value)
{
int retValue;
unsafe {
fixed (uint* p_value = value)
{
Debug.Assert(Delegates.pglXQueryGLXPbufferSGIX != null, "pglXQueryGLXPbufferSGIX not implemented");
retValue = Delegates.pglXQueryGLXPbufferSGIX(dpy, pbuf, attribute, p_value);
LogCommand("glXQueryGLXPbufferSGIX", retValue, dpy, pbuf, attribute, value );
}
}
DebugCheckErrors(retValue);
return (retValue);
}
/// <summary>
/// [GLX] glXSelectEventSGIX: Binding for glXSelectEventSGIX.
/// </summary>
/// <param name="dpy">
/// A <see cref="T:IntPtr"/>.
/// </param>
/// <param name="drawable">
/// A <see cref="T:IntPtr"/>.
/// </param>
/// <param name="mask">
/// A <see cref="T:uint"/>.
/// </param>
[RequiredByFeature("GLX_SGIX_pbuffer")]
public static void SelectEventSGIX(IntPtr dpy, IntPtr drawable, uint mask)
{
Debug.Assert(Delegates.pglXSelectEventSGIX != null, "pglXSelectEventSGIX not implemented");
Delegates.pglXSelectEventSGIX(dpy, drawable, mask);
LogCommand("glXSelectEventSGIX", null, dpy, drawable, mask );
DebugCheckErrors(null);
}
/// <summary>
/// [GLX] glXGetSelectedEventSGIX: Binding for glXGetSelectedEventSGIX.
/// </summary>
/// <param name="dpy">
/// A <see cref="T:IntPtr"/>.
/// </param>
/// <param name="drawable">
/// A <see cref="T:IntPtr"/>.
/// </param>
/// <param name="mask">
/// A <see cref="T:uint[]"/>.
/// </param>
[RequiredByFeature("GLX_SGIX_pbuffer")]
public static void GetSelectedEventSGIX(IntPtr dpy, IntPtr drawable, [Out] uint[] mask)
{
unsafe {
fixed (uint* p_mask = mask)
{
Debug.Assert(Delegates.pglXGetSelectedEventSGIX != null, "pglXGetSelectedEventSGIX not implemented");
Delegates.pglXGetSelectedEventSGIX(dpy, drawable, p_mask);
LogCommand("glXGetSelectedEventSGIX", null, dpy, drawable, mask );
}
}
DebugCheckErrors(null);
}
internal static unsafe partial class Delegates
{
[RequiredByFeature("GLX_SGIX_pbuffer")]
[SuppressUnmanagedCodeSecurity]
internal delegate IntPtr glXCreateGLXPbufferSGIX(IntPtr dpy, IntPtr config, uint width, uint height, int* attrib_list);
[RequiredByFeature("GLX_SGIX_pbuffer")]
internal static glXCreateGLXPbufferSGIX pglXCreateGLXPbufferSGIX;
[RequiredByFeature("GLX_SGIX_pbuffer")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glXDestroyGLXPbufferSGIX(IntPtr dpy, IntPtr pbuf);
[RequiredByFeature("GLX_SGIX_pbuffer")]
internal static glXDestroyGLXPbufferSGIX pglXDestroyGLXPbufferSGIX;
[RequiredByFeature("GLX_SGIX_pbuffer")]
[SuppressUnmanagedCodeSecurity]
internal delegate int glXQueryGLXPbufferSGIX(IntPtr dpy, IntPtr pbuf, int attribute, uint* value);
[RequiredByFeature("GLX_SGIX_pbuffer")]
internal static glXQueryGLXPbufferSGIX pglXQueryGLXPbufferSGIX;
[RequiredByFeature("GLX_SGIX_pbuffer")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glXSelectEventSGIX(IntPtr dpy, IntPtr drawable, uint mask);
[RequiredByFeature("GLX_SGIX_pbuffer")]
internal static glXSelectEventSGIX pglXSelectEventSGIX;
[RequiredByFeature("GLX_SGIX_pbuffer")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glXGetSelectedEventSGIX(IntPtr dpy, IntPtr drawable, uint* mask);
[RequiredByFeature("GLX_SGIX_pbuffer")]
internal static glXGetSelectedEventSGIX pglXGetSelectedEventSGIX;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Kaboom.Serializer;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace Kaboom.Sources
{
class Map : DrawableGameComponent
{
private readonly Square[,] board_;
private readonly List<List<Hud.BombInfo>> bombsets_;
private readonly SpriteBatch sb_;
private bool endGame_;
public event EventHandler EndGameManager;
public int NbExplosions { get; private set; }
/// <summary>
/// Initialize a new map from a MapElements
/// </summary>
/// <param name="g">Game</param>
/// <param name="sb">Spritebatch used to render texture</param>
/// <param name="me">MapElement used to construct entities in the map</param>
public Map(Game g, SpriteBatch sb, MapElements me)
: base(g)
{
this.sb_ = sb;
this.SizeX = me.SizeX;
this.SizeY = me.SizeY;
var typeArray = Pattern.All;
this.bombsets_ = new List<List<Hud.BombInfo>>();
foreach (var bombset in me.Bombset)
{
this.bombsets_.Add(
bombset.Select(bomb => new Hud.BombInfo(typeArray[bomb.Type], bomb.Quantity, bomb.Name))
.ToList());
}
((MainGame)this.Game).BombSet(this.bombsets_[0]);
this.board_ = new Square[this.SizeX,this.SizeY];
for (var i = 0; i < this.SizeX; i++)
{
for (var j = 0; j < this.SizeY; j++)
{
this.board_[i, j] = new Square(new Point(i, j));
this.board_[i, j].Explosion += ExplosionRuler;
this.board_[i, j].EndGame += ManageEndGame;
this.board_[i, j].Bombset +=
(sender, args) =>
((MainGame) this.Game).BombSet(this.bombsets_[((CheckPoint) sender).BombsetIdx]);
foreach (var entity in me.Board[i][j].Entities)
{
var bombProxy = entity as BombProxy;
var blockProxy = entity as BlockProxy;
var checkPointProxy = entity as CheckPointProxy;
if (bombProxy != null)
{
this.board_[i, j].AddEntity(
new Bomb(typeArray[bombProxy.Type], KaboomResources.Sprites[bombProxy.TileIdentifier].Clone(), ""));
}
else if (checkPointProxy != null)
{
this.board_[i, j].AddEntity(
new CheckPoint(KaboomResources.Sprites[checkPointProxy.TileIdentifier].Clone(), 500,
checkPointProxy.Activated, checkPointProxy.Bombsetidx));
}
else if (blockProxy != null)
{
this.board_[i, j].AddEntity(
new Block(KaboomResources.Sprites[blockProxy.TileIdentifier].Clone(),
blockProxy.Destroyable, blockProxy.GameEnd));
}
else
{
this.board_[i, j].AddEntity(
new Entity(entity.ZIndex,
new SpriteSheet(
KaboomResources.Textures[entity.TileIdentifier],
entity.TileFramePerAnim,
entity.TileTotalAnim,
entity.TileFrameSpeed)));
}
}
}
}
}
/// <summary>
/// Initialize a new map
/// </summary>
/// <param name="g">Game instance</param>
/// <param name="sb">Spritebatch used to draw textures</param>
/// <param name="sizex">X map number of entities</param>
/// <param name="sizey">Y map number of entities</param>
public Map(Game g, SpriteBatch sb, int sizex, int sizey)
: base(g)
{
this.sb_ = sb;
this.board_ = new Square[sizex,sizey];
this.SizeX = sizex;
this.SizeY = sizey;
for (var i = 0; i < this.SizeX; i++)
{
for (var j = 0; j < this.SizeY; j++)
{
this.board_[i, j] = new Square(new Point(i, j));
this.board_[i, j].Explosion += ExplosionRuler;
}
}
}
/// <summary>
/// Test if the line in posY is contain in the rectangle
/// </summary>
/// <param name="vision">Testing rectangle</param>
/// <param name="posY">Testing line</param>
/// <returns></returns>
public Boolean LineIsContainHorizontaly(Rectangle vision, int posY)
{
for (var i = 0; i < this.SizeX; i++)
{
if (
vision.Contains(
new Rectangle((board_[i, posY].Base.X * Camera.Instance.DimX) + Camera.Instance.OffX,
(board_[i, posY].Base.Y * Camera.Instance.DimY) + Camera.Instance.OffY,
Camera.Instance.DimX, Camera.Instance.DimY)))
{
return true;
}
}
return false;
}
/// <summary>
/// Test if the column in posX is contain in the rectangle
/// </summary>
/// <param name="vision">Testing rectangle</param>
/// <param name="posX">Testing column</param>
/// <returns></returns>
public Boolean LineIsContainVerticaly(Rectangle vision, int posX)
{
for (var i = 0; i < this.SizeY; i++)
{
if (
vision.Contains(
new Rectangle((board_[posX, i].Base.X * Camera.Instance.DimX) + Camera.Instance.OffX,
(board_[posX, i].Base.Y * Camera.Instance.DimY) + Camera.Instance.OffY,
Camera.Instance.DimX, Camera.Instance.DimY)))
{
return true;
}
}
return false;
}
/// <summary>
/// Place an entity on the map
/// </summary>
/// <param name="entity">the entity to place on the map</param>
/// <param name="coordinates">coordinates of the entity</param>
public bool AddNewEntity(Entity entity, Point coordinates)
{
return this.board_[coordinates.X, coordinates.Y].AddEntity(entity);
}
public void RemoveEntity(Point coordinates, int offset = 5)
{
this.board_[coordinates.X, coordinates.Y].RemoveEntity(offset);
}
/// <summary>
/// Return the coordinates of the square matching the given position
/// Throw IndexOutOfRangeException when position outside the board
/// </summary>
/// <param name="position">Position to poll</param>
/// <returns>Matching coordinates</returns>
public Point GetCoordByPos(Vector2 position)
{
var r = new Rectangle(0, 0, Camera.Instance.DimX, Camera.Instance.DimY);
foreach (var square in this.board_)
{
r.X = (square.Base.X * Camera.Instance.DimX) + Camera.Instance.OffX;
r.Y = (square.Base.Y * Camera.Instance.DimY) + Camera.Instance.OffY;
if (r.Contains(new Point((int) position.X, (int) position.Y)))
return square.Base;
}
throw new IndexOutOfRangeException();
}
/// <summary>
/// Return the highest Z-Index for the square matching the given coordinates
/// </summary>
/// <param name="point">Coordinates</param>
/// <returns>Highest Z-Index found at this position. -1 if no entities on the square</returns>
public int GetMaxZIndexOnCoord(Point point)
{
return this.board_[point.X, point.Y].GetMaxZIndex();
}
/// <summary>
/// Update all map's entities
/// </summary>
/// <param name="gameTime">GameClock</param>
public override void Update(GameTime gameTime)
{
base.Update(gameTime);
NbExplosions = 0;
foreach (var item in this.board_)
{
item.Update(gameTime);
NbExplosions += item.NbCurrentExplosions;
}
if (NbExplosions == 0 && endGame_)
{
EndGameManager(this, null);
}
}
/// <summary>
/// Draw all map's entities. Call SpriteBatch's begin and end
/// </summary>
/// <param name="gameTime">GameClock</param>
public override void Draw(GameTime gameTime)
{
base.Draw(gameTime);
this.sb_.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend);
foreach (var item in this.board_)
{
item.Draw(this.sb_, gameTime);
}
this.sb_.End();
}
/// <summary>
/// Deleguate for explosion
/// </summary>
/// <param name="bomb">Bomb ready to boom</param>
/// <param name="pos">Position of the bomb</param>
public void ExplosionRuler(Bomb bomb, Point pos)
{
if (bomb == null)
return;
var t = new Rectangle(0, 0, this.SizeX, this.SizeY);
foreach (var elt in bomb.GetPattern().Where(elt => t.Contains(new Point(pos.X + elt.Point.X, pos.Y + elt.Point.Y))))
{
this.board_[pos.X + elt.Point.X, pos.Y + elt.Point.Y].Explode(elt.Time);
}
}
/// <summary>
/// Search for active detonators
/// </summary>
public void ActivateDetonators()
{
foreach (var square in board_)
{
square.ActiveDetonator();
}
}
/// <summary>
/// Launch an explosion on given position
/// </summary>
/// <param name="pos">Position to start explosion</param>
public void SetExplosion(Point pos)
{
board_[pos.X, pos.Y].Explode(500);
}
/// <summary>
/// Event handler for end of game
/// </summary>
/// <param name="sender"></param>
/// <param name="ea"></param>
public void ManageEndGame(object sender, EventArgs ea)
{
this.endGame_ = true;
}
/// <summary>
/// Dimension of the map (in square)
/// </summary>
public int SizeX { get; private set; }
/// <summary>
/// Dimension of the map (in square)
/// </summary>
public int SizeY { get; private set; }
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="_AutoWebProxyScriptHelper.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
#pragma warning disable 618
#define AUTOPROXY_MANAGED_JSCRIPT
namespace System.Net
{
#if AUTOPROXY_MANAGED_JSCRIPT
using System.Security.Permissions;
using System.Collections.Generic;
#endif
using System.Net.NetworkInformation;
using System.Text;
using System.Text.RegularExpressions;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Net.Sockets;
/// <summary>
/// Provides a set of functions that can be called by the JS script. There are based on
/// an earlier API set that is used for these networking scripts.
/// for a description of the API see:
/// http://home.netscape.com/eng/mozilla/2.0/relnotes/demo/proxy-live.html
/// </summary>
#if !AUTOPROXY_MANAGED_JSCRIPT
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.AutoDispatch)]
public sealed class WebProxyScriptHelper
{
internal WebProxyScriptHelper() { }
#else
internal class WebProxyScriptHelper : IReflect
{
private class MyMethodInfo : MethodInfo {
string name;
// used by JScript
public MyMethodInfo(string name) : base() {
GlobalLog.Print("MyMethodInfo::.ctor() name:" + name);
this.name = name;
}
// used by JScript
public override Type ReturnType {
get {
GlobalLog.Print("MyMethodInfo::ReturnType()");
Type type = null;
if (string.Compare(name, "isPlainHostName", StringComparison.Ordinal)==0) {
type = typeof(bool);
}
else if (string.Compare(name, "dnsDomainIs", StringComparison.Ordinal)==0) {
type = typeof(bool);
}
else if (string.Compare(name, "localHostOrDomainIs", StringComparison.Ordinal)==0) {
type = typeof(bool);
}
else if (string.Compare(name, "isResolvable", StringComparison.Ordinal)==0) {
type = typeof(bool);
}
else if (string.Compare(name, "dnsResolve", StringComparison.Ordinal)==0) {
type = typeof(string);
}
else if (string.Compare(name, "myIpAddress", StringComparison.Ordinal)==0) {
type = typeof(string);
}
else if (string.Compare(name, "dnsDomainLevels", StringComparison.Ordinal)==0) {
type = typeof(int);
}
else if (string.Compare(name, "isInNet", StringComparison.Ordinal)==0) {
type = typeof(bool);
}
else if (string.Compare(name, "shExpMatch", StringComparison.Ordinal)==0) {
type = typeof(bool);
}
else if (string.Compare(name, "weekdayRange", StringComparison.Ordinal)==0) {
type = typeof(bool);
}
//-------------------------------------
//Don't even inject these methods
//if the OS does not support IPv6
//-------------------------------------
else if(Socket.OSSupportsIPv6)
{
//---------------------------------------------------------------------
//The following changes are made to support IPv6
//IE7 ships with this support and WinInet ships with this support
//we are adding support for Ipv6
//---------------------------------------------------------------------
if (string.Compare(name, "dnsResolveEx", StringComparison.Ordinal)==0) {
type = typeof(string);
}
else if (string.Compare(name, "isResolvableEx", StringComparison.Ordinal)==0) {
type = typeof(bool);
}
else if (string.Compare(name, "myIpAddressEx", StringComparison.Ordinal)==0) {
type = typeof(string);
}
else if (string.Compare(name, "isInNetEx", StringComparison.Ordinal)==0) {
type = typeof(bool);
}
else if (string.Compare(name, "sortIpAddressList", StringComparison.Ordinal)==0) {
type = typeof(string);
}
else if (string.Compare(name, "getClientVersion", StringComparison.Ordinal)==0) {
type = typeof(string);
}
}
GlobalLog.Print("MyMethodInfo::ReturnType() name:" + name + " type:" + type.FullName);
return type;
}
}
// used by JScript
public override ICustomAttributeProvider ReturnTypeCustomAttributes {
get {
GlobalLog.Print("MyMethodInfo::ReturnTypeCustomAttributes()");
return null;
}
}
public override RuntimeMethodHandle MethodHandle {
get {
GlobalLog.Print("MyMethodInfo::MethodHandle()");
return new RuntimeMethodHandle();
}
}
public override MethodAttributes Attributes {
get {
GlobalLog.Print("MyMethodInfo::Attributes()");
return MethodAttributes.Public;
}
}
public override string Name {
get {
GlobalLog.Print("MyMethodInfo::Name()");
return name;
}
}
// used by JScript
public override Type DeclaringType {
get {
GlobalLog.Print("MyMethodInfo::DeclaringType()");
return typeof(MyMethodInfo);
}
}
public override Type ReflectedType {
get {
GlobalLog.Print("MyMethodInfo::ReflectedType()");
return null;
}
}
public override object[] GetCustomAttributes(bool inherit) {
GlobalLog.Print("MyMethodInfo::GetCustomAttributes() inherit:" + inherit);
return null;
}
public override object[] GetCustomAttributes(Type type, bool inherit) {
GlobalLog.Print("MyMethodInfo::GetCustomAttributes() inherit:" + inherit);
return null;
}
public override bool IsDefined(Type type, bool inherit) {
GlobalLog.Print("MyMethodInfo::IsDefined() type:" + type.FullName + " inherit:" + inherit);
return type.Equals(typeof(WebProxyScriptHelper));
}
// used by JScript
public override object Invoke(object target, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture) {
GlobalLog.Print("MyMethodInfo::Invoke() target:" + target);
return typeof(WebProxyScriptHelper).GetMethod(name, (BindingFlags)unchecked(-1)).Invoke(target, (BindingFlags)unchecked(-1), binder, args, culture);
}
public override ParameterInfo[] GetParameters() {
GlobalLog.Print("MyMethodInfo::GetParameters() name:" + name);
ParameterInfo[] pars = typeof(WebProxyScriptHelper).GetMethod(name, (BindingFlags)unchecked(-1)).GetParameters();
GlobalLog.Print("MyMethodInfo::GetParameters() returning pars.Length:" + pars.Length);
return pars;
}
public override MethodImplAttributes GetMethodImplementationFlags() {
GlobalLog.Print("MyMethodInfo::GetMethodImplementationFlags()");
return MethodImplAttributes.IL;
}
public override MethodInfo GetBaseDefinition() {
GlobalLog.Print("MyMethodInfo::GetBaseDefinition()");
return null;
}
public override Module Module
{
get
{
return GetType().Module;
}
}
}
MethodInfo IReflect.GetMethod(string name, BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers) {
GlobalLog.Print("WebProxyScriptHelper::IReflect() GetMethod(1) name:" + ValidationHelper.ToString(name) + " bindingAttr:" + bindingAttr);
return null;
}
MethodInfo IReflect.GetMethod(string name, BindingFlags bindingAttr) {
GlobalLog.Print("WebProxyScriptHelper::IReflect() GetMethod(2) name:" + ValidationHelper.ToString(name) + " bindingAttr:" + bindingAttr);
return null;
}
MethodInfo[] IReflect.GetMethods(BindingFlags bindingAttr) {
GlobalLog.Print("WebProxyScriptHelper::IReflect() GetMethods() bindingAttr:" + bindingAttr);
return new MethodInfo[0];
}
FieldInfo IReflect.GetField(string name, BindingFlags bindingAttr) {
GlobalLog.Print("WebProxyScriptHelper::IReflect() GetField() name:" + ValidationHelper.ToString(name) + " bindingAttr:" + bindingAttr);
return null;
}
FieldInfo[] IReflect.GetFields(BindingFlags bindingAttr) {
GlobalLog.Print("WebProxyScriptHelper::IReflect() GetFields() bindingAttr:" + bindingAttr);
return new FieldInfo[0];
}
PropertyInfo IReflect.GetProperty(string name, BindingFlags bindingAttr) {
GlobalLog.Print("WebProxyScriptHelper::IReflect() GetProperty(1) name:" + ValidationHelper.ToString(name) + " bindingAttr:" + bindingAttr);
return null;
}
PropertyInfo IReflect.GetProperty(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) {
GlobalLog.Print("WebProxyScriptHelper::IReflect() GetProperty(2) name:" + ValidationHelper.ToString(name) + " bindingAttr:" + bindingAttr);
return null;
}
PropertyInfo[] IReflect.GetProperties(BindingFlags bindingAttr) {
GlobalLog.Print("WebProxyScriptHelper::IReflect() GetProperties() bindingAttr:" + bindingAttr);
return new PropertyInfo[0];
}
// used by JScript
MemberInfo[] IReflect.GetMember(string name, BindingFlags bindingAttr) {
GlobalLog.Print("WebProxyScriptHelper::IReflect() GetMember() name:" + ValidationHelper.ToString(name) + " bindingAttr:" + bindingAttr);
return new MemberInfo[]{new MyMethodInfo(name)};
}
MemberInfo[] IReflect.GetMembers(BindingFlags bindingAttr) {
GlobalLog.Print("WebProxyScriptHelper::IReflect() GetMembers() bindingAttr:" + bindingAttr);
return new MemberInfo[0];
}
object IReflect.InvokeMember(string name, BindingFlags bindingAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters) {
GlobalLog.Print("WebProxyScriptHelper::IReflect() InvokeMember() name:" + ValidationHelper.ToString(name) + " bindingAttr:" + bindingAttr);
return null;
}
Type IReflect.UnderlyingSystemType {
get {
GlobalLog.Print("WebProxyScriptHelper::IReflect() UnderlyingSystemType_get()");
return null;
}
}
#endif
public bool isPlainHostName(string hostName) {
GlobalLog.Print("WebProxyScriptHelper::isPlainHostName() hostName:" + ValidationHelper.ToString(hostName));
if (hostName==null) {
if(Logging.On)Logging.PrintWarning(Logging.Web, SR.GetString(SR.net_log_proxy_called_with_null_parameter, "WebProxyScriptHelper.isPlainHostName()", "hostName"));
throw new ArgumentNullException("hostName");
}
return hostName.IndexOf('.') == -1;
}
public bool dnsDomainIs(string host, string domain) {
GlobalLog.Print("WebProxyScriptHelper::dnsDomainIs() host:" + ValidationHelper.ToString(host) + " domain:" + ValidationHelper.ToString(domain));
if (host==null) {
if(Logging.On)Logging.PrintWarning(Logging.Web, SR.GetString(SR.net_log_proxy_called_with_null_parameter, "WebProxyScriptHelper.dnsDomainIs()", "host"));
throw new ArgumentNullException("host");
}
if (domain==null) {
if(Logging.On)Logging.PrintWarning(Logging.Web, SR.GetString(SR.net_log_proxy_called_with_null_parameter, "WebProxyScriptHelper.dnsDomainIs()", "domain"));
throw new ArgumentNullException("domain");
}
int index = host.LastIndexOf(domain);
return index != -1 && (index+domain.Length) == host.Length;
}
/// <devdoc>
/// <para>
/// This is a strange function, if its not a local hostname
/// we do a straight compare against the passed in domain
/// string. If its not a direct match, then its false,
/// even if the root of the domain/hostname are the same.
/// </para>
/// </devdoc>
public bool localHostOrDomainIs(string host, string hostDom) {
GlobalLog.Print("WebProxyScriptHelper::localHostOrDomainIs() host:" + ValidationHelper.ToString(host) + " hostDom:" + ValidationHelper.ToString(hostDom));
if (host==null) {
if(Logging.On)Logging.PrintWarning(Logging.Web, SR.GetString(SR.net_log_proxy_called_with_null_parameter, "WebProxyScriptHelper.localHostOrDomainIs()", "host"));
throw new ArgumentNullException("host");
}
if (hostDom==null) {
if(Logging.On)Logging.PrintWarning(Logging.Web, SR.GetString(SR.net_log_proxy_called_with_null_parameter, "WebProxyScriptHelper.localHostOrDomainIs()", "hostDom"));
throw new ArgumentNullException("hostDom");
}
if (isPlainHostName(host)) {
int index = hostDom.IndexOf('.');
if (index > 0) {
hostDom = hostDom.Substring(0,index);
}
}
return string.Compare(host, hostDom, StringComparison.OrdinalIgnoreCase)==0;
}
public bool isResolvable(string host) {
GlobalLog.Print("WebProxyScriptHelper::isResolvable() host:" + ValidationHelper.ToString(host));
if (host==null) {
if(Logging.On)Logging.PrintWarning(Logging.Web, SR.GetString(SR.net_log_proxy_called_with_null_parameter, "WebProxyScriptHelper.isResolvable()", "host"));
throw new ArgumentNullException("host");
}
IPHostEntry ipHostEntry = null;
try
{
ipHostEntry = Dns.InternalGetHostByName(host);
}
catch { }
if (ipHostEntry == null)
{
return false;
}
for (int i = 0; i < ipHostEntry.AddressList.Length; i++)
{
if (ipHostEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
{
return true;
}
}
return false;
}
public string dnsResolve(string host) {
GlobalLog.Print("WebProxyScriptHelper::dnsResolve() host:" + ValidationHelper.ToString(host));
if (host==null) {
if(Logging.On)Logging.PrintWarning(Logging.Web, SR.GetString(SR.net_log_proxy_called_with_null_parameter, "WebProxyScriptHelper.dnsResolve()", "host"));
throw new ArgumentNullException("host");
}
IPHostEntry ipHostEntry = null;
try
{
ipHostEntry = Dns.InternalGetHostByName(host);
}
catch { }
if (ipHostEntry == null)
{
return string.Empty;
}
for (int i = 0; i < ipHostEntry.AddressList.Length; i++)
{
if (ipHostEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
{
return ipHostEntry.AddressList[i].ToString();
}
}
return string.Empty;
}
public string myIpAddress() {
GlobalLog.Print("WebProxyScriptHelper::myIpAddress()");
IPAddress[] ipAddresses = NclUtilities.LocalAddresses;
for (int i = 0; i < ipAddresses.Length; i++)
{
if (!IPAddress.IsLoopback(ipAddresses[i]) && ipAddresses[i].AddressFamily == AddressFamily.InterNetwork)
{
return ipAddresses[i].ToString();
}
}
return string.Empty;
}
public int dnsDomainLevels(string host) {
GlobalLog.Print("WebProxyScriptHelper::dnsDomainLevels() host:" + ValidationHelper.ToString(host));
if (host==null) {
if(Logging.On)Logging.PrintWarning(Logging.Web, SR.GetString(SR.net_log_proxy_called_with_null_parameter, "WebProxyScriptHelper.dnsDomainLevels()", "host"));
throw new ArgumentNullException("host");
}
int index = 0;
int domainCount = 0;
while((index = host.IndexOf('.', index)) != -1) {
domainCount++;
index++;
}
return domainCount;
}
public bool isInNet(string host, string pattern, string mask) {
GlobalLog.Print("WebProxyScriptHelper::isInNet() host:" + ValidationHelper.ToString(host) + " pattern:" + ValidationHelper.ToString(pattern) + " mask:" + ValidationHelper.ToString(mask));
if (host==null) {
if(Logging.On)Logging.PrintWarning(Logging.Web, SR.GetString(SR.net_log_proxy_called_with_null_parameter, "WebProxyScriptHelper.isInNet()", "host"));
throw new ArgumentNullException("host");
}
if (pattern==null) {
if(Logging.On)Logging.PrintWarning(Logging.Web, SR.GetString(SR.net_log_proxy_called_with_null_parameter, "WebProxyScriptHelper.isInNet()", "pattern"));
throw new ArgumentNullException("pattern");
}
if (mask==null) {
if(Logging.On)Logging.PrintWarning(Logging.Web, SR.GetString(SR.net_log_proxy_called_with_null_parameter, "WebProxyScriptHelper.isInNet()", "mask"));
throw new ArgumentNullException("mask");
}
try {
IPAddress hostAddress = IPAddress.Parse(host);
IPAddress patternAddress = IPAddress.Parse(pattern);
IPAddress maskAddress = IPAddress.Parse(mask);
byte[] maskAddressBytes = maskAddress.GetAddressBytes();
byte[] hostAddressBytes = hostAddress.GetAddressBytes();
byte[] patternAddressBytes = patternAddress.GetAddressBytes();
if (maskAddressBytes.Length!=hostAddressBytes.Length || maskAddressBytes.Length!=patternAddressBytes.Length) {
return false;
}
for (int i=0; i<maskAddressBytes.Length; i++) {
if ( (patternAddressBytes[i] & maskAddressBytes[i]) != (hostAddressBytes[i] & maskAddressBytes[i]) ) {
return false;
}
}
}
catch {
return false;
}
return true;
}
// See bug 87334 for details on the implementation.
public bool shExpMatch(string host, string pattern) {
GlobalLog.Print("WebProxyScriptHelper::shExpMatch() host:" + ValidationHelper.ToString(host) + " pattern:" + ValidationHelper.ToString(pattern));
if (host==null) {
if(Logging.On)Logging.PrintWarning(Logging.Web, SR.GetString(SR.net_log_proxy_called_with_null_parameter, "WebProxyScriptHelper.shExpMatch()", "host"));
throw new ArgumentNullException("host");
}
if (pattern==null) {
if(Logging.On)Logging.PrintWarning(Logging.Web, SR.GetString(SR.net_log_proxy_called_with_null_parameter, "WebProxyScriptHelper.shExpMatch()", "pattern"));
throw new ArgumentNullException("pattern");
}
try
{
// This can throw - treat as no match.
ShellExpression exp = new ShellExpression(pattern);
return exp.IsMatch(host);
}
catch (FormatException)
{
return false;
}
}
public bool weekdayRange(string wd1, [Optional] object wd2, [Optional] object gmt)
{
GlobalLog.Print("WebProxyScriptHelper::weekdayRange() wd1:" + ValidationHelper.ToString(wd1) + " wd2:" + ValidationHelper.ToString(wd2) + " gmt:" + ValidationHelper.ToString(gmt));
if (wd1 == null)
{
if(Logging.On)Logging.PrintWarning(Logging.Web, SR.GetString(SR.net_log_proxy_called_with_null_parameter, "WebProxyScriptHelper.weekdayRange()", "wd1"));
throw new ArgumentNullException("wd1");
}
string _gmt = null;
string _wd2 = null;
if (gmt != null && gmt != DBNull.Value && gmt != Missing.Value)
{
_gmt = gmt as string;
if (_gmt == null)
{
throw new ArgumentException(SR.GetString(SR.net_param_not_string, gmt.GetType().FullName), "gmt");
}
}
if (wd2 != null && wd2 != DBNull.Value && gmt != Missing.Value)
{
_wd2 = wd2 as string;
if (_wd2 == null)
{
throw new ArgumentException(SR.GetString(SR.net_param_not_string, wd2.GetType().FullName), "wd2");
}
}
if (_gmt != null)
{
if (!isGMT(_gmt))
{
if(Logging.On)Logging.PrintWarning(Logging.Web, SR.GetString(SR.net_log_proxy_called_with_null_parameter, "WebProxyScriptHelper.weekdayRange()", "gmt"));
throw new ArgumentException(SR.GetString(SR.net_proxy_not_gmt), "gmt");
}
return weekdayRangeInternal(DateTime.UtcNow, dayOfWeek(wd1), dayOfWeek(_wd2));
}
if (_wd2 != null)
{
if (isGMT(_wd2))
{
return weekdayRangeInternal(DateTime.UtcNow, dayOfWeek(wd1), dayOfWeek(wd1));
}
return weekdayRangeInternal(DateTime.Now, dayOfWeek(wd1), dayOfWeek(_wd2));
}
return weekdayRangeInternal(DateTime.Now, dayOfWeek(wd1), dayOfWeek(wd1));
}
private static bool isGMT(string gmt)
{
return string.Compare(gmt, "GMT", StringComparison.OrdinalIgnoreCase)==0;
}
private static DayOfWeek dayOfWeek(string weekDay)
{
if (weekDay!=null && weekDay.Length==3) {
if (weekDay[0]=='T' || weekDay[0]=='t') {
if ((weekDay[1]=='U' || weekDay[1]=='u') && (weekDay[2]=='E' || weekDay[2]=='e')) {
return DayOfWeek.Tuesday;
}
if ((weekDay[1]=='H' || weekDay[1]=='h') && (weekDay[2]=='U' || weekDay[2]=='u')) {
return DayOfWeek.Thursday;
}
}
if (weekDay[0]=='S' || weekDay[0]=='s') {
if ((weekDay[1]=='U' || weekDay[1]=='u') && (weekDay[2]=='N' || weekDay[2]=='n')) {
return DayOfWeek.Sunday;
}
if ((weekDay[1]=='A' || weekDay[1]=='a') && (weekDay[2]=='T' || weekDay[2]=='t')) {
return DayOfWeek.Saturday;
}
}
if ((weekDay[0]=='M' || weekDay[0]=='m') && (weekDay[1]=='O' || weekDay[1]=='o') && (weekDay[2]=='N' || weekDay[2]=='n')) {
return DayOfWeek.Monday;
}
if ((weekDay[0]=='W' || weekDay[0]=='w') && (weekDay[1]=='E' || weekDay[1]=='e') && (weekDay[2]=='D' || weekDay[2]=='d')) {
return DayOfWeek.Wednesday;
}
if ((weekDay[0]=='F' || weekDay[0]=='f') && (weekDay[1]=='R' || weekDay[1]=='r') && (weekDay[2]=='I' || weekDay[2]=='i')) {
return DayOfWeek.Friday;
}
}
return (DayOfWeek)unchecked(-1);
}
private static bool weekdayRangeInternal(DateTime now, DayOfWeek wd1, DayOfWeek wd2)
{
if (wd1<0 || wd2<0) {
if(Logging.On)Logging.PrintWarning(Logging.Web, SR.GetString(SR.net_log_proxy_called_with_invalid_parameter, "WebProxyScriptHelper.weekdayRange()"));
throw new ArgumentException(SR.GetString(SR.net_proxy_invalid_dayofweek), wd1 < 0 ? "wd1" : "wd2");
}
if (wd1<=wd2) {
return wd1<=now.DayOfWeek && now.DayOfWeek<=wd2;
}
return wd2>=now.DayOfWeek || now.DayOfWeek>=wd1;
}
//-----------------------------------------------
//Additional methods for IPv6 support
//-----------------------------------------------
public string getClientVersion()
{
return "1.0";
}
private static int MAX_IPADDRESS_LIST_LENGTH = 1024;
public string sortIpAddressList(string IPAddressList)
{
//---------------------------------------------------------------
//If the input is nothing, return nothing
//---------------------------------------------------------------
if(IPAddressList == null || IPAddressList.Length == 0)
{
return string.Empty;
}
//---------------------------------------------------------------
//The input string is supposed to be a list of IPAddress strings
//separated by a semicolon
//---------------------------------------------------------------
string[] IPAddressStrings = IPAddressList.Split(new char[] {';'});
if(IPAddressStrings.Length > MAX_IPADDRESS_LIST_LENGTH)
{
throw new ArgumentException(string.Format(
SR.GetString(SR.net_max_ip_address_list_length_exceeded),
MAX_IPADDRESS_LIST_LENGTH), "IPAddressList");
}
//----------------------------------------------------------------
//If there are no separators, just return the original string
//----------------------------------------------------------------
if(IPAddressStrings.Length == 1)
{
return IPAddressList;
}
//----------------------------------------------------------------
//Parse the strings into Socket Address buffers
//----------------------------------------------------------------
SocketAddress[] SockAddrIn6List = new SocketAddress[IPAddressStrings.Length];
for(int i = 0; i < IPAddressStrings.Length; i++)
{
//Trim leading and trailing spaces
IPAddressStrings[i] = IPAddressStrings[i].Trim();
if(IPAddressStrings[i].Length == 0)
throw new ArgumentException(SR.GetString(SR.dns_bad_ip_address), "IPAddressList");
SocketAddress saddrv6 = new SocketAddress(AddressFamily.InterNetworkV6,
SocketAddress.IPv6AddressSize);
//Parse the string to a v6 address structure
SocketError errorCode =
UnsafeNclNativeMethods.OSSOCK.WSAStringToAddress(
IPAddressStrings[i],
AddressFamily.InterNetworkV6,
IntPtr.Zero,
saddrv6.m_Buffer,
ref saddrv6.m_Size );
if(errorCode != SocketError.Success)
{
//Could not parse this into a SOCKADDR_IN6
//See if we can parse this into s SOCKEADDR_IN
SocketAddress saddrv4 = new SocketAddress(AddressFamily.InterNetwork, SocketAddress.IPv4AddressSize);
errorCode =
UnsafeNclNativeMethods.OSSOCK.WSAStringToAddress(
IPAddressStrings[i],
AddressFamily.InterNetwork,
IntPtr.Zero,
saddrv4.m_Buffer,
ref saddrv4.m_Size );
if(errorCode != SocketError.Success)
{
//This address is neither IPv4 nor IPv6 string throw
throw new ArgumentException(SR.GetString(SR.dns_bad_ip_address), "IPAddressList");
}
else
{
//This is a valid IPv4 address. We need to map this to a mapped v6 address
IPEndPoint dummy = new IPEndPoint(IPAddress.Any, 0);
IPEndPoint IPv4EndPoint = (IPEndPoint)dummy.Create(saddrv4);
byte[] IPv4AddressBytes = IPv4EndPoint.Address.GetAddressBytes();
byte[] IPv6MappedAddressBytes = new byte[16]; //IPv6 is 16 bytes address
for(int j = 0; j < 10; j++) IPv6MappedAddressBytes[j] = 0x00;
IPv6MappedAddressBytes[10] = 0xFF;
IPv6MappedAddressBytes[11] = 0xFF;
IPv6MappedAddressBytes[12] = IPv4AddressBytes[0];
IPv6MappedAddressBytes[13] = IPv4AddressBytes[1];
IPv6MappedAddressBytes[14] = IPv4AddressBytes[2];
IPv6MappedAddressBytes[15] = IPv4AddressBytes[3];
IPAddress v6Address = new IPAddress(IPv6MappedAddressBytes);
IPEndPoint IPv6EndPoint = new IPEndPoint(v6Address, IPv4EndPoint.Port);
saddrv6 = IPv6EndPoint.Serialize();
}
}
//At this point,we have SOCKADDR_IN6 buffer
//add them to the list
SockAddrIn6List[i] = saddrv6;
}
//----------------------------------------------------------------
//All the IPAddress strings are parsed into
//either a native v6 address or mapped v6 address
//The Next step is to prepare for calling the WSAIOctl
//By creating a SOCKET_ADDRESS_LIST
//----------------------------------------------------------------
int cbRequiredBytes = Marshal.SizeOf(typeof(UnsafeNclNativeMethods.OSSOCK.SOCKET_ADDRESS_LIST)) +
(SockAddrIn6List.Length -1)*Marshal.SizeOf(typeof(UnsafeNclNativeMethods.OSSOCK.SOCKET_ADDRESS));
Dictionary<IntPtr, KeyValuePair<SocketAddress, string> > UnmanagedToManagedMapping = new Dictionary<IntPtr, KeyValuePair<SocketAddress, string>>();
GCHandle[] GCHandles = new GCHandle[SockAddrIn6List.Length];
for(int i = 0; i < SockAddrIn6List.Length; i++)
{
GCHandles[i] = GCHandle.Alloc(SockAddrIn6List[i].m_Buffer, GCHandleType.Pinned);
}
IntPtr pSocketAddressList = Marshal.AllocHGlobal(cbRequiredBytes);
try
{
//---------------------------------------------------
//Create a socket address list structure
//and set the pointers to the pinned sock addr buffers
//---------------------------------------------------
unsafe
{
UnsafeNclNativeMethods.OSSOCK.SOCKET_ADDRESS_LIST* pList
= (UnsafeNclNativeMethods.OSSOCK.SOCKET_ADDRESS_LIST*)pSocketAddressList;
pList->iAddressCount = SockAddrIn6List.Length; //Set the number of addresses
UnsafeNclNativeMethods.OSSOCK.SOCKET_ADDRESS* pSocketAddresses =
&pList->Addresses;
for(int i = 0; i < pList->iAddressCount; i++)
{
pSocketAddresses[i].iSockaddrLength = SocketAddress.IPv6AddressSize;
pSocketAddresses[i].lpSockAddr = GCHandles[i].AddrOfPinnedObject();
UnmanagedToManagedMapping[pSocketAddresses[i].lpSockAddr]
= new KeyValuePair<SocketAddress, string>(SockAddrIn6List[i], IPAddressStrings[i]);
}
//---------------------------------------------------
//Create a socket and ask it to sort the list
//---------------------------------------------------
Socket s = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
int cbProcessed = s.IOControl(
IOControlCode.AddressListSort,
pSocketAddressList, //Input buffer
cbRequiredBytes, //Buffer size
pSocketAddressList, //Outbuffer - same as in buffer
cbRequiredBytes //out buffer size - same as in buffer size
);
//---------------------------------------------------
//At this point The sorting is complete
//---------------------------------------------------
StringBuilder sb = new StringBuilder();
for(int i = 0; i < pList->iAddressCount; i++)
{
IntPtr lpSockAddr = pSocketAddresses[i].lpSockAddr;
KeyValuePair<SocketAddress, string> kv = UnmanagedToManagedMapping[lpSockAddr];
sb.Append(kv.Value);
if(i != pList->iAddressCount - 1) sb.Append(";");
}
return sb.ToString();
}
}
finally
{
if(pSocketAddressList != IntPtr.Zero)
{
Marshal.FreeHGlobal(pSocketAddressList);
}
for(int i = 0; i < GCHandles.Length; i++)
{
if(GCHandles[i].IsAllocated)
GCHandles[i].Free();
}
}
}
public bool isInNetEx(string ipAddress, string ipPrefix)
{
//---------------------------------------------------------------
//Check for Null arguments
//---------------------------------------------------------------
if (ipAddress==null) {
if(Logging.On)Logging.PrintWarning(Logging.Web, SR.GetString(SR.net_log_proxy_called_with_null_parameter, "WebProxyScriptHelper.isResolvable()", "ipAddress"));
throw new ArgumentNullException("ipAddress");
}
if (ipPrefix==null) {
if(Logging.On)Logging.PrintWarning(Logging.Web, SR.GetString(SR.net_log_proxy_called_with_null_parameter, "WebProxyScriptHelper.isResolvable()", "ipPrefix"));
throw new ArgumentNullException("ipPrefix");
}
//---------------------------------------------------------------
//Try parsing the ipAddress given
//If we can't parse throw a bad ip address exception
//---------------------------------------------------------------
IPAddress address;
if(!IPAddress.TryParse(ipAddress, out address))
{
throw new FormatException(SR.GetString(SR.dns_bad_ip_address));
}
//---------------------------------------------------------------
//First check if there is a separator for prefix
//---------------------------------------------------------------
int prefixSeparatorIndex = ipPrefix.IndexOf("/");
if(prefixSeparatorIndex < 0)
{
//There is no separator - throw an exception - we require a prefix
throw new FormatException(SR.GetString(SR.net_bad_ip_address_prefix));
}
//---------------------------------------------------------------
//Now separate the prefix into address and prefix length
//---------------------------------------------------------------
string[] parts = ipPrefix.Split(new char[] {'/'});
if(parts.Length != 2 || parts[0] == null || parts[0].Length == 0 ||
parts[1] == null || parts[1].Length == 0 || parts[1].Length > 2)
{
//Invalid address or prefix lengths
throw new FormatException(SR.GetString(SR.net_bad_ip_address_prefix));
}
//---------------------------------------------------------------
//Now that we have an address and a prefix length, validate
//the address and prefix lengths
//---------------------------------------------------------------
IPAddress prefixAddress;
if(!IPAddress.TryParse(parts[0], out prefixAddress))
{
throw new FormatException(SR.GetString(SR.dns_bad_ip_address));
}
int prefixLength = 0;
if(!Int32.TryParse(parts[1], out prefixLength))
{
throw new FormatException(SR.GetString(SR.net_bad_ip_address_prefix));
}
//---------------------------------------------------------------
//Now check that the AddressFamilies match
//---------------------------------------------------------------
if(address.AddressFamily != prefixAddress.AddressFamily)
{
throw new FormatException(SR.GetString(SR.net_bad_ip_address_prefix));
}
//---------------------------------------------------------------
//We have validated the input.
//Now check the prefix match
//---------------------------------------------------------------
//----------------------------------------------
//IPv6 prefix length can not be greater than 64 for v6
//and can't be greater than 32 for v4
//----------------------------------------------
if (
( (address.AddressFamily == AddressFamily.InterNetworkV6) &&
( prefixLength < 1 || prefixLength > 64) ) ||
( (address.AddressFamily == AddressFamily.InterNetwork) &&
( prefixLength < 1 || prefixLength > 32) )
)
{
throw new FormatException(SR.GetString(SR.net_bad_ip_address_prefix));
}
//----------------------------------------------
//Validate that the Prefix address supplied
//has zeros after the prefix length
//for example: feco:2002::/16 is invalid
//because the bits other than the first 16 bits [top most]
//are non-zero
//----------------------------------------------
byte[] prefixAddressBytes = prefixAddress.GetAddressBytes();
//----------------------------------------------
//Get the number of complete bytes and then the
//remaning bits
//----------------------------------------------
byte prefixBytes = (byte)(prefixLength/8);
byte prefixExtraBits = (byte)(prefixLength%8);
byte i = prefixBytes;
//----------------------------------------------
//If the extra bits are non zero the bits
//must come from the byte after the "prefixBytes"
//For example in the feco:2000/19 prefix
//19 = 2 * 8 + 3
//So the extra bits must come from the 3rd byte
//which is at the index 2 in the addressbytes array
//
//Now in the 3rd byte at index 2, anything after the
//3rd bit must be zero
//Thats what we are testing below
//----------------------------------------------
if(prefixExtraBits != 0)
{
if( (0xFF & (prefixAddressBytes[prefixBytes] << prefixExtraBits)) != 0)
{
throw new FormatException(SR.GetString(SR.net_bad_ip_address_prefix));
}
i++;
}
//-----------------------------------------------
//Now that we checked the last byte any
//byte after that must be zero
//Note that i here is at 3 in the example above
//after incrementing from the above if statement
//That means anything from the 4th byte [inclusive]
//must be zero
//-----------------------------------------------
int MaxBytes = (prefixAddress.AddressFamily == AddressFamily.InterNetworkV6)?IPAddress.IPv6AddressBytes:IPAddress.IPv4AddressBytes;
while( i < MaxBytes)
{
if(prefixAddressBytes[i++] != 0)
{
throw new FormatException(SR.GetString(SR.net_bad_ip_address_prefix));
}
}
//------------------------------------------------
//Now that we verifiex the prefix
//we must make sure that that the
//bits match until the prefix
//------------------------------------------------
byte[] addressBytes = address.GetAddressBytes();
for( i = 0; i < prefixBytes; i++)
{
if(addressBytes[i] != prefixAddressBytes[i])
{
return false;
}
}
//-------------------------------------------------
//Compare the remaining bits
//-------------------------------------------------
if(prefixExtraBits > 0)
{
byte addrbyte = addressBytes[prefixBytes];
byte prefixbyte = prefixAddressBytes[prefixBytes];
//Clear 8 - Remaining bits from the addr byte
addrbyte = (byte)(addrbyte >> (8 - prefixExtraBits));
addrbyte = (byte)(addrbyte << (8 - prefixExtraBits));
if(addrbyte != prefixbyte)
{
return false;
}
}
return true;
}
public string myIpAddressEx()
{
StringBuilder sb = new StringBuilder();
try
{
GlobalLog.Print("WebProxyScriptHelper::myIPAddressesEx()");
IPAddress[] ipAddresses = NclUtilities.LocalAddresses;
for (int i = 0; i < ipAddresses.Length; i++)
{
if (!IPAddress.IsLoopback(ipAddresses[i]))
{
sb.Append(ipAddresses[i].ToString());
if(i != ipAddresses.Length -1)
sb.Append(";");
}
}
}
catch {}
return sb.Length > 0 ? sb.ToString(): string.Empty;
}
public string dnsResolveEx(string host) {
GlobalLog.Print("WebProxyScriptHelper::dnsResolveEx() host:" + ValidationHelper.ToString(host));
if (host==null) {
if(Logging.On)Logging.PrintWarning(Logging.Web, SR.GetString(SR.net_log_proxy_called_with_null_parameter, "WebProxyScriptHelper.dnsResolve()", "host"));
throw new ArgumentNullException("host");
}
IPHostEntry ipHostEntry = null;
try
{
ipHostEntry = Dns.InternalGetHostByName(host);
}
catch { }
if (ipHostEntry == null)
{
return string.Empty;
}
IPAddress[] addresses = ipHostEntry.AddressList;
if(addresses.Length == 0)
{
return string.Empty;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < addresses.Length; i++)
{
sb.Append(addresses[i].ToString());
if(i != addresses.Length -1)
sb.Append(";");
}
return sb.Length > 0 ? sb.ToString(): string.Empty;
}
public bool isResolvableEx(string host) {
GlobalLog.Print("WebProxyScriptHelper::dnsResolveEx() host:" + ValidationHelper.ToString(host));
if (host==null) {
if(Logging.On)Logging.PrintWarning(Logging.Web, SR.GetString(SR.net_log_proxy_called_with_null_parameter, "WebProxyScriptHelper.dnsResolve()", "host"));
throw new ArgumentNullException("host");
}
IPHostEntry ipHostEntry = null;
try
{
ipHostEntry = Dns.InternalGetHostByName(host);
}
catch { }
if (ipHostEntry == null)
{
return false;
}
IPAddress[] addresses = ipHostEntry.AddressList;
if(addresses.Length == 0)
{
return false;
}
return true;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Threading;
using System.Threading.Tasks;
using Orleans.GrainDirectory;
using Orleans.Providers;
using Orleans.Runtime.Configuration;
using Orleans.Runtime.GrainDirectory;
using Orleans.Runtime.Placement;
using Orleans.Runtime.Scheduler;
using Orleans.Storage;
namespace Orleans.Runtime
{
internal class Catalog : SystemTarget, ICatalog, IPlacementContext, ISiloStatusListener
{
/// <summary>
/// Exception to indicate that the activation would have been a duplicate so messages pending for it should be redirected.
/// </summary>
[Serializable]
internal class DuplicateActivationException : Exception
{
public ActivationAddress ActivationToUse { get; private set; }
public SiloAddress PrimaryDirectoryForGrain { get; private set; } // for diagnostics only!
public DuplicateActivationException() : base("DuplicateActivationException") { }
public DuplicateActivationException(string msg) : base(msg) { }
public DuplicateActivationException(string message, Exception innerException) : base(message, innerException) { }
public DuplicateActivationException(ActivationAddress activationToUse)
: base("DuplicateActivationException")
{
ActivationToUse = activationToUse;
}
public DuplicateActivationException(ActivationAddress activationToUse, SiloAddress primaryDirectoryForGrain)
: base("DuplicateActivationException")
{
ActivationToUse = activationToUse;
PrimaryDirectoryForGrain = primaryDirectoryForGrain;
}
// Implementation of exception serialization with custom properties according to:
// http://stackoverflow.com/questions/94488/what-is-the-correct-way-to-make-a-custom-net-exception-serializable
protected DuplicateActivationException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
if (info != null)
{
ActivationToUse = (ActivationAddress) info.GetValue("ActivationToUse", typeof (ActivationAddress));
PrimaryDirectoryForGrain = (SiloAddress) info.GetValue("PrimaryDirectoryForGrain", typeof (SiloAddress));
}
}
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info != null)
{
info.AddValue("ActivationToUse", ActivationToUse, typeof (ActivationAddress));
info.AddValue("PrimaryDirectoryForGrain", PrimaryDirectoryForGrain, typeof (SiloAddress));
}
// MUST call through to the base class to let it save its own state
base.GetObjectData(info, context);
}
}
[Serializable]
internal class NonExistentActivationException : Exception
{
public ActivationAddress NonExistentActivation { get; private set; }
public bool IsStatelessWorker { get; private set; }
public NonExistentActivationException() : base("NonExistentActivationException") { }
public NonExistentActivationException(string msg) : base(msg) { }
public NonExistentActivationException(string message, Exception innerException)
: base(message, innerException) { }
public NonExistentActivationException(string msg, ActivationAddress nonExistentActivation, bool isStatelessWorker)
: base(msg)
{
NonExistentActivation = nonExistentActivation;
IsStatelessWorker = isStatelessWorker;
}
protected NonExistentActivationException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
if (info != null)
{
NonExistentActivation = (ActivationAddress)info.GetValue("NonExistentActivation", typeof(ActivationAddress));
IsStatelessWorker = (bool)info.GetValue("IsStatelessWorker", typeof(bool));
}
}
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info != null)
{
info.AddValue("NonExistentActivation", NonExistentActivation, typeof(ActivationAddress));
info.AddValue("IsStatelessWorker", IsStatelessWorker, typeof(bool));
}
// MUST call through to the base class to let it save its own state
base.GetObjectData(info, context);
}
}
public GrainTypeManager GrainTypeManager { get; private set; }
public SiloAddress LocalSilo { get; private set; }
internal ISiloStatusOracle SiloStatusOracle { get; set; }
internal readonly ActivationCollector ActivationCollector;
private readonly ILocalGrainDirectory directory;
private readonly OrleansTaskScheduler scheduler;
private readonly ActivationDirectory activations;
private IStorageProviderManager storageProviderManager;
private Dispatcher dispatcher;
private readonly Logger logger;
private int collectionNumber;
private int destroyActivationsNumber;
private IDisposable gcTimer;
private readonly GlobalConfiguration config;
private readonly string localSiloName;
private readonly CounterStatistic activationsCreated;
private readonly CounterStatistic activationsDestroyed;
private readonly CounterStatistic activationsFailedToActivate;
private readonly IntValueStatistic inProcessRequests;
private readonly CounterStatistic collectionCounter;
private readonly GrainCreator grainCreator;
internal Catalog(
GrainId grainId,
SiloAddress silo,
string siloName,
ILocalGrainDirectory grainDirectory,
GrainTypeManager typeManager,
OrleansTaskScheduler scheduler,
ActivationDirectory activationDirectory,
ClusterConfiguration config,
GrainCreator grainCreator,
out Action<Dispatcher> setDispatcher)
: base(grainId, silo)
{
LocalSilo = silo;
localSiloName = siloName;
directory = grainDirectory;
activations = activationDirectory;
this.scheduler = scheduler;
GrainTypeManager = typeManager;
collectionNumber = 0;
destroyActivationsNumber = 0;
this.grainCreator = grainCreator;
logger = LogManager.GetLogger("Catalog", Runtime.LoggerType.Runtime);
this.config = config.Globals;
setDispatcher = d => dispatcher = d;
ActivationCollector = new ActivationCollector(config);
GC.GetTotalMemory(true); // need to call once w/true to ensure false returns OK value
config.OnConfigChange("Globals/Activation", () => scheduler.RunOrQueueAction(Start, SchedulingContext), false);
IntValueStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_COUNT, () => activations.Count);
activationsCreated = CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_CREATED);
activationsDestroyed = CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_DESTROYED);
activationsFailedToActivate = CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_FAILED_TO_ACTIVATE);
collectionCounter = CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_COLLECTION_NUMBER_OF_COLLECTIONS);
inProcessRequests = IntValueStatistic.FindOrCreate(StatisticNames.MESSAGING_PROCESSING_ACTIVATION_DATA_ALL, () =>
{
long counter = 0;
lock (activations)
{
foreach (var activation in activations)
{
ActivationData data = activation.Value;
counter += data.GetRequestCount();
}
}
return counter;
});
}
internal void SetStorageManager(IStorageProviderManager storageManager)
{
storageProviderManager = storageManager;
}
internal void Start()
{
if (gcTimer != null) gcTimer.Dispose();
var t = GrainTimer.FromTaskCallback(OnTimer, null, TimeSpan.Zero, ActivationCollector.Quantum, "Catalog.GCTimer");
t.Start();
gcTimer = t;
}
private Task OnTimer(object _)
{
return CollectActivationsImpl(true);
}
public Task CollectActivations(TimeSpan ageLimit)
{
return CollectActivationsImpl(false, ageLimit);
}
private async Task CollectActivationsImpl(bool scanStale, TimeSpan ageLimit = default(TimeSpan))
{
var watch = new Stopwatch();
watch.Start();
var number = Interlocked.Increment(ref collectionNumber);
long memBefore = GC.GetTotalMemory(false) / (1024 * 1024);
logger.Info(ErrorCode.Catalog_BeforeCollection, "Before collection#{0}: memory={1}MB, #activations={2}, collector={3}.",
number, memBefore, activations.Count, ActivationCollector.ToString());
List<ActivationData> list = scanStale ? ActivationCollector.ScanStale() : ActivationCollector.ScanAll(ageLimit);
collectionCounter.Increment();
var count = 0;
if (list != null && list.Count > 0)
{
count = list.Count;
if (logger.IsVerbose) logger.Verbose("CollectActivations{0}", list.ToStrings(d => d.Grain.ToString() + d.ActivationId));
await DeactivateActivationsFromCollector(list);
}
long memAfter = GC.GetTotalMemory(false) / (1024 * 1024);
watch.Stop();
logger.Info(ErrorCode.Catalog_AfterCollection, "After collection#{0}: memory={1}MB, #activations={2}, collected {3} activations, collector={4}, collection time={5}.",
number, memAfter, activations.Count, count, ActivationCollector.ToString(), watch.Elapsed);
}
public List<Tuple<GrainId, string, int>> GetGrainStatistics()
{
var counts = new Dictionary<string, Dictionary<GrainId, int>>();
lock (activations)
{
foreach (var activation in activations)
{
ActivationData data = activation.Value;
if (data == null || data.GrainInstance == null) continue;
// TODO: generic type expansion
var grainTypeName = TypeUtils.GetFullName(data.GrainInstanceType);
Dictionary<GrainId, int> grains;
int n;
if (!counts.TryGetValue(grainTypeName, out grains))
{
counts.Add(grainTypeName, new Dictionary<GrainId, int> { { data.Grain, 1 } });
}
else if (!grains.TryGetValue(data.Grain, out n))
grains[data.Grain] = 1;
else
grains[data.Grain] = n + 1;
}
}
return counts
.SelectMany(p => p.Value.Select(p2 => Tuple.Create(p2.Key, p.Key, p2.Value)))
.ToList();
}
public List<DetailedGrainStatistic> GetDetailedGrainStatistics(string[] types=null)
{
var stats = new List<DetailedGrainStatistic>();
lock (activations)
{
foreach (var activation in activations)
{
ActivationData data = activation.Value;
if (data == null || data.GrainInstance == null) continue;
if (types==null || types.Contains(TypeUtils.GetFullName(data.GrainInstanceType)))
{
stats.Add(new DetailedGrainStatistic()
{
GrainType = TypeUtils.GetFullName(data.GrainInstanceType),
GrainIdentity = data.Grain,
SiloAddress = data.Silo,
Category = data.Grain.Category.ToString()
});
}
}
}
return stats;
}
public IEnumerable<KeyValuePair<string, long>> GetSimpleGrainStatistics()
{
return activations.GetSimpleGrainStatistics();
}
public DetailedGrainReport GetDetailedGrainReport(GrainId grain)
{
var report = new DetailedGrainReport
{
Grain = grain,
SiloAddress = LocalSilo,
SiloName = localSiloName,
LocalCacheActivationAddresses = directory.GetLocalCacheData(grain),
LocalDirectoryActivationAddresses = directory.GetLocalDirectoryData(grain).Addresses,
PrimaryForGrain = directory.GetPrimaryForGrain(grain)
};
try
{
PlacementStrategy unused;
MultiClusterRegistrationStrategy unusedActivationStrategy;
string grainClassName;
GrainTypeManager.GetTypeInfo(grain.GetTypeCode(), out grainClassName, out unused, out unusedActivationStrategy);
report.GrainClassTypeName = grainClassName;
}
catch (Exception exc)
{
report.GrainClassTypeName = exc.ToString();
}
List<ActivationData> acts = activations.FindTargets(grain);
report.LocalActivations = acts != null ?
acts.Select(activationData => activationData.ToDetailedString()).ToList() :
new List<string>();
return report;
}
#region MessageTargets
/// <summary>
/// Register a new object to which messages can be delivered with the local lookup table and scheduler.
/// </summary>
/// <param name="activation"></param>
public void RegisterMessageTarget(ActivationData activation)
{
var context = new SchedulingContext(activation);
scheduler.RegisterWorkContext(context);
activations.RecordNewTarget(activation);
activationsCreated.Increment();
}
/// <summary>
/// Unregister message target and stop delivering messages to it
/// </summary>
/// <param name="activation"></param>
public void UnregisterMessageTarget(ActivationData activation)
{
activations.RemoveTarget(activation);
// this should be removed once we've refactored the deactivation code path. For now safe to keep.
ActivationCollector.TryCancelCollection(activation);
activationsDestroyed.Increment();
scheduler.UnregisterWorkContext(new SchedulingContext(activation));
if (activation.GrainInstance == null) return;
var grainTypeName = TypeUtils.GetFullName(activation.GrainInstanceType);
activations.DecrementGrainCounter(grainTypeName);
activation.SetGrainInstance(null);
}
/// <summary>
/// FOR TESTING PURPOSES ONLY!!
/// </summary>
/// <param name="grain"></param>
internal int UnregisterGrainForTesting(GrainId grain)
{
var acts = activations.FindTargets(grain);
if (acts == null) return 0;
int numActsBefore = acts.Count;
foreach (var act in acts)
UnregisterMessageTarget(act);
return numActsBefore;
}
#endregion
#region Grains
internal bool IsReentrantGrain(ActivationId running)
{
ActivationData target;
GrainTypeData data;
return TryGetActivationData(running, out target) &&
target.GrainInstance != null &&
GrainTypeManager.TryGetData(TypeUtils.GetFullName(target.GrainInstanceType), out data) &&
data.IsReentrant;
}
public void GetGrainTypeInfo(int typeCode, out string grainClass, out PlacementStrategy placement, out MultiClusterRegistrationStrategy activationStrategy, string genericArguments = null)
{
GrainTypeManager.GetTypeInfo(typeCode, out grainClass, out placement, out activationStrategy, genericArguments);
}
#endregion
#region Activations
public int ActivationCount { get { return activations.Count; } }
/// <summary>
/// If activation already exists, use it
/// Otherwise, create an activation of an existing grain by reading its state.
/// Return immediately using a dummy that will queue messages.
/// Concurrently start creating and initializing the real activation and replace it when it is ready.
/// </summary>
/// <param name="address">Grain's activation address</param>
/// <param name="newPlacement">Creation of new activation was requested by the placement director.</param>
/// <param name="grainType">The type of grain to be activated or created</param>
/// <param name="genericArguments">Specific generic type of grain to be activated or created</param>
/// <param name="requestContextData">Request context data.</param>
/// <param name="activatedPromise"></param>
/// <returns></returns>
public ActivationData GetOrCreateActivation(
ActivationAddress address,
bool newPlacement,
string grainType,
string genericArguments,
Dictionary<string, object> requestContextData,
out Task activatedPromise)
{
ActivationData result;
activatedPromise = TaskDone.Done;
PlacementStrategy placement;
lock (activations)
{
if (TryGetActivationData(address.Activation, out result))
{
return result;
}
int typeCode = address.Grain.GetTypeCode();
string actualGrainType = null;
MultiClusterRegistrationStrategy activationStrategy;
if (typeCode != 0)
{
GetGrainTypeInfo(typeCode, out actualGrainType, out placement, out activationStrategy, genericArguments);
}
else
{
// special case for Membership grain.
placement = SystemPlacement.Singleton;
activationStrategy = ClusterLocalRegistration.Singleton;
}
if (newPlacement && !SiloStatusOracle.CurrentStatus.IsTerminating())
{
// create a dummy activation that will queue up messages until the real data arrives
if (string.IsNullOrEmpty(grainType))
{
grainType = actualGrainType;
}
// We want to do this (RegisterMessageTarget) under the same lock that we tested TryGetActivationData. They both access ActivationDirectory.
result = new ActivationData(
address,
genericArguments,
placement,
activationStrategy,
ActivationCollector,
config.Application.GetCollectionAgeLimit(grainType));
RegisterMessageTarget(result);
}
} // End lock
// Did not find and did not start placing new
if (result == null)
{
var msg = String.Format("Non-existent activation: {0}, grain type: {1}.",
address.ToFullString(), grainType);
if (logger.IsVerbose) logger.Verbose(ErrorCode.CatalogNonExistingActivation2, msg);
CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_NON_EXISTENT_ACTIVATIONS).Increment();
throw new NonExistentActivationException(msg, address, placement is StatelessWorkerPlacement);
}
SetupActivationInstance(result, grainType, genericArguments);
activatedPromise = InitActivation(result, grainType, genericArguments, requestContextData);
return result;
}
private void SetupActivationInstance(ActivationData result, string grainType, string genericArguments)
{
lock (result)
{
if (result.GrainInstance == null)
{
CreateGrainInstance(grainType, result, genericArguments);
}
}
}
private async Task InitActivation(ActivationData activation, string grainType, string genericArguments, Dictionary<string, object> requestContextData)
{
// We've created a dummy activation, which we'll eventually return, but in the meantime we'll queue up (or perform promptly)
// the operations required to turn the "dummy" activation into a real activation
ActivationAddress address = activation.Address;
int initStage = 0;
// A chain of promises that will have to complete in order to complete the activation
// Register with the grain directory, register with the store if necessary and call the Activate method on the new activation.
try
{
initStage = 1;
await RegisterActivationInGrainDirectoryAndValidate(activation);
initStage = 2;
await SetupActivationState(activation, String.IsNullOrEmpty(genericArguments) ? grainType : $"{grainType}[{genericArguments}]");
initStage = 3;
await InvokeActivate(activation, requestContextData);
ActivationCollector.ScheduleCollection(activation);
// Success!! Log the result, and start processing messages
if (logger.IsVerbose) logger.Verbose("InitActivation is done: {0}", address);
}
catch (Exception ex)
{
lock (activation)
{
activation.SetState(ActivationState.Invalid);
try
{
UnregisterMessageTarget(activation);
}
catch (Exception exc)
{
logger.Warn(ErrorCode.Catalog_UnregisterMessageTarget4, String.Format("UnregisterMessageTarget failed on {0}.", activation), exc);
}
switch (initStage)
{
case 1: // failed to RegisterActivationInGrainDirectory
ActivationAddress target = null;
Exception dupExc;
// Failure!! Could it be that this grain uses single activation placement, and there already was an activation?
if (Utils.TryFindException(ex, typeof (DuplicateActivationException), out dupExc))
{
target = ((DuplicateActivationException) dupExc).ActivationToUse;
CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_DUPLICATE_ACTIVATIONS)
.Increment();
}
activation.ForwardingAddress = target;
if (target != null)
{
var primary = ((DuplicateActivationException)dupExc).PrimaryDirectoryForGrain;
// If this was a duplicate, it's not an error, just a race.
// Forward on all of the pending messages, and then forget about this activation.
string logMsg = String.Format("Tried to create a duplicate activation {0}, but we'll use {1} instead. " +
"GrainInstanceType is {2}. " +
"{3}" +
"Full activation address is {4}. We have {5} messages to forward.",
address,
target,
activation.GrainInstanceType,
primary != null ? "Primary Directory partition for this grain is " + primary + ". " : String.Empty,
address.ToFullString(),
activation.WaitingCount);
if (activation.IsUsingGrainDirectory)
{
logger.Info(ErrorCode.Catalog_DuplicateActivation, logMsg);
}
else
{
if (logger.IsVerbose) logger.Verbose(ErrorCode.Catalog_DuplicateActivation, logMsg);
}
RerouteAllQueuedMessages(activation, target, "Duplicate activation", ex);
}
else
{
logger.Warn(ErrorCode.Runtime_Error_100064,
String.Format("Failed to RegisterActivationInGrainDirectory for {0}.",
activation), ex);
// Need to undo the registration we just did earlier
if (activation.IsUsingGrainDirectory)
{
scheduler.RunOrQueueTask(() => directory.UnregisterAsync(address, UnregistrationCause.Force),
SchedulingContext).Ignore();
}
RerouteAllQueuedMessages(activation, null,
"Failed RegisterActivationInGrainDirectory", ex);
}
break;
case 2: // failed to setup persistent state
logger.Warn(ErrorCode.Catalog_Failed_SetupActivationState,
String.Format("Failed to SetupActivationState for {0}.", activation), ex);
// Need to undo the registration we just did earlier
if (activation.IsUsingGrainDirectory)
{
scheduler.RunOrQueueTask(() => directory.UnregisterAsync(address, UnregistrationCause.Force),
SchedulingContext).Ignore();
}
RerouteAllQueuedMessages(activation, null, "Failed SetupActivationState", ex);
break;
case 3: // failed to InvokeActivate
logger.Warn(ErrorCode.Catalog_Failed_InvokeActivate,
String.Format("Failed to InvokeActivate for {0}.", activation), ex);
// Need to undo the registration we just did earlier
if (activation.IsUsingGrainDirectory)
{
scheduler.RunOrQueueTask(() => directory.UnregisterAsync(address, UnregistrationCause.Force),
SchedulingContext).Ignore();
}
RerouteAllQueuedMessages(activation, null, "Failed InvokeActivate", ex);
break;
}
}
throw;
}
}
/// <summary>
/// Perform just the prompt, local part of creating an activation object
/// Caller is responsible for registering locally, registering with store and calling its activate routine
/// </summary>
/// <param name="grainTypeName"></param>
/// <param name="data"></param>
/// <param name="genericArguments"></param>
/// <returns></returns>
private void CreateGrainInstance(string grainTypeName, ActivationData data, string genericArguments)
{
string grainClassName;
if (!GrainTypeManager.TryGetPrimaryImplementation(grainTypeName, out grainClassName))
{
// Lookup from grain type code
var typeCode = data.Grain.GetTypeCode();
if (typeCode != 0)
{
PlacementStrategy unused;
MultiClusterRegistrationStrategy unusedActivationStrategy;
GetGrainTypeInfo(typeCode, out grainClassName, out unused, out unusedActivationStrategy, genericArguments);
}
else
{
grainClassName = grainTypeName;
}
}
GrainTypeData grainTypeData = GrainTypeManager[grainClassName];
//Get the grain's type
Type grainType = grainTypeData.Type;
//Gets the type for the grain's state
Type stateObjectType = grainTypeData.StateObjectType;
lock (data)
{
Grain grain;
//Create a new instance of a stateless grain
if (stateObjectType == null)
{
//Create a new instance of the given grain type
grain = grainCreator.CreateGrainInstance(grainType, data.Identity);
}
//Create a new instance of a stateful grain
else
{
SetupStorageProvider(grainType, data);
grain = grainCreator.CreateGrainInstance(grainType, data.Identity, stateObjectType, data.StorageProvider);
}
grain.Data = data;
data.SetGrainInstance(grain);
}
activations.IncrementGrainCounter(grainClassName);
if (logger.IsVerbose) logger.Verbose("CreateGrainInstance {0}{1}", data.Grain, data.ActivationId);
}
private void SetupStorageProvider(Type grainType, ActivationData data)
{
var grainTypeName = grainType.FullName;
// Get the storage provider name, using the default if not specified.
var attr = grainType.GetTypeInfo().GetCustomAttributes<StorageProviderAttribute>(true).FirstOrDefault();
var storageProviderName = attr != null ? attr.ProviderName : Constants.DEFAULT_STORAGE_PROVIDER_NAME;
IStorageProvider provider;
if (storageProviderManager == null || storageProviderManager.GetNumLoadedProviders() == 0)
{
var errMsg = string.Format("No storage providers found loading grain type {0}", grainTypeName);
logger.Error(ErrorCode.Provider_CatalogNoStorageProvider_1, errMsg);
throw new BadProviderConfigException(errMsg);
}
if (string.IsNullOrWhiteSpace(storageProviderName))
{
// Use default storage provider
provider = storageProviderManager.GetDefaultProvider();
}
else
{
// Look for MemoryStore provider as special case name
bool caseInsensitive = Constants.MEMORY_STORAGE_PROVIDER_NAME.Equals(storageProviderName, StringComparison.OrdinalIgnoreCase);
storageProviderManager.TryGetProvider(storageProviderName, out provider, caseInsensitive);
if (provider == null)
{
var errMsg = string.Format(
"Cannot find storage provider with Name={0} for grain type {1}", storageProviderName,
grainTypeName);
logger.Error(ErrorCode.Provider_CatalogNoStorageProvider_2, errMsg);
throw new BadProviderConfigException(errMsg);
}
}
data.StorageProvider = provider;
if (logger.IsVerbose2)
{
string msg = string.Format("Assigned storage provider with Name={0} to grain type {1}",
storageProviderName, grainTypeName);
logger.Verbose2(ErrorCode.Provider_CatalogStorageProviderAllocated, msg);
}
}
private async Task SetupActivationState(ActivationData result, string grainType)
{
var statefulGrain = result.GrainInstance as IStatefulGrain;
if (statefulGrain == null)
{
return;
}
var state = statefulGrain.GrainState;
if (result.StorageProvider != null && state != null)
{
var sw = Stopwatch.StartNew();
var innerState = statefulGrain.GrainState.State;
// Populate state data
try
{
var grainRef = result.GrainReference;
await scheduler.RunOrQueueTask(() =>
result.StorageProvider.ReadStateAsync(grainType, grainRef, state),
new SchedulingContext(result));
sw.Stop();
StorageStatisticsGroup.OnStorageActivate(result.StorageProvider, grainType, result.GrainReference, sw.Elapsed);
}
catch (Exception ex)
{
StorageStatisticsGroup.OnStorageActivateError(result.StorageProvider, grainType, result.GrainReference);
sw.Stop();
if (!(ex.GetBaseException() is KeyNotFoundException))
throw;
statefulGrain.GrainState.State = innerState; // Just keep original empty state object
}
}
}
/// <summary>
/// Try to get runtime data for an activation
/// </summary>
/// <param name="activationId"></param>
/// <param name="data"></param>
/// <returns></returns>
public bool TryGetActivationData(ActivationId activationId, out ActivationData data)
{
data = null;
if (activationId.IsSystem) return false;
data = activations.FindTarget(activationId);
return data != null;
}
private Task DeactivateActivationsFromCollector(List<ActivationData> list)
{
logger.Info(ErrorCode.Catalog_ShutdownActivations_1, "DeactivateActivationsFromCollector: total {0} to promptly Destroy.", list.Count);
CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_SHUTDOWN_VIA_COLLECTION).IncrementBy(list.Count);
foreach (var activation in list)
{
lock (activation)
{
activation.PrepareForDeactivation(); // Don't accept any new messages
}
}
return DestroyActivations(list);
}
// To be called fro within Activation context.
// Cannot be awaitable, since after DestroyActivation is done the activation is in Invalid state and cannot await any Task.
internal void DeactivateActivationOnIdle(ActivationData data)
{
bool promptly = false;
bool alreadBeingDestroyed = false;
lock (data)
{
if (data.State == ActivationState.Valid)
{
// Change the ActivationData state here, since we're about to give up the lock.
data.PrepareForDeactivation(); // Don't accept any new messages
ActivationCollector.TryCancelCollection(data);
if (!data.IsCurrentlyExecuting)
{
promptly = true;
}
else // busy, so destroy later.
{
data.AddOnInactive(() => DestroyActivationVoid(data));
}
}
else if (data.State == ActivationState.Create)
{
throw new InvalidOperationException(String.Format(
"Activation {0} has called DeactivateOnIdle from within a constructor, which is not allowed.",
data.ToString()));
}
else if (data.State == ActivationState.Activating)
{
throw new InvalidOperationException(String.Format(
"Activation {0} has called DeactivateOnIdle from within OnActivateAsync, which is not allowed.",
data.ToString()));
}
else
{
alreadBeingDestroyed = true;
}
}
logger.Info(ErrorCode.Catalog_ShutdownActivations_2,
"DeactivateActivationOnIdle: {0} {1}.", data.ToString(), promptly ? "promptly" : (alreadBeingDestroyed ? "already being destroyed or invalid" : "later when become idle"));
CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_SHUTDOWN_VIA_DEACTIVATE_ON_IDLE).Increment();
if (promptly)
{
DestroyActivationVoid(data); // Don't await or Ignore, since we are in this activation context and it may have alraedy been destroyed!
}
}
/// <summary>
/// Gracefully deletes activations, putting it into a shutdown state to
/// complete and commit outstanding transactions before deleting it.
/// To be called not from within Activation context, so can be awaited.
/// </summary>
/// <param name="list"></param>
/// <returns></returns>
internal async Task DeactivateActivations(List<ActivationData> list)
{
if (list == null || list.Count == 0) return;
if (logger.IsVerbose) logger.Verbose("DeactivateActivations: {0} activations.", list.Count);
List<ActivationData> destroyNow = null;
List<MultiTaskCompletionSource> destroyLater = null;
int alreadyBeingDestroyed = 0;
foreach (var d in list)
{
var activationData = d; // capture
lock (activationData)
{
if (activationData.State == ActivationState.Valid)
{
// Change the ActivationData state here, since we're about to give up the lock.
activationData.PrepareForDeactivation(); // Don't accept any new messages
ActivationCollector.TryCancelCollection(activationData);
if (!activationData.IsCurrentlyExecuting)
{
if (destroyNow == null)
{
destroyNow = new List<ActivationData>();
}
destroyNow.Add(activationData);
}
else // busy, so destroy later.
{
if (destroyLater == null)
{
destroyLater = new List<MultiTaskCompletionSource>();
}
var tcs = new MultiTaskCompletionSource(1);
destroyLater.Add(tcs);
activationData.AddOnInactive(() => DestroyActivationAsync(activationData, tcs));
}
}
else
{
alreadyBeingDestroyed++;
}
}
}
int numDestroyNow = destroyNow == null ? 0 : destroyNow.Count;
int numDestroyLater = destroyLater == null ? 0 : destroyLater.Count;
logger.Info(ErrorCode.Catalog_ShutdownActivations_3,
"DeactivateActivations: total {0} to shutdown, out of them {1} promptly, {2} later when become idle and {3} are already being destroyed or invalid.",
list.Count, numDestroyNow, numDestroyLater, alreadyBeingDestroyed);
CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_SHUTDOWN_VIA_DIRECT_SHUTDOWN).IncrementBy(list.Count);
if (destroyNow != null && destroyNow.Count > 0)
{
await DestroyActivations(destroyNow);
}
if (destroyLater != null && destroyLater.Count > 0)
{
await Task.WhenAll(destroyLater.Select(t => t.Task).ToArray());
}
}
public Task DeactivateAllActivations()
{
logger.Info(ErrorCode.Catalog_DeactivateAllActivations, "DeactivateAllActivations.");
var activationsToShutdown = activations.Where(kv => !kv.Value.IsExemptFromCollection).Select(kv => kv.Value).ToList();
return DeactivateActivations(activationsToShutdown);
}
/// <summary>
/// Deletes activation immediately regardless of active transactions etc.
/// For use by grain delete, transaction abort, etc.
/// </summary>
/// <param name="activation"></param>
private void DestroyActivationVoid(ActivationData activation)
{
StartDestroyActivations(new List<ActivationData> { activation });
}
private void DestroyActivationAsync(ActivationData activation, MultiTaskCompletionSource tcs)
{
StartDestroyActivations(new List<ActivationData> { activation }, tcs);
}
/// <summary>
/// Forcibly deletes activations now, without waiting for any outstanding transactions to complete.
/// Deletes activation immediately regardless of active transactions etc.
/// For use by grain delete, transaction abort, etc.
/// </summary>
/// <param name="list"></param>
/// <returns></returns>
// Overall code flow:
// Deactivating state was already set before, in the correct context under lock.
// that means no more new requests will be accepted into this activation and all timer were stopped (no new ticks will be delivered or enqueued)
// Wait for all already scheduled ticks to finish
// CallGrainDeactivate
// when AsyncDeactivate promise is resolved (NOT when all Deactivate turns are done, which may be orphan tasks):
// Unregister in the directory
// when all AsyncDeactivate turns are done (Dispatcher.OnActivationCompletedRequest):
// Set Invalid state
// UnregisterMessageTarget -> no new tasks will be enqueue (if an orphan task get enqueud, it is ignored and dropped on the floor).
// InvalidateCacheEntry
// Reroute pending
private Task DestroyActivations(List<ActivationData> list)
{
var tcs = new MultiTaskCompletionSource(list.Count);
StartDestroyActivations(list, tcs);
return tcs.Task;
}
private async void StartDestroyActivations(List<ActivationData> list, MultiTaskCompletionSource tcs = null)
{
int number = destroyActivationsNumber;
destroyActivationsNumber++;
try
{
logger.Info(ErrorCode.Catalog_DestroyActivations, "Starting DestroyActivations #{0} of {1} activations", number, list.Count);
// step 1 - WaitForAllTimersToFinish
var tasks1 = new List<Task>();
foreach (var activation in list)
{
tasks1.Add(activation.WaitForAllTimersToFinish());
}
try
{
await Task.WhenAll(tasks1);
}
catch (Exception exc)
{
logger.Warn(ErrorCode.Catalog_WaitForAllTimersToFinish_Exception, String.Format("WaitForAllTimersToFinish {0} failed.", list.Count), exc);
}
// step 2 - CallGrainDeactivate
var tasks2 = new List<Tuple<Task, ActivationData>>();
foreach (var activation in list)
{
var activationData = activation; // Capture loop variable
var task = scheduler.RunOrQueueTask(() => CallGrainDeactivateAndCleanupStreams(activationData), new SchedulingContext(activationData));
tasks2.Add(new Tuple<Task, ActivationData>(task, activationData));
}
var asyncQueue = new AsyncBatchedContinuationQueue<ActivationData>();
asyncQueue.Queue(tasks2, tupleList =>
{
FinishDestroyActivations(tupleList.Select(t => t.Item2).ToList(), number, tcs);
GC.KeepAlive(asyncQueue); // not sure about GC not collecting the asyncQueue local var prematuraly, so just want to capture it here to make sure. Just to be safe.
});
}
catch (Exception exc)
{
logger.Warn(ErrorCode.Catalog_DeactivateActivation_Exception, String.Format("StartDestroyActivations #{0} failed with {1} Activations.", number, list.Count), exc);
}
}
private async void FinishDestroyActivations(List<ActivationData> list, int number, MultiTaskCompletionSource tcs)
{
try
{
//logger.Info(ErrorCode.Catalog_DestroyActivations_Done, "Starting FinishDestroyActivations #{0} - with {1} Activations.", number, list.Count);
// step 3 - UnregisterManyAsync
try
{
List<ActivationAddress> activationsToDeactivate = list.
Where((ActivationData d) => d.IsUsingGrainDirectory).
Select((ActivationData d) => ActivationAddress.GetAddress(LocalSilo, d.Grain, d.ActivationId)).ToList();
if (activationsToDeactivate.Count > 0)
{
await scheduler.RunOrQueueTask(() =>
directory.UnregisterManyAsync(activationsToDeactivate, UnregistrationCause.Force),
SchedulingContext);
}
}
catch (Exception exc)
{
logger.Warn(ErrorCode.Catalog_UnregisterManyAsync, String.Format("UnregisterManyAsync {0} failed.", list.Count), exc);
}
// step 4 - UnregisterMessageTarget and OnFinishedGrainDeactivate
foreach (var activationData in list)
{
try
{
lock (activationData)
{
activationData.SetState(ActivationState.Invalid); // Deactivate calls on this activation are finished
}
UnregisterMessageTarget(activationData);
}
catch (Exception exc)
{
logger.Warn(ErrorCode.Catalog_UnregisterMessageTarget2, String.Format("UnregisterMessageTarget failed on {0}.", activationData), exc);
}
try
{
// IMPORTANT: no more awaits and .Ignore after that point.
// Just use this opportunity to invalidate local Cache Entry as well.
// If this silo is not the grain directory partition for this grain, it may have it in its cache.
directory.InvalidateCacheEntry(activationData.Address);
RerouteAllQueuedMessages(activationData, null, "Finished Destroy Activation");
}
catch (Exception exc)
{
logger.Warn(ErrorCode.Catalog_UnregisterMessageTarget3, String.Format("Last stage of DestroyActivations failed on {0}.", activationData), exc);
}
}
// step 5 - Resolve any waiting TaskCompletionSource
if (tcs != null)
{
tcs.SetMultipleResults(list.Count);
}
logger.Info(ErrorCode.Catalog_DestroyActivations_Done, "Done FinishDestroyActivations #{0} - Destroyed {1} Activations.", number, list.Count);
}catch (Exception exc)
{
logger.Error(ErrorCode.Catalog_FinishDeactivateActivation_Exception, String.Format("FinishDestroyActivations #{0} failed with {1} Activations.", number, list.Count), exc);
}
}
private void RerouteAllQueuedMessages(ActivationData activation, ActivationAddress forwardingAddress, string failedOperation, Exception exc = null)
{
lock (activation)
{
List<Message> msgs = activation.DequeueAllWaitingMessages();
if (msgs == null || msgs.Count <= 0) return;
if (logger.IsVerbose) logger.Verbose(ErrorCode.Catalog_RerouteAllQueuedMessages, String.Format("RerouteAllQueuedMessages: {0} msgs from Invalid activation {1}.", msgs.Count(), activation));
dispatcher.ProcessRequestsToInvalidActivation(msgs, activation.Address, forwardingAddress, failedOperation, exc);
}
}
private async Task CallGrainActivate(ActivationData activation, Dictionary<string, object> requestContextData)
{
var grainTypeName = activation.GrainInstanceType.FullName;
// Note: This call is being made from within Scheduler.Queue wrapper, so we are already executing on worker thread
if (logger.IsVerbose) logger.Verbose(ErrorCode.Catalog_BeforeCallingActivate, "About to call {1} grain's OnActivateAsync() method {0}", activation, grainTypeName);
// Call OnActivateAsync inline, but within try-catch wrapper to safely capture any exceptions thrown from called function
try
{
RequestContext.Import(requestContextData);
await activation.GrainInstance.OnActivateAsync();
if (logger.IsVerbose) logger.Verbose(ErrorCode.Catalog_AfterCallingActivate, "Returned from calling {1} grain's OnActivateAsync() method {0}", activation, grainTypeName);
lock (activation)
{
if (activation.State == ActivationState.Activating)
{
activation.SetState(ActivationState.Valid); // Activate calls on this activation are finished
}
if (!activation.IsCurrentlyExecuting)
{
activation.RunOnInactive();
}
// Run message pump to see if there is a new request is queued to be processed
dispatcher.RunMessagePump(activation);
}
}
catch (Exception exc)
{
logger.Error(ErrorCode.Catalog_ErrorCallingActivate,
string.Format("Error calling grain's OnActivateAsync() method - Grain type = {1} Activation = {0}", activation, grainTypeName), exc);
activation.SetState(ActivationState.Invalid); // Mark this activation as unusable
activationsFailedToActivate.Increment();
throw;
}
}
private async Task<ActivationData> CallGrainDeactivateAndCleanupStreams(ActivationData activation)
{
try
{
var grainTypeName = activation.GrainInstanceType.FullName;
// Note: This call is being made from within Scheduler.Queue wrapper, so we are already executing on worker thread
if (logger.IsVerbose) logger.Verbose(ErrorCode.Catalog_BeforeCallingDeactivate, "About to call {1} grain's OnDeactivateAsync() method {0}", activation, grainTypeName);
// Call OnDeactivateAsync inline, but within try-catch wrapper to safely capture any exceptions thrown from called function
try
{
// just check in case this activation data is already Invalid or not here at all.
ActivationData ignore;
if (TryGetActivationData(activation.ActivationId, out ignore) &&
activation.State == ActivationState.Deactivating)
{
RequestContext.Clear(); // Clear any previous RC, so it does not leak into this call by mistake.
await activation.GrainInstance.OnDeactivateAsync();
}
if (logger.IsVerbose) logger.Verbose(ErrorCode.Catalog_AfterCallingDeactivate, "Returned from calling {1} grain's OnDeactivateAsync() method {0}", activation, grainTypeName);
}
catch (Exception exc)
{
logger.Error(ErrorCode.Catalog_ErrorCallingDeactivate,
string.Format("Error calling grain's OnDeactivateAsync() method - Grain type = {1} Activation = {0}", activation, grainTypeName), exc);
}
if (activation.IsUsingStreams)
{
try
{
await activation.DeactivateStreamResources();
}
catch (Exception exc)
{
logger.Warn(ErrorCode.Catalog_DeactivateStreamResources_Exception, String.Format("DeactivateStreamResources Grain type = {0} Activation = {1} failed.", grainTypeName, activation), exc);
}
}
}
catch(Exception exc)
{
logger.Error(ErrorCode.Catalog_FinishGrainDeactivateAndCleanupStreams_Exception, String.Format("CallGrainDeactivateAndCleanupStreams Activation = {0} failed.", activation), exc);
}
return activation;
}
private async Task RegisterActivationInGrainDirectoryAndValidate(ActivationData activation)
{
ActivationAddress address = activation.Address;
// Currently, the only grain type that is not registered in the Grain Directory is StatelessWorker.
// Among those that are registered in the directory, we currently do not have any multi activations.
if (activation.IsUsingGrainDirectory)
{
var result = await scheduler.RunOrQueueTask(() => directory.RegisterAsync(address, singleActivation:true), this.SchedulingContext);
if (address.Equals(result.Address)) return;
SiloAddress primaryDirectoryForGrain = directory.GetPrimaryForGrain(address.Grain);
throw new DuplicateActivationException(result.Address, primaryDirectoryForGrain);
}
else
{
StatelessWorkerPlacement stPlacement = activation.PlacedUsing as StatelessWorkerPlacement;
int maxNumLocalActivations = stPlacement.MaxLocal;
lock (activations)
{
List<ActivationData> local;
if (!LocalLookup(address.Grain, out local) || local.Count <= maxNumLocalActivations)
return;
var id = StatelessWorkerDirector.PickRandom(local).Address;
throw new DuplicateActivationException(id);
}
}
// We currently don't have any other case for multiple activations except for StatelessWorker.
}
#endregion
#region Activations - private
/// <summary>
/// Invoke the activate method on a newly created activation
/// </summary>
/// <param name="activation"></param>
/// <param name="requestContextData"></param>
/// <returns></returns>
private Task InvokeActivate(ActivationData activation, Dictionary<string, object> requestContextData)
{
// NOTE: This should only be called with the correct schedulering context for the activation to be invoked.
lock (activation)
{
activation.SetState(ActivationState.Activating);
}
return scheduler.QueueTask(() => CallGrainActivate(activation, requestContextData), new SchedulingContext(activation)); // Target grain's scheduler context);
// ActivationData will transition out of ActivationState.Activating via Dispatcher.OnActivationCompletedRequest
}
#endregion
#region IPlacementContext
public Logger Logger => logger;
public bool FastLookup(GrainId grain, out AddressesAndTag addresses)
{
return directory.LocalLookup(grain, out addresses) && addresses.Addresses != null && addresses.Addresses.Count > 0;
// NOTE: only check with the local directory cache.
// DO NOT check in the local activations TargetDirectory!!!
// The only source of truth about which activation should be legit to is the state of the ditributed directory.
// Everyone should converge to that (that is the meaning of "eventualy consistency - eventualy we converge to one truth").
// If we keep using the local activation, it may not be registered in th directory any more, but we will never know that and keep using it,
// thus volaiting the single-activation semantics and not converging even eventualy!
}
public Task<AddressesAndTag> FullLookup(GrainId grain)
{
return scheduler.RunOrQueueTask(() => directory.LookupAsync(grain), this.SchedulingContext);
}
public Task<AddressesAndTag> LookupInCluster(GrainId grain, string clusterId)
{
return scheduler.RunOrQueueTask(() => directory.LookupInCluster(grain, clusterId), this.SchedulingContext);
}
public bool LocalLookup(GrainId grain, out List<ActivationData> addresses)
{
addresses = activations.FindTargets(grain);
return addresses != null;
}
public List<SiloAddress> AllActiveSilos
{
get
{
var result = SiloStatusOracle.GetApproximateSiloStatuses(true).Select(s => s.Key).ToList();
if (result.Count > 0) return result;
logger.Warn(ErrorCode.Catalog_GetApproximateSiloStatuses, "AllActiveSilos SiloStatusOracle.GetApproximateSiloStatuses empty");
return new List<SiloAddress> { LocalSilo };
}
}
#endregion
#region Implementation of ICatalog
public Task CreateSystemGrain(GrainId grainId, string grainType)
{
ActivationAddress target = ActivationAddress.NewActivationAddress(LocalSilo, grainId);
Task activatedPromise;
GetOrCreateActivation(target, true, grainType, null, null, out activatedPromise);
return activatedPromise ?? TaskDone.Done;
}
public Task DeleteActivations(List<ActivationAddress> addresses)
{
return DestroyActivations(TryGetActivationDatas(addresses));
}
private List<ActivationData> TryGetActivationDatas(List<ActivationAddress> addresses)
{
var datas = new List<ActivationData>(addresses.Count);
foreach (var activationAddress in addresses)
{
ActivationData data;
if (TryGetActivationData(activationAddress.Activation, out data))
datas.Add(data);
}
return datas;
}
#endregion
#region Implementation of ISiloStatusListener
public void SiloStatusChangeNotification(SiloAddress updatedSilo, SiloStatus status)
{
// ignore joining events and also events on myself.
if (updatedSilo.Equals(LocalSilo)) return;
// We deactivate those activations when silo goes either of ShuttingDown/Stopping/Dead states,
// since this is what Directory is doing as well. Directory removes a silo based on all those 3 statuses,
// thus it will only deliver a "remove" notification for a given silo once to us. Therefore, we need to react the fist time we are notified.
// We may review the directory behaiviour in the future and treat ShuttingDown differently ("drain only") and then this code will have to change a well.
if (!status.IsTerminating()) return;
if (status == SiloStatus.Dead)
{
RuntimeClient.Current.BreakOutstandingMessagesToDeadSilo(updatedSilo);
}
var activationsToShutdown = new List<ActivationData>();
try
{
// scan all activations in activation directory and deactivate the ones that the removed silo is their primary partition owner.
lock (activations)
{
foreach (var activation in activations)
{
try
{
var activationData = activation.Value;
if (!activationData.IsUsingGrainDirectory) continue;
if (!directory.GetPrimaryForGrain(activationData.Grain).Equals(updatedSilo)) continue;
lock (activationData)
{
// adapted from InsideGarinClient.DeactivateOnIdle().
activationData.ResetKeepAliveRequest();
activationsToShutdown.Add(activationData);
}
}
catch (Exception exc)
{
logger.Error(ErrorCode.Catalog_SiloStatusChangeNotification_Exception,
String.Format("Catalog has thrown an exception while executing SiloStatusChangeNotification of silo {0}.", updatedSilo.ToStringWithHashCode()), exc);
}
}
}
logger.Info(ErrorCode.Catalog_SiloStatusChangeNotification,
String.Format("Catalog is deactivating {0} activations due to a failure of silo {1}, since it is a primary directory partiton to these grain ids.",
activationsToShutdown.Count, updatedSilo.ToStringWithHashCode()));
}
finally
{
// outside the lock.
if (activationsToShutdown.Count > 0)
{
DeactivateActivations(activationsToShutdown).Ignore();
}
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
#if !NETFX_CORE
using System.IO.IsolatedStorage;
#endif
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace CocosSharp
{
// Class that creates that manages how and when to execute the Scenes.
public class CCDirector
{
#if !NETFX_CORE
const string storageDirName = "CocosSharpDirector";
const string saveFileName = "SceneList.dat";
const string sceneSaveFileName = "Scene{0}.dat";
#endif
readonly List<CCScene> scenesStack = new List<CCScene>();
#region Properties
public bool IsSendCleanupToScene { get; private set; }
public CCScene RunningScene { get; private set; }
internal bool IsPurgeDirectorInNextLoop { get; set; }
internal CCScene NextScene { get; private set; }
public bool CanPopScene
{
get
{
int c = scenesStack.Count;
return (c > 1);
}
}
public int SceneCount
{
get { return scenesStack.Count; }
}
#endregion Properties
#region Constructors
public CCDirector()
{
}
#endregion Constructors
#region Cleaning up
internal void End()
{
IsPurgeDirectorInNextLoop = true;
}
internal void PurgeDirector()
{
if (RunningScene != null)
{
RunningScene.OnExitTransitionDidStart();
RunningScene.OnExit();
RunningScene.Cleanup();
}
RunningScene = null;
NextScene = null;
// remove all objects, but don't release it.
// runWithScene might be executed after 'end'.
scenesStack.Clear();
}
#endregion Cleaning up
#region Scene Management
public void ResetSceneStack()
{
CCLog.Log("CCDirector(): ResetSceneStack, clearing out {0} scenes.", scenesStack.Count);
RunningScene = null;
scenesStack.Clear();
NextScene = null;
}
public void RunWithScene(CCScene scene)
{
Debug.Assert(scene != null, "the scene should not be null");
Debug.Assert(RunningScene == null, "Use runWithScene: instead to start the director");
PushScene(scene);
}
// Replaces the current scene at the top of the stack with the given scene.
public void ReplaceScene(CCScene scene)
{
Debug.Assert(RunningScene != null, "Use runWithScene: instead to start the director");
Debug.Assert(scene != null, "the scene should not be null");
int index = scenesStack.Count;
IsSendCleanupToScene = true;
if (index == 0)
{
scenesStack.Add(scene);
}
else
{
scenesStack[index - 1] = scene;
}
NextScene = scene;
}
// Push the given scene to the top of the scene stack.
public void PushScene(CCScene pScene)
{
Debug.Assert(pScene != null, "the scene should not null");
IsSendCleanupToScene = false;
scenesStack.Add(pScene);
NextScene = pScene;
}
public void PopScene(float t, CCTransitionScene s)
{
Debug.Assert(RunningScene != null, "m_pRunningScene cannot be null");
if (scenesStack.Count > 0)
{
// CCScene s = m_pobScenesStack[m_pobScenesStack.Count - 1];
scenesStack.RemoveAt(scenesStack.Count - 1);
}
int c = scenesStack.Count;
if (c == 0)
{
End(); // This should not happen here b/c we need to capture the current state and just deactivate the game (for Android).
}
else
{
IsSendCleanupToScene = true;
NextScene = scenesStack[c - 1];
if (s != null)
{
NextScene.Visible = true;
s.Reset(t, NextScene);
scenesStack.Add(s);
NextScene = s;
}
}
}
public void PopScene()
{
PopScene(0, null);
}
/** Pops out all scenes from the queue until the root scene in the queue.
* This scene will replace the running one.
* Internally it will call `PopToSceneStackLevel(1)`
*/
public void PopToRootScene()
{
PopToSceneStackLevel(1);
}
/** Pops out all scenes from the queue until it reaches `level`.
* If level is 0, it will end the director.
* If level is 1, it will pop all scenes until it reaches to root scene.
* If level is <= than the current stack level, it won't do anything.
*/
public void PopToSceneStackLevel(int level)
{
Debug.Assert(RunningScene != null, "A running Scene is needed");
int c = scenesStack.Count;
// level 0? -> end
if (level == 0)
{
End();
return;
}
// current level or lower -> nothing
if (level >= c)
return;
// pop stack until reaching desired level
while (c > level)
{
var current = scenesStack[scenesStack.Count - 1];
if (current.IsRunning)
{
current.OnExitTransitionDidStart();
current.OnExit();
}
current.Cleanup();
scenesStack.RemoveAt(scenesStack.Count - 1);
c--;
}
NextScene = scenesStack[scenesStack.Count - 1];
IsSendCleanupToScene = false;
}
internal void SetNextScene()
{
bool runningIsTransition = RunningScene != null && RunningScene.IsTransition;// is CCTransitionScene;
// If it is not a transition, call onExit/cleanup
if (!NextScene.IsTransition)
{
if (RunningScene != null)
{
RunningScene.OnExitTransitionDidStart();
RunningScene.OnExit();
// issue #709. the root node (scene) should receive the cleanup message too
// otherwise it might be leaked.
if (IsSendCleanupToScene)
{
RunningScene.Cleanup();
}
}
}
if (NextScene.Director != this)
{
NextScene.Director = this;
}
if (RunningScene != null && NextScene.Window != RunningScene.Window)
{
NextScene.Window = RunningScene.Window;
}
RunningScene = NextScene;
NextScene = null;
if (!runningIsTransition && RunningScene != null)
{
RunningScene.OnEnter();
RunningScene.OnEnterTransitionDidFinish();
}
}
#endregion Scene management
#region State Management
#if !NETFX_CORE
// Write out the current state of the director and all of its scenes.
public void SerializeState()
{
// open up isolated storage
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
// if our screen manager directory already exists, delete the contents
if (storage.DirectoryExists(storageDirName))
{
DeleteState(storage);
}
// otherwise just create the directory
else
{
storage.CreateDirectory(storageDirName);
}
// create a file we'll use to store the list of screens in the stack
CCLog.Log("Saving CCDirector state to file: " + Path.Combine(storageDirName, saveFileName));
try
{
using (IsolatedStorageFileStream stream = storage.OpenFile(Path.Combine(storageDirName, saveFileName), FileMode.OpenOrCreate))
{
using (StreamWriter writer = new StreamWriter(stream))
{
// write out the full name of all the types in our stack so we can
// recreate them if needed.
foreach (CCScene scene in scenesStack)
{
if (scene.IsSerializable)
{
writer.WriteLine(scene.GetType().AssemblyQualifiedName);
}
else
{
CCLog.Log("Scene is not serializable: " + scene.GetType().FullName);
}
}
// Write out our local state
if (RunningScene != null && RunningScene.IsSerializable)
{
writer.WriteLine("m_pRunningScene");
writer.WriteLine(RunningScene.GetType().AssemblyQualifiedName);
}
// Add my own state
// [*]name=value
//
}
}
// now we create a new file stream for each screen so it can save its state
// if it needs to. we name each file "ScreenX.dat" where X is the index of
// the screen in the stack, to ensure the files are uniquely named
int screenIndex = 0;
string fileName = null;
foreach (CCScene scene in scenesStack)
{
if (scene.IsSerializable)
{
fileName = string.Format(Path.Combine(storageDirName, sceneSaveFileName), screenIndex);
// open up the stream and let the screen serialize whatever state it wants
using (IsolatedStorageFileStream stream = storage.CreateFile(fileName))
{
scene.Serialize(stream);
}
screenIndex++;
}
}
// Write the current running scene
if (RunningScene != null && RunningScene.IsSerializable)
{
fileName = string.Format(Path.Combine(storageDirName, sceneSaveFileName), "XX");
// open up the stream and let the screen serialize whatever state it wants
using (IsolatedStorageFileStream stream = storage.CreateFile(fileName))
{
RunningScene.Serialize(stream);
}
}
}
catch (Exception ex)
{
CCLog.Log("Failed to serialize the CCDirector state. Erasing the save files.");
CCLog.Log(ex.ToString());
DeleteState(storage);
}
}
}
void DeserializeMyState(string name, string v)
{
// TODO
}
public bool DeserializeState()
{
try
{
// open up isolated storage
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
// see if our saved state directory exists
if (storage.DirectoryExists(storageDirName))
{
string saveFile = System.IO.Path.Combine(storageDirName, saveFileName);
try
{
CCLog.Log("Loading director data file: {0}", saveFile);
// see if we have a screen list
if (storage.FileExists(saveFile))
{
// load the list of screen types
using (IsolatedStorageFileStream stream = storage.OpenFile(saveFile, FileMode.Open, FileAccess.Read))
{
using (StreamReader reader = new StreamReader(stream))
{
CCLog.Log("Director save file contains {0} bytes.", reader.BaseStream.Length);
try
{
while (true)
{
// read a line from our file
string line = reader.ReadLine();
if (line == null)
{
break;
}
CCLog.Log("Restoring: {0}", line);
// if it isn't blank, we can create a screen from it
if (!string.IsNullOrEmpty(line))
{
if (line.StartsWith("[*]"))
{
// Reading my state
string s = line.Substring(3);
int idx = s.IndexOf('=');
if (idx > -1)
{
string name = s.Substring(0, idx);
string v = s.Substring(idx + 1);
CCLog.Log("Restoring: {0} = {1}", name, v);
DeserializeMyState(name, v);
}
}
else
{
Type screenType = Type.GetType(line);
CCScene scene = Activator.CreateInstance(screenType) as CCScene;
PushScene(scene);
// m_pobScenesStack.Add(scene);
}
}
}
}
catch (Exception)
{
// EndOfStreamException
// this is OK here.
}
}
}
// Now we deserialize our own state.
}
else
{
CCLog.Log("save file does not exist.");
}
// next we give each screen a chance to deserialize from the disk
for (int i = 0; i < scenesStack.Count; i++)
{
string filename = System.IO.Path.Combine(storageDirName, string.Format(sceneSaveFileName, i));
if (storage.FileExists(filename))
{
using (IsolatedStorageFileStream stream = storage.OpenFile(filename, FileMode.Open, FileAccess.Read))
{
CCLog.Log("Restoring state for scene {0}", filename);
scenesStack[i].Deserialize(stream);
}
}
}
if (scenesStack.Count > 0)
{
CCLog.Log("Director is running with scene..");
RunWithScene(scenesStack[scenesStack.Count - 1]); // always at the top of the stack
}
return (scenesStack.Count > 0 && RunningScene != null);
}
catch (Exception ex)
{
// if an exception was thrown while reading, odds are we cannot recover
// from the saved state, so we will delete it so the game can correctly
// launch.
DeleteState(storage);
CCLog.Log("Failed to deserialize the director state, removing old storage file.");
CCLog.Log(ex.ToString());
}
}
}
}
catch (Exception ex)
{
CCLog.Log("Failed to deserialize director state.");
CCLog.Log(ex.ToString());
}
return false;
}
// Deletes the saved state files from isolated storage.
void DeleteState(IsolatedStorageFile storage)
{
// glob on all of the files in the directory and delete them
string[] files = storage.GetFileNames(System.IO.Path.Combine(storageDirName, "*"));
foreach (string file in files)
{
storage.DeleteFile(Path.Combine(storageDirName, file));
}
}
#endif
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace DotNetty.Buffers
{
using System;
using System.Diagnostics.Contracts;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using DotNetty.Common;
using DotNetty.Common.Utilities;
/// <summary>
/// Abstract base class implementation of a <see cref="IByteBuffer"/>
/// </summary>
public abstract class AbstractByteBuffer : IByteBuffer
{
int markedReaderIndex;
int markedWriterIndex;
protected AbstractByteBuffer(int maxCapacity)
{
this.MaxCapacity = maxCapacity;
}
public abstract int Capacity { get; }
public abstract IByteBuffer AdjustCapacity(int newCapacity);
public int MaxCapacity { get; protected set; }
public abstract IByteBufferAllocator Allocator { get; }
public virtual int ReaderIndex { get; protected set; }
public virtual int WriterIndex { get; protected set; }
public virtual IByteBuffer SetWriterIndex(int writerIndex)
{
if (writerIndex < this.ReaderIndex || writerIndex > this.Capacity)
{
throw new IndexOutOfRangeException(string.Format("WriterIndex: {0} (expected: 0 <= readerIndex({1}) <= writerIndex <= capacity ({2})", writerIndex, this.ReaderIndex, this.Capacity));
}
this.WriterIndex = writerIndex;
return this;
}
public virtual IByteBuffer SetReaderIndex(int readerIndex)
{
if (readerIndex < 0 || readerIndex > this.WriterIndex)
{
throw new IndexOutOfRangeException(string.Format("ReaderIndex: {0} (expected: 0 <= readerIndex <= writerIndex({1})", readerIndex, this.WriterIndex));
}
this.ReaderIndex = readerIndex;
return this;
}
public virtual IByteBuffer SetIndex(int readerIndex, int writerIndex)
{
if (readerIndex < 0 || readerIndex > writerIndex || writerIndex > this.Capacity)
{
throw new IndexOutOfRangeException(string.Format("ReaderIndex: {0}, WriterIndex: {1} (expected: 0 <= readerIndex <= writerIndex <= capacity ({2})", readerIndex, writerIndex, this.Capacity));
}
this.ReaderIndex = readerIndex;
this.WriterIndex = writerIndex;
return this;
}
public virtual int ReadableBytes
{
get { return this.WriterIndex - this.ReaderIndex; }
}
public virtual int WritableBytes
{
get { return this.Capacity - this.WriterIndex; }
}
public virtual int MaxWritableBytes
{
get { return this.MaxCapacity - this.WriterIndex; }
}
public bool IsReadable()
{
return this.IsReadable(1);
}
public bool IsReadable(int size)
{
return this.ReadableBytes >= size;
}
public bool IsWritable()
{
return this.IsWritable(1);
}
public bool IsWritable(int size)
{
return this.WritableBytes >= size;
}
public virtual IByteBuffer Clear()
{
this.ReaderIndex = this.WriterIndex = 0;
return this;
}
public virtual IByteBuffer MarkReaderIndex()
{
this.markedReaderIndex = this.ReaderIndex;
return this;
}
public virtual IByteBuffer ResetReaderIndex()
{
this.SetReaderIndex(this.markedReaderIndex);
return this;
}
public virtual IByteBuffer MarkWriterIndex()
{
this.markedWriterIndex = this.WriterIndex;
return this;
}
public virtual IByteBuffer ResetWriterIndex()
{
this.SetWriterIndex(this.markedWriterIndex);
return this;
}
public virtual IByteBuffer DiscardReadBytes()
{
this.EnsureAccessible();
if (this.ReaderIndex == 0)
{
return this;
}
if (this.ReaderIndex != this.WriterIndex)
{
this.SetBytes(0, this, this.ReaderIndex, this.WriterIndex - this.ReaderIndex);
this.WriterIndex -= this.ReaderIndex;
this.AdjustMarkers(this.ReaderIndex);
this.ReaderIndex = 0;
}
else
{
this.AdjustMarkers(this.ReaderIndex);
this.WriterIndex = this.ReaderIndex = 0;
}
return this;
}
public virtual IByteBuffer EnsureWritable(int minWritableBytes)
{
if (minWritableBytes < 0)
{
throw new ArgumentOutOfRangeException("minWritableBytes",
"expected minWritableBytes to be greater than zero");
}
if (minWritableBytes <= this.WritableBytes)
{
return this;
}
if (minWritableBytes > this.MaxCapacity - this.WriterIndex)
{
throw new IndexOutOfRangeException(string.Format(
"writerIndex({0}) + minWritableBytes({1}) exceeds maxCapacity({2}): {3}",
this.WriterIndex, minWritableBytes, this.MaxCapacity, this));
}
//Normalize the current capacity to the power of 2
int newCapacity = this.CalculateNewCapacity(this.WriterIndex + minWritableBytes);
//Adjust to the new capacity
this.AdjustCapacity(newCapacity);
return this;
}
int CalculateNewCapacity(int minNewCapacity)
{
int maxCapacity = this.MaxCapacity;
const int Threshold = 4 * 1024 * 1024; // 4 MiB page
int newCapacity;
if (minNewCapacity == Threshold)
{
return Threshold;
}
// If over threshold, do not double but just increase by threshold.
if (minNewCapacity > Threshold)
{
newCapacity = minNewCapacity - (minNewCapacity % Threshold);
return Math.Min(maxCapacity, newCapacity + Threshold);
}
// Not over threshold. Double up to 4 MiB, starting from 64.
newCapacity = 64;
while (newCapacity < minNewCapacity)
{
newCapacity <<= 1;
}
return Math.Min(newCapacity, maxCapacity);
}
public virtual bool GetBoolean(int index)
{
return this.GetByte(index) != 0;
}
public virtual byte GetByte(int index)
{
this.CheckIndex(index);
return this._GetByte(index);
}
protected abstract byte _GetByte(int index);
public virtual short GetShort(int index)
{
this.CheckIndex(index, 2);
return this._GetShort(index);
}
protected abstract short _GetShort(int index);
public virtual ushort GetUnsignedShort(int index)
{
unchecked
{
return (ushort)(this.GetShort(index));
}
}
public virtual int GetInt(int index)
{
this.CheckIndex(index, 4);
return this._GetInt(index);
}
protected abstract int _GetInt(int index);
public virtual uint GetUnsignedInt(int index)
{
unchecked
{
return (uint)(this.GetInt(index));
}
}
public virtual long GetLong(int index)
{
this.CheckIndex(index, 8);
return this._GetLong(index);
}
protected abstract long _GetLong(int index);
public virtual char GetChar(int index)
{
return Convert.ToChar(this.GetShort(index));
}
public virtual double GetDouble(int index)
{
return BitConverter.Int64BitsToDouble(this.GetLong(index));
}
public virtual IByteBuffer GetBytes(int index, IByteBuffer destination)
{
this.GetBytes(index, destination, destination.WritableBytes);
return this;
}
public virtual IByteBuffer GetBytes(int index, IByteBuffer destination, int length)
{
this.GetBytes(index, destination, destination.WriterIndex, length);
return this;
}
public abstract IByteBuffer GetBytes(int index, IByteBuffer destination, int dstIndex, int length);
public virtual IByteBuffer GetBytes(int index, byte[] destination)
{
this.GetBytes(index, destination, 0, destination.Length);
return this;
}
public abstract IByteBuffer GetBytes(int index, byte[] destination, int dstIndex, int length);
public abstract IByteBuffer GetBytes(int index, Stream destination, int length);
public virtual IByteBuffer SetBoolean(int index, bool value)
{
this.SetByte(index, value ? 1 : 0);
return this;
}
public virtual IByteBuffer SetByte(int index, int value)
{
this.CheckIndex(index);
this._SetByte(index, value);
return this;
}
protected abstract void _SetByte(int index, int value);
public virtual IByteBuffer SetShort(int index, int value)
{
this.CheckIndex(index, 2);
this._SetShort(index, value);
return this;
}
public IByteBuffer SetUnsignedShort(int index, int value)
{
this.SetShort(index, value);
return this;
}
protected abstract void _SetShort(int index, int value);
public virtual IByteBuffer SetInt(int index, int value)
{
this.CheckIndex(index, 4);
this._SetInt(index, value);
return this;
}
public IByteBuffer SetUnsignedInt(int index, uint value)
{
unchecked
{
this.SetInt(index, (int)value);
}
return this;
}
protected abstract void _SetInt(int index, int value);
public virtual IByteBuffer SetLong(int index, long value)
{
this.CheckIndex(index, 8);
this._SetLong(index, value);
return this;
}
protected abstract void _SetLong(int index, long value);
public virtual IByteBuffer SetChar(int index, char value)
{
this.SetShort(index, value);
return this;
}
public virtual IByteBuffer SetDouble(int index, double value)
{
this.SetLong(index, BitConverter.DoubleToInt64Bits(value));
return this;
}
public virtual IByteBuffer SetBytes(int index, IByteBuffer src)
{
this.SetBytes(index, src, src.ReadableBytes);
return this;
}
public virtual IByteBuffer SetBytes(int index, IByteBuffer src, int length)
{
this.CheckIndex(index, length);
if (src == null)
{
throw new NullReferenceException("src cannot be null");
}
if (length > src.ReadableBytes)
{
throw new IndexOutOfRangeException(string.Format(
"length({0}) exceeds src.readableBytes({1}) where src is: {2}", length, src.ReadableBytes, src));
}
this.SetBytes(index, src, src.ReaderIndex, length);
src.SetReaderIndex(src.ReaderIndex + length);
return this;
}
public abstract IByteBuffer SetBytes(int index, IByteBuffer src, int srcIndex, int length);
public virtual IByteBuffer SetBytes(int index, byte[] src)
{
this.SetBytes(index, src, 0, src.Length);
return this;
}
public abstract IByteBuffer SetBytes(int index, byte[] src, int srcIndex, int length);
public abstract Task<int> SetBytesAsync(int index, Stream src, int length, CancellationToken cancellationToken);
public virtual bool ReadBoolean()
{
return this.ReadByte() != 0;
}
public virtual byte ReadByte()
{
this.CheckReadableBytes(1);
int i = this.ReaderIndex;
byte b = this.GetByte(i);
this.ReaderIndex = i + 1;
return b;
}
public virtual short ReadShort()
{
this.CheckReadableBytes(2);
short v = this._GetShort(this.ReaderIndex);
this.ReaderIndex += 2;
return v;
}
public virtual ushort ReadUnsignedShort()
{
unchecked
{
return (ushort)(this.ReadShort());
}
}
public virtual int ReadInt()
{
this.CheckReadableBytes(4);
int v = this._GetInt(this.ReaderIndex);
this.ReaderIndex += 4;
return v;
}
public virtual uint ReadUnsignedInt()
{
unchecked
{
return (uint)(this.ReadInt());
}
}
public virtual long ReadLong()
{
this.CheckReadableBytes(8);
long v = this._GetLong(this.ReaderIndex);
this.ReaderIndex += 8;
return v;
}
public virtual char ReadChar()
{
return (char)this.ReadShort();
}
public virtual double ReadDouble()
{
return BitConverter.Int64BitsToDouble(this.ReadLong());
}
public IByteBuffer ReadBytes(int length)
{
this.CheckReadableBytes(length);
if (length == 0)
{
return Unpooled.Empty;
}
IByteBuffer buf = Unpooled.Buffer(length, this.MaxCapacity);
buf.WriteBytes(this, this.ReaderIndex, length);
this.ReaderIndex += length;
return buf;
}
public virtual IByteBuffer ReadBytes(IByteBuffer destination)
{
this.ReadBytes(destination, destination.WritableBytes);
return this;
}
public virtual IByteBuffer ReadBytes(IByteBuffer destination, int length)
{
if (length > destination.WritableBytes)
{
throw new IndexOutOfRangeException(string.Format("length({0}) exceeds destination.WritableBytes({1}) where destination is: {2}",
length, destination.WritableBytes, destination));
}
this.ReadBytes(destination, destination.WriterIndex, length);
destination.SetWriterIndex(destination.WriterIndex + length);
return this;
}
public virtual IByteBuffer ReadBytes(IByteBuffer destination, int dstIndex, int length)
{
this.CheckReadableBytes(length);
this.GetBytes(this.ReaderIndex, destination, dstIndex, length);
this.ReaderIndex += length;
return this;
}
public virtual IByteBuffer ReadBytes(byte[] destination)
{
this.ReadBytes(destination, 0, destination.Length);
return this;
}
public virtual IByteBuffer ReadBytes(byte[] destination, int dstIndex, int length)
{
this.CheckReadableBytes(length);
this.GetBytes(this.ReaderIndex, destination, dstIndex, length);
this.ReaderIndex += length;
return this;
}
public virtual IByteBuffer ReadBytes(Stream destination, int length)
{
this.CheckReadableBytes(length);
this.GetBytes(this.ReaderIndex, destination, length);
this.ReaderIndex += length;
return this;
}
public virtual IByteBuffer SkipBytes(int length)
{
this.CheckReadableBytes(length);
this.ReaderIndex += length;
return this;
}
public virtual IByteBuffer WriteBoolean(bool value)
{
this.WriteByte(value ? 1 : 0);
return this;
}
public virtual IByteBuffer WriteByte(int value)
{
this.EnsureWritable(1);
this.SetByte(this.WriterIndex, value);
this.WriterIndex += 1;
return this;
}
public virtual IByteBuffer WriteShort(int value)
{
this.EnsureWritable(2);
this._SetShort(this.WriterIndex, value);
this.WriterIndex += 2;
return this;
}
public IByteBuffer WriteUnsignedShort(int value)
{
unchecked
{
this.WriteShort((short)value);
}
return this;
}
public virtual IByteBuffer WriteInt(int value)
{
this.EnsureWritable(4);
this._SetInt(this.WriterIndex, value);
this.WriterIndex += 4;
return this;
}
public IByteBuffer WriteUnsignedInt(uint value)
{
unchecked
{
this.WriteInt((int)value);
}
return this;
}
public virtual IByteBuffer WriteLong(long value)
{
this.EnsureWritable(8);
this._SetLong(this.WriterIndex, value);
this.WriterIndex += 8;
return this;
}
public virtual IByteBuffer WriteChar(char value)
{
this.WriteShort(value);
return this;
}
public virtual IByteBuffer WriteDouble(double value)
{
this.WriteLong(BitConverter.DoubleToInt64Bits(value));
return this;
}
public virtual IByteBuffer WriteBytes(IByteBuffer src)
{
this.WriteBytes(src, src.ReadableBytes);
return this;
}
public virtual IByteBuffer WriteBytes(IByteBuffer src, int length)
{
if (length > src.ReadableBytes)
{
throw new IndexOutOfRangeException(string.Format("length({0}) exceeds src.readableBytes({1}) where src is: {2}", length, src.ReadableBytes, src));
}
this.WriteBytes(src, src.ReaderIndex, length);
src.SetReaderIndex(src.ReaderIndex + length);
return this;
}
public virtual IByteBuffer WriteBytes(IByteBuffer src, int srcIndex, int length)
{
this.EnsureAccessible();
this.EnsureWritable(length);
this.SetBytes(this.WriterIndex, src, srcIndex, length);
this.WriterIndex += length;
return this;
}
public virtual IByteBuffer WriteBytes(byte[] src)
{
this.WriteBytes(src, 0, src.Length);
return this;
}
public virtual IByteBuffer WriteBytes(byte[] src, int srcIndex, int length)
{
this.EnsureAccessible();
this.EnsureWritable(length);
this.SetBytes(this.WriterIndex, src, srcIndex, length);
this.WriterIndex += length;
return this;
}
public async Task WriteBytesAsync(Stream stream, int length, CancellationToken cancellationToken)
{
this.EnsureAccessible();
this.EnsureWritable(length);
if (this.WritableBytes < length)
{
throw new ArgumentOutOfRangeException("length");
}
int writerIndex = this.WriterIndex;
int wrote = await this.SetBytesAsync(writerIndex, stream, length, cancellationToken);
Contract.Assert(writerIndex == this.WriterIndex);
this.SetWriterIndex(writerIndex + wrote);
}
public Task WriteBytesAsync(Stream stream, int length)
{
return this.WriteBytesAsync(stream, length, CancellationToken.None);
}
public abstract bool HasArray { get; }
public abstract byte[] Array { get; }
public abstract int ArrayOffset { get; }
public virtual byte[] ToArray()
{
int readableBytes = this.ReadableBytes;
if (readableBytes == 0)
{
return ByteArrayExtensions.Empty;
}
if (this.HasArray)
{
return this.Array.Slice(this.ArrayOffset + this.ReaderIndex, readableBytes);
}
var bytes = new byte[readableBytes];
this.GetBytes(this.ReaderIndex, bytes);
return bytes;
}
public virtual IByteBuffer Duplicate()
{
return new DuplicatedByteBuffer(this);
}
public abstract IByteBuffer Unwrap();
public virtual ByteOrder Order // todo: push to actual implementations for them to decide
{
get { return ByteOrder.BigEndian; }
}
public IByteBuffer WithOrder(ByteOrder order)
{
if (order == this.Order)
{
return this;
}
throw new NotImplementedException("TODO: bring over SwappedByteBuf");
}
protected void AdjustMarkers(int decrement)
{
int markedReaderIndex = this.markedReaderIndex;
if (markedReaderIndex <= decrement)
{
this.markedReaderIndex = 0;
int markedWriterIndex = this.markedWriterIndex;
if (markedWriterIndex <= decrement)
{
this.markedWriterIndex = 0;
}
else
{
this.markedWriterIndex = markedWriterIndex - decrement;
}
}
else
{
this.markedReaderIndex = markedReaderIndex - decrement;
this.markedWriterIndex -= decrement;
}
}
protected void CheckIndex(int index)
{
this.EnsureAccessible();
if (index < 0 || index >= this.Capacity)
{
throw new IndexOutOfRangeException(string.Format("index: {0} (expected: range(0, {1})", index, this.Capacity));
}
}
protected void CheckIndex(int index, int fieldLength)
{
this.EnsureAccessible();
if (fieldLength < 0)
{
throw new IndexOutOfRangeException(string.Format("length: {0} (expected: >= 0)", fieldLength));
}
if (index < 0 || index > this.Capacity - fieldLength)
{
throw new IndexOutOfRangeException(string.Format("index: {0}, length: {1} (expected: range(0, {2})", index, fieldLength, this.Capacity));
}
}
protected void CheckSrcIndex(int index, int length, int srcIndex, int srcCapacity)
{
this.CheckIndex(index, length);
if (srcIndex < 0 || srcIndex > srcCapacity - length)
{
throw new IndexOutOfRangeException(string.Format(
"srcIndex: {0}, length: {1} (expected: range(0, {2}))", srcIndex, length, srcCapacity));
}
}
protected void CheckDstIndex(int index, int length, int dstIndex, int dstCapacity)
{
this.CheckIndex(index, length);
if (dstIndex < 0 || dstIndex > dstCapacity - length)
{
throw new IndexOutOfRangeException(string.Format(
"dstIndex: {0}, length: {1} (expected: range(0, {2}))", dstIndex, length, dstCapacity));
}
}
/// <summary>
/// Throws a <see cref="IndexOutOfRangeException"/> if the current <see cref="ReadableBytes"/> of this buffer
/// is less than <see cref="minimumReadableBytes"/>.
/// </summary>
protected void CheckReadableBytes(int minimumReadableBytes)
{
this.EnsureAccessible();
if (minimumReadableBytes < 0)
{
throw new ArgumentOutOfRangeException("minimumReadableBytes", string.Format("minimumReadableBytes: {0} (expected: >= 0)", minimumReadableBytes));
}
if (this.ReaderIndex > this.WriterIndex - minimumReadableBytes)
{
throw new IndexOutOfRangeException(string.Format(
"readerIndex({0}) + length({1}) exceeds writerIndex({2}): {3}",
this.ReaderIndex, minimumReadableBytes, this.WriterIndex, this));
}
}
protected void EnsureAccessible()
{
if (this.ReferenceCount == 0)
{
throw new IllegalReferenceCountException(0);
}
}
public IByteBuffer Copy()
{
return this.Copy(this.ReaderIndex, this.ReadableBytes);
}
public abstract IByteBuffer Copy(int index, int length);
public IByteBuffer Slice()
{
return this.Slice(this.ReaderIndex, this.ReadableBytes);
}
public virtual IByteBuffer Slice(int index, int length)
{
return new SlicedByteBuffer(this, index, length);
}
public IByteBuffer ReadSlice(int length)
{
IByteBuffer slice = this.Slice(this.ReaderIndex, length);
this.ReaderIndex += length;
return slice;
}
public abstract int ReferenceCount { get; }
public abstract IReferenceCounted Retain();
public abstract IReferenceCounted Retain(int increment);
public abstract bool Release();
public abstract bool Release(int decrement);
protected void DiscardMarkers()
{
this.markedReaderIndex = this.markedWriterIndex = 0;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsBodyInteger
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Models;
/// <summary>
/// Extension methods for IntModel.
/// </summary>
public static partial class IntModelExtensions
{
/// <summary>
/// Get null Int value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static int? GetNull(this IIntModel operations)
{
return Task.Factory.StartNew(s => ((IIntModel)s).GetNullAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get null Int value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<int?> GetNullAsync(this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetNullWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get invalid Int value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static int? GetInvalid(this IIntModel operations)
{
return Task.Factory.StartNew(s => ((IIntModel)s).GetInvalidAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get invalid Int value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<int?> GetInvalidAsync(this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetInvalidWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get overflow Int32 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static int? GetOverflowInt32(this IIntModel operations)
{
return Task.Factory.StartNew(s => ((IIntModel)s).GetOverflowInt32Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get overflow Int32 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<int?> GetOverflowInt32Async(this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetOverflowInt32WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get underflow Int32 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static int? GetUnderflowInt32(this IIntModel operations)
{
return Task.Factory.StartNew(s => ((IIntModel)s).GetUnderflowInt32Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get underflow Int32 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<int?> GetUnderflowInt32Async(this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetUnderflowInt32WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get overflow Int64 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static long? GetOverflowInt64(this IIntModel operations)
{
return Task.Factory.StartNew(s => ((IIntModel)s).GetOverflowInt64Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get overflow Int64 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<long?> GetOverflowInt64Async(this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetOverflowInt64WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get underflow Int64 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static long? GetUnderflowInt64(this IIntModel operations)
{
return Task.Factory.StartNew(s => ((IIntModel)s).GetUnderflowInt64Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get underflow Int64 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<long?> GetUnderflowInt64Async(this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetUnderflowInt64WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put max int32 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='intBody'>
/// </param>
public static void PutMax32(this IIntModel operations, int intBody)
{
Task.Factory.StartNew(s => ((IIntModel)s).PutMax32Async(intBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put max int32 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='intBody'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutMax32Async(this IIntModel operations, int intBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutMax32WithHttpMessagesAsync(intBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Put max int64 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='intBody'>
/// </param>
public static void PutMax64(this IIntModel operations, long intBody)
{
Task.Factory.StartNew(s => ((IIntModel)s).PutMax64Async(intBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put max int64 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='intBody'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutMax64Async(this IIntModel operations, long intBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutMax64WithHttpMessagesAsync(intBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Put min int32 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='intBody'>
/// </param>
public static void PutMin32(this IIntModel operations, int intBody)
{
Task.Factory.StartNew(s => ((IIntModel)s).PutMin32Async(intBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put min int32 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='intBody'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutMin32Async(this IIntModel operations, int intBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutMin32WithHttpMessagesAsync(intBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Put min int64 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='intBody'>
/// </param>
public static void PutMin64(this IIntModel operations, long intBody)
{
Task.Factory.StartNew(s => ((IIntModel)s).PutMin64Async(intBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put min int64 value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='intBody'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutMin64Async(this IIntModel operations, long intBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutMin64WithHttpMessagesAsync(intBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get datetime encoded as Unix time value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static DateTime? GetUnixTime(this IIntModel operations)
{
return Task.Factory.StartNew(s => ((IIntModel)s).GetUnixTimeAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get datetime encoded as Unix time value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DateTime?> GetUnixTimeAsync(this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetUnixTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put datetime encoded as Unix time
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='intBody'>
/// </param>
public static void PutUnixTimeDate(this IIntModel operations, DateTime intBody)
{
Task.Factory.StartNew(s => ((IIntModel)s).PutUnixTimeDateAsync(intBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put datetime encoded as Unix time
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='intBody'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutUnixTimeDateAsync(this IIntModel operations, DateTime intBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutUnixTimeDateWithHttpMessagesAsync(intBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get invalid Unix time value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static DateTime? GetInvalidUnixTime(this IIntModel operations)
{
return Task.Factory.StartNew(s => ((IIntModel)s).GetInvalidUnixTimeAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get invalid Unix time value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DateTime?> GetInvalidUnixTimeAsync(this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetInvalidUnixTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get null Unix time value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static DateTime? GetNullUnixTime(this IIntModel operations)
{
return Task.Factory.StartNew(s => ((IIntModel)s).GetNullUnixTimeAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get null Unix time value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DateTime?> GetNullUnixTimeAsync(this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetNullUnixTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
#region Header
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Copyright (c) 2007-2008 James Nies and NArrange contributors.
* All rights reserved.
*
* This program and the accompanying materials are made available under
* the terms of the Common Public License v1.0 which accompanies this
* distribution.
*
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*<author>James Nies</author>
*<contributor>Justin Dearing</contributor>
*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
#endregion Header
namespace NArrange.Core
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using NArrange.Core.CodeElements;
using NArrange.Core.Configuration;
/// <summary>
/// Provides project/file retrieval and storage functionality.
/// </summary>
public class ProjectManager
{
#region Fields
/// <summary>
/// Code configuration.
/// </summary>
private readonly CodeConfiguration _configuration;
/// <summary>
/// Project extension handler dictionary.
/// </summary>
private Dictionary<string, ProjectHandler> _projectExtensionHandlers;
/// <summary>
/// Source file extension handler dictionary.
/// </summary>
private Dictionary<string, SourceHandler> _sourceExtensionHandlers;
#endregion Fields
#region Constructors
/// <summary>
/// Creates a new FileManager.
/// </summary>
/// <param name="configuration">The configuration.</param>
public ProjectManager(CodeConfiguration configuration)
{
if (configuration == null)
{
throw new ArgumentNullException("configuration");
}
_configuration = configuration;
Initialize();
}
#endregion Constructors
#region Methods
/// <summary>
/// Gets the file extension.
/// </summary>
/// <param name="inputFile">The input file.</param>
/// <returns>The file extension.</returns>
public static string GetExtension(string inputFile)
{
return Path.GetExtension(inputFile).TrimStart('.');
}
/// <summary>
/// Determines whether or not the specified file is a solution.
/// </summary>
/// <param name="inputFile">The input file.</param>
/// <returns>
/// <c>true</c> if the specified input file is solution; otherwise, <c>false</c>.
/// </returns>
public static bool IsSolution(string inputFile)
{
return SolutionParser.Instance.IsSolution(inputFile);
}
/// <summary>
/// Determines whether or not the specified file can be parsed.
/// </summary>
/// <param name="inputFile">The input file.</param>
/// <returns>
/// <c>true</c> if this instance can parse the specified input file; otherwise, <c>false</c>.
/// </returns>
public bool CanParse(string inputFile)
{
return GetSourceHandler(inputFile) != null;
}
/// <summary>
/// Gets all parse-able source files that are children of the specified
/// solution or project. If an individual source file is provided, the
/// same file name is returned.
/// </summary>
/// <param name="fileName">Name of the file.</param>
/// <returns>The list of source files.</returns>
public ReadOnlyCollection<string> GetSourceFiles(string fileName)
{
List<string> sourceFiles = new List<string>();
if (IsSolution(fileName))
{
sourceFiles.AddRange(GetSolutionSourceFiles(fileName));
}
else if (IsProject(fileName))
{
sourceFiles.AddRange(GetProjectSourceFiles(fileName));
}
else if (IsRecognizedSourceFile(fileName))
{
sourceFiles.Add(fileName);
}
else if (Directory.Exists(fileName))
{
sourceFiles.AddRange(GetDirectorySourceFiles(fileName));
}
return sourceFiles.AsReadOnly();
}
/// <summary>
/// Retrieves an extension handler.
/// </summary>
/// <param name="fileName">Name of the file.</param>
/// <returns>Source handler.</returns>
public SourceHandler GetSourceHandler(string fileName)
{
string extension = GetExtension(fileName);
SourceHandler handler = null;
_sourceExtensionHandlers.TryGetValue(extension, out handler);
return handler;
}
/// <summary>
/// Determines whether or not the specified file is a project.
/// </summary>
/// <param name="inputFile">Input file.</param>
/// <returns>Whether or not the file is a recognized project file.</returns>
public bool IsProject(string inputFile)
{
return _projectExtensionHandlers.ContainsKey(GetExtension(inputFile));
}
/// <summary>
/// Parses code elements from the input file.
/// </summary>
/// <param name="inputFile">The input file.</param>
/// <param name="text">The text of the input file.</param>
/// <returns>Collection of parsed code elements.</returns>
public ReadOnlyCollection<ICodeElement> ParseElements(string inputFile, string text)
{
ReadOnlyCollection<ICodeElement> elements = null;
SourceHandler sourceHandler = GetSourceHandler(inputFile);
if (sourceHandler != null)
{
ICodeElementParser parser = sourceHandler.CodeParser;
if (parser != null)
{
parser.Configuration = _configuration;
using (StringReader reader = new StringReader(text))
{
elements = parser.Parse(reader);
}
}
}
return elements;
}
/// <summary>
/// Gets a boolean indicating whether or not the file is a
/// recognized source file.
/// </summary>
/// <param name="fileName">File to test.</param>
/// <param name="extensions">Extension configurations.</param>
/// <returns>A boolean indicating whehther or not the file is recognized.</returns>
private static bool IsRecognizedFile(string fileName, ExtensionConfigurationCollection extensions)
{
bool isRecognizedFile = true;
string extension = GetExtension(fileName);
ExtensionConfiguration extensionConfiguration = null;
foreach (ExtensionConfiguration extensionEntry in extensions)
{
if (extensionEntry.Name == extension)
{
extensionConfiguration = extensionEntry;
break;
}
}
if (extensionConfiguration != null && extensionConfiguration.FilterBy != null)
{
FilterBy filterBy = extensionConfiguration.FilterBy;
FileFilter fileFilter = new FileFilter(filterBy.Condition);
if (File.Exists(fileName))
{
isRecognizedFile = fileFilter.IsMatch(new FileInfo(fileName));
}
}
return isRecognizedFile;
}
/// <summary>
/// Gets all source file for a directory.
/// </summary>
/// <param name="directory">Directory to process.</param>
/// <returns>Collection of source files in the directory.</returns>
private ReadOnlyCollection<string> GetDirectorySourceFiles(string directory)
{
List<string> sourceFiles = new List<string>();
DirectoryInfo directoryInfo = new DirectoryInfo(directory);
FileInfo[] files = directoryInfo.GetFiles("*.*", SearchOption.AllDirectories);
foreach (FileInfo file in files)
{
if (IsRecognizedSourceFile(file.FullName))
{
sourceFiles.Add(file.FullName);
}
}
return sourceFiles.AsReadOnly();
}
/// <summary>
/// Retrieves an extension handler for a project file.
/// </summary>
/// <param name="fileName">File name.</param>
/// <returns>Project handler for the file if available, otherwise null.</returns>
private ProjectHandler GetProjectHandler(string fileName)
{
string extension = GetExtension(fileName);
ProjectHandler projectHandler = null;
_projectExtensionHandlers.TryGetValue(extension, out projectHandler);
return projectHandler;
}
/// <summary>
/// Gets all source files associated with a project.
/// </summary>
/// <param name="fileName">Project file name.</param>
/// <returns>A collection of source files associated with the project.</returns>
private ReadOnlyCollection<string> GetProjectSourceFiles(string fileName)
{
List<string> sourceFiles = new List<string>();
ProjectHandler handler = GetProjectHandler(fileName);
if (handler != null)
{
bool isRecognizedProject = IsRecognizedFile(fileName, handler.Configuration.ProjectExtensions);
if (isRecognizedProject)
{
IProjectParser projectParser = handler.ProjectParser;
ReadOnlyCollection<string> fileNames = projectParser.Parse(fileName);
foreach (string sourceFile in fileNames)
{
if (IsRecognizedSourceFile(sourceFile))
{
sourceFiles.Add(sourceFile);
}
}
}
}
return sourceFiles.AsReadOnly();
}
/// <summary>
/// Gets all source files associated with a solution.
/// </summary>
/// <param name="fileName">Solution file name.</param>
/// <returns>Collection of source file names.</returns>
private ReadOnlyCollection<string> GetSolutionSourceFiles(string fileName)
{
List<string> sourceFiles = new List<string>();
ReadOnlyCollection<string> projectFiles = SolutionParser.Instance.Parse(fileName);
foreach (string projectFile in projectFiles)
{
sourceFiles.AddRange(GetProjectSourceFiles(projectFile));
}
return sourceFiles.AsReadOnly();
}
/// <summary>
/// Initializes the manager from the configuration supplied
/// during constuction.
/// </summary>
private void Initialize()
{
//
// Load extension handlers
//
_projectExtensionHandlers = new Dictionary<string, ProjectHandler>(
StringComparer.OrdinalIgnoreCase);
_sourceExtensionHandlers = new Dictionary<string, SourceHandler>(
StringComparer.OrdinalIgnoreCase);
foreach (HandlerConfiguration handlerConfiguration in _configuration.Handlers)
{
switch (handlerConfiguration.HandlerType)
{
case HandlerType.Source:
SourceHandlerConfiguration sourceConfiguration = handlerConfiguration as SourceHandlerConfiguration;
SourceHandler sourceHandler = new SourceHandler(sourceConfiguration);
foreach (ExtensionConfiguration extension in sourceConfiguration.SourceExtensions)
{
_sourceExtensionHandlers.Add(extension.Name, sourceHandler);
}
break;
case HandlerType.Project:
ProjectHandlerConfiguration projectConfiguration = handlerConfiguration as ProjectHandlerConfiguration;
ProjectHandler projectHandler = new ProjectHandler(projectConfiguration);
foreach (ExtensionConfiguration extension in projectConfiguration.ProjectExtensions)
{
_projectExtensionHandlers.Add(extension.Name, projectHandler);
}
break;
default:
throw new InvalidOperationException(
string.Format(
CultureInfo.InvariantCulture,
"Unrecognized handler configuration {0}",
handlerConfiguration));
}
}
}
/// <summary>
/// Gets a boolean indicating whether or not the file is a
/// recognized source file.
/// </summary>
/// <param name="fileName">File to test.</param>
/// <returns>A boolean indicating whehther or not the file is recognized.</returns>
private bool IsRecognizedSourceFile(string fileName)
{
bool recognized = false;
SourceHandler handler = GetSourceHandler(fileName);
if (handler != null)
{
recognized = IsRecognizedFile(fileName, handler.Configuration.SourceExtensions);
}
return recognized;
}
#endregion Methods
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using AutoRest.Core.Model;
using AutoRest.Core.Utilities;
using AutoRest.Extensions;
using Newtonsoft.Json;
namespace AutoRest.CSharp.Model
{
public class MethodCs : Method
{
public MethodCs()
{
}
public bool IsCustomBaseUri
=> CodeModel.Extensions.ContainsKey(SwaggerExtensions.ParameterizedHostExtension);
public SyncMethodsGenerationMode SyncMethods { get; set; }
/// <summary>
/// Get the predicate to determine of the http operation status code indicates failure
/// </summary>
public string FailureStatusCodePredicate
{
get
{
if (Responses.Any())
{
List<string> predicates = new List<string>();
foreach (var responseStatus in Responses.Keys)
{
predicates.Add(string.Format(CultureInfo.InvariantCulture,
"(int)_statusCode != {0}", GetStatusCodeReference(responseStatus)));
}
return string.Join(" && ", predicates);
}
return "!_httpResponse.IsSuccessStatusCode";
}
}
/// <summary>
/// Generate the method parameter declaration for async methods and extensions
/// </summary>
public virtual string GetAsyncMethodParameterDeclaration()
{
return this.GetAsyncMethodParameterDeclaration(false);
}
/// <summary>
/// Generate the method parameter declaration for sync methods and extensions
/// </summary>
/// <param name="addCustomHeaderParameters">If true add the customHeader to the parameters</param>
/// <returns>Generated string of parameters</returns>
public virtual string GetSyncMethodParameterDeclaration(bool addCustomHeaderParameters)
{
List<string> declarations = new List<string>();
foreach (var parameter in LocalParameters)
{
string format = (parameter.IsRequired ? "{0} {1}" : "{0} {1} = {2}");
string defaultValue = $"default({parameter.ModelTypeName})";
if (!string.IsNullOrEmpty(parameter.DefaultValue) && parameter.ModelType is PrimaryType)
{
defaultValue = parameter.DefaultValue;
}
declarations.Add(string.Format(CultureInfo.InvariantCulture,
format, parameter.ModelTypeName, parameter.Name, defaultValue));
}
if (addCustomHeaderParameters)
{
declarations.Add("System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null");
}
return string.Join(", ", declarations);
}
/// <summary>
/// Generate the method parameter declaration for async methods and extensions
/// </summary>
/// <param name="addCustomHeaderParameters">If true add the customHeader to the parameters</param>
/// <returns>Generated string of parameters</returns>
public virtual string GetAsyncMethodParameterDeclaration(bool addCustomHeaderParameters)
{
var declarations = this.GetSyncMethodParameterDeclaration(addCustomHeaderParameters);
if (!string.IsNullOrEmpty(declarations))
{
declarations += ", ";
}
declarations += "System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)";
return declarations;
}
/// <summary>
/// Arguments for invoking the method from a synchronous extension method
/// </summary>
public string SyncMethodInvocationArgs => string.Join(", ", LocalParameters.Select(each => each.Name));
/// <summary>
/// Get the invocation args for an invocation with an async method
/// </summary>
public string GetAsyncMethodInvocationArgs(string customHeaderReference, string cancellationTokenReference = "cancellationToken") => string.Join(", ", LocalParameters.Select(each => (string)each.Name).Concat(new[] { customHeaderReference, cancellationTokenReference }));
/// <summary>
/// Get the parameters that are actually method parameters in the order they appear in the method signature
/// exclude global parameters
/// </summary>
[JsonIgnore]
public IEnumerable<ParameterCs> LocalParameters
{
get
{
return
Parameters.Where(parameter =>
parameter != null &&
!parameter.IsClientProperty &&
!string.IsNullOrWhiteSpace(parameter.Name) &&
!parameter.IsConstant)
.OrderBy(item => !item.IsRequired).Cast<ParameterCs>();
}
}
/// <summary>
/// Get the return type name for the underlying interface method
/// </summary>
public virtual string OperationResponseReturnTypeString
{
get
{
if (ReturnType.Body != null && ReturnType.Headers != null)
{
return $"Microsoft.Rest.HttpOperationResponse<{ReturnType.Body.AsNullableType(HttpMethod != HttpMethod.Head && IsXNullableReturnType)},{ReturnType.Headers.AsNullableType(HttpMethod != HttpMethod.Head)}>";
}
if (ReturnType.Body != null)
{
return $"Microsoft.Rest.HttpOperationResponse<{ReturnType.Body.AsNullableType(HttpMethod != HttpMethod.Head && IsXNullableReturnType)}>";
}
if (ReturnType.Headers != null)
{
return $"Microsoft.Rest.HttpOperationHeaderResponse<{ReturnType.Headers.AsNullableType(HttpMethod != HttpMethod.Head)}>";
}
return "Microsoft.Rest.HttpOperationResponse";
}
}
/// <summary>
/// Get the return type for the async extension method
/// </summary>
public virtual string TaskExtensionReturnTypeString
{
get
{
if (ReturnType.Body != null)
{
return string.Format(CultureInfo.InvariantCulture,
"System.Threading.Tasks.Task<{0}>", ReturnType.Body.AsNullableType(HttpMethod != HttpMethod.Head && IsXNullableReturnType));
}
else if (ReturnType.Headers != null)
{
return string.Format(CultureInfo.InvariantCulture,
"System.Threading.Tasks.Task<{0}>", ReturnType.Headers.AsNullableType(HttpMethod != HttpMethod.Head));
}
else
{
return "System.Threading.Tasks.Task";
}
}
}
/// <summary>
/// Get the type for operation exception
/// </summary>
public virtual string OperationExceptionTypeString
{
get
{
if (this.DefaultResponse.Body is CompositeType)
{
CompositeType type = this.DefaultResponse.Body as CompositeType;
if (type.Extensions.ContainsKey(SwaggerExtensions.NameOverrideExtension))
{
var ext = type.Extensions[SwaggerExtensions.NameOverrideExtension] as Newtonsoft.Json.Linq.JContainer;
if (ext != null && ext["name"] != null)
{
return ext["name"].ToString();
}
}
return type.Name + "Exception";
}
else
{
return "Microsoft.Rest.HttpOperationException";
}
}
}
/// <summary>
/// Get the expression for exception initialization with message.
/// </summary>
public virtual string InitializeExceptionWithMessage
{
get
{
return string.Empty;
}
}
/// <summary>
/// Get the expression for exception initialization with message.
/// </summary>
public virtual string InitializeException
{
get
{
return string.Empty;
}
}
/// <summary>
/// Gets the expression for response body initialization.
/// </summary>
public virtual string InitializeResponseBody
{
get
{
return string.Empty;
}
}
/// <summary>
/// Gets the expression for default header setting.
/// </summary>
public virtual string SetDefaultHeaders
{
get
{
return string.Empty;
}
}
/// <summary>
/// Get the type name for the method's return type
/// </summary>
public virtual string ReturnTypeString
{
get
{
if (ReturnType.Body != null)
{
return ReturnType.Body.AsNullableType(HttpMethod != HttpMethod.Head && IsXNullableReturnType);
}
if (ReturnType.Headers != null)
{
return ReturnType.Headers.AsNullableType(HttpMethod != HttpMethod.Head);
}
else
{
return "void";
}
}
}
/// <summary>
/// Get the method's request body (or null if there is no request body)
/// </summary>
[JsonIgnore]
public ParameterCs RequestBody => Body as ParameterCs;
[JsonIgnore]
public string AccessModifier => Hidden ? "internal" : "public";
/// <summary>
/// Generate a reference to the ServiceClient
/// </summary>
[JsonIgnore]
public string ClientReference => Group.IsNullOrEmpty() ? "this" : "this.Client";
/// <summary>
/// Returns serialization settings reference.
/// </summary>
/// <param name="serializationType"></param>
/// <returns></returns>
public string GetSerializationSettingsReference(IModelType serializationType)
{
if (serializationType.IsOrContainsPrimaryType(KnownPrimaryType.Date))
{
return "new Microsoft.Rest.Serialization.DateJsonConverter()";
}
else if (serializationType.IsOrContainsPrimaryType(KnownPrimaryType.DateTimeRfc1123))
{
return "new Microsoft.Rest.Serialization.DateTimeRfc1123JsonConverter()";
}
else if (serializationType.IsOrContainsPrimaryType(KnownPrimaryType.Base64Url))
{
return "new Microsoft.Rest.Serialization.Base64UrlJsonConverter()";
}
else if (serializationType.IsOrContainsPrimaryType(KnownPrimaryType.UnixTime))
{
return "new Microsoft.Rest.Serialization.UnixTimeJsonConverter()";
}
return ClientReference + ".SerializationSettings";
}
/// <summary>
/// Returns deserialization settings reference.
/// </summary>
/// <param name="deserializationType"></param>
/// <returns></returns>
public string GetDeserializationSettingsReference(IModelType deserializationType)
{
if (deserializationType.IsOrContainsPrimaryType(KnownPrimaryType.Date))
{
return "new Microsoft.Rest.Serialization.DateJsonConverter()";
}
else if (deserializationType.IsOrContainsPrimaryType(KnownPrimaryType.Base64Url))
{
return "new Microsoft.Rest.Serialization.Base64UrlJsonConverter()";
}
else if (deserializationType.IsOrContainsPrimaryType(KnownPrimaryType.UnixTime))
{
return "new Microsoft.Rest.Serialization.UnixTimeJsonConverter()";
}
return ClientReference + ".DeserializationSettings";
}
public string GetExtensionParameters(string methodParameters)
{
string operationsParameter = "this I" + MethodGroup.TypeName + " operations";
return string.IsNullOrWhiteSpace(methodParameters)
? operationsParameter
: operationsParameter + ", " + methodParameters;
}
public static string GetStatusCodeReference(HttpStatusCode code)
{
return ((int)code).ToString(CultureInfo.InvariantCulture);
}
/// <summary>
/// Generate code to build the URL from a url expression and method parameters
/// </summary>
/// <param name="variableName">The variable to store the url in.</param>
/// <returns></returns>
public virtual string BuildUrl(string variableName)
{
var builder = new IndentedStringBuilder();
foreach (var pathParameter in this.LogicalParameters.Where(p => p.Location == ParameterLocation.Path))
{
string replaceString = "{0} = {0}.Replace(\"{{{1}}}\", System.Uri.EscapeDataString({2}));";
if (pathParameter.SkipUrlEncoding())
{
replaceString = "{0} = {0}.Replace(\"{{{1}}}\", {2});";
}
var urlPathName = pathParameter.SerializedName;
if (pathParameter.ModelType is SequenceType)
{
builder.AppendLine(replaceString,
variableName,
urlPathName,
pathParameter.GetFormattedReferenceValue(ClientReference));
}
else
{
builder.AppendLine(replaceString,
variableName,
urlPathName,
pathParameter.ModelType.ToString(ClientReference, pathParameter.Name));
}
}
if (this.LogicalParameters.Any(p => p.Location == ParameterLocation.Query))
{
builder.AppendLine("System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();");
foreach (var queryParameter in this.LogicalParameters.Where(p => p.Location == ParameterLocation.Query))
{
var replaceString = "_queryParameters.Add(string.Format(\"{0}={{0}}\", System.Uri.EscapeDataString({1})));";
if ((queryParameter as ParameterCs).IsNullable())
{
builder.AppendLine("if ({0} != null)", queryParameter.Name)
.AppendLine("{").Indent();
}
if (queryParameter.SkipUrlEncoding())
{
replaceString = "_queryParameters.Add(string.Format(\"{0}={{0}}\", {1}));";
}
if (queryParameter.CollectionFormat == CollectionFormat.Multi)
{
builder.AppendLine("if ({0}.Count == 0)", queryParameter.Name)
.AppendLine("{").Indent()
.AppendLine(replaceString, queryParameter.SerializedName, "string.Empty").Outdent()
.AppendLine("}")
.AppendLine("else")
.AppendLine("{").Indent()
.AppendLine("foreach (var _item in {0})", queryParameter.Name)
.AppendLine("{").Indent()
.AppendLine(replaceString, queryParameter.SerializedName, "\"\" + _item").Outdent()
.AppendLine("}").Outdent()
.AppendLine("}").Outdent();
}
else
{
builder.AppendLine(replaceString,
queryParameter.SerializedName, queryParameter.GetFormattedReferenceValue(ClientReference));
}
if ((queryParameter as ParameterCs).IsNullable())
{
builder.Outdent()
.AppendLine("}");
}
}
builder.AppendLine("if (_queryParameters.Count > 0)")
.AppendLine("{").Indent();
if (this.Extensions.ContainsKey("nextLinkMethod") && (bool)this.Extensions["nextLinkMethod"])
{
builder.AppendLine("{0} += ({0}.Contains(\"?\") ? \"&\" : \"?\") + string.Join(\"&\", _queryParameters);", variableName);
}
else
{
builder.AppendLine("{0} += \"?\" + string.Join(\"&\", _queryParameters);", variableName);
}
builder.Outdent().AppendLine("}");
}
return builder.ToString();
}
/// <summary>
/// Generates input mapping code block.
/// </summary>
/// <returns></returns>
public virtual string BuildInputMappings()
{
var builder = new IndentedStringBuilder();
foreach (var transformation in InputParameterTransformation)
{
var compositeOutputParameter = transformation.OutputParameter.ModelType as CompositeType;
if (transformation.OutputParameter.IsRequired && compositeOutputParameter != null)
{
builder.AppendLine("{0} {1} = new {0}();",
transformation.OutputParameter.ModelTypeName,
transformation.OutputParameter.Name);
}
else
{
builder.AppendLine("{0} {1} = default({0});",
transformation.OutputParameter.ModelTypeName,
transformation.OutputParameter.Name);
}
var nullCheck = BuildNullCheckExpression(transformation);
if (!string.IsNullOrEmpty(nullCheck))
{
builder.AppendLine("if ({0})", nullCheck)
.AppendLine("{").Indent();
}
if (transformation.ParameterMappings.Any(m => !string.IsNullOrEmpty(m.OutputParameterProperty)) &&
compositeOutputParameter != null && !transformation.OutputParameter.IsRequired)
{
builder.AppendLine("{0} = new {1}();",
transformation.OutputParameter.Name,
transformation.OutputParameter.ModelType.Name);
}
foreach (var mapping in transformation.ParameterMappings)
{
builder.AppendLine("{0};", mapping.CreateCode(transformation.OutputParameter));
}
if (!string.IsNullOrEmpty(nullCheck))
{
builder.Outdent()
.AppendLine("}");
}
}
return builder.ToString();
}
private static string BuildNullCheckExpression(ParameterTransformation transformation)
{
if (transformation == null)
{
throw new ArgumentNullException("transformation");
}
return string.Join(" || ",
transformation.ParameterMappings
.Where(m => m.InputParameter.IsNullable())
.Select(m => m.InputParameter.Name + " != null"));
}
}
}
| |
#region Copyright notice and license
// Copyright 2015, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Grpc.Core.Internal;
using Grpc.Core.Logging;
using Grpc.Core.Utils;
namespace Grpc.Core
{
/// <summary>
/// Encapsulates initialization and shutdown of gRPC library.
/// </summary>
public class GrpcEnvironment
{
const int MinDefaultThreadPoolSize = 4;
static object staticLock = new object();
static GrpcEnvironment instance;
static int refCount;
static int? customThreadPoolSize;
static int? customCompletionQueueCount;
static readonly HashSet<Channel> registeredChannels = new HashSet<Channel>();
static readonly HashSet<Server> registeredServers = new HashSet<Server>();
static ILogger logger = new NullLogger();
readonly object myLock = new object();
readonly GrpcThreadPool threadPool;
readonly DebugStats debugStats = new DebugStats();
readonly AtomicCounter cqPickerCounter = new AtomicCounter();
bool isClosed;
/// <summary>
/// Returns a reference-counted instance of initialized gRPC environment.
/// Subsequent invocations return the same instance unless reference count has dropped to zero previously.
/// </summary>
internal static GrpcEnvironment AddRef()
{
ShutdownHooks.Register();
lock (staticLock)
{
refCount++;
if (instance == null)
{
instance = new GrpcEnvironment();
}
return instance;
}
}
/// <summary>
/// Decrements the reference count for currently active environment and asynchronously shuts down the gRPC environment if reference count drops to zero.
/// </summary>
internal static async Task ReleaseAsync()
{
GrpcEnvironment instanceToShutdown = null;
lock (staticLock)
{
GrpcPreconditions.CheckState(refCount > 0);
refCount--;
if (refCount == 0)
{
instanceToShutdown = instance;
instance = null;
}
}
if (instanceToShutdown != null)
{
await instanceToShutdown.ShutdownAsync().ConfigureAwait(false);
}
}
internal static int GetRefCount()
{
lock (staticLock)
{
return refCount;
}
}
internal static void RegisterChannel(Channel channel)
{
lock (staticLock)
{
GrpcPreconditions.CheckNotNull(channel);
registeredChannels.Add(channel);
}
}
internal static void UnregisterChannel(Channel channel)
{
lock (staticLock)
{
GrpcPreconditions.CheckNotNull(channel);
GrpcPreconditions.CheckArgument(registeredChannels.Remove(channel), "Channel not found in the registered channels set.");
}
}
internal static void RegisterServer(Server server)
{
lock (staticLock)
{
GrpcPreconditions.CheckNotNull(server);
registeredServers.Add(server);
}
}
internal static void UnregisterServer(Server server)
{
lock (staticLock)
{
GrpcPreconditions.CheckNotNull(server);
GrpcPreconditions.CheckArgument(registeredServers.Remove(server), "Server not found in the registered servers set.");
}
}
/// <summary>
/// Requests shutdown of all channels created by the current process.
/// </summary>
public static Task ShutdownChannelsAsync()
{
HashSet<Channel> snapshot = null;
lock (staticLock)
{
snapshot = new HashSet<Channel>(registeredChannels);
}
return Task.WhenAll(snapshot.Select((channel) => channel.ShutdownAsync()));
}
/// <summary>
/// Requests immediate shutdown of all servers created by the current process.
/// </summary>
public static Task KillServersAsync()
{
HashSet<Server> snapshot = null;
lock (staticLock)
{
snapshot = new HashSet<Server>(registeredServers);
}
return Task.WhenAll(snapshot.Select((server) => server.KillAsync()));
}
/// <summary>
/// Gets application-wide logger used by gRPC.
/// </summary>
/// <value>The logger.</value>
public static ILogger Logger
{
get
{
return logger;
}
}
/// <summary>
/// Sets the application-wide logger that should be used by gRPC.
/// </summary>
public static void SetLogger(ILogger customLogger)
{
GrpcPreconditions.CheckNotNull(customLogger, "customLogger");
logger = customLogger;
}
/// <summary>
/// Sets the number of threads in the gRPC thread pool that polls for internal RPC events.
/// Can be only invoke before the <c>GrpcEnviroment</c> is started and cannot be changed afterwards.
/// Setting thread pool size is an advanced setting and you should only use it if you know what you are doing.
/// Most users should rely on the default value provided by gRPC library.
/// Note: this method is part of an experimental API that can change or be removed without any prior notice.
/// </summary>
public static void SetThreadPoolSize(int threadCount)
{
lock (staticLock)
{
GrpcPreconditions.CheckState(instance == null, "Can only be set before GrpcEnvironment is initialized");
GrpcPreconditions.CheckArgument(threadCount > 0, "threadCount needs to be a positive number");
customThreadPoolSize = threadCount;
}
}
/// <summary>
/// Sets the number of completion queues in the gRPC thread pool that polls for internal RPC events.
/// Can be only invoke before the <c>GrpcEnviroment</c> is started and cannot be changed afterwards.
/// Setting the number of completions queues is an advanced setting and you should only use it if you know what you are doing.
/// Most users should rely on the default value provided by gRPC library.
/// Note: this method is part of an experimental API that can change or be removed without any prior notice.
/// </summary>
public static void SetCompletionQueueCount(int completionQueueCount)
{
lock (staticLock)
{
GrpcPreconditions.CheckState(instance == null, "Can only be set before GrpcEnvironment is initialized");
GrpcPreconditions.CheckArgument(completionQueueCount > 0, "threadCount needs to be a positive number");
customCompletionQueueCount = completionQueueCount;
}
}
/// <summary>
/// Creates gRPC environment.
/// </summary>
private GrpcEnvironment()
{
GrpcNativeInit();
threadPool = new GrpcThreadPool(this, GetThreadPoolSizeOrDefault(), GetCompletionQueueCountOrDefault());
threadPool.Start();
}
/// <summary>
/// Gets the completion queues used by this gRPC environment.
/// </summary>
internal IReadOnlyCollection<CompletionQueueSafeHandle> CompletionQueues
{
get
{
return this.threadPool.CompletionQueues;
}
}
internal bool IsAlive
{
get
{
return this.threadPool.IsAlive;
}
}
/// <summary>
/// Picks a completion queue in a round-robin fashion.
/// Shouldn't be invoked on a per-call basis (used at per-channel basis).
/// </summary>
internal CompletionQueueSafeHandle PickCompletionQueue()
{
var cqIndex = (int) ((cqPickerCounter.Increment() - 1) % this.threadPool.CompletionQueues.Count);
return this.threadPool.CompletionQueues.ElementAt(cqIndex);
}
/// <summary>
/// Gets the completion queue used by this gRPC environment.
/// </summary>
internal DebugStats DebugStats
{
get
{
return this.debugStats;
}
}
/// <summary>
/// Gets version of gRPC C core.
/// </summary>
internal static string GetCoreVersionString()
{
var ptr = NativeMethods.Get().grpcsharp_version_string(); // the pointer is not owned
return Marshal.PtrToStringAnsi(ptr);
}
internal static void GrpcNativeInit()
{
NativeMethods.Get().grpcsharp_init();
}
internal static void GrpcNativeShutdown()
{
NativeMethods.Get().grpcsharp_shutdown();
}
/// <summary>
/// Shuts down this environment.
/// </summary>
private async Task ShutdownAsync()
{
if (isClosed)
{
throw new InvalidOperationException("Close has already been called");
}
await threadPool.StopAsync().ConfigureAwait(false);
GrpcNativeShutdown();
isClosed = true;
debugStats.CheckOK();
}
private int GetThreadPoolSizeOrDefault()
{
if (customThreadPoolSize.HasValue)
{
return customThreadPoolSize.Value;
}
// In systems with many cores, use half of the cores for GrpcThreadPool
// and the other half for .NET thread pool. This heuristic definitely needs
// more work, but seems to work reasonably well for a start.
return Math.Max(MinDefaultThreadPoolSize, Environment.ProcessorCount / 2);
}
private int GetCompletionQueueCountOrDefault()
{
if (customCompletionQueueCount.HasValue)
{
return customCompletionQueueCount.Value;
}
// by default, create a completion queue for each thread
return GetThreadPoolSizeOrDefault();
}
private static class ShutdownHooks
{
static object staticLock = new object();
static bool hooksRegistered;
public static void Register()
{
lock (staticLock)
{
if (!hooksRegistered)
{
#if NETSTANDARD1_5
System.Runtime.Loader.AssemblyLoadContext.Default.Unloading += (assemblyLoadContext) => { HandleShutdown(); };
#else
AppDomain.CurrentDomain.ProcessExit += (sender, eventArgs) => { HandleShutdown(); };
AppDomain.CurrentDomain.DomainUnload += (sender, eventArgs) => { HandleShutdown(); };
#endif
}
hooksRegistered = true;
}
}
/// <summary>
/// Handler for AppDomain.DomainUnload, AppDomain.ProcessExit and AssemblyLoadContext.Unloading hooks.
/// </summary>
private static void HandleShutdown()
{
Task.WaitAll(GrpcEnvironment.ShutdownChannelsAsync(), GrpcEnvironment.KillServersAsync());
}
}
}
}
| |
/*
* 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 System.Text;
using log4net;
using OpenMetaverse;
using OpenSim.Data;
namespace OpenSim.Framework.Communications.Cache
{
internal delegate void AddItemDelegate(InventoryItemBase itemInfo);
internal delegate void UpdateItemDelegate(InventoryItemBase itemInfo);
internal delegate void DeleteItemDelegate(UUID itemID);
internal delegate void QueryItemDelegate(UUID itemID);
internal delegate void QueryFolderDelegate(UUID folderID);
internal delegate void CreateFolderDelegate(string folderName, UUID folderID, ushort folderType, UUID parentID);
internal delegate void MoveFolderDelegate(UUID folderID, UUID parentID);
internal delegate void PurgeFolderDelegate(UUID folderID);
internal delegate void UpdateFolderDelegate(string name, UUID folderID, ushort type, UUID parentID);
internal delegate void SendInventoryDescendentsDelegate(
IClientAPI client, UUID folderID, bool fetchFolders, bool fetchItems);
public delegate void OnItemReceivedDelegate(UUID itemID);
/// <summary>
/// Stores user profile and inventory data received from backend services for a particular user.
/// </summary>
public class CachedUserInfo
{
public event OnItemReceivedDelegate OnItemReceived;
private static readonly ILog m_log
= LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// The comms manager holds references to services (user, grid, inventory, etc.)
/// </summary>
private readonly CommunicationsManager m_commsManager;
public UserProfileData UserProfile { get { return m_userProfile; } }
private UserProfileData m_userProfile;
/// <summary>
/// Have we received the user's inventory from the inventory service?
/// </summary>
public bool HasReceivedInventory { get { return true; } }
/// <summary>
/// This is a list of all of the inventory items that are of type "CallingCard" in the
/// "Calling Card"/Friends/All folder to work around a bug with the viewer creating
/// multiple copies of the same calling card
/// </summary>
private List<string> _namesOfCallingCardsInCallingCardsFriendsAllFolder = null;
private object _namesOfCallingCardsInCallingCardsFriendsAllFolderLock = new object();
private System.Threading.AutoResetEvent _namesOfCallingCardsInCallingCardsFriendsAllFolderWaitLock = null;
/// <summary>
/// Holds the most appropriate folders for the given type.
/// Note: Thus far in the code, this folder doesn't have to be kept up to date as it will
/// only be used to retrieve an ID. If this ever changes, this collection will have to be kept up to date
/// </summary>
private Dictionary<int, InventoryFolderBase> _folderTypeCache = new Dictionary<int, InventoryFolderBase>();
public UUID SessionID
{
get { return m_session_id; }
set { m_session_id = value; }
}
private UUID m_session_id = UUID.Zero;
/// <summary>
/// List of friends for this user
/// </summary>
private List<FriendListItem> _friends;
/// <summary>
/// Stores the permissions that were given to me by friends
/// </summary>
private Dictionary<UUID, uint> _permissionsGivenByFriends = new Dictionary<UUID, uint>();
/// <summary>
/// Constructor
/// </summary>
/// <param name="commsManager"></param>
/// <param name="userProfile"></param>
public CachedUserInfo(CommunicationsManager commsManager, UserProfileData userProfile, List<FriendListItem> friendInfos)
{
m_commsManager = commsManager;
m_userProfile = userProfile;
_friends = friendInfos;
this.IndexFriendPermissions();
}
private void FetchFriends(bool force)
{
if (m_userProfile == null) return; // no current user
if (force || (_friends == null))
{
_friends = m_commsManager.UserService.GetUserFriendList(m_userProfile.ID);
this.IndexFriendPermissions();
}
}
public bool HasPermissionFromFriend(UUID friendId, uint permissionMask)
{
FetchFriends(false);
lock (_permissionsGivenByFriends)
{
uint permsGiven;
if (_permissionsGivenByFriends.TryGetValue(friendId, out permsGiven))
{
if ((permsGiven & permissionMask) != 0)
{
return true; // friend has permission
}
else
{
return false; // friend does not have permission
}
}
else
{
return false; // not a friend
}
}
}
private void IndexFriendPermissions()
{
lock (_permissionsGivenByFriends)
{
_permissionsGivenByFriends.Clear();
if (_friends == null)
return;
//index user permissions given by each friend
foreach (FriendListItem friendItem in _friends)
{
_permissionsGivenByFriends.Add(friendItem.Friend, friendItem.FriendListOwnerPerms);
}
}
}
public void AdjustPermissionsFromFriend(UUID friendId, uint newPermissions)
{
lock (_permissionsGivenByFriends)
{
_permissionsGivenByFriends[friendId] = newPermissions;
}
}
public void RemoveFromFriendsCache(UUID friendId)
{
lock (_permissionsGivenByFriends)
{
if (_permissionsGivenByFriends.ContainsKey(friendId))
_permissionsGivenByFriends.Remove(friendId);
}
}
/// <summary>
/// Check if a calling card already exists in the given folder with the name given
/// </summary>
/// <param name="folderId">Folder to check for calling cards in</param>
/// <param name="name">Name of user whose name may be on one of the calling cards</param>
/// <returns></returns>
public bool CheckIfCallingCardAlreadyExistsForUser(UUID folderId, string name)
{
//On 2015-12-15, a problem with calling cards occurred such that all calling cards
// would be duplicated by the viewer when logging in, which caused users to not
// display themselves and in extreme cases, would block them from doing anything
// along with generating 65000 calling cards for one user
//To address this issue, we make sure that the viewer cannot add calling cards
// that already exist for that user in the "Calling Cards"/Friends/All folder.
// We will ignore the requests.
PopulateCallingCardCache(folderId);
lock (_namesOfCallingCardsInCallingCardsFriendsAllFolderLock)
{
if (_namesOfCallingCardsInCallingCardsFriendsAllFolder != null)
{
return _namesOfCallingCardsInCallingCardsFriendsAllFolder.Contains(name);
}
//Something went wrong and we weren't able to populate the calling card cache
return false;
}
}
/// <summary>
/// Populates the calling card cache for the user for the given folder
/// </summary>
/// <param name="folderId"></param>
private void PopulateCallingCardCache(UUID folderId)
{
bool mustWait = true;
//Make sure that multiple threads are not trying to populate the cache at the same time
// as the inventory operations are heavy
lock (_namesOfCallingCardsInCallingCardsFriendsAllFolderLock)
{
if (_namesOfCallingCardsInCallingCardsFriendsAllFolder != null)
{
//The cache exists, we don't need to populate it
return;
}
if (_namesOfCallingCardsInCallingCardsFriendsAllFolderWaitLock == null)
{
//We were the first one here, we get to create the lock and have the other threads wait
// as we don't want all threads that might come in here requesting all of the folder contents multiple times
mustWait = false;
_namesOfCallingCardsInCallingCardsFriendsAllFolderWaitLock = new System.Threading.AutoResetEvent(false);
}
}
if (mustWait)
{
//Wait for another thread to finish populating the cache, but dDo not block indefinitely - wait a max of 10 seconds
// before proceeding on even though the other thread hasn't finished... this might allow some duplicate calling
// cards, but if something is going so wrong that after 10 seconds it hasn't gotten the folders, we should just
// give up and try to move on
_namesOfCallingCardsInCallingCardsFriendsAllFolderWaitLock.WaitOne(10000);
return;
}
List<string> callingCardItemNames = null;
try
{
InventoryFolderBase potentialCallingCardsFolder = FindTopLevelFolderFor(folderId);
if (potentialCallingCardsFolder == null || //This can happen if MySQL is used for inventory
potentialCallingCardsFolder.Type == (short)InventoryType.CallingCard)
{
InventoryFolderBase newCallingCardFolder = GetFolder(folderId);
//We only check in the All folder as the bug with calling card duplication
// only occurs in "Calling Cards"/Friends/All - not other folders
if (newCallingCardFolder.Name == "All")
{
callingCardItemNames = new List<string>();
foreach (InventoryItemBase itm in newCallingCardFolder.Items)
{
if (itm.AssetType == (int)AssetType.CallingCard)
{
//Add the item name to the list - as the user cannot edit this in the viewer
// as it is disabled, it is safe to check just based on the name
callingCardItemNames.Add(itm.Name);
}
}
}
}
}
catch (Exception e)
{
m_log.ErrorFormat("[INVENTORY] An exception occurred finding calling cards in folderID {0}: {1}", folderId, e);
}
finally
{
//Now under the lock, set the list of calling cards and then pulse the wait lock to inform other threads
// that they can run now too
lock (_namesOfCallingCardsInCallingCardsFriendsAllFolderLock)
{
_namesOfCallingCardsInCallingCardsFriendsAllFolder = callingCardItemNames;
_namesOfCallingCardsInCallingCardsFriendsAllFolderWaitLock.Set();
if (callingCardItemNames == null)
{
//It failed, so clear the wait lock and let someone else try later
_namesOfCallingCardsInCallingCardsFriendsAllFolderWaitLock = null;
}
}
}
}
public InventoryFolderBase GetFolderAttributes(UUID folderId)
{
IInventoryProviderSelector inventorySelect = ProviderRegistry.Instance.Get<IInventoryProviderSelector>();
InventoryFolderBase folderInfo = inventorySelect.GetProvider(m_userProfile.ID).GetFolderAttributes(folderId);
return folderInfo;
}
public InventoryFolderBase GetFolderAttributesChecked(UUID folderId)
{
IInventoryProviderSelector inventorySelect = ProviderRegistry.Instance.Get<IInventoryProviderSelector>();
InventoryFolderBase folderInfo = inventorySelect.GetCheckedProvider(m_userProfile.ID).GetFolderAttributes(m_userProfile.ID, folderId);
return folderInfo;
}
public InventoryItemBase FindItem(UUID itemId)
{
try
{
IInventoryProviderSelector inventorySelect = ProviderRegistry.Instance.Get<IInventoryProviderSelector>();
InventoryItemBase itemInfo = inventorySelect.GetCheckedProvider(m_userProfile.ID).GetItem(m_userProfile.ID, itemId, UUID.Zero);
return itemInfo;
}
catch (InventoryStorageException e)
{
m_log.ErrorFormat("[INVENTORY] Could not find requested item {0}: {1}", itemId, e);
}
return null;
}
/// <summary>
/// Fetch inventory for this user.
/// </summary>
/// This has to be executed as a separate step once user information is retreived.
/// This will occur synchronously if the inventory service is in the same process as this class, and
/// asynchronously otherwise.
public void FetchInventory()
{
}
/// <summary>
/// Flushes the folder type cache
/// </summary>
public void DropInventory()
{
lock (_folderTypeCache)
{
_folderTypeCache.Clear();
}
}
/// <summary>
/// Callback invoked when an item is received from an async request to the inventory service.
///
/// We're assuming here that items are always received after all the folders
/// received.
/// If folder is null, we will search for it starting from RootFolder (an O(n) operation),
/// otherwise we'll just put it into folder
/// </summary>
/// <param name="folderInfo"></param>
private void ItemReceive(InventoryItemBase itemInfo, InventoryFolderImpl folder)
{
if (OnItemReceived != null)
OnItemReceived(itemInfo.ID);
}
/// <summary>
/// Create a folder in this agent's inventory.
/// </summary>
///
/// If the inventory service has not yet delievered the inventory
/// for this user then the request will be queued.
///
/// <param name="parentID"></param>
/// <returns></returns>
public InventoryFolderBase CreateFolder(string folderName, UUID folderID, short folderType, UUID parentID)
{
InventoryFolderBase createdBaseFolder = new InventoryFolderBase();
createdBaseFolder.Owner = UserProfile.ID;
createdBaseFolder.ID = folderID;
createdBaseFolder.Name = folderName;
createdBaseFolder.ParentID = parentID;
createdBaseFolder.Type = (short)folderType;
createdBaseFolder.Version = 1;
IInventoryProviderSelector inventorySelect = ProviderRegistry.Instance.Get<IInventoryProviderSelector>();
inventorySelect.GetCheckedProvider(m_userProfile.ID).CreateFolder(UserProfile.ID, createdBaseFolder);
return createdBaseFolder;
}
/// <summary>
/// Handle a client request to update the inventory folder
/// </summary>
///
/// If the inventory service has not yet delievered the inventory
/// for this user then the request will be queued.
///
/// FIXME: We call add new inventory folder because in the data layer, we happen to use an SQL REPLACE
/// so this will work to rename an existing folder. Needless to say, to rely on this is very confusing,
/// and needs to be changed.
///
/// <param name="folderID"></param>
/// <param name="type"></param>
/// <param name="name"></param>
/// <param name="parentID"></param>
public bool UpdateFolder(InventoryFolderBase baseFolder)
{
IInventoryProviderSelector inventorySelect = ProviderRegistry.Instance.Get<IInventoryProviderSelector>();
inventorySelect.GetProvider(m_userProfile.ID).SaveFolder(baseFolder);
return true;
}
/// <summary>
/// Handle an inventory folder move request from the client.
///
/// If the inventory service has not yet delievered the inventory
/// for this user then the request will be queued.
/// </summary>
///
/// <param name="folderID"></param>
/// <param name="parentID"></param>
/// <returns>
/// true if the delete was successful, or if it was queued pending folder receipt
/// false if the folder to be deleted did not exist.
/// </returns>
public bool MoveFolder(UUID folderID, UUID parentID)
{
try
{
IInventoryProviderSelector inventorySelect = ProviderRegistry.Instance.Get<IInventoryProviderSelector>();
inventorySelect.GetCheckedProvider(m_userProfile.ID).MoveFolder(m_userProfile.ID, folderID, parentID);
return true;
}
catch (InventoryStorageException)
{
}
return false;
}
/// <summary>
/// This method will delete all the items and folders in the given folder.
/// </summary>
/// If the inventory service has not yet delievered the inventory
/// for this user then the request will be queued.
///
/// <param name="folderID"></param>
public bool PurgeFolderContents(InventoryFolderBase folder)
{
try
{
IInventoryProviderSelector inventorySelect = ProviderRegistry.Instance.Get<IInventoryProviderSelector>();
inventorySelect.GetProvider(m_userProfile.ID).PurgeFolderContents(folder);
return true;
}
catch (InventoryStorageException)
{
}
return false;
}
/// <summary>
/// This method will delete the given folder and all the items and folders in it.
/// </summary>
/// If the inventory service has not yet delievered the inventory
/// for this user then the request will be queued.
///
/// <param name="folderID"></param>
public bool PurgeFolder(InventoryFolderBase folder)
{
try
{
IInventoryProviderSelector inventorySelect = ProviderRegistry.Instance.Get<IInventoryProviderSelector>();
inventorySelect.GetProvider(m_userProfile.ID).PurgeFolder(folder);
return true;
}
catch (InventoryStorageException)
{
}
return false;
}
/// <summary>
/// Add an item to the user's inventory.
/// </summary>
/// If the item has no folder set (i.e. it is UUID.Zero), then it is placed in the most appropriate folder
/// for that type.
/// <param name="itemInfo"></param>
public void AddItem(InventoryItemBase item)
{
if (item.Folder == UUID.Zero)
{
InventoryFolderBase f = FindFolderForType(item.AssetType);
if (f != null)
{
item.Folder = f.ID;
}
else
{
InventoryFolderBase folder = FindFolderForType((int)FolderType.Root);
item.Folder = folder.ID;
}
}
IInventoryProviderSelector selector = ProviderRegistry.Instance.Get<IInventoryProviderSelector>();
selector.GetCheckedProvider(m_userProfile.ID).CreateItem(m_userProfile.ID, item);
ItemReceive(item, null);
}
public InventoryItemBase ResolveLink(InventoryItemBase baseItem)
{
// Resolve Links if needed
const int LINK_RECURSION_LIMIT = 32;
int counter = 0;
while ((baseItem != null) && (baseItem.AssetType == (int)AssetType.Link) && (++counter < LINK_RECURSION_LIMIT))
{
baseItem = this.FindItem(baseItem.AssetID);
}
if (baseItem == null)
{
//broken link cannot be followed
return null;
}
if (baseItem.AssetType == (int)AssetType.Link)
{
//recursion limit was hit
return null;
}
return baseItem;
}
/// <summary>
/// Update an item in the user's inventory
/// </summary>
/// <param name="userID"></param>
/// <param name="itemInfo"></param>
public void UpdateItem(InventoryItemBase item)
{
IInventoryProviderSelector selector = ProviderRegistry.Instance.Get<IInventoryProviderSelector>();
selector.GetProvider(item.Owner).SaveItem(item);
}
/// <summary>
/// Delete an item from the user's inventory
///
/// If the inventory service has not yet delievered the inventory
/// for this user then the request will be queued.
/// </summary>
/// <param name="item"></param>
/// <returns>
/// true on a successful delete or a if the request is queued.
/// Returns false on an immediate failure
/// </returns>
public bool DeleteItem(InventoryItemBase item)
{
IInventoryProviderSelector selector = ProviderRegistry.Instance.Get<IInventoryProviderSelector>();
IInventoryStorage provider = selector.GetProvider(item.Owner);
provider.PurgeItem(item);
return true;
}
/// <summary>
/// Send details of the inventory items and/or folders in a given folder to the client.
/// </summary>
/// <param name="client"></param>
/// <param name="folderID"></param>
/// <param name="fetchFolders"></param>
/// <param name="fetchItems"></param>
/// <returns>true if the request was queued or successfully processed, false otherwise</returns>
public bool SendInventoryDecendents(IClientAPI client, UUID folderID, bool fetchFolders, bool fetchItems)
{
IInventoryProviderSelector selector = ProviderRegistry.Instance.Get<IInventoryProviderSelector>();
InventoryFolderBase folder = selector.GetCheckedProvider(client.AgentId).GetFolder(client.AgentId, folderID);
List<InventoryFolderBase> subFolders = new List<InventoryFolderBase>();
List<InventoryItemBase> items = new List<InventoryItemBase>();
//sort into items and folders
foreach (InventorySubFolderBase subFolder in folder.SubFolders)
{
subFolders.Add(new InventoryFolderBase {
ID = subFolder.ID, ParentID = folderID, Name = subFolder.Name, Owner = subFolder.Owner, Type = subFolder.Type });
}
items.AddRange(folder.Items);
client.SendInventoryFolderDetails(client.AgentId, folder, items, subFolders, fetchFolders, fetchItems);
return true;
}
/// <summary>
/// Find an appropriate folder for the given asset type
/// </summary>
/// <param name="type"></param>
/// <returns>null if no appropriate folder exists</returns>
public InventoryFolderBase FindFolderForType(int type)
{
InventoryFolderBase bestFolderForType;
lock (_folderTypeCache)
{
_folderTypeCache.TryGetValue(type, out bestFolderForType);
if (bestFolderForType != null) return bestFolderForType;
}
IInventoryProviderSelector inventorySelect = ProviderRegistry.Instance.Get<IInventoryProviderSelector>();
IInventoryStorage provider = inventorySelect.GetProvider(m_userProfile.ID);
try
{
bestFolderForType = provider.FindFolderForType(m_userProfile.ID, (AssetType)type);
}
catch
{ }
if (bestFolderForType == null)
{
//next best folder will be the user root folder, it has to exist
try
{
bestFolderForType = provider.FindFolderForType(m_userProfile.ID, (AssetType)FolderType.Root);
}
catch
{ }
if (bestFolderForType == null)
{
throw new InventoryStorageException(
String.Format("Can not retrieve a destination folder for types, user {0} has no root folder", m_userProfile.ID));
}
}
lock (_folderTypeCache)
{
if (_folderTypeCache.ContainsKey(type))
{
_folderTypeCache[type] = bestFolderForType;
}
else
{
_folderTypeCache.Add(type, bestFolderForType);
}
}
return bestFolderForType;
}
// Searches the parentage tree for an ancestor folder with a matching type (e.g. Trash)
public InventoryFolderBase FindTopLevelFolderFor(UUID folderID)
{
IInventoryProviderSelector inventorySelect = ProviderRegistry.Instance.Get<IInventoryProviderSelector>();
IInventoryStorage provider = inventorySelect.GetProvider(m_userProfile.ID);
InventoryFolderBase folder;
try
{
folder = provider.FindTopLevelFolderFor(m_userProfile.ID, folderID);
}
catch
{
folder = null;
}
return folder;
}
// Load additional items that other regions have put into the database
// The item will be added tot he local cache. Returns true if the item
// was found and can be sent to the client
//
public bool QueryItem(UUID itemId)
{
try
{
IInventoryProviderSelector inventorySelect = ProviderRegistry.Instance.Get<IInventoryProviderSelector>();
InventoryItemBase itemInfo = inventorySelect.GetCheckedProvider(m_userProfile.ID).GetItem(m_userProfile.ID, itemId, UUID.Zero);
if (itemInfo != null)
{
ItemReceive(itemInfo, null);
return true;
}
}
catch (InventoryStorageException)
{
}
return false;
}
public bool QueryFolder(InventoryFolderBase folder)
{
return true;
}
public void MoveItemToTrash(InventoryItemBase item, InventoryFolderBase trashFolder)
{
IInventoryProviderSelector inventorySelect = ProviderRegistry.Instance.Get<IInventoryProviderSelector>();
inventorySelect.GetProvider(item.Owner).SendItemToTrash(item, trashFolder.ID);
}
public void CheckedDeleteItem(UUID userId, UUID inventoryID)
{
IInventoryProviderSelector selector = ProviderRegistry.Instance.Get<IInventoryProviderSelector>();
ICheckedInventoryStorage provider = selector.GetCheckedProvider(userId);
provider.PurgeItem(userId, inventoryID);
}
public InventoryFolderBase GetFolder(UUID folderId)
{
IInventoryProviderSelector selector = ProviderRegistry.Instance.Get<IInventoryProviderSelector>();
ICheckedInventoryStorage provider = selector.GetCheckedProvider(m_userProfile.ID);
return provider.GetFolder(m_userProfile.ID, folderId);
}
public void MoveItem(UUID itemId, UUID folderID)
{
IInventoryProviderSelector selector = ProviderRegistry.Instance.Get<IInventoryProviderSelector>();
ICheckedInventoryStorage provider = selector.GetCheckedProvider(m_userProfile.ID);
provider.MoveItem(m_userProfile.ID, itemId, folderID);
}
public void ModifyAndMoveItem(InventoryItemBase item, UUID folderID)
{
IInventoryProviderSelector selector = ProviderRegistry.Instance.Get<IInventoryProviderSelector>();
ICheckedInventoryStorage provider = selector.GetCheckedProvider(m_userProfile.ID);
provider.ModifyAndMoveItem(m_userProfile.ID, item, folderID);
}
}
/// <summary>
/// Should be implemented by callers which require a callback when the user's inventory is received
/// </summary>
public interface IInventoryRequest
{
/// <summary>
/// This is the method executed once we have received the user's inventory by which the request can be fulfilled.
/// </summary>
void Execute();
}
/// <summary>
/// Generic inventory request
/// </summary>
class InventoryRequest : IInventoryRequest
{
private Delegate m_delegate;
private Object[] m_args;
internal InventoryRequest(Delegate delegat, Object[] args)
{
m_delegate = delegat;
m_args = args;
}
public void Execute()
{
if (m_delegate != null)
m_delegate.DynamicInvoke(m_args);
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.PythonTools.Common;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Logging;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Imaging;
using Microsoft.VisualStudio.Imaging.Interop;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudioTools;
using Microsoft.VisualStudioTools.Project;
using Clipboard = System.Windows.Forms.Clipboard;
using Task = System.Threading.Tasks.Task;
using VsCommands2K = Microsoft.VisualStudio.VSConstants.VSStd2KCmdID;
using VsMenus = Microsoft.VisualStudioTools.Project.VsMenus;
namespace Microsoft.PythonTools.Project {
/// <summary>
/// Represents an interpreter as a node in the Solution Explorer.
/// </summary>
[ComVisible(true)]
internal class InterpretersNode : HierarchyNode {
private readonly IInterpreterRegistryService _interpreterService;
internal readonly IPythonInterpreterFactory _factory;
internal readonly IPackageManager _packageManager;
private readonly bool _isReference;
private readonly bool _canDelete, _canRemove;
private readonly string _captionSuffix;
private bool _suppressPackageRefresh;
private bool _checkedItems, _checkingItems, _disposed;
internal readonly string _absentId;
internal readonly bool _isGlobalDefault;
public static readonly object InstallPackageLockMoniker = new object();
public InterpretersNode(
PythonProjectNode project,
IPythonInterpreterFactory factory,
bool isInterpreterReference,
bool canDelete,
bool isGlobalDefault = false,
bool? canRemove = null
)
: base(project, MakeElement(project)) {
ExcludeNodeFromScc = true;
_interpreterService = project.Site.GetComponentModel().GetService<IInterpreterRegistryService>();
_factory = factory;
_isReference = isInterpreterReference;
_canDelete = canDelete;
_isGlobalDefault = isGlobalDefault;
_canRemove = canRemove.HasValue ? canRemove.Value : !isGlobalDefault;
_captionSuffix = isGlobalDefault ? Strings.GlobalDefaultSuffix : "";
var interpreterOpts = project.Site.GetComponentModel().GetService<IInterpreterOptionsService>();
_packageManager = interpreterOpts?.GetPackageManagers(factory).FirstOrDefault();
if (_packageManager != null) {
_packageManager.InstalledPackagesChanged += InstalledPackagesChanged;
_packageManager.EnableNotifications();
}
}
private InterpretersNode(PythonProjectNode project, string id) : base(project, MakeElement(project)) {
_absentId = id;
_canRemove = true;
_captionSuffix = Strings.MissingSuffix;
}
public static InterpretersNode CreateAbsentInterpreterNode(PythonProjectNode project, string id) {
return new InterpretersNode(project, id);
}
public override int MenuCommandId {
get { return PythonConstants.EnvironmentMenuId; }
}
public override Guid MenuGroupId {
get { return CommonGuidList.guidPythonToolsCmdSet; }
}
private static ProjectElement MakeElement(PythonProjectNode project) {
return new VirtualProjectElement(project);
}
public override void Close() {
if (!_disposed) {
if (_packageManager != null) {
_packageManager.InstalledPackagesChanged -= InstalledPackagesChanged;
}
}
_disposed = true;
base.Close();
}
private void InstalledPackagesChanged(object sender, EventArgs e) {
RefreshPackages();
}
private void RefreshPackages() {
RefreshPackagesAsync(_packageManager)
.SilenceException<OperationCanceledException>()
.HandleAllExceptions(ProjectMgr.Site, GetType())
.DoNotWait();
}
private async Task RefreshPackagesAsync(IPackageManager packageManager) {
if (_suppressPackageRefresh || packageManager == null) {
return;
}
bool prevChecked = _checkedItems;
// Use _checkingItems to prevent the expanded state from
// disappearing too quickly.
_checkingItems = true;
_checkedItems = true;
var packages = new Dictionary<string, PackageSpec>();
foreach (var p in await packageManager.GetInstalledPackagesAsync(CancellationToken.None)) {
packages[p.FullSpec] = p;
}
await ProjectMgr.Site.GetUIThread().InvokeAsync(() => {
if (ProjectMgr == null || ProjectMgr.IsClosed) {
return;
}
try {
var logger = ProjectMgr.Site.GetPythonToolsService().Logger;
if (logger != null) {
foreach (var p in packages) {
logger.LogEvent(PythonLogEvent.PythonPackage,
new PackageInfo {Name = p.Value.Name.ToLowerInvariant()});
}
}
} catch (Exception ex) {
Debug.Fail(ex.ToUnhandledExceptionMessage(GetType()));
}
bool anyChanges = false;
var existing = AllChildren.OfType<InterpretersPackageNode>().ToDictionary(c => c.Url);
// remove the nodes which were uninstalled.
foreach (var keyValue in existing) {
if (!packages.Remove(keyValue.Key)) {
RemoveChild(keyValue.Value);
anyChanges = true;
}
}
// add the new nodes
foreach (var p in packages.OrderBy(kv => kv.Key)) {
AddChild(new InterpretersPackageNode(ProjectMgr, p.Value));
anyChanges = true;
}
_checkingItems = false;
ProjectMgr.OnInvalidateItems(this);
if (!prevChecked) {
if (anyChanges) {
ProjectMgr.OnPropertyChanged(this, (int)__VSHPROPID.VSHPROPID_Expandable, 0);
}
if (ProjectMgr.ParentHierarchy != null) {
ExpandItem(EXPANDFLAGS.EXPF_CollapseFolder);
}
}
});
}
/// <summary>
/// Disables the file watcher. This function may be called as many times
/// as you like, but it only requires one call to
/// <see cref="ResumeWatching"/> to re-enable the watcher.
/// </summary>
public void StopWatching() {
_suppressPackageRefresh = true;
}
/// <summary>
/// Enables the file watcher, regardless of how many times
/// <see cref="StopWatching"/> was called. If the file watcher was
/// enabled successfully, the list of packages is updated.
/// </summary>
public void ResumeWatching() {
_suppressPackageRefresh = false;
RefreshPackagesAsync(_packageManager)
.SilenceException<OperationCanceledException>()
.HandleAllExceptions(ProjectMgr.Site, GetType())
.DoNotWait();
}
public override Guid ItemTypeGuid {
get { return PythonConstants.InterpreterItemTypeGuid; }
}
internal override int ExecCommandOnNode(Guid cmdGroup, uint cmd, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) {
if (cmdGroup == VsMenus.guidStandardCommandSet2K) {
switch ((VsCommands2K)cmd) {
case CommonConstants.OpenFolderInExplorerCmdId:
Process.Start(new ProcessStartInfo {
FileName = _factory.Configuration.GetPrefixPath(),
Verb = "open",
UseShellExecute = true
});
return VSConstants.S_OK;
}
}
if (cmdGroup == ProjectMgr.SharedCommandGuid) {
switch ((SharedCommands)cmd) {
case SharedCommands.OpenCommandPromptHere:
var pyProj = ProjectMgr as PythonProjectNode;
if (pyProj != null && _factory != null && _factory.Configuration != null) {
return pyProj.OpenCommandPrompt(
_factory.Configuration.GetPrefixPath(),
_factory.Configuration,
_factory.Configuration.Description
);
}
break;
case SharedCommands.CopyFullPath:
Clipboard.SetText(_factory.Configuration.InterpreterPath);
return VSConstants.S_OK;
}
}
return base.ExecCommandOnNode(cmdGroup, cmd, nCmdexecopt, pvaIn, pvaOut);
}
public new PythonProjectNode ProjectMgr {
get {
return (PythonProjectNode)base.ProjectMgr;
}
}
internal override bool CanDeleteItem(__VSDELETEITEMOPERATION deleteOperation) {
if (deleteOperation == __VSDELETEITEMOPERATION.DELITEMOP_RemoveFromProject) {
// Interpreter and InterpreterReference can both be removed from
// the project, but the default environment cannot
return _canRemove;
} else if (deleteOperation == __VSDELETEITEMOPERATION.DELITEMOP_DeleteFromStorage) {
// Only Interpreter can be deleted.
return _canDelete;
}
return false;
}
public override bool Remove(bool removeFromStorage) {
// If _canDelete, a prompt has already been shown by VS.
return Remove(removeFromStorage, !_canDelete);
}
private bool Remove(bool removeFromStorage, bool showPrompt) {
if (!_canRemove || (removeFromStorage && !_canDelete)) {
// Prevent the environment from being deleted or removed if not
// supported.
throw new NotSupportedException();
}
if (showPrompt && !Utilities.IsInAutomationFunction(ProjectMgr.Site)) {
string message = !removeFromStorage ?
Strings.EnvironmentRemoveConfirmation.FormatUI(Caption) :
_factory == null ?
Strings.EnvironmentDeleteConfirmation_NoPath.FormatUI(Caption) :
Strings.EnvironmentDeleteConfirmation.FormatUI(Caption, _factory.Configuration.GetPrefixPath());
int res = VsShellUtilities.ShowMessageBox(
ProjectMgr.Site,
string.Empty,
message,
OLEMSGICON.OLEMSGICON_WARNING,
OLEMSGBUTTON.OLEMSGBUTTON_OKCANCEL,
OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
if (res != 1) {
return false;
}
}
//Make sure we can edit the project file
if (!ProjectMgr.QueryEditProjectFile(false)) {
throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED);
}
if (!string.IsNullOrEmpty(_absentId)) {
Debug.Assert(!removeFromStorage, "Cannot remove absent environment from storage");
ProjectMgr.RemoveInterpreterFactory(_absentId);
return true;
}
if (_factory == null) {
Debug.Fail("Attempted to remove null factory from project");
return true;
}
ProjectMgr.RemoveInterpreter(_factory, !_isReference && removeFromStorage && _canDelete);
return true;
}
/// <summary>
/// Show interpreter display (description and version).
/// </summary>
public override string Caption {
get {
if (!string.IsNullOrEmpty(_absentId)) {
string company, tag;
if (CPythonInterpreterFactoryConstants.TryParseInterpreterId(_absentId, out company, out tag)) {
if (company == PythonRegistrySearch.PythonCoreCompany) {
company = "Python";
}
return "{0} {1}{2}".FormatUI(company, tag, _captionSuffix);
}
return _absentId + _captionSuffix;
}
if (_factory == null) {
Debug.Fail("null factory in interpreter node");
return "(null)";
}
return _factory.Configuration.Description + _captionSuffix;
}
}
/// <summary>
/// Prevent editing the description
/// </summary>
public override string GetEditLabel() {
return null;
}
protected override VSOVERLAYICON OverlayIconIndex {
get {
if (!Directory.Exists(Url)) {
return (VSOVERLAYICON)__VSOVERLAYICON2.OVERLAYICON_NOTONDISK;
} else if (_isReference) {
return VSOVERLAYICON.OVERLAYICON_SHORTCUT;
}
return base.OverlayIconIndex;
}
}
protected override bool SupportsIconMonikers {
get { return true; }
}
protected override ImageMoniker GetIconMoniker(bool open) {
if (_factory == null || !_factory.Configuration.IsAvailable()) {
// TODO: Find a better icon
return KnownMonikers.DocumentWarning;
} else if (ProjectMgr.ActiveInterpreter == _factory) {
return KnownMonikers.ActiveEnvironment;
}
// TODO: Change to PYEnvironment
return KnownMonikers.DockPanel;
}
/// <summary>
/// Interpreter node cannot be dragged.
/// </summary>
protected internal override string PrepareSelectedNodesForClipBoard() {
return null;
}
/// <summary>
/// Disable Copy/Cut/Paste commands on interpreter node.
/// </summary>
internal override int QueryStatusOnNode(Guid cmdGroup, uint cmd, IntPtr pCmdText, ref QueryStatusResult result) {
if (cmdGroup == VsMenus.guidStandardCommandSet2K) {
switch ((VsCommands2K)cmd) {
case CommonConstants.OpenFolderInExplorerCmdId:
result = QueryStatusResult.SUPPORTED;
if (_factory != null && Directory.Exists(_factory.Configuration.GetPrefixPath())) {
result |= QueryStatusResult.ENABLED;
}
return VSConstants.S_OK;
}
}
if (cmdGroup == CommonGuidList.guidPythonToolsCmdSet) {
switch (cmd) {
case PythonConstants.ActivateEnvironment:
result |= QueryStatusResult.SUPPORTED;
if (_factory != null && _factory.Configuration.IsAvailable() &&
ProjectMgr.ActiveInterpreter != _factory &&
Directory.Exists(_factory.Configuration.GetPrefixPath())
) {
result |= QueryStatusResult.ENABLED;
}
return VSConstants.S_OK;
case PythonConstants.InstallPythonPackage:
result |= QueryStatusResult.SUPPORTED;
if (_factory != null && _factory.Configuration.IsAvailable() &&
Directory.Exists(_factory.Configuration.GetPrefixPath())
) {
result |= QueryStatusResult.ENABLED;
}
return VSConstants.S_OK;
case PythonConstants.InstallRequirementsTxt:
result |= QueryStatusResult.SUPPORTED;
if (_factory != null && _factory.IsRunnable() &&
File.Exists(PathUtils.GetAbsoluteFilePath(ProjectMgr.ProjectHome, "requirements.txt"))) {
result |= QueryStatusResult.ENABLED;
}
return VSConstants.S_OK;
case PythonConstants.GenerateRequirementsTxt:
result |= QueryStatusResult.SUPPORTED;
if (_factory != null && _factory.Configuration.IsAvailable()) {
result |= QueryStatusResult.ENABLED;
}
return VSConstants.S_OK;
case PythonConstants.OpenInteractiveForEnvironment:
result |= QueryStatusResult.SUPPORTED;
if (_factory != null && _factory.Configuration.IsAvailable() &&
File.Exists(_factory.Configuration.InterpreterPath)
) {
result |= QueryStatusResult.ENABLED;
}
return VSConstants.S_OK;
}
}
if (cmdGroup == ProjectMgr.SharedCommandGuid) {
switch ((SharedCommands)cmd) {
case SharedCommands.OpenCommandPromptHere:
result |= QueryStatusResult.SUPPORTED;
if (_factory != null && _factory.Configuration.IsAvailable() &&
Directory.Exists(_factory.Configuration.GetPrefixPath()) &&
File.Exists(_factory.Configuration.InterpreterPath)) {
result |= QueryStatusResult.ENABLED;
}
return VSConstants.S_OK;
case SharedCommands.CopyFullPath:
result |= QueryStatusResult.SUPPORTED;
if (_factory != null && _factory.Configuration.IsAvailable() &&
Directory.Exists(_factory.Configuration.GetPrefixPath()) &&
File.Exists(_factory.Configuration.InterpreterPath)) {
result |= QueryStatusResult.ENABLED;
}
return VSConstants.S_OK;
}
}
return base.QueryStatusOnNode(cmdGroup, cmd, pCmdText, ref result);
}
public override string Url {
get {
if (!string.IsNullOrEmpty(_absentId)) {
return "UnknownInterpreter\\{0}".FormatInvariant(_absentId);
}
if (_factory == null) {
Debug.Fail("null factory in interpreter node");
return "UnknownInterpreter";
}
if (!PathUtils.IsValidPath(_factory.Configuration.GetPrefixPath())) {
return "UnknownInterpreter\\{0}".FormatInvariant(_factory.Configuration.Id);
}
return _factory.Configuration.GetPrefixPath();
}
}
/// <summary>
/// Defines whether this node is valid node for painting the interpreter
/// icon.
/// </summary>
protected override bool CanShowDefaultIcon() {
return true;
}
public override bool CanAddFiles {
get {
return false;
}
}
protected override NodeProperties CreatePropertiesObject() {
return new InterpretersNodeProperties(this);
}
public override object GetProperty(int propId) {
if (propId == (int)__VSHPROPID.VSHPROPID_Expandable) {
if (_packageManager == null) {
// No package manager, so we are not expandable
return false;
}
if (!_checkedItems) {
// We haven't checked if we have files on disk yet, report
// that we can expand until we do.
// We do this lazily so we don't need to spawn a process for
// each interpreter on project load.
ThreadPool.QueueUserWorkItem(_ => RefreshPackages());
return true;
} else if (_checkingItems) {
// Still checking, so keep reporting true.
return true;
}
}
return base.GetProperty(propId);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using Microsoft.Practices.Prism.Logging;
using Microsoft.Practices.Prism.MefExtensions.Properties;
using Microsoft.Practices.Prism.Modularity;
using Microsoft.Practices.Prism.Regions;
using Microsoft.Practices.ServiceLocation;
using System.Collections.Generic;
using System.Linq;
namespace Microsoft.Practices.Prism.MefExtensions
{
/// <summary>
/// Base class that provides a basic bootstrapping sequence that registers most of the Prism Library assets in a MEF <see cref="CompositionContainer"/>.
/// </summary>
/// <remarks>
/// This class must be overridden to provide application specific configuration.
/// </remarks>
public abstract class MefBootstrapper : Bootstrapper
{
/// <summary>
/// Gets or sets the default <see cref="AggregateCatalog"/> for the application.
/// </summary>
/// <value>The default <see cref="AggregateCatalog"/> instance.</value>
protected AggregateCatalog AggregateCatalog { get; set; }
/// <summary>
/// Gets or sets the default <see cref="CompositionContainer"/> for the application.
/// </summary>
/// <value>The default <see cref="CompositionContainer"/> instance.</value>
protected CompositionContainer Container { get; set; }
/// <summary>
/// Run the bootstrapper process.
/// </summary>
/// <param name="runWithDefaultConfiguration">If <see langword="true"/>, registers default
/// Prism Library services in the container. This is the default behavior.</param>
public override void Run(bool runWithDefaultConfiguration)
{
this.Logger = this.CreateLogger();
if (this.Logger == null)
{
throw new InvalidOperationException(Resources.NullLoggerFacadeException);
}
this.Logger.Log(Resources.LoggerWasCreatedSuccessfully, Category.Debug, Priority.Low);
this.Logger.Log(Resources.CreatingModuleCatalog, Category.Debug, Priority.Low);
this.ModuleCatalog = this.CreateModuleCatalog();
if (this.ModuleCatalog == null)
{
throw new InvalidOperationException(Resources.NullModuleCatalogException);
}
this.Logger.Log(Resources.ConfiguringModuleCatalog, Category.Debug, Priority.Low);
this.ConfigureModuleCatalog();
this.Logger.Log(Resources.CreatingCatalogForMEF, Category.Debug, Priority.Low);
this.AggregateCatalog = this.CreateAggregateCatalog();
this.Logger.Log(Resources.ConfiguringCatalogForMEF, Category.Debug, Priority.Low);
this.ConfigureAggregateCatalog();
this.RegisterDefaultTypesIfMissing();
this.Logger.Log(Resources.CreatingMefContainer, Category.Debug, Priority.Low);
this.Container = this.CreateContainer();
if (this.Container == null)
{
throw new InvalidOperationException(Resources.NullCompositionContainerException);
}
this.Logger.Log(Resources.ConfiguringMefContainer, Category.Debug, Priority.Low);
this.ConfigureContainer();
this.Logger.Log(Resources.ConfiguringServiceLocatorSingleton, Category.Debug, Priority.Low);
this.ConfigureServiceLocator();
this.Logger.Log(Resources.ConfiguringRegionAdapters, Category.Debug, Priority.Low);
this.ConfigureRegionAdapterMappings();
this.Logger.Log(Resources.ConfiguringDefaultRegionBehaviors, Category.Debug, Priority.Low);
this.ConfigureDefaultRegionBehaviors();
this.Logger.Log(Resources.RegisteringFrameworkExceptionTypes, Category.Debug, Priority.Low);
this.RegisterFrameworkExceptionTypes();
this.Logger.Log(Resources.CreatingShell, Category.Debug, Priority.Low);
this.Shell = this.CreateShell();
if (this.Shell != null)
{
this.Logger.Log(Resources.SettingTheRegionManager, Category.Debug, Priority.Low);
RegionManager.SetRegionManager(this.Shell, this.Container.GetExportedValue<IRegionManager>());
this.Logger.Log(Resources.UpdatingRegions, Category.Debug, Priority.Low);
RegionManager.UpdateRegions();
this.Logger.Log(Resources.InitializingShell, Category.Debug, Priority.Low);
this.InitializeShell();
}
IEnumerable<Lazy<object, object>> exports = this.Container.GetExports(typeof(IModuleManager), null, null);
if ((exports != null) && (exports.Count() > 0))
{
this.Logger.Log(Resources.InitializingModules, Category.Debug, Priority.Low);
this.InitializeModules();
}
this.Logger.Log(Resources.BootstrapperSequenceCompleted, Category.Debug, Priority.Low);
}
/// <summary>
/// Configures the <see cref="AggregateCatalog"/> used by MEF.
/// </summary>
/// <remarks>
/// The base implementation returns a new AggregateCatalog.
/// </remarks>
/// <returns>An <see cref="AggregateCatalog"/> to be used by the bootstrapper.</returns>
protected virtual AggregateCatalog CreateAggregateCatalog()
{
return new AggregateCatalog();
}
/// <summary>
/// Configures the <see cref="AggregateCatalog"/> used by MEF.
/// </summary>
/// <remarks>
/// The base implementation does nothing.
/// </remarks>
protected virtual void ConfigureAggregateCatalog()
{
}
/// <summary>
/// Creates the <see cref="CompositionContainer"/> that will be used as the default container.
/// </summary>
/// <returns>A new instance of <see cref="CompositionContainer"/>.</returns>
/// <remarks>
/// The base implementation registers a default MEF catalog of exports of key Prism types.
/// Exporting your own types will replace these defaults.
/// </remarks>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability",
"CA2000:Dispose objects before losing scope",
Justification = "The default export provider is in the container and disposed by MEF.")]
protected virtual CompositionContainer CreateContainer()
{
CompositionContainer container = new CompositionContainer(this.AggregateCatalog);
return container;
}
/// <summary>
/// Configures the <see cref="CompositionContainer"/>.
/// May be overwritten in a derived class to add specific type mappings required by the application.
/// </summary>
/// <remarks>
/// The base implementation registers all the types direct instantiated by the bootstrapper with the container.
/// If the method is overwritten, the new implementation should call the base class version.
/// </remarks>
protected virtual void ConfigureContainer()
{
this.RegisterBootstrapperProvidedTypes();
}
/// <summary>
/// Helper method for configuring the <see cref="CompositionContainer"/>.
/// Registers defaults for all the types necessary for Prism to work, if they are not already registered.
/// </summary>
public virtual void RegisterDefaultTypesIfMissing()
{
this.AggregateCatalog = DefaultPrismServiceRegistrar.RegisterRequiredPrismServicesIfMissing(this.AggregateCatalog);
}
/// <summary>
/// Helper method for configuring the <see cref="CompositionContainer"/>.
/// Registers all the types direct instantiated by the bootstrapper with the container.
/// </summary>
protected virtual void RegisterBootstrapperProvidedTypes()
{
this.Container.ComposeExportedValue<ILoggerFacade>(this.Logger);
this.Container.ComposeExportedValue<IModuleCatalog>(this.ModuleCatalog);
this.Container.ComposeExportedValue<IServiceLocator>(new MefServiceLocatorAdapter(this.Container));
this.Container.ComposeExportedValue<AggregateCatalog>(this.AggregateCatalog);
}
/// <summary>
/// Configures the LocatorProvider for the <see cref="Microsoft.Practices.ServiceLocation.ServiceLocator" />.
/// </summary>
/// <remarks>
/// The base implementation also sets the ServiceLocator provider singleton.
/// </remarks>
protected override void ConfigureServiceLocator()
{
IServiceLocator serviceLocator = this.Container.GetExportedValue<IServiceLocator>();
ServiceLocator.SetLocatorProvider(() => serviceLocator);
}
/// <summary>
/// Initializes the shell.
/// </summary>
/// <remarks>
/// The base implementation ensures the shell is composed in the container.
/// </remarks>
protected override void InitializeShell()
{
this.Container.ComposeParts(this.Shell);
}
/// <summary>
/// Initializes the modules. May be overwritten in a derived class to use a custom Modules Catalog
/// </summary>
protected override void InitializeModules()
{
IModuleManager manager = this.Container.GetExportedValue<IModuleManager>();
manager.Run();
}
}
}
| |
using System;
using System.Collections.Generic;
using Lucene.Net.Documents;
namespace Lucene.Net.Index
{
using NUnit.Framework;
using System.IO;
using BaseDirectory = Lucene.Net.Store.BaseDirectory;
using BufferedIndexInput = Lucene.Net.Store.BufferedIndexInput;
using Directory = Lucene.Net.Store.Directory;
using Document = Documents.Document;
using DocumentStoredFieldVisitor = DocumentStoredFieldVisitor;
using Field = Field;
using IndexInput = Lucene.Net.Store.IndexInput;
using IndexOutput = Lucene.Net.Store.IndexOutput;
using IOContext = Lucene.Net.Store.IOContext;
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 OpenMode_e = Lucene.Net.Index.IndexWriterConfig.OpenMode_e;
using TestUtil = Lucene.Net.Util.TestUtil;
[TestFixture]
public class TestFieldsReader : LuceneTestCase
{
private static Directory Dir;
private static Document TestDoc;
private static FieldInfos.Builder FieldInfos = null;
[TestFixtureSetUp]
public static void BeforeClass()
{
TestDoc = new Document();
FieldInfos = new FieldInfos.Builder();
DocHelper.SetupDoc(TestDoc);
foreach (IndexableField field in TestDoc)
{
FieldInfos.AddOrUpdate(field.Name(), field.FieldType());
}
Dir = NewDirectory();
IndexWriterConfig conf = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMergePolicy(NewLogMergePolicy());
conf.MergePolicy.NoCFSRatio = 0.0;
IndexWriter writer = new IndexWriter(Dir, conf);
writer.AddDocument(TestDoc);
writer.Dispose();
FaultyIndexInput.DoFail = false;
}
[TestFixtureTearDown]
public static void AfterClass()
{
Dir.Dispose();
Dir = null;
FieldInfos = null;
TestDoc = null;
}
[Test]
public virtual void Test()
{
Assert.IsTrue(Dir != null);
Assert.IsTrue(FieldInfos != null);
IndexReader reader = DirectoryReader.Open(Dir);
Document doc = reader.Document(0);
Assert.IsTrue(doc != null);
Assert.IsTrue(doc.GetField(DocHelper.TEXT_FIELD_1_KEY) != null);
Field field = (Field)doc.GetField(DocHelper.TEXT_FIELD_2_KEY);
Assert.IsTrue(field != null);
Assert.IsTrue(field.FieldType().StoreTermVectors);
Assert.IsFalse(field.FieldType().OmitNorms);
Assert.IsTrue(field.FieldType().IndexOptions == FieldInfo.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS);
field = (Field)doc.GetField(DocHelper.TEXT_FIELD_3_KEY);
Assert.IsTrue(field != null);
Assert.IsFalse(field.FieldType().StoreTermVectors);
Assert.IsTrue(field.FieldType().OmitNorms);
Assert.IsTrue(field.FieldType().IndexOptions == FieldInfo.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS);
field = (Field)doc.GetField(DocHelper.NO_TF_KEY);
Assert.IsTrue(field != null);
Assert.IsFalse(field.FieldType().StoreTermVectors);
Assert.IsFalse(field.FieldType().OmitNorms);
Assert.IsTrue(field.FieldType().IndexOptions == FieldInfo.IndexOptions.DOCS_ONLY);
DocumentStoredFieldVisitor visitor = new DocumentStoredFieldVisitor(DocHelper.TEXT_FIELD_3_KEY);
reader.Document(0, visitor);
IList<IndexableField> fields = visitor.Document.Fields;
Assert.AreEqual(1, fields.Count);
Assert.AreEqual(DocHelper.TEXT_FIELD_3_KEY, fields[0].Name());
reader.Dispose();
}
public class FaultyFSDirectory : BaseDirectory
{
internal Directory FsDir;
public FaultyFSDirectory(DirectoryInfo dir)
{
FsDir = NewFSDirectory(dir);
_lockFactory = FsDir.LockFactory;
}
public override IndexInput OpenInput(string name, IOContext context)
{
return new FaultyIndexInput(FsDir.OpenInput(name, context));
}
public override string[] ListAll()
{
return FsDir.ListAll();
}
public override bool FileExists(string name)
{
return FsDir.FileExists(name);
}
public override void DeleteFile(string name)
{
FsDir.DeleteFile(name);
}
public override long FileLength(string name)
{
return FsDir.FileLength(name);
}
public override IndexOutput CreateOutput(string name, IOContext context)
{
return FsDir.CreateOutput(name, context);
}
public override void Sync(ICollection<string> names)
{
FsDir.Sync(names);
}
public override void Dispose()
{
FsDir.Dispose();
}
}
private class FaultyIndexInput : BufferedIndexInput
{
internal IndexInput @delegate;
internal static bool DoFail;
internal int Count;
internal FaultyIndexInput(IndexInput @delegate)
: base("FaultyIndexInput(" + @delegate + ")", BufferedIndexInput.BUFFER_SIZE)
{
this.@delegate = @delegate;
}
internal virtual void SimOutage()
{
if (DoFail && Count++ % 2 == 1)
{
throw new IOException("Simulated network outage");
}
}
protected override void ReadInternal(byte[] b, int offset, int length)
{
SimOutage();
@delegate.Seek(FilePointer);
@delegate.ReadBytes(b, offset, length);
}
protected override void SeekInternal(long pos)
{
}
public override long Length()
{
return @delegate.Length();
}
public override void Dispose()
{
@delegate.Dispose();
}
public override object Clone()
{
FaultyIndexInput i = new FaultyIndexInput((IndexInput)@delegate.Clone());
// seek the clone to our current position
try
{
i.Seek(FilePointer);
}
catch (IOException e)
{
throw new Exception();
}
return i;
}
}
// LUCENE-1262
[Test]
public virtual void TestExceptions()
{
DirectoryInfo indexDir = CreateTempDir("testfieldswriterexceptions");
try
{
Directory dir = new FaultyFSDirectory(indexDir);
IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetOpenMode(OpenMode_e.CREATE);
IndexWriter writer = new IndexWriter(dir, iwc);
for (int i = 0; i < 2; i++)
{
writer.AddDocument(TestDoc);
}
writer.ForceMerge(1);
writer.Dispose();
IndexReader reader = DirectoryReader.Open(dir);
FaultyIndexInput.DoFail = true;
bool exc = false;
for (int i = 0; i < 2; i++)
{
try
{
reader.Document(i);
}
catch (IOException ioe)
{
// expected
exc = true;
}
try
{
reader.Document(i);
}
catch (IOException ioe)
{
// expected
exc = true;
}
}
Assert.IsTrue(exc);
reader.Dispose();
dir.Dispose();
}
finally
{
System.IO.Directory.Delete(indexDir.FullName, true);
}
}
}
}
| |
namespace WorkoutWotch.ViewModels
{
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Reactive;
using System.Reactive.Concurrency;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Windows.Input;
using Genesis.Ensure;
using Genesis.Logging;
using ReactiveUI;
using WorkoutWotch.Models;
public delegate ExerciseProgramViewModel ExerciseProgramViewModelFactory(ExerciseProgram model);
public sealed class ExerciseProgramViewModel : ReactiveObject, IRoutableViewModel, ISupportsActivation
{
// if an exercise has progressed less that this threshold and the user skips backwards, we will skip to the prior exercise
// otherwise, we'll return to the start of the current exercise
private static readonly TimeSpan skipBackwardsThreshold = TimeSpan.FromMilliseconds(500);
private readonly ViewModelActivator activator;
private readonly ILogger logger;
private readonly IScheduler scheduler;
private readonly ExerciseProgram model;
private readonly IScreen hostScreen;
private readonly ReactiveCommand<TimeSpan?, Unit> startCommand;
private readonly ReactiveCommand<Unit, Unit> pauseCommand;
private readonly ReactiveCommand<Unit, Unit> resumeCommand;
private readonly ReactiveCommand<Unit, Unit> skipBackwardsCommand;
private readonly ReactiveCommand<Unit, Unit> skipForwardsCommand;
private readonly ICommand playbackCommand;
private readonly IImmutableList<ExerciseViewModel> exercises;
private readonly ObservableAsPropertyHelper<bool> isStarted;
private readonly ObservableAsPropertyHelper<bool> isPaused;
private readonly ObservableAsPropertyHelper<bool> isStartVisible;
private readonly ObservableAsPropertyHelper<bool> isPauseVisible;
private readonly ObservableAsPropertyHelper<bool> isResumeVisible;
private readonly ObservableAsPropertyHelper<TimeSpan> progressTimeSpan;
private readonly ObservableAsPropertyHelper<double> progress;
private readonly ObservableAsPropertyHelper<ExerciseViewModel> currentExercise;
private ExecutionContext executionContext;
public ExerciseProgramViewModel(
ExerciseViewModelFactory exerciseViewModelFactory,
IScheduler scheduler,
IScreen hostScreen,
ExerciseProgram model)
{
Ensure.ArgumentNotNull(exerciseViewModelFactory, nameof(exerciseViewModelFactory));
Ensure.ArgumentNotNull(scheduler, nameof(scheduler));
Ensure.ArgumentNotNull(hostScreen, nameof(hostScreen));
Ensure.ArgumentNotNull(model, nameof(model));
this.logger = LoggerService.GetLogger(this.GetType());
using (this.logger.Perf("Construction"))
{
this.activator = new ViewModelActivator();
this.scheduler = scheduler;
this.model = model;
this.hostScreen = hostScreen;
this.exercises = this
.model
.Exercises
.Select(exercise => exerciseViewModelFactory(exercise, this.WhenAnyValue(y => y.ExecutionContext)))
.ToImmutableList();
this.isStarted = this
.WhenAnyValue(
x => x.ExecutionContext,
x => x.ExecutionContext.IsCancelled,
(ec, isCancelled) => ec != null && !isCancelled)
.ToProperty(this, x => x.IsStarted, scheduler: scheduler);
this.isPaused = this
.WhenAnyValue(x => x.ExecutionContext)
.Select(x => x == null ? Observables.False : x.WhenAnyValue(y => y.IsPaused))
.Switch()
.ToProperty(this, x => x.IsPaused, scheduler: scheduler);
this.progressTimeSpan = this
.WhenAnyValue(x => x.ExecutionContext)
.Select(x => x == null ? Observable.Return(TimeSpan.Zero) : x.WhenAnyValue(y => y.Progress))
.Switch()
.ToProperty(this, x => x.ProgressTimeSpan, scheduler: scheduler);
this.progress = this
.WhenAnyValue(x => x.ProgressTimeSpan)
.Select(x => x.TotalMilliseconds / this.model.Duration.TotalMilliseconds)
.ToProperty(this, x => x.Progress);
this.currentExercise = this
.WhenAnyValue(
x => x.ExecutionContext,
x => x.ExecutionContext.CurrentExercise,
(ec, currentExercise) => ec == null ? null : currentExercise)
.Select(x => this.Exercises.SingleOrDefault(y => y.Model == x))
.ToProperty(this, x => x.CurrentExercise, scheduler: scheduler);
var canStart = this
.WhenAnyValue(x => x.IsStarted)
.Select(x => !x);
this.startCommand = ReactiveCommand
.CreateFromObservable<TimeSpan?, Unit>(this.OnStart, canStart, scheduler);
var canPause = this
.WhenAnyValue(x => x.IsStarted)
.CombineLatest(this.WhenAnyValue(x => x.ExecutionContext.IsPaused), (isStarted, isPaused) => isStarted && !isPaused)
.ObserveOn(scheduler);
this.pauseCommand = ReactiveCommand
.CreateFromObservable(this.OnPause, canPause, scheduler);
var canResume = this
.WhenAnyValue(x => x.IsStarted)
.CombineLatest(this.WhenAnyValue(x => x.ExecutionContext.IsPaused), (isStarted, isPaused) => isStarted && isPaused)
.ObserveOn(scheduler);
this.resumeCommand = ReactiveCommand
.CreateFromObservable(this.OnResume, canResume, scheduler);
var canSkipBackwards = this
.WhenAnyValue(
x => x.ExecutionContext,
x => x.ProgressTimeSpan,
(ec, progress) => new { ExecutionContext = ec, Progress = progress })
.Select(x => x.ExecutionContext != null && x.Progress >= skipBackwardsThreshold)
.ObserveOn(scheduler);
this.skipBackwardsCommand = ReactiveCommand
.CreateFromObservable(this.OnSkipBackwards, canSkipBackwards, scheduler);
var canSkipForwards = this
.WhenAnyValue(
x => x.ExecutionContext,
x => x.CurrentExercise,
(ec, currentExercise) => new { ExecutionContext = ec, CurrentExercise = currentExercise })
.Select(x => x.ExecutionContext != null && x.CurrentExercise != null && x.CurrentExercise != this.exercises.LastOrDefault())
.ObserveOn(scheduler);
this.skipForwardsCommand = ReactiveCommand
.CreateFromObservable(this.OnSkipForwards, canSkipForwards, scheduler);
this.isStartVisible = this
.startCommand
.CanExecute
.ToProperty(this, x => x.IsStartVisible);
this.isPauseVisible = this
.pauseCommand
.CanExecute
.ToProperty(this, x => x.IsPauseVisible);
this.isResumeVisible = this
.resumeCommand
.CanExecute
.ToProperty(this, x => x.IsResumeVisible);
this.startCommand
.ThrownExceptions
.SubscribeSafe(ex => this.OnThrownException("start", ex));
this.pauseCommand
.ThrownExceptions
.SubscribeSafe(ex => this.OnThrownException("pause", ex));
this.resumeCommand
.ThrownExceptions
.SubscribeSafe(ex => this.OnThrownException("resume", ex));
this.skipBackwardsCommand
.ThrownExceptions
.SubscribeSafe(ex => this.OnThrownException("skip backwards", ex));
this.skipForwardsCommand
.ThrownExceptions
.SubscribeSafe(ex => this.OnThrownException("skip forwards", ex));
// we don't use a reactive command here because switching in different commands causes it to get confused and
// command binding leaves the target button disabled. We could also have not used command binding to get around
// this problem
this.playbackCommand = new PlaybackCommandImpl(this);
this
.WhenActivated(
disposables =>
{
using (this.logger.Perf("Activation"))
{
// cancel the exercise program if the user navigates away
this
.hostScreen
.Router
.NavigationStack
.ItemsRemoved
.OfType<ExerciseProgramViewModel>()
.SelectMany(x => x.Stop())
.SubscribeSafe()
.AddTo(disposables);
}
});
}
}
public ViewModelActivator Activator => this.activator;
public IScreen HostScreen => this.hostScreen;
public string UrlPathSegment => this.Name;
public string Name => this.model.Name;
public TimeSpan Duration => this.model.Duration;
public TimeSpan ProgressTimeSpan => this.progressTimeSpan.Value;
public double Progress => this.progress.Value;
public IImmutableList<ExerciseViewModel> Exercises => this.exercises;
public ExerciseViewModel CurrentExercise => this.currentExercise.Value;
public bool IsStarted => this.isStarted.Value;
public bool IsPaused => this.isPaused.Value;
public bool IsStartVisible => this.isStartVisible.Value;
public bool IsPauseVisible => this.isPauseVisible.Value;
public bool IsResumeVisible => this.isResumeVisible.Value;
public ReactiveCommand<TimeSpan?, Unit> StartCommand => this.startCommand;
public ReactiveCommand<Unit, Unit> PauseCommand => this.pauseCommand;
public ReactiveCommand<Unit, Unit> ResumeCommand => this.resumeCommand;
public ReactiveCommand<Unit, Unit> SkipBackwardsCommand => this.skipBackwardsCommand;
public ReactiveCommand<Unit, Unit> SkipForwardsCommand => this.skipForwardsCommand;
public ICommand PlaybackCommand => this.playbackCommand;
private ExecutionContext ExecutionContext
{
get { return this.executionContext; }
set { this.RaiseAndSetIfChanged(ref this.executionContext, value); }
}
private IObservable<Unit> OnStart(TimeSpan? skipAhead) =>
this.Start(skipAhead.GetValueOrDefault(TimeSpan.Zero));
private IObservable<Unit> OnPause() =>
Observable
.Start(() => this.ExecutionContext.IsPaused = true, this.scheduler)
.ToSignal();
private IObservable<Unit> OnResume() =>
Observable
.Start(() => this.ExecutionContext.IsPaused = false, this.scheduler)
.ToSignal();
private IObservable<Unit> OnSkipBackwards() =>
this.SkipBackwards();
private IObservable<Unit> OnSkipForwards() =>
this.SkipForwards();
private IObservable<Unit> Start(TimeSpan skipTo = default(TimeSpan), bool isPaused = false)
{
this.logger.Debug("Starting {0} from {1}.", isPaused ? "paused" : "unpaused", skipTo);
var executionContext = new ExecutionContext(skipTo)
{
IsPaused = isPaused
};
return Observable
.Using(
() => Disposable.Create(() => this.ExecutionContext = null),
_ =>
Observable
.Start(() => this.ExecutionContext = executionContext, this.scheduler)
.SelectMany(__ => this.model.Execute(executionContext)))
.Catch<Unit, OperationCanceledException>(_ => Observables.Unit);
}
public IObservable<Unit> Stop()
{
this.logger.Debug("Stopping.");
var executionContext = this.ExecutionContext;
if (executionContext == null)
{
this.logger.Warn("Execution context is null - cannot stop.");
return Observables.Unit;
}
executionContext.Cancel();
return this
.WhenAnyValue(x => x.IsStarted)
.Where(x => !x)
.ToSignal()
.Do(_ => this.logger.Debug("Stop completed."))
.FirstAsync();
}
private IObservable<Unit> SkipBackwards()
{
this.logger.Debug("Skipping backwards.");
var executionContext = this.ExecutionContext;
if (executionContext == null)
{
this.logger.Warn("Execution context is null - cannot skip backwards.");
return Observables.Unit;
}
var totalProgress = executionContext.Progress;
var currentExerciseProgress = executionContext.CurrentExerciseProgress;
var currentExercise = executionContext.CurrentExercise;
var isPaused = executionContext.IsPaused;
Exercise priorExercise = null;
foreach (var exercise in this.exercises)
{
if (exercise.Model == currentExercise)
{
break;
}
priorExercise = exercise.Model;
}
return this
.Stop()
.Do(
_ =>
{
var skipTo = totalProgress -
currentExerciseProgress -
(currentExerciseProgress < skipBackwardsThreshold && priorExercise != null ? priorExercise.Duration : TimeSpan.Zero);
this
.Start(skipTo, isPaused)
.SubscribeSafe();
this.logger.Debug("Skip backwards completed.");
})
.FirstAsync();
}
private IObservable<Unit> SkipForwards()
{
this.logger.Debug("Skipping forwards.");
var executionContext = this.ExecutionContext;
if (executionContext == null)
{
this.logger.Warn("Execution context is null - cannot skip forwards.");
return Observables.Unit;
}
var totalProgress = executionContext.Progress;
var currentExerciseProgress = executionContext.CurrentExerciseProgress;
var currentExercise = executionContext.CurrentExercise;
var isPaused = executionContext.IsPaused;
return this
.Stop()
.Do(
_ =>
{
this
.Start(totalProgress - currentExerciseProgress + currentExercise.Duration, isPaused)
.SubscribeSafe();
this.logger.Debug("Skip forwards completed.");
})
.FirstAsync();
}
private void OnThrownException(string source, Exception exception)
{
this.logger.Error(exception, "An unhandled exception occurred in the {0} command handler.", source);
// don't just swallow it - now that we've logged it, make sure it isn't ignored
throw new InvalidOperationException("Unhandled exception in command handler.", exception);
}
private sealed class PlaybackCommandImpl : ICommand
{
private readonly ExerciseProgramViewModel owner;
public PlaybackCommandImpl(ExerciseProgramViewModel owner)
{
this.owner = owner;
}
#pragma warning disable CS0067
public event EventHandler CanExecuteChanged;
#pragma warning restore CS0067
public bool CanExecute(object parameter) =>
true;
public void Execute(object parameter)
{
if (this.owner.IsStartVisible)
{
this
.owner
.StartCommand
.Execute((TimeSpan?)parameter)
.SubscribeSafe();
}
else if (this.owner.IsPauseVisible)
{
this
.owner
.PauseCommand
.Execute()
.SubscribeSafe();
}
else
{
this
.owner
.ResumeCommand
.Execute()
.SubscribeSafe();
}
}
}
}
}
| |
//
// InternetRadioSource.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2008 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 System.Collections.Generic;
using Mono.Unix;
using Gtk;
using Hyena;
using Banshee.Base;
using Banshee.Sources;
using Banshee.Streaming;
using Banshee.ServiceStack;
using Banshee.Collection;
using Banshee.Collection.Database;
using Banshee.Configuration;
using Banshee.PlaybackController;
using Banshee.Gui;
using Banshee.Sources.Gui;
namespace Banshee.InternetRadio
{
public class InternetRadioSource : PrimarySource, IDisposable, IBasicPlaybackController
{
private InternetRadioSourceContents source_contents;
private uint ui_id;
public InternetRadioSource () : base (Catalog.GetString ("Radio"), Catalog.GetString ("Radio"), "internet-radio", 220)
{
Properties.SetString ("Icon.Name", "radio");
TypeUniqueId = "internet-radio";
IsLocal = false;
AfterInitialized ();
InterfaceActionService uia_service = ServiceManager.Get<InterfaceActionService> ();
uia_service.GlobalActions.AddImportant (
new ActionEntry ("AddRadioStationAction", Stock.Add,
Catalog.GetString ("Add Station"), null,
Catalog.GetString ("Add a new Internet Radio station or playlist"),
OnAddStation)
);
ui_id = uia_service.UIManager.AddUiFromResource ("GlobalUI.xml");
Properties.SetString ("ActiveSourceUIResource", "ActiveSourceUI.xml");
Properties.Set<bool> ("ActiveSourceUIResourcePropagate", true);
Properties.Set<System.Reflection.Assembly> ("ActiveSourceUIResource.Assembly", typeof(InternetRadioSource).Assembly);
Properties.SetString ("GtkActionPath", "/InternetRadioContextMenu");
source_contents = new InternetRadioSourceContents ();
Properties.Set<bool> ("Nereid.SourceContentsPropagate", true);
Properties.Set<ISourceContents> ("Nereid.SourceContents", source_contents);
Properties.SetString ("TrackEditorActionLabel", Catalog.GetString ("Edit Station"));
Properties.Set<InvokeHandler> ("TrackEditorActionHandler", delegate {
ITrackModelSource active_track_model_source =
(ITrackModelSource) ServiceManager.SourceManager.ActiveSource;
if (active_track_model_source.TrackModel.SelectedItems == null ||
active_track_model_source.TrackModel.SelectedItems.Count <= 0) {
return;
}
foreach (TrackInfo track in active_track_model_source.TrackModel.SelectedItems) {
DatabaseTrackInfo station_track = track as DatabaseTrackInfo;
if (station_track != null) {
EditStation (station_track);
return;
}
}
});
Properties.SetString ("TrackView.ColumnControllerXml", String.Format (@"
<column-controller>
<!--<column modify-default=""IndicatorColumn"">
<renderer type=""Banshee.Podcasting.Gui.ColumnCellPodcastStatusIndicator"" />
</column>-->
<add-default column=""IndicatorColumn"" />
<add-default column=""GenreColumn"" />
<column modify-default=""GenreColumn"">
<visible>false</visible>
</column>
<add-default column=""TitleColumn"" />
<column modify-default=""TitleColumn"">
<title>{0}</title>
<long-title>{0}</long-title>
</column>
<add-default column=""ArtistColumn"" />
<column modify-default=""ArtistColumn"">
<title>{1}</title>
<long-title>{1}</long-title>
</column>
<add-default column=""CommentColumn"" />
<column modify-default=""CommentColumn"">
<title>{2}</title>
<long-title>{2}</long-title>
</column>
<add-default column=""RatingColumn"" />
<add-default column=""PlayCountColumn"" />
<add-default column=""LastPlayedColumn"" />
<add-default column=""LastSkippedColumn"" />
<add-default column=""DateAddedColumn"" />
<add-default column=""UriColumn"" />
<sort-column direction=""asc"">genre</sort-column>
</column-controller>",
Catalog.GetString ("Station"),
Catalog.GetString ("Creator"),
Catalog.GetString ("Description")
));
ServiceManager.PlayerEngine.TrackIntercept += OnPlayerEngineTrackIntercept;
//ServiceManager.PlayerEngine.ConnectEvent (OnTrackInfoUpdated, Banshee.MediaEngine.PlayerEvent.TrackInfoUpdated);
TrackEqualHandler = delegate (DatabaseTrackInfo a, TrackInfo b) {
RadioTrackInfo radio_track = b as RadioTrackInfo;
return radio_track != null && DatabaseTrackInfo.TrackEqual (
radio_track.ParentTrack as DatabaseTrackInfo, a);
};
if (new XspfMigrator (this).Migrate ()) {
Reload ();
}
}
protected override IEnumerable<IFilterListModel> CreateFiltersFor (DatabaseSource src)
{
DatabaseQueryFilterModel<string> genre_model = new DatabaseQueryFilterModel<string> (src, src.DatabaseTrackModel, ServiceManager.DbConnection,
Catalog.GetString ("All Genres ({0})"), src.UniqueId, Banshee.Query.BansheeQuery.GenreField, "Genre");
if (this == src) {
this.genre_model = genre_model;
}
yield return genre_model;
}
public override void Dispose ()
{
base.Dispose ();
//ServiceManager.PlayerEngine.DisconnectEvent (OnTrackInfoUpdated);
InterfaceActionService uia_service = ServiceManager.Get<InterfaceActionService> ();
if (uia_service == null) {
return;
}
if (ui_id > 0) {
uia_service.UIManager.RemoveUi (ui_id);
uia_service.GlobalActions.Remove ("AddRadioStationAction");
ui_id = 0;
}
ServiceManager.PlayerEngine.TrackIntercept -= OnPlayerEngineTrackIntercept;
}
// TODO the idea with this is to grab and display cover art when we get updated info
// for a radio station (eg it changes song and lets us know). The problem is I'm not sure
// if that info ever/usually includes the album name, and also we would probably want to mark
// such downloaded/cached cover art as temporary.
/*private void OnTrackInfoUpdated (Banshee.MediaEngine.PlayerEventArgs args)
{
RadioTrackInfo radio_track = ServiceManager.PlaybackController.CurrentTrack as RadioTrackInfo;
if (radio_track != null) {
Banshee.Metadata.MetadataService.Instance.Lookup (radio_track);
}
}*/
private bool OnPlayerEngineTrackIntercept (TrackInfo track)
{
DatabaseTrackInfo station = track as DatabaseTrackInfo;
if (station == null || station.PrimarySource != this) {
return false;
}
new RadioTrackInfo (station).Play ();
return true;
}
private void OnAddStation (object o, EventArgs args)
{
EditStation (null);
}
private void EditStation (DatabaseTrackInfo track)
{
StationEditor editor = new StationEditor (track);
editor.Response += OnStationEditorResponse;
editor.Show ();
}
private void OnStationEditorResponse (object o, ResponseArgs args)
{
StationEditor editor = (StationEditor)o;
bool destroy = true;
try {
if (args.ResponseId == ResponseType.Ok) {
DatabaseTrackInfo track = editor.Track ?? new DatabaseTrackInfo ();
track.PrimarySource = this;
track.IsLive = true;
try {
track.Uri = new SafeUri (editor.StreamUri);
} catch {
destroy = false;
editor.ErrorMessage = Catalog.GetString ("Please provide a valid station URI");
}
if (!String.IsNullOrEmpty (editor.StationCreator)) {
track.ArtistName = editor.StationCreator;
}
track.Comment = editor.Description;
if (!String.IsNullOrEmpty (editor.Genre)) {
track.Genre = editor.Genre;
} else {
destroy = false;
editor.ErrorMessage = Catalog.GetString ("Please provide a station genre");
}
if (!String.IsNullOrEmpty (editor.StationTitle)) {
track.TrackTitle = editor.StationTitle;
track.AlbumTitle = editor.StationTitle;
} else {
destroy = false;
editor.ErrorMessage = Catalog.GetString ("Please provide a station title");
}
track.Rating = editor.Rating;
if (destroy) {
track.Save ();
}
}
} finally {
if (destroy) {
editor.Response -= OnStationEditorResponse;
editor.Destroy ();
}
}
}
#region IBasicPlaybackController implementation
public bool First ()
{
return false;
}
public bool Next (bool restart)
{
RadioTrackInfo radio_track = ServiceManager.PlaybackController.CurrentTrack as RadioTrackInfo;
if (radio_track != null && radio_track.PlayNextStream ()) {
return true;
} else {
return false;
}
}
public bool Previous (bool restart)
{
RadioTrackInfo radio_track = ServiceManager.PlaybackController.CurrentTrack as RadioTrackInfo;
if (radio_track != null && radio_track.PlayPreviousStream ()) {
return true;
} else {
return false;
}
}
#endregion
public override bool AcceptsInputFromSource (Source source)
{
return false;
}
public override bool CanDeleteTracks {
get { return false; }
}
public override bool ShowBrowser {
get { return true; }
}
public override bool CanRename {
get { return false; }
}
protected override bool HasArtistAlbum {
get { return false; }
}
public override bool HasViewableTrackProperties {
get { return false; }
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using Xunit;
using Shouldly;
using System.Linq;
using System.Dynamic;
using System.Linq.Expressions;
namespace AutoMapper.UnitTests.ArraysAndLists
{
public class When_mapping_to_an_array_as_ICollection_with_MapAtRuntime : AutoMapperSpecBase
{
Destination _destination;
SourceItem[] _sourceItems = new [] { new SourceItem { Value = "1" }, new SourceItem { Value = "2" }, new SourceItem { Value = "3" } };
public class Source
{
public ICollection<SourceItem> Items { get; set; }
}
public class Destination
{
public ICollection<DestinationItem> Items { get; set; }
}
public class SourceItem
{
public string Value { get; set; }
}
public class DestinationItem
{
public string Value { get; set; }
}
protected override MapperConfiguration Configuration => new MapperConfiguration(c =>
{
c.CreateMap<Source, Destination>().ForMember(d=>d.Items, o=>o.MapAtRuntime());
c.CreateMap<SourceItem, DestinationItem>();
});
protected override void Because_of()
{
var source = new Source { Items = _sourceItems };
_destination = Mapper.Map(source, new Destination { Items = new[] { new DestinationItem { Value = "4" } } });
}
[Fact]
public void Should_map_ok()
{
_destination.Items.Select(i => i.Value).SequenceEqual(_sourceItems.Select(i => i.Value)).ShouldBeTrue();
}
}
public class When_mapping_an_array : AutoMapperSpecBase
{
decimal[] _source = Enumerable.Range(1, 10).Select(i=>(decimal)i).ToArray();
decimal[] _destination;
protected override MapperConfiguration Configuration => new MapperConfiguration(c =>{});
protected override void Because_of()
{
_destination = Mapper.Map<decimal[]>(_source);
}
[Fact]
public void Should_return_a_copy()
{
_destination.ShouldNotBeSameAs(_source);
}
}
public class When_mapping_a_primitive_array : AutoMapperSpecBase
{
int[] _source = Enumerable.Range(1, 10).ToArray();
long[] _destination;
protected override MapperConfiguration Configuration => new MapperConfiguration(c =>{});
protected override void Because_of()
{
_destination = Mapper.Map<long[]>(_source);
}
[Fact]
public void Should_return_a_copy()
{
var source = new int[] {1, 2, 3, 4};
var dest = new long[4];
Array.Copy(source, dest, 4);
dest[3].ShouldBe(4L);
var plan = Configuration.BuildExecutionPlan(typeof(int[]), typeof(long[]));
_destination.ShouldNotBeSameAs(_source);
}
}
public class When_mapping_a_primitive_array_with_custom_mapping_function : AutoMapperSpecBase
{
int[] _source = Enumerable.Range(1, 10).ToArray();
int[] _destination;
protected override MapperConfiguration Configuration => new MapperConfiguration(c => c.CreateMap<int, int>().ConstructUsing(i => i * 1000));
protected override void Because_of()
{
_destination = Mapper.Map<int[]>(_source);
}
[Fact]
public void Should_map_each_item()
{
for (var i = 0; i < _source.Length; i++)
{
_destination[i].ShouldBe((i+1) * 1000);
}
}
}
public class When_mapping_a_primitive_array_with_custom_object_mapper : AutoMapperSpecBase
{
int[] _source = Enumerable.Range(1, 10).ToArray();
int[] _destination;
private class IntToIntMapper : IObjectMapper
{
public bool IsMatch(TypePair context)
=> context.SourceType == typeof(int) && context.DestinationType == typeof(int);
public Expression MapExpression(IConfigurationProvider configurationProvider, ProfileMap profileMap,
IMemberMap memberMap,
Expression sourceExpression, Expression destExpression, Expression contextExpression)
=> Expression.Multiply(Expression.Convert(sourceExpression, typeof(int)), Expression.Constant(1000));
}
protected override MapperConfiguration Configuration => new MapperConfiguration(c => c.Mappers.Insert(0, new IntToIntMapper()));
protected override void Because_of()
{
_destination = Mapper.Map<int[]>(_source);
}
[Fact]
public void Should_not_use_custom_mapper_but_probably_should()
{
for (var i = 0; i < _source.Length; i++)
{
_destination[i].ShouldBe(i + 1);
}
}
}
public class When_mapping_null_list_to_array: AutoMapperSpecBase
{
Destination _destination;
class Source
{
public List<SourceItem> Items { get; set; }
}
class Destination
{
public DestinationItem[] Items { get; set; }
}
class SourceItem
{
public int Value { get; set; }
}
class DestinationItem
{
public int Value { get; set; }
}
protected override MapperConfiguration Configuration => new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>();
cfg.CreateMap<SourceItem, DestinationItem>();
});
protected override void Because_of()
{
_destination = Mapper.Map<Destination>(new Source());
}
[Fact]
public void Should_map_ok()
{
_destination.Items.Length.ShouldBe(0);
}
}
public class When_mapping_null_array_to_list : AutoMapperSpecBase
{
Destination _destination;
class Source
{
public SourceItem[] Items { get; set; }
}
class Destination
{
public List<DestinationItem> Items { get; set; }
}
class SourceItem
{
public int Value { get; set; }
}
class DestinationItem
{
public int Value { get; set; }
}
protected override MapperConfiguration Configuration => new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>();
cfg.CreateMap<SourceItem, DestinationItem>();
});
protected override void Because_of()
{
_destination = Mapper.Map<Destination>(new Source());
}
[Fact]
public void Should_map_ok()
{
_destination.Items.Count.ShouldBe(0);
}
}
public class When_mapping_collections : AutoMapperSpecBase
{
Author mappedAuthor;
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(delegate{});
protected override void Because_of()
{
dynamic authorDynamic = new ExpandoObject();
authorDynamic.Name = "Charles Dickens";
dynamic book1 = new ExpandoObject();
book1.Name = "Great Expectations";
dynamic book2 = new ExpandoObject();
book2.Name = "Oliver Twist";
authorDynamic.Books = new List<object> { book1, book2 };
mappedAuthor = Mapper.Map<Author>(authorDynamic);
}
[Fact]
public void Should_map_by_item_type()
{
mappedAuthor.Name.ShouldBe("Charles Dickens");
mappedAuthor.Books[0].Name.ShouldBe("Great Expectations");
mappedAuthor.Books[1].Name.ShouldBe("Oliver Twist");
}
public class Author
{
public string Name { get; set; }
public Book[] Books { get; set; }
}
public class Book
{
public string Name { get; set; }
}
}
public class When_mapping_to_an_existing_array_typed_as_IEnumerable : AutoMapperSpecBase
{
private Destination _destination = new Destination();
public class Source
{
public int[] IntCollection { get; set; } = new int[0];
}
public class Destination
{
public IEnumerable<int> IntCollection { get; set; } = new[] { 1, 2, 3, 4, 5 };
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>();
});
protected override void Because_of()
{
_destination = Mapper.Map(new Source(), _destination);
}
[Fact]
public void Should_create_destination_array_the_same_size_as_the_source()
{
_destination.IntCollection.Count().ShouldBe(0);
}
}
public class When_mapping_to_a_concrete_non_generic_ienumerable : AutoMapperSpecBase
{
private Destination _destination;
public class Source
{
public int[] Values { get; set; }
public List<int> Values2 { get; set; }
}
public class Destination
{
public IEnumerable Values { get; set; }
public IEnumerable Values2 { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>();
});
protected override void Because_of()
{
_destination = Mapper.Map<Source, Destination>(new Source { Values = new[] { 1, 2, 3, 4 }, Values2 = new List<int> { 9, 8, 7, 6 } });
}
[Fact]
public void Should_map_the_list_of_source_items()
{
_destination.Values.ShouldNotBeNull();
_destination.Values.ShouldContain(1);
_destination.Values.ShouldContain(2);
_destination.Values.ShouldContain(3);
_destination.Values.ShouldContain(4);
}
[Fact]
public void Should_map_from_the_generic_list_of_values()
{
_destination.Values2.ShouldNotBeNull();
_destination.Values2.ShouldContain(9);
_destination.Values2.ShouldContain(8);
_destination.Values2.ShouldContain(7);
_destination.Values2.ShouldContain(6);
}
}
public class When_mapping_to_a_concrete_generic_ienumerable : AutoMapperSpecBase
{
private Destination _destination;
public class Source
{
public int[] Values { get; set; }
public List<int> Values2 { get; set; }
}
public class Destination
{
public IEnumerable<int> Values { get; set; }
public IEnumerable<string> Values2 { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>();
});
protected override void Because_of()
{
_destination = Mapper.Map<Source, Destination>(new Source { Values = new[] { 1, 2, 3, 4 }, Values2 = new List<int> { 9, 8, 7, 6 } });
}
[Fact]
public void Should_map_the_list_of_source_items()
{
_destination.Values.ShouldNotBeNull();
_destination.Values.ShouldContain(1);
_destination.Values.ShouldContain(2);
_destination.Values.ShouldContain(3);
_destination.Values.ShouldContain(4);
}
[Fact]
public void Should_map_from_the_generic_list_of_values_with_formatting()
{
_destination.Values2.ShouldNotBeNull();
_destination.Values2.ShouldContain("9");
_destination.Values2.ShouldContain("8");
_destination.Values2.ShouldContain("7");
_destination.Values2.ShouldContain("6");
}
}
public class When_mapping_to_a_concrete_non_generic_icollection : AutoMapperSpecBase
{
private Destination _destination;
public class Source
{
public int[] Values { get; set; }
public List<int> Values2 { get; set; }
}
public class Destination
{
public ICollection Values { get; set; }
public ICollection Values2 { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>();
});
protected override void Because_of()
{
_destination = Mapper.Map<Source, Destination>(new Source { Values = new[] { 1, 2, 3, 4 }, Values2 = new List<int> { 9, 8, 7, 6 } });
}
[Fact]
public void Should_map_the_list_of_source_items()
{
_destination.Values.ShouldNotBeNull();
_destination.Values.ShouldContain(1);
_destination.Values.ShouldContain(2);
_destination.Values.ShouldContain(3);
_destination.Values.ShouldContain(4);
}
[Fact]
public void Should_map_from_a_non_array_source()
{
_destination.Values2.ShouldNotBeNull();
_destination.Values2.ShouldContain(9);
_destination.Values2.ShouldContain(8);
_destination.Values2.ShouldContain(7);
_destination.Values2.ShouldContain(6);
}
}
public class When_mapping_to_a_concrete_generic_icollection : AutoMapperSpecBase
{
private Destination _destination;
public class Source
{
public int[] Values { get; set; }
}
public class Destination
{
public ICollection<string> Values { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>();
});
protected override void Because_of()
{
_destination = Mapper.Map<Source, Destination>(new Source { Values = new[] { 1, 2, 3, 4 } });
}
[Fact]
public void Should_map_the_list_of_source_items()
{
_destination.Values.ShouldNotBeNull();
_destination.Values.ShouldContain("1");
_destination.Values.ShouldContain("2");
_destination.Values.ShouldContain("3");
_destination.Values.ShouldContain("4");
}
}
public class When_mapping_to_a_concrete_ilist : AutoMapperSpecBase
{
private Destination _destination;
public class Source
{
public int[] Values { get; set; }
}
public class Destination
{
public IList Values { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>();
});
protected override void Because_of()
{
_destination = Mapper.Map<Source, Destination>(new Source { Values = new[] { 1, 2, 3, 4 } });
}
[Fact]
public void Should_map_the_list_of_source_items()
{
_destination.Values.ShouldNotBeNull();
_destination.Values.ShouldContain(1);
_destination.Values.ShouldContain(2);
_destination.Values.ShouldContain(3);
_destination.Values.ShouldContain(4);
}
}
public class When_mapping_to_a_concrete_generic_ilist : AutoMapperSpecBase
{
private Destination _destination;
public class Source
{
public int[] Values { get; set; }
}
public class Destination
{
public IList<string> Values { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>();
});
protected override void Because_of()
{
_destination = Mapper.Map<Source, Destination>(new Source { Values = new[] { 1, 2, 3, 4 } });
}
[Fact]
public void Should_map_the_list_of_source_items()
{
_destination.Values.ShouldNotBeNull();
_destination.Values.ShouldContain("1");
_destination.Values.ShouldContain("2");
_destination.Values.ShouldContain("3");
_destination.Values.ShouldContain("4");
}
}
public class When_mapping_to_a_custom_list_with_the_same_type : AutoMapperSpecBase
{
private Destination _destination;
private Source _source;
public class ValueCollection : Collection<int>
{
}
public class Source
{
public ValueCollection Values { get; set; }
}
public class Destination
{
public ValueCollection Values { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>();
});
protected override void Because_of()
{
_source = new Source { Values = new ValueCollection { 1, 2, 3, 4 } };
_destination = Mapper.Map<Source, Destination>(_source);
}
[Fact]
public void Should_assign_the_value_directly()
{
_source.Values.ShouldBe(_destination.Values);
}
}
public class When_mapping_to_a_custom_collection_with_the_same_type_not_implementing_IList : AutoMapperSpecBase
{
private Source _source;
private Destination _destination;
public class ValueCollection : IEnumerable<int>
{
private List<int> implementation = new List<int>();
public ValueCollection(IEnumerable<int> items)
{
implementation = items.ToList();
}
public IEnumerator<int> GetEnumerator()
{
return implementation.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable)implementation).GetEnumerator();
}
}
public class Source
{
public ValueCollection Values { get; set; }
}
public class Destination
{
public ValueCollection Values { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>();
});
protected override void Establish_context()
{
_source = new Source { Values = new ValueCollection(new[] { 1, 2, 3, 4 }) };
}
protected override void Because_of()
{
_destination = Mapper.Map<Source, Destination>(_source);
}
[Fact]
public void Should_map_the_list_of_source_items()
{
// here not the EnumerableMapper is used, but just the AssignableMapper!
_destination.Values.ShouldBeSameAs(_source.Values);
_destination.Values.ShouldNotBeNull();
_destination.Values.ShouldContain(1);
_destination.Values.ShouldContain(2);
_destination.Values.ShouldContain(3);
_destination.Values.ShouldContain(4);
}
}
public class When_mapping_to_a_collection_with_instantiation_managed_by_the_destination : AutoMapperSpecBase
{
private Destination _destination;
private Source _source;
public class SourceItem
{
public int Value { get; set; }
}
public class DestItem
{
public int Value { get; set; }
}
public class Source
{
public List<SourceItem> Values { get; set; }
}
public class Destination
{
private List<DestItem> _values = new List<DestItem>();
public List<DestItem> Values
{
get { return _values; }
}
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>()
.ForMember(dest => dest.Values, opt => opt.UseDestinationValue());
cfg.CreateMap<SourceItem, DestItem>();
});
protected override void Because_of()
{
_source = new Source { Values = new List<SourceItem> { new SourceItem { Value = 5 }, new SourceItem { Value = 10 } } };
_destination = Mapper.Map<Source, Destination>(_source);
}
[Fact]
public void Should_assign_the_value_directly()
{
_destination.Values.Count.ShouldBe(2);
_destination.Values[0].Value.ShouldBe(5);
_destination.Values[1].Value.ShouldBe(10);
}
}
public class When_mapping_to_an_existing_list_with_existing_items : AutoMapperSpecBase
{
private Destination _destination;
private Source _source;
public class SourceItem
{
public int Value { get; set; }
}
public class DestItem
{
public int Value { get; set; }
}
public class Source
{
public List<SourceItem> Values { get; set; }
}
public class Destination
{
private List<DestItem> _values = new List<DestItem>();
public List<DestItem> Values
{
get { return _values; }
}
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>()
.ForMember(dest => dest.Values, opt => opt.UseDestinationValue());
cfg.CreateMap<SourceItem, DestItem>();
});
protected override void Because_of()
{
_source = new Source { Values = new List<SourceItem> { new SourceItem { Value = 5 }, new SourceItem { Value = 10 } } };
_destination = new Destination();
_destination.Values.Add(new DestItem());
Mapper.Map(_source, _destination);
}
[Fact]
public void Should_clear_the_list_before_mapping()
{
_destination.Values.Count.ShouldBe(2);
}
}
public class When_mapping_a_collection_with_null_members : AutoMapperSpecBase
{
const string FirstString = null;
private IEnumerable<string> _strings = new List<string> { FirstString };
private List<string> _mappedStrings = new List<string>();
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.AllowNullDestinationValues = true;
});
protected override void Because_of()
{
_mappedStrings = Mapper.Map<IEnumerable<string>, List<string>>(_strings);
}
[Fact]
public void Should_map_correctly()
{
_mappedStrings.ShouldNotBeNull();
_mappedStrings.Count.ShouldBe(1);
_mappedStrings[0].ShouldBeNull();
}
}
}
| |
// 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 Internal.Runtime.CompilerServices;
using System.Text;
using System.Diagnostics;
namespace System.IO
{
public class BinaryReader : IDisposable
{
private const int MaxCharBytesSize = 128;
private Stream _stream;
private byte[] _buffer;
private Decoder _decoder;
private byte[] _charBytes;
private char[] _singleChar;
private char[] _charBuffer;
private int _maxCharsSize; // From MaxCharBytesSize & Encoding
// Performance optimization for Read() w/ Unicode. Speeds us up by ~40%
private bool _2BytesPerChar;
private bool _isMemoryStream; // "do we sit on MemoryStream?" for Read/ReadInt32 perf
private bool _leaveOpen;
public BinaryReader(Stream input) : this(input, Encoding.UTF8, 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(nameof(input));
}
if (encoding == null)
{
throw new ArgumentNullException(nameof(encoding));
}
if (!input.CanRead)
{
throw new ArgumentException(SR.Argument_StreamNotReadable);
}
_stream = input;
_decoder = encoding.GetDecoder();
_maxCharsSize = encoding.GetMaxCharCount(MaxCharBytesSize);
int minBufferSize = encoding.GetMaxByteCount(1); // max bytes per one char
if (minBufferSize < 16)
{
minBufferSize = 16;
}
_buffer = new byte[minBufferSize];
// _charBuffer and _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.
_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
_isMemoryStream = (_stream.GetType() == typeof(MemoryStream));
_leaveOpen = leaveOpen;
Debug.Assert(_decoder != null, "[BinaryReader.ctor]_decoder!=null");
}
public virtual Stream BaseStream
{
get
{
return _stream;
}
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
Stream copyOfStream = _stream;
_stream = null;
if (copyOfStream != null && !_leaveOpen)
{
copyOfStream.Dispose();
}
}
_stream = null;
_buffer = null;
_decoder = null;
_charBytes = null;
_singleChar = null;
_charBuffer = null;
}
public void Dispose()
{
Dispose(true);
}
/// <remarks>
/// Override Dispose(bool) instead of Close(). This API exists for compatibility purposes.
/// </remarks>
public virtual void Close()
{
Dispose(true);
}
public virtual int PeekChar()
{
if (_stream == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_FileClosed);
}
if (!_stream.CanSeek)
{
return -1;
}
long origPos = _stream.Position;
int ch = Read();
_stream.Position = origPos;
return ch;
}
public virtual int Read()
{
if (_stream == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_FileClosed);
}
return InternalReadOneChar();
}
public virtual bool ReadBoolean()
{
FillBuffer(1);
return (_buffer[0] != 0);
}
public virtual byte ReadByte()
{
// Inlined to avoid some method call overhead with FillBuffer.
if (_stream == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_FileClosed);
}
int b = _stream.ReadByte();
if (b == -1)
{
throw new EndOfStreamException(SR.IO_EOF_ReadBeyondEOF);
}
return (byte)b;
}
[CLSCompliant(false)]
public virtual sbyte ReadSByte()
{
FillBuffer(1);
return (sbyte)(_buffer[0]);
}
public virtual char ReadChar()
{
int value = Read();
if (value == -1)
{
throw new EndOfStreamException(SR.IO_EOF_ReadBeyondEOF);
}
return (char)value;
}
public virtual short ReadInt16()
{
FillBuffer(2);
return (short)(_buffer[0] | _buffer[1] << 8);
}
[CLSCompliant(false)]
public virtual ushort ReadUInt16()
{
FillBuffer(2);
return (ushort)(_buffer[0] | _buffer[1] << 8);
}
public virtual int ReadInt32()
{
if (_isMemoryStream)
{
if (_stream == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_FileClosed);
}
// read directly from MemoryStream buffer
MemoryStream mStream = _stream as MemoryStream;
Debug.Assert(mStream != null, "_stream as MemoryStream != null");
return mStream.InternalReadInt32();
}
else
{
FillBuffer(4);
return (int)(_buffer[0] | _buffer[1] << 8 | _buffer[2] << 16 | _buffer[3] << 24);
}
}
[CLSCompliant(false)]
public virtual uint ReadUInt32()
{
FillBuffer(4);
return (uint)(_buffer[0] | _buffer[1] << 8 | _buffer[2] << 16 | _buffer[3] << 24);
}
public virtual long ReadInt64()
{
FillBuffer(8);
uint lo = (uint)(_buffer[0] | _buffer[1] << 8 |
_buffer[2] << 16 | _buffer[3] << 24);
uint hi = (uint)(_buffer[4] | _buffer[5] << 8 |
_buffer[6] << 16 | _buffer[7] << 24);
return (long)((ulong)hi) << 32 | lo;
}
[CLSCompliant(false)]
public virtual ulong ReadUInt64()
{
FillBuffer(8);
uint lo = (uint)(_buffer[0] | _buffer[1] << 8 |
_buffer[2] << 16 | _buffer[3] << 24);
uint hi = (uint)(_buffer[4] | _buffer[5] << 8 |
_buffer[6] << 16 | _buffer[7] << 24);
return ((ulong)hi) << 32 | lo;
}
public virtual unsafe float ReadSingle()
{
FillBuffer(4);
uint tmpBuffer = (uint)(_buffer[0] | _buffer[1] << 8 | _buffer[2] << 16 | _buffer[3] << 24);
return *((float*)&tmpBuffer);
}
public virtual unsafe double ReadDouble()
{
FillBuffer(8);
uint lo = (uint)(_buffer[0] | _buffer[1] << 8 |
_buffer[2] << 16 | _buffer[3] << 24);
uint hi = (uint)(_buffer[4] | _buffer[5] << 8 |
_buffer[6] << 16 | _buffer[7] << 24);
ulong tmpBuffer = ((ulong)hi) << 32 | lo;
return *((double*)&tmpBuffer);
}
public virtual decimal ReadDecimal()
{
FillBuffer(16);
int[] ints = new int[4];
Buffer.BlockCopy(_buffer, 0, ints, 0, 16);
try
{
return new decimal(ints);
}
catch (ArgumentException e)
{
// ReadDecimal cannot leak out ArgumentException
throw new IOException(SR.Arg_DecBitCtor, e);
}
}
public virtual string ReadString()
{
if (_stream == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_FileClosed);
}
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(SR.Format(SR.IO_IO_InvalidStringLen_Len, stringLength));
}
if (stringLength == 0)
{
return string.Empty;
}
if (_charBytes == null)
{
_charBytes = new byte[MaxCharBytesSize];
}
if (_charBuffer == null)
{
_charBuffer = new char[_maxCharsSize];
}
StringBuilder sb = null;
do
{
readLength = ((stringLength - currPos) > MaxCharBytesSize) ? MaxCharBytesSize : (stringLength - currPos);
n = _stream.Read(_charBytes, 0, readLength);
if (n == 0)
{
throw new EndOfStreamException(SR.IO_EOF_ReadBeyondEOF);
}
charsRead = _decoder.GetChars(_charBytes, 0, n, _charBuffer, 0);
if (currPos == 0 && n == stringLength)
{
return new string(_charBuffer, 0, charsRead);
}
if (sb == null)
{
sb = StringBuilderCache.Acquire(stringLength); // Actual string length in chars may be smaller.
}
sb.Append(_charBuffer, 0, charsRead);
currPos += n;
} while (currPos < stringLength);
return StringBuilderCache.GetStringAndRelease(sb);
}
public virtual int Read(char[] buffer, int index, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
}
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - index < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
if (_stream == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_FileClosed);
}
// SafeCritical: index and count have already been verified to be a valid range for the buffer
return InternalReadChars(buffer, index, count);
}
private int InternalReadChars(char[] buffer, int index, int count)
{
Debug.Assert(buffer != null);
Debug.Assert(index >= 0 && count >= 0);
Debug.Assert(_stream != null);
int numBytes = 0;
int charsRemaining = count;
if (_charBytes == null)
{
_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;
if (_2BytesPerChar)
{
numBytes <<= 1;
}
if (numBytes > MaxCharBytesSize)
{
numBytes = MaxCharBytesSize;
}
int position = 0;
byte[] byteBuffer = null;
if (_isMemoryStream)
{
MemoryStream mStream = _stream as MemoryStream;
Debug.Assert(mStream != null, "_stream as MemoryStream != null");
position = mStream.InternalGetPosition();
numBytes = mStream.InternalEmulateRead(numBytes);
byteBuffer = mStream.InternalGetBuffer();
}
else
{
numBytes = _stream.Read(_charBytes, 0, numBytes);
byteBuffer = _charBytes;
}
if (numBytes == 0)
{
return (count - charsRemaining);
}
Debug.Assert(byteBuffer != null, "expected byteBuffer to be non-null");
checked
{
if (position < 0 || numBytes < 0 || position > byteBuffer.Length - numBytes)
{
throw new ArgumentOutOfRangeException(nameof(numBytes));
}
if (index < 0 || charsRemaining < 0 || index > buffer.Length - charsRemaining)
{
throw new ArgumentOutOfRangeException(nameof(charsRemaining));
}
unsafe
{
fixed (byte* pBytes = byteBuffer)
fixed (char* pChars = buffer)
{
charsRead = _decoder.GetChars(pBytes + position, numBytes, pChars + index, charsRemaining, flush: false);
}
}
}
charsRemaining -= charsRead;
index += charsRead;
}
// this should never fail
Debug.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 (_stream.CanSeek)
{
posSav = _stream.Position;
}
if (_charBytes == null)
{
_charBytes = new byte[MaxCharBytesSize]; //REVIEW: We need at most 2 bytes/char here?
}
if (_singleChar == null)
{
_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 _2BytesPerChar is true.
numBytes = _2BytesPerChar ? 2 : 1;
int r = _stream.ReadByte();
_charBytes[0] = (byte)r;
if (r == -1)
{
numBytes = 0;
}
if (numBytes == 2)
{
r = _stream.ReadByte();
_charBytes[1] = (byte)r;
if (r == -1)
{
numBytes = 1;
}
}
if (numBytes == 0)
{
// Console.WriteLine("Found no bytes. We're outta here.");
return -1;
}
Debug.Assert(numBytes == 1 || numBytes == 2, "BinaryReader::InternalReadOneChar assumes it's reading one or 2 bytes only.");
try
{
charsRead = _decoder.GetChars(_charBytes, 0, numBytes, _singleChar, 0);
}
catch
{
// Handle surrogate char
if (_stream.CanSeek)
{
_stream.Seek((posSav - _stream.Position), SeekOrigin.Current);
}
// else - we can't do much here
throw;
}
Debug.Assert(charsRead < 2, "InternalReadOneChar - assuming we only got 0 or 1 char, not 2!");
// Console.WriteLine("That became: " + charsRead + " characters.");
}
Debug.Assert(charsRead != 0);
return _singleChar[0];
}
public virtual char[] ReadChars(int count)
{
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (_stream == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_FileClosed);
}
if (count == 0)
{
return Array.Empty<char>();
}
// 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.BlockCopy(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(nameof(buffer), SR.ArgumentNull_Buffer);
}
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - index < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
if (_stream == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_FileClosed);
}
return _stream.Read(buffer, index, count);
}
public virtual byte[] ReadBytes(int count)
{
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (_stream == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_FileClosed);
}
if (count == 0)
{
return Array.Empty<byte>();
}
byte[] result = new byte[count];
int numRead = 0;
do
{
int n = _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.BlockCopy(result, 0, copy, 0, numRead);
result = copy;
}
return result;
}
protected virtual void FillBuffer(int numBytes)
{
if (_buffer != null && (numBytes < 0 || numBytes > _buffer.Length))
{
throw new ArgumentOutOfRangeException(nameof(numBytes), SR.ArgumentOutOfRange_BinaryReaderFillBuffer);
}
int bytesRead = 0;
int n = 0;
if (_stream == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_FileClosed);
}
// 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 = _stream.ReadByte();
if (n == -1)
{
throw new EndOfStreamException(SR.IO_EOF_ReadBeyondEOF);
}
_buffer[0] = (byte)n;
return;
}
do
{
n = _stream.Read(_buffer, bytesRead, numBytes - bytesRead);
if (n == 0)
{
throw new EndOfStreamException(SR.IO_EOF_ReadBeyondEOF);
}
bytesRead += n;
} while (bytesRead < numBytes);
}
protected internal 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(SR.Format_Bad7BitInt32);
}
// ReadByte handles end of stream cases for us.
b = ReadByte();
count |= (b & 0x7F) << shift;
shift += 7;
} while ((b & 0x80) != 0);
return count;
}
}
}
| |
//
// Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.UnitTests.LayoutRenderers
{
using System;
using System.Globalization;
using Xunit;
public class MessageTests : NLogTestBase
{
[Fact]
public void MessageWithoutPaddingTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
logger.Debug("a");
AssertDebugLastMessage("debug", "a");
logger.Debug("a{0}", 1);
AssertDebugLastMessage("debug", "a1");
logger.Debug("a{0}{1}", 1, "2");
AssertDebugLastMessage("debug", "a12");
logger.Debug(CultureInfo.InvariantCulture, "a{0}", new DateTime(2005, 1, 1));
AssertDebugLastMessage("debug", "a01/01/2005 00:00:00");
}
[Fact]
public void MessageRightPaddingTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message:padding=3}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
logger.Debug("a");
AssertDebugLastMessage("debug", " a");
logger.Debug("a{0}", 1);
AssertDebugLastMessage("debug", " a1");
logger.Debug("a{0}{1}", 1, "2");
AssertDebugLastMessage("debug", "a12");
logger.Debug(CultureInfo.InvariantCulture, "a{0}", new DateTime(2005, 1, 1));
AssertDebugLastMessage("debug", "a01/01/2005 00:00:00");
}
[Fact]
public void MessageFixedLengthRightPaddingLeftAlignmentTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message:padding=3:fixedlength=true}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
logger.Debug("a");
AssertDebugLastMessage("debug", " a");
logger.Debug("a{0}", 1);
AssertDebugLastMessage("debug", " a1");
logger.Debug("a{0}{1}", 1, "2");
AssertDebugLastMessage("debug", "a12");
logger.Debug(CultureInfo.InvariantCulture, "a{0}", new DateTime(2005, 1, 1));
AssertDebugLastMessage("debug", "a01");
}
[Fact]
public void MessageFixedLengthRightPaddingRightAlignmentTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message:padding=3:fixedlength=true:alignmentOnTruncation=right}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
logger.Debug("a");
AssertDebugLastMessage("debug", " a");
logger.Debug("a{0}", 1);
AssertDebugLastMessage("debug", " a1");
logger.Debug("a{0}{1}", 1, "2");
AssertDebugLastMessage("debug", "a12");
logger.Debug(CultureInfo.InvariantCulture, "a{0}", new DateTime(2005, 1, 1));
AssertDebugLastMessage("debug", ":00");
}
[Fact]
public void MessageLeftPaddingTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message:padding=-3:padcharacter=x}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
logger.Debug("a");
AssertDebugLastMessage("debug", "axx");
logger.Debug("a{0}", 1);
AssertDebugLastMessage("debug", "a1x");
logger.Debug("a{0}{1}", 1, "2");
AssertDebugLastMessage("debug", "a12");
logger.Debug(CultureInfo.InvariantCulture, "a{0}", new DateTime(2005, 1, 1));
AssertDebugLastMessage("debug", "a01/01/2005 00:00:00");
}
[Fact]
public void MessageFixedLengthLeftPaddingLeftAlignmentTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message:padding=-3:padcharacter=x:fixedlength=true}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
logger.Debug("a");
AssertDebugLastMessage("debug", "axx");
logger.Debug("a{0}", 1);
AssertDebugLastMessage("debug", "a1x");
logger.Debug("a{0}{1}", 1, "2");
AssertDebugLastMessage("debug", "a12");
logger.Debug(CultureInfo.InvariantCulture, "a{0}", new DateTime(2005, 1, 1));
AssertDebugLastMessage("debug", "a01");
}
[Fact]
public void MessageFixedLengthLeftPaddingRightAlignmentTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message:padding=-3:padcharacter=x:fixedlength=true:alignmentOnTruncation=right}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
logger.Debug("a");
AssertDebugLastMessage("debug", "axx");
logger.Debug("a{0}", 1);
AssertDebugLastMessage("debug", "a1x");
logger.Debug("a{0}{1}", 1, "2");
AssertDebugLastMessage("debug", "a12");
logger.Debug(CultureInfo.InvariantCulture, "a{0}", new DateTime(2005, 1, 1));
AssertDebugLastMessage("debug", ":00");
}
[Fact]
public void MessageWithExceptionTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog exceptionLoggingOldStyle='true'>
<targets><target name='debug' type='Debug' layout='${message:withException=true}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
logger.Debug("a");
AssertDebugLastMessage("debug", "a");
var ex = new InvalidOperationException("Exception message.");
string newline = Environment.NewLine;
#pragma warning disable 0618
// Obsolete method requires testing until completely removed.
logger.DebugException("Foo", ex);
AssertDebugLastMessage("debug", "Foo" + newline + ex.ToString());
#pragma warning restore 0618
logger.Debug(ex, "Foo");
AssertDebugLastMessage("debug", "Foo" + newline + ex.ToString());
logger.Debug( "Foo", ex);
AssertDebugLastMessage("debug", "Foo" + newline + ex.ToString());
}
[Fact]
public void MessageWithExceptionAndCustomSeparatorTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message:withException=true:exceptionSeparator=,}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
logger.Debug("a");
AssertDebugLastMessage("debug", "a");
var ex = new InvalidOperationException("Exception message.");
#pragma warning disable 0618
// Obsolete method requires testing until completely removed.
logger.DebugException("Foo", ex);
AssertDebugLastMessage("debug", "Foo," + ex.ToString());
#pragma warning restore 0618
logger.Debug(ex, "Foo");
AssertDebugLastMessage("debug", "Foo," + ex.ToString());
}
}
}
| |
#region license
// Copyright (c) 2009 Rodrigo B. de Oliveira (rbo@acm.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * 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 Rodrigo B. de Oliveira nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
//
// DO NOT EDIT THIS FILE!
//
// This file was generated automatically by astgen.boo.
//
namespace Boo.Lang.Compiler.Ast
{
using System.Collections;
using System.Runtime.Serialization;
[System.Serializable]
public partial class StructDefinition : TypeDefinition
{
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
new public StructDefinition CloneNode()
{
return (StructDefinition)Clone();
}
/// <summary>
/// <see cref="Node.CleanClone"/>
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
new public StructDefinition CleanClone()
{
return (StructDefinition)base.CleanClone();
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public NodeType NodeType
{
get { return NodeType.StructDefinition; }
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public void Accept(IAstVisitor visitor)
{
visitor.OnStructDefinition(this);
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public bool Matches(Node node)
{
if (node == null) return false;
if (NodeType != node.NodeType) return false;
var other = ( StructDefinition)node;
if (_modifiers != other._modifiers) return NoMatch("StructDefinition._modifiers");
if (_name != other._name) return NoMatch("StructDefinition._name");
if (!Node.AllMatch(_attributes, other._attributes)) return NoMatch("StructDefinition._attributes");
if (!Node.AllMatch(_members, other._members)) return NoMatch("StructDefinition._members");
if (!Node.AllMatch(_baseTypes, other._baseTypes)) return NoMatch("StructDefinition._baseTypes");
if (!Node.AllMatch(_genericParameters, other._genericParameters)) return NoMatch("StructDefinition._genericParameters");
return true;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public bool Replace(Node existing, Node newNode)
{
if (base.Replace(existing, newNode))
{
return true;
}
if (_attributes != null)
{
Attribute item = existing as Attribute;
if (null != item)
{
Attribute newItem = (Attribute)newNode;
if (_attributes.Replace(item, newItem))
{
return true;
}
}
}
if (_members != null)
{
TypeMember item = existing as TypeMember;
if (null != item)
{
TypeMember newItem = (TypeMember)newNode;
if (_members.Replace(item, newItem))
{
return true;
}
}
}
if (_baseTypes != null)
{
TypeReference item = existing as TypeReference;
if (null != item)
{
TypeReference newItem = (TypeReference)newNode;
if (_baseTypes.Replace(item, newItem))
{
return true;
}
}
}
if (_genericParameters != null)
{
GenericParameterDeclaration item = existing as GenericParameterDeclaration;
if (null != item)
{
GenericParameterDeclaration newItem = (GenericParameterDeclaration)newNode;
if (_genericParameters.Replace(item, newItem))
{
return true;
}
}
}
return false;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public object Clone()
{
StructDefinition clone = new StructDefinition();
clone._lexicalInfo = _lexicalInfo;
clone._endSourceLocation = _endSourceLocation;
clone._documentation = _documentation;
clone._isSynthetic = _isSynthetic;
clone._entity = _entity;
if (_annotations != null) clone._annotations = (Hashtable)_annotations.Clone();
clone._modifiers = _modifiers;
clone._name = _name;
if (null != _attributes)
{
clone._attributes = _attributes.Clone() as AttributeCollection;
clone._attributes.InitializeParent(clone);
}
if (null != _members)
{
clone._members = _members.Clone() as TypeMemberCollection;
clone._members.InitializeParent(clone);
}
if (null != _baseTypes)
{
clone._baseTypes = _baseTypes.Clone() as TypeReferenceCollection;
clone._baseTypes.InitializeParent(clone);
}
if (null != _genericParameters)
{
clone._genericParameters = _genericParameters.Clone() as GenericParameterDeclarationCollection;
clone._genericParameters.InitializeParent(clone);
}
return clone;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override internal void ClearTypeSystemBindings()
{
_annotations = null;
_entity = null;
if (null != _attributes)
{
_attributes.ClearTypeSystemBindings();
}
if (null != _members)
{
_members.ClearTypeSystemBindings();
}
if (null != _baseTypes)
{
_baseTypes.ClearTypeSystemBindings();
}
if (null != _genericParameters)
{
_genericParameters.ClearTypeSystemBindings();
}
}
}
}
| |
//
// This file is generated by ReactPackageGenerator.tt
//
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
//
using ReactNative.Bridge;
using ReactNative.Modules.Core;
using ReactNative.UIManager;
using System.Collections.Generic;
namespace ReactNative
{
class CoreModulesPackageWrapper : IReactPackage
{
private readonly IReactPackage _reactPackage;
public CoreModulesPackageWrapper(CoreModulesPackage reactPackage)
{
_reactPackage = reactPackage;
}
public IReadOnlyList<INativeModule> CreateNativeModules(ReactContext reactContext)
{
var nativeModules = _reactPackage.CreateNativeModules(reactContext);
return new List<INativeModule>
{
new DeviceEventManagerModuleWrapper((ReactNative.Modules.Core.DeviceEventManagerModule)nativeModules[0]),
new DeviceInfoModuleWrapper((ReactNative.Modules.DeviceInfo.DeviceInfoModule)nativeModules[1]),
new ExceptionsManagerModuleWrapper((ReactNative.Modules.Core.ExceptionsManagerModule)nativeModules[2]),
new PlatformConstantsModuleWrapper((ReactNative.Modules.SystemInfo.PlatformConstantsModule)nativeModules[3]),
new SourceCodeModuleWrapper((ReactNative.Modules.DevSupport.SourceCodeModule)nativeModules[4]),
new TimingWrapper((ReactNative.Modules.Core.Timing)nativeModules[5]),
new UIManagerModuleWrapper((ReactNative.UIManager.UIManagerModule)nativeModules[6]),
};
}
public IReadOnlyList<IViewManager> CreateViewManagers(ReactContext reactContext)
{
return _reactPackage.CreateViewManagers(reactContext);
}
class DeviceEventManagerModuleWrapper : NativeModuleWrapperBase<ReactNative.Modules.Core.DeviceEventManagerModule>
{
public DeviceEventManagerModuleWrapper(ReactNative.Modules.Core.DeviceEventManagerModule nativeModule)
: base(nativeModule)
{
}
public override IReadOnlyDictionary<string, INativeMethod> Methods
{
get
{
return new Dictionary<string, INativeMethod>
{
{
nameof(ReactNative.Modules.Core.DeviceEventManagerModule.invokeDefaultBackPressHandler),
new NativeMethod("async", (invokeCallback, args) =>
Module.invokeDefaultBackPressHandler(
)
)
},
};
}
}
}
class DeviceInfoModuleWrapper : NativeModuleWrapperBase<ReactNative.Modules.DeviceInfo.DeviceInfoModule>
{
public DeviceInfoModuleWrapper(ReactNative.Modules.DeviceInfo.DeviceInfoModule nativeModule)
: base(nativeModule)
{
}
public override IReadOnlyDictionary<string, INativeMethod> Methods
{
get
{
return new Dictionary<string, INativeMethod>
{
};
}
}
}
class ExceptionsManagerModuleWrapper : NativeModuleWrapperBase<ReactNative.Modules.Core.ExceptionsManagerModule>
{
public ExceptionsManagerModuleWrapper(ReactNative.Modules.Core.ExceptionsManagerModule nativeModule)
: base(nativeModule)
{
}
public override IReadOnlyDictionary<string, INativeMethod> Methods
{
get
{
return new Dictionary<string, INativeMethod>
{
{
nameof(ReactNative.Modules.Core.ExceptionsManagerModule.reportFatalException),
new NativeMethod("async", (invokeCallback, args) =>
Module.reportFatalException(
args[0].ToObject<System.String>(),
CastJToken<Newtonsoft.Json.Linq.JArray>(args[1]),
args[2].ToObject<System.Int32>()
)
)
},
{
nameof(ReactNative.Modules.Core.ExceptionsManagerModule.reportSoftException),
new NativeMethod("async", (invokeCallback, args) =>
Module.reportSoftException(
args[0].ToObject<System.String>(),
CastJToken<Newtonsoft.Json.Linq.JArray>(args[1]),
args[2].ToObject<System.Int32>()
)
)
},
{
nameof(ReactNative.Modules.Core.ExceptionsManagerModule.updateExceptionMessage),
new NativeMethod("async", (invokeCallback, args) =>
Module.updateExceptionMessage(
args[0].ToObject<System.String>(),
CastJToken<Newtonsoft.Json.Linq.JArray>(args[1]),
args[2].ToObject<System.Int32>()
)
)
},
{
nameof(ReactNative.Modules.Core.ExceptionsManagerModule.dismissRedbox),
new NativeMethod("async", (invokeCallback, args) =>
Module.dismissRedbox(
)
)
},
};
}
}
}
class PlatformConstantsModuleWrapper : NativeModuleWrapperBase<ReactNative.Modules.SystemInfo.PlatformConstantsModule>
{
public PlatformConstantsModuleWrapper(ReactNative.Modules.SystemInfo.PlatformConstantsModule nativeModule)
: base(nativeModule)
{
}
public override IReadOnlyDictionary<string, INativeMethod> Methods
{
get
{
return new Dictionary<string, INativeMethod>
{
};
}
}
}
class SourceCodeModuleWrapper : NativeModuleWrapperBase<ReactNative.Modules.DevSupport.SourceCodeModule>
{
public SourceCodeModuleWrapper(ReactNative.Modules.DevSupport.SourceCodeModule nativeModule)
: base(nativeModule)
{
}
public override IReadOnlyDictionary<string, INativeMethod> Methods
{
get
{
return new Dictionary<string, INativeMethod>
{
{
nameof(ReactNative.Modules.DevSupport.SourceCodeModule.getScriptText),
new NativeMethod("promise", (invokeCallback, args) =>
Module.getScriptText(
new Promise(
new Callback(args[0].ToObject<int>(), invokeCallback),
new Callback(args[1].ToObject<int>(), invokeCallback)
)
)
)
},
};
}
}
}
class TimingWrapper : NativeModuleWrapperBase<ReactNative.Modules.Core.Timing>
{
public TimingWrapper(ReactNative.Modules.Core.Timing nativeModule)
: base(nativeModule)
{
}
public override IReadOnlyDictionary<string, INativeMethod> Methods
{
get
{
return new Dictionary<string, INativeMethod>
{
{
nameof(ReactNative.Modules.Core.Timing.createTimer),
new NativeMethod("async", (invokeCallback, args) =>
Module.createTimer(
args[0].ToObject<System.Int32>(),
args[1].ToObject<System.Int32>(),
args[2].ToObject<System.Double>(),
args[3].ToObject<System.Boolean>()
)
)
},
{
nameof(ReactNative.Modules.Core.Timing.deleteTimer),
new NativeMethod("async", (invokeCallback, args) =>
Module.deleteTimer(
args[0].ToObject<System.Int32>()
)
)
},
{
nameof(ReactNative.Modules.Core.Timing.setSendIdleEvents),
new NativeMethod("async", (invokeCallback, args) =>
Module.setSendIdleEvents(
args[0].ToObject<System.Boolean>()
)
)
},
};
}
}
}
class UIManagerModuleWrapper : NativeModuleWrapperBase<ReactNative.UIManager.UIManagerModule>
{
public UIManagerModuleWrapper(ReactNative.UIManager.UIManagerModule nativeModule)
: base(nativeModule)
{
}
public override IReadOnlyDictionary<string, INativeMethod> Methods
{
get
{
return new Dictionary<string, INativeMethod>
{
{
nameof(ReactNative.UIManager.UIManagerModule.removeRootView),
new NativeMethod("async", (invokeCallback, args) =>
Module.removeRootView(
args[0].ToObject<System.Int32>()
)
)
},
{
nameof(ReactNative.UIManager.UIManagerModule.createView),
new NativeMethod("async", (invokeCallback, args) =>
Module.createView(
args[0].ToObject<System.Int32>(),
args[1].ToObject<System.String>(),
args[2].ToObject<System.Int32>(),
CastJToken<Newtonsoft.Json.Linq.JObject>(args[3])
)
)
},
{
nameof(ReactNative.UIManager.UIManagerModule.updateView),
new NativeMethod("async", (invokeCallback, args) =>
Module.updateView(
args[0].ToObject<System.Int32>(),
args[1].ToObject<System.String>(),
CastJToken<Newtonsoft.Json.Linq.JObject>(args[2])
)
)
},
{
nameof(ReactNative.UIManager.UIManagerModule.manageChildren),
new NativeMethod("async", (invokeCallback, args) =>
Module.manageChildren(
args[0].ToObject<System.Int32>(),
args[1].ToObject<System.Int32[]>(),
args[2].ToObject<System.Int32[]>(),
args[3].ToObject<System.Int32[]>(),
args[4].ToObject<System.Int32[]>(),
args[5].ToObject<System.Int32[]>()
)
)
},
{
nameof(ReactNative.UIManager.UIManagerModule.setChildren),
new NativeMethod("async", (invokeCallback, args) =>
Module.setChildren(
args[0].ToObject<System.Int32>(),
args[1].ToObject<System.Int32[]>()
)
)
},
{
nameof(ReactNative.UIManager.UIManagerModule.replaceExistingNonRootView),
new NativeMethod("async", (invokeCallback, args) =>
Module.replaceExistingNonRootView(
args[0].ToObject<System.Int32>(),
args[1].ToObject<System.Int32>()
)
)
},
{
nameof(ReactNative.UIManager.UIManagerModule.removeSubviewsFromContainerWithID),
new NativeMethod("async", (invokeCallback, args) =>
Module.removeSubviewsFromContainerWithID(
args[0].ToObject<System.Int32>()
)
)
},
{
nameof(ReactNative.UIManager.UIManagerModule.measure),
new NativeMethod("async", (invokeCallback, args) =>
Module.measure(
args[0].ToObject<System.Int32>(),
new Callback(args[1].ToObject<int>(), invokeCallback)
)
)
},
{
nameof(ReactNative.UIManager.UIManagerModule.measureInWindow),
new NativeMethod("async", (invokeCallback, args) =>
Module.measureInWindow(
args[0].ToObject<System.Int32>(),
new Callback(args[1].ToObject<int>(), invokeCallback)
)
)
},
{
nameof(ReactNative.UIManager.UIManagerModule.measureLayout),
new NativeMethod("async", (invokeCallback, args) =>
Module.measureLayout(
args[0].ToObject<System.Int32>(),
args[1].ToObject<System.Int32>(),
new Callback(args[2].ToObject<int>(), invokeCallback),
new Callback(args[3].ToObject<int>(), invokeCallback)
)
)
},
{
nameof(ReactNative.UIManager.UIManagerModule.measureLayoutRelativeToParent),
new NativeMethod("async", (invokeCallback, args) =>
Module.measureLayoutRelativeToParent(
args[0].ToObject<System.Int32>(),
new Callback(args[1].ToObject<int>(), invokeCallback),
new Callback(args[2].ToObject<int>(), invokeCallback)
)
)
},
{
nameof(ReactNative.UIManager.UIManagerModule.findSubviewIn),
new NativeMethod("async", (invokeCallback, args) =>
Module.findSubviewIn(
args[0].ToObject<System.Int32>(),
CastJToken<Newtonsoft.Json.Linq.JArray>(args[1]),
new Callback(args[2].ToObject<int>(), invokeCallback)
)
)
},
{
nameof(ReactNative.UIManager.UIManagerModule.setJSResponder),
new NativeMethod("async", (invokeCallback, args) =>
Module.setJSResponder(
args[0].ToObject<System.Int32>(),
args[1].ToObject<System.Boolean>()
)
)
},
{
nameof(ReactNative.UIManager.UIManagerModule.clearJSResponder),
new NativeMethod("async", (invokeCallback, args) =>
Module.clearJSResponder(
)
)
},
{
nameof(ReactNative.UIManager.UIManagerModule.dispatchViewManagerCommand),
new NativeMethod("async", (invokeCallback, args) =>
Module.dispatchViewManagerCommand(
args[0].ToObject<System.Int32>(),
args[1].ToObject<System.Int32>(),
CastJToken<Newtonsoft.Json.Linq.JArray>(args[2])
)
)
},
{
nameof(ReactNative.UIManager.UIManagerModule.showPopupMenu),
new NativeMethod("async", (invokeCallback, args) =>
Module.showPopupMenu(
args[0].ToObject<System.Int32>(),
args[1].ToObject<System.String[]>(),
new Callback(args[2].ToObject<int>(), invokeCallback),
new Callback(args[3].ToObject<int>(), invokeCallback)
)
)
},
{
nameof(ReactNative.UIManager.UIManagerModule.configureNextLayoutAnimation),
new NativeMethod("async", (invokeCallback, args) =>
Module.configureNextLayoutAnimation(
CastJToken<Newtonsoft.Json.Linq.JObject>(args[0]),
new Callback(args[1].ToObject<int>(), invokeCallback),
new Callback(args[2].ToObject<int>(), invokeCallback)
)
)
},
{
nameof(ReactNative.UIManager.UIManagerModule.getConstantsForViewManager),
new NativeMethod("sync", (invokeCallback, args) =>
Module.getConstantsForViewManager(
args[0].ToObject<System.String>()
)
)
},
{
nameof(ReactNative.UIManager.UIManagerModule.getDefaultEventTypes),
new NativeMethod("sync", (invokeCallback, args) =>
Module.getDefaultEventTypes(
)
)
},
};
}
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace RealtimeDotNetTests
{
[TestClass]
public class RealtimeTests
{
[TestMethod]
public async Task TestEvents()
{
Trace.WriteLine("TestStates");
//Set App Key
Assert.IsFalse(string.IsNullOrEmpty(RealtimeTestClient.AppKey));
var master = new RealtimeTestClient();
var client = master.client;
bool didConnect = false;
bool didDiconnect = false;
bool didSub = false;
bool didUnSub = false;
bool didSend = false;
client.OnConnected += sender => didConnect = true;
client.OnDisconnected += sender => didDiconnect = true;
client.OnSubscribed += (sender, channel) => didSub = true;
client.OnUnsubscribed += (sender, channel) => didUnSub = true;
await master.Connect();
Assert.IsTrue(didConnect);
await master.Subscribe("TestStates", true, (sender, channel, message) => didSend = true);
Assert.IsTrue(didSub);
master.Send("TestStates", "Hello");
await Task.Delay(1000);
Assert.IsTrue(didSend);
await master.UnSubscribe("TestStates");
Assert.IsTrue(didUnSub);
await master.Disconnect();
await Task.Delay(1000);
Assert.IsTrue(didDiconnect);
}
[TestMethod]
public async Task TestChat()
{
Trace.WriteLine("Test10Clients");
//Set App Key
Assert.IsFalse(string.IsNullOrEmpty(RealtimeTestClient.AppKey));
var master = new RealtimeTestClient();
var slave = new RealtimeTestClient();
//connect
await master.Connect();
Assert.IsTrue(master.client.IsConnected);
await slave.Connect();
Assert.IsTrue(slave.client.IsConnected);
var scounter = 0;
var mcounter = 0;
var sStop = false;
var mStop = false;
await master.Subscribe("Master", true, (sender, channel, message) =>
{
Trace.WriteLine(message);
mcounter++;
if (mcounter < 20)
{
master.client.Send("Slave", "Hello " + mcounter);
}
else
{
mStop = true;
}
});
await Task.Delay(200);
await slave.Subscribe("Slave", true, (sender, channel, message) =>
{
Trace.WriteLine(message);
scounter++;
if (scounter < 20)
{
slave.client.Send("Master", "Hello " + scounter);
}
else
{
sStop = true;
}
});
master.client.Send("Slave", "Start");
var fault = DateTime.UtcNow.AddMinutes(3);
while (
master.client.IsConnected
&& slave.client.IsConnected
&& !sStop
&& !mStop
&& DateTime.UtcNow < fault)
{
await Task.Delay(100);
}
Assert.IsTrue(slave.client.IsConnected);
Assert.IsTrue(master.client.IsConnected);
Assert.IsTrue(scounter == mcounter + 1);
await master.Disconnect();
await slave.Disconnect();
}
[TestMethod]
public async Task Test10Clients()
{
Trace.WriteLine("Test10Clients");
//Set App Key
Assert.IsFalse(string.IsNullOrEmpty(RealtimeTestClient.AppKey));
var ten = 10;
for (int i = 0;i < ten;i++)
{
Trace.WriteLine("Test Client " + i);
var counter = 0;
var client = new RealtimeTestClient();
await client.Connect();
Assert.IsTrue(client.client.IsConnected);
await client.Subscribe("Hello", true, (sender, channel, message) =>
{
Trace.WriteLine(message);
counter++;
});
for (int j = 0;j < ten;j++)
{
client.client.Send("Hello", "Message" + j);
await Task.Delay(100);
}
await Task.Delay(100);
Assert.IsTrue(counter == ten);
Trace.WriteLine("Time " + client.Watch.ElapsedMilliseconds);
await client.Disconnect();
}
}
[TestMethod]
public async Task TestThreadedSpam()
{
Trace.WriteLine("TestThreadedSpam");
//Set App Key
Assert.IsFalse(string.IsNullOrEmpty(RealtimeTestClient.AppKey));
var master = new RealtimeTestClient();
var slave = new RealtimeTestClient();
//connect
await master.Connect();
await slave.Connect();
Assert.IsTrue(slave.client.IsConnected);
var scounter = 0;
await Task.Delay(1000);
await slave.Subscribe("Slave", true, (sender, channel, message) =>
{
Trace.WriteLine(message);
scounter++;
});
await Task.Delay(1000);
var num = 5;
var actions = new Action[num];
for (int i = 0;i < num;i++)
{
actions[i] = () =>
{
for (int j = 0;j < num;j++)
{
master.client.Send("Slave", j.ToString());
}
};
}
Parallel.Invoke(actions);
await Task.Delay(5000);
Assert.IsTrue(slave.client.IsConnected);
Assert.IsTrue(master.client.IsConnected);
Assert.IsTrue(scounter == (num * num));
await master.Disconnect();
await slave.Disconnect();
}
// Test for Chat messages
public async Task TestChunkMessages()
{
Trace.WriteLine("TestChunking");
//Set App Key
Assert.IsFalse(string.IsNullOrEmpty(RealtimeTestClient.AppKey));
// Make 2 clients and wait for them to connect.
var master = new RealtimeTestClient();
var slave = new RealtimeTestClient();
await master.Connect();
await slave.Connect();
Assert.IsTrue(master.client.IsConnected);
Assert.IsTrue(slave.client.IsConnected);
var sb = new StringBuilder();
for (int i = 0;i < 3000;i++)
{
sb.Append("A");
}
var BigText = sb.ToString();
var scounter = 0;
var mcounter = 0;
var sStop = false;
var mStop = false;
// Handle Messages
master.client.Subscribe("Master", true, (sender, channel, message) =>
{
Trace.WriteLine(message);
Assert.AreEqual(message, BigText);
mcounter++;
if (mcounter < 2)
{
master.client.Send("Slave", BigText);
}
else
{
mStop = true;
}
});
await Task.Delay(200);
slave.client.Subscribe("Slave", true, (sender, channel, message) =>
{
Trace.WriteLine(message);
Assert.AreEqual(message, BigText);
scounter++;
if (scounter < 2)
{
slave.client.Send("Master", BigText);
}
else
{
sStop = true;
}
});
await Task.Delay(200);
//Send BigText 3000 bytes
master.client.Send("Slave", BigText);
// wait for complete. Give 1 minute
var fault = DateTime.UtcNow.AddMinutes(1);
while (
master.client.IsConnected
&& slave.client.IsConnected
&& !sStop
&& !mStop
&& DateTime.UtcNow < fault)
{
await Task.Delay(100);
}
//Asset messages received
Assert.IsTrue(slave.client.IsConnected);
Assert.IsTrue(master.client.IsConnected);
Assert.IsTrue(scounter == mcounter + 1);
//end
await master.Disconnect();
await slave.Disconnect();
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Security;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System.Text;
using System.Runtime.InteropServices;
using System.Globalization;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
using System.Threading;
namespace System.IO
{
public static class Directory
{
public static DirectoryInfo GetParent(String path)
{
if (path == null)
throw new ArgumentNullException("path");
if (path.Length == 0)
throw new ArgumentException(SR.Argument_PathEmpty, "path");
Contract.EndContractBlock();
String fullPath = PathHelpers.GetFullPathInternal(path);
String s = Path.GetDirectoryName(fullPath);
if (s == null)
return null;
return new DirectoryInfo(s);
}
[System.Security.SecuritySafeCritical]
public static DirectoryInfo CreateDirectory(String path)
{
if (path == null)
throw new ArgumentNullException("path");
if (path.Length == 0)
throw new ArgumentException(SR.Argument_PathEmpty);
Contract.EndContractBlock();
String fullPath = PathHelpers.GetFullPathInternal(path);
FileSystem.Current.CreateDirectory(fullPath);
return new DirectoryInfo(fullPath, null);
}
// Input to this method should already be fullpath. This method will ensure that we append
// the trailing slash only when appropriate.
internal static String EnsureTrailingDirectorySeparator(string fullPath)
{
String fullPathWithTrailingDirectorySeparator;
if (!PathHelpers.EndsInDirectorySeparator(fullPath))
fullPathWithTrailingDirectorySeparator = fullPath + PathHelpers.DirectorySeparatorCharAsString;
else
fullPathWithTrailingDirectorySeparator = fullPath;
return fullPathWithTrailingDirectorySeparator;
}
// Tests if the given path refers to an existing DirectoryInfo on disk.
//
// Your application must have Read permission to the directory's
// contents.
//
[System.Security.SecuritySafeCritical] // auto-generated
public static bool Exists(String path)
{
try
{
if (path == null)
return false;
if (path.Length == 0)
return false;
String fullPath = PathHelpers.GetFullPathInternal(path);
return FileSystem.Current.DirectoryExists(fullPath);
}
catch (ArgumentException) { }
catch (NotSupportedException) { } // Security can throw this on ":"
catch (SecurityException) { }
catch (IOException) { }
catch (UnauthorizedAccessException) { }
return false;
}
public static void SetCreationTime(String path, DateTime creationTime)
{
String fullPath = PathHelpers.GetFullPathInternal(path);
FileSystem.Current.SetCreationTime(fullPath, creationTime, asDirectory: true);
}
public static void SetCreationTimeUtc(String path, DateTime creationTimeUtc)
{
String fullPath = PathHelpers.GetFullPathInternal(path);
FileSystem.Current.SetCreationTime(fullPath, File.GetUtcDateTimeOffset(creationTimeUtc), asDirectory: true);
}
public static DateTime GetCreationTime(String path)
{
return File.GetCreationTime(path);
}
public static DateTime GetCreationTimeUtc(String path)
{
return File.GetCreationTimeUtc(path);
}
public static void SetLastWriteTime(String path, DateTime lastWriteTime)
{
String fullPath = PathHelpers.GetFullPathInternal(path);
FileSystem.Current.SetLastWriteTime(fullPath, lastWriteTime, asDirectory: true);
}
public static void SetLastWriteTimeUtc(String path, DateTime lastWriteTimeUtc)
{
String fullPath = PathHelpers.GetFullPathInternal(path);
FileSystem.Current.SetLastWriteTime(fullPath, File.GetUtcDateTimeOffset(lastWriteTimeUtc), asDirectory: true);
}
public static DateTime GetLastWriteTime(String path)
{
return File.GetLastWriteTime(path);
}
public static DateTime GetLastWriteTimeUtc(String path)
{
return File.GetLastWriteTimeUtc(path);
}
public static void SetLastAccessTime(String path, DateTime lastAccessTime)
{
String fullPath = PathHelpers.GetFullPathInternal(path);
FileSystem.Current.SetLastAccessTime(fullPath, lastAccessTime, asDirectory: true);
}
public static void SetLastAccessTimeUtc(String path, DateTime lastAccessTimeUtc)
{
String fullPath = PathHelpers.GetFullPathInternal(path);
FileSystem.Current.SetLastAccessTime(fullPath, File.GetUtcDateTimeOffset(lastAccessTimeUtc), asDirectory: true);
}
public static DateTime GetLastAccessTime(String path)
{
return File.GetLastAccessTime(path);
}
public static DateTime GetLastAccessTimeUtc(String path)
{
return File.GetLastAccessTimeUtc(path);
}
// Returns an array of filenames in the DirectoryInfo specified by path
public static String[] GetFiles(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
return InternalGetFiles(path, "*", SearchOption.TopDirectoryOnly);
}
// Returns an array of Files in the current DirectoryInfo matching the
// given search pattern (ie, "*.txt").
public static String[] GetFiles(String path, String searchPattern)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
return InternalGetFiles(path, searchPattern, SearchOption.TopDirectoryOnly);
}
// Returns an array of Files in the current DirectoryInfo matching the
// given search pattern (ie, "*.txt") and search option
public static String[] GetFiles(String path, String searchPattern, SearchOption searchOption)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum);
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
return InternalGetFiles(path, searchPattern, searchOption);
}
// Returns an array of Files in the current DirectoryInfo matching the
// given search pattern (ie, "*.txt") and search option
private static String[] InternalGetFiles(String path, String searchPattern, SearchOption searchOption)
{
Contract.Requires(path != null);
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
return InternalGetFileDirectoryNames(path, path, searchPattern, true, false, searchOption);
}
// Returns an array of Directories in the current directory.
public static String[] GetDirectories(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
return InternalGetDirectories(path, "*", SearchOption.TopDirectoryOnly);
}
// Returns an array of Directories in the current DirectoryInfo matching the
// given search criteria (ie, "*.txt").
public static String[] GetDirectories(String path, String searchPattern)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
return InternalGetDirectories(path, searchPattern, SearchOption.TopDirectoryOnly);
}
// Returns an array of Directories in the current DirectoryInfo matching the
// given search criteria (ie, "*.txt").
public static String[] GetDirectories(String path, String searchPattern, SearchOption searchOption)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum);
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
return InternalGetDirectories(path, searchPattern, searchOption);
}
// Returns an array of Directories in the current DirectoryInfo matching the
// given search criteria (ie, "*.txt").
private static String[] InternalGetDirectories(String path, String searchPattern, SearchOption searchOption)
{
Contract.Requires(path != null);
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
Contract.Ensures(Contract.Result<String[]>() != null);
return InternalGetFileDirectoryNames(path, path, searchPattern, false, true, searchOption);
}
// Returns an array of strongly typed FileSystemInfo entries in the path
public static String[] GetFileSystemEntries(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
return InternalGetFileSystemEntries(path, "*", SearchOption.TopDirectoryOnly);
}
// Returns an array of strongly typed FileSystemInfo entries in the path with the
// given search criteria (ie, "*.txt"). We disallow .. as a part of the search criteria
public static String[] GetFileSystemEntries(String path, String searchPattern)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
return InternalGetFileSystemEntries(path, searchPattern, SearchOption.TopDirectoryOnly);
}
// Returns an array of strongly typed FileSystemInfo entries in the path with the
// given search criteria (ie, "*.txt"). We disallow .. as a part of the search criteria
public static String[] GetFileSystemEntries(String path, String searchPattern, SearchOption searchOption)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum);
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
return InternalGetFileSystemEntries(path, searchPattern, searchOption);
}
private static String[] InternalGetFileSystemEntries(String path, String searchPattern, SearchOption searchOption)
{
Contract.Requires(path != null);
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
return InternalGetFileDirectoryNames(path, path, searchPattern, true, true, searchOption);
}
// Private class that holds search data that is passed around
// in the heap based stack recursion
internal sealed class SearchData
{
public SearchData(String fullPath, String userPath, SearchOption searchOption)
{
Contract.Requires(fullPath != null && fullPath.Length > 0);
Contract.Requires(userPath != null && userPath.Length > 0);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
this.fullPath = fullPath;
this.userPath = userPath;
this.searchOption = searchOption;
}
public readonly string fullPath; // Fully qualified search path excluding the search criteria in the end (ex, c:\temp\bar\foo)
public readonly string userPath; // User specified path (ex, bar\foo)
public readonly SearchOption searchOption;
}
// Returns fully qualified user path of dirs/files that matches the search parameters.
// For recursive search this method will search through all the sub dirs and execute
// the given search criteria against every dir.
// For all the dirs/files returned, it will then demand path discovery permission for
// their parent folders (it will avoid duplicate permission checks)
internal static String[] InternalGetFileDirectoryNames(String path, String userPathOriginal, String searchPattern, bool includeFiles, bool includeDirs, SearchOption searchOption)
{
Contract.Requires(path != null);
Contract.Requires(userPathOriginal != null);
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
IEnumerable<String> enumerable = FileSystem.Current.EnumeratePaths(path, searchPattern, searchOption,
(includeFiles ? SearchTarget.Files : 0) | (includeDirs ? SearchTarget.Directories : 0));
List<String> fileList = new List<String>(enumerable);
return fileList.ToArray();
}
public static IEnumerable<String> EnumerateDirectories(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.EndContractBlock();
return InternalEnumerateDirectories(path, "*", SearchOption.TopDirectoryOnly);
}
public static IEnumerable<String> EnumerateDirectories(String path, String searchPattern)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
Contract.EndContractBlock();
return InternalEnumerateDirectories(path, searchPattern, SearchOption.TopDirectoryOnly);
}
public static IEnumerable<String> EnumerateDirectories(String path, String searchPattern, SearchOption searchOption)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum);
Contract.EndContractBlock();
return InternalEnumerateDirectories(path, searchPattern, searchOption);
}
private static IEnumerable<String> InternalEnumerateDirectories(String path, String searchPattern, SearchOption searchOption)
{
Contract.Requires(path != null);
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
return EnumerateFileSystemNames(path, searchPattern, searchOption, false, true);
}
public static IEnumerable<String> EnumerateFiles(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
Contract.EndContractBlock();
return InternalEnumerateFiles(path, "*", SearchOption.TopDirectoryOnly);
}
public static IEnumerable<String> EnumerateFiles(String path, String searchPattern)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
Contract.EndContractBlock();
return InternalEnumerateFiles(path, searchPattern, SearchOption.TopDirectoryOnly);
}
public static IEnumerable<String> EnumerateFiles(String path, String searchPattern, SearchOption searchOption)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum);
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
Contract.EndContractBlock();
return InternalEnumerateFiles(path, searchPattern, searchOption);
}
private static IEnumerable<String> InternalEnumerateFiles(String path, String searchPattern, SearchOption searchOption)
{
Contract.Requires(path != null);
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
return EnumerateFileSystemNames(path, searchPattern, searchOption, true, false);
}
public static IEnumerable<String> EnumerateFileSystemEntries(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
Contract.EndContractBlock();
return InternalEnumerateFileSystemEntries(path, "*", SearchOption.TopDirectoryOnly);
}
public static IEnumerable<String> EnumerateFileSystemEntries(String path, String searchPattern)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
Contract.EndContractBlock();
return InternalEnumerateFileSystemEntries(path, searchPattern, SearchOption.TopDirectoryOnly);
}
public static IEnumerable<String> EnumerateFileSystemEntries(String path, String searchPattern, SearchOption searchOption)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum);
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
Contract.EndContractBlock();
return InternalEnumerateFileSystemEntries(path, searchPattern, searchOption);
}
private static IEnumerable<String> InternalEnumerateFileSystemEntries(String path, String searchPattern, SearchOption searchOption)
{
Contract.Requires(path != null);
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
return EnumerateFileSystemNames(path, searchPattern, searchOption, true, true);
}
private static IEnumerable<String> EnumerateFileSystemNames(String path, String searchPattern, SearchOption searchOption,
bool includeFiles, bool includeDirs)
{
Contract.Requires(path != null);
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
return FileSystem.Current.EnumeratePaths(path, searchPattern, searchOption,
(includeFiles ? SearchTarget.Files : 0) | (includeDirs ? SearchTarget.Directories : 0));
}
[System.Security.SecuritySafeCritical]
public static String GetDirectoryRoot(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.EndContractBlock();
String fullPath = PathHelpers.GetFullPathInternal(path);
String root = fullPath.Substring(0, PathHelpers.GetRootLength(fullPath));
return root;
}
internal static String InternalGetDirectoryRoot(String path)
{
if (path == null) return null;
return path.Substring(0, PathHelpers.GetRootLength(path));
}
/*===============================CurrentDirectory===============================
**Action: Provides a getter and setter for the current directory. The original
** current DirectoryInfo is the one from which the process was started.
**Returns: The current DirectoryInfo (from the getter). Void from the setter.
**Arguments: The current DirectoryInfo to which to switch to the setter.
**Exceptions:
==============================================================================*/
[System.Security.SecuritySafeCritical]
public static String GetCurrentDirectory()
{
return FileSystem.Current.GetCurrentDirectory();
}
[System.Security.SecurityCritical] // auto-generated
public static void SetCurrentDirectory(String path)
{
if (path == null)
throw new ArgumentNullException("value");
if (path.Length == 0)
throw new ArgumentException(SR.Argument_PathEmpty);
Contract.EndContractBlock();
if (path.Length >= FileSystem.Current.MaxPath)
throw new PathTooLongException(SR.IO_PathTooLong);
String fulldestDirName = PathHelpers.GetFullPathInternal(path);
FileSystem.Current.SetCurrentDirectory(fulldestDirName);
}
[System.Security.SecuritySafeCritical]
public static void Move(String sourceDirName, String destDirName)
{
if (sourceDirName == null)
throw new ArgumentNullException("sourceDirName");
if (sourceDirName.Length == 0)
throw new ArgumentException(SR.Argument_EmptyFileName, "sourceDirName");
if (destDirName == null)
throw new ArgumentNullException("destDirName");
if (destDirName.Length == 0)
throw new ArgumentException(SR.Argument_EmptyFileName, "destDirName");
Contract.EndContractBlock();
String fullsourceDirName = PathHelpers.GetFullPathInternal(sourceDirName);
String sourcePath = EnsureTrailingDirectorySeparator(fullsourceDirName);
int maxDirectoryPath = FileSystem.Current.MaxDirectoryPath;
if (sourcePath.Length >= maxDirectoryPath)
throw new PathTooLongException(SR.IO_PathTooLong);
String fulldestDirName = PathHelpers.GetFullPathInternal(destDirName);
String destPath = EnsureTrailingDirectorySeparator(fulldestDirName);
if (destPath.Length >= maxDirectoryPath)
throw new PathTooLongException(SR.IO_PathTooLong);
StringComparison pathComparison = PathInternal.GetComparison();
if (String.Compare(sourcePath, destPath, pathComparison) == 0)
throw new IOException(SR.IO_SourceDestMustBeDifferent);
String sourceRoot = Path.GetPathRoot(sourcePath);
String destinationRoot = Path.GetPathRoot(destPath);
if (String.Compare(sourceRoot, destinationRoot, pathComparison) != 0)
throw new IOException(SR.IO_SourceDestMustHaveSameRoot);
FileSystem.Current.MoveDirectory(fullsourceDirName, fulldestDirName);
}
[System.Security.SecuritySafeCritical]
public static void Delete(String path)
{
String fullPath = PathHelpers.GetFullPathInternal(path);
FileSystem.Current.RemoveDirectory(fullPath, false);
}
[System.Security.SecuritySafeCritical]
public static void Delete(String path, bool recursive)
{
String fullPath = PathHelpers.GetFullPathInternal(path);
FileSystem.Current.RemoveDirectory(fullPath, recursive);
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Diagnostics.TypeStyle;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.CSharp.TypeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.UnitTests;
using Microsoft.CodeAnalysis.Options;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.UseExplicitType
{
public partial class UseExplicitTypeTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
internal override Tuple<DiagnosticAnalyzer, CodeFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) =>
new Tuple<DiagnosticAnalyzer, CodeFixProvider>(
new CSharpUseExplicitTypeDiagnosticAnalyzer(),
new UseExplicitTypeCodeFixProvider());
private readonly CodeStyleOption<bool> onWithNone = new CodeStyleOption<bool>(true, NotificationOption.None);
private readonly CodeStyleOption<bool> offWithNone = new CodeStyleOption<bool>(false, NotificationOption.None);
private readonly CodeStyleOption<bool> onWithInfo = new CodeStyleOption<bool>(true, NotificationOption.Suggestion);
private readonly CodeStyleOption<bool> offWithInfo = new CodeStyleOption<bool>(false, NotificationOption.Suggestion);
private readonly CodeStyleOption<bool> onWithWarning = new CodeStyleOption<bool>(true, NotificationOption.Warning);
private readonly CodeStyleOption<bool> offWithWarning = new CodeStyleOption<bool>(false, NotificationOption.Warning);
private readonly CodeStyleOption<bool> onWithError = new CodeStyleOption<bool>(true, NotificationOption.Error);
private readonly CodeStyleOption<bool> offWithError = new CodeStyleOption<bool>(false, NotificationOption.Error);
// specify all options explicitly to override defaults.
private IDictionary<OptionKey, object> ExplicitTypeEverywhere() => OptionsSet(
SingleOption(CSharpCodeStyleOptions.UseImplicitTypeWherePossible, offWithInfo),
SingleOption(CSharpCodeStyleOptions.UseImplicitTypeWhereApparent, offWithInfo),
SingleOption(CSharpCodeStyleOptions.UseImplicitTypeForIntrinsicTypes, offWithInfo));
private IDictionary<OptionKey, object> ExplicitTypeExceptWhereApparent() => OptionsSet(
SingleOption(CSharpCodeStyleOptions.UseImplicitTypeWherePossible, offWithInfo),
SingleOption(CSharpCodeStyleOptions.UseImplicitTypeWhereApparent, onWithInfo),
SingleOption(CSharpCodeStyleOptions.UseImplicitTypeForIntrinsicTypes, offWithInfo));
private IDictionary<OptionKey, object> ExplicitTypeForBuiltInTypesOnly() => OptionsSet(
SingleOption(CSharpCodeStyleOptions.UseImplicitTypeWherePossible, onWithInfo),
SingleOption(CSharpCodeStyleOptions.UseImplicitTypeWhereApparent, onWithInfo),
SingleOption(CSharpCodeStyleOptions.UseImplicitTypeForIntrinsicTypes, offWithInfo));
private IDictionary<OptionKey, object> ExplicitTypeEnforcements() => OptionsSet(
SingleOption(CSharpCodeStyleOptions.UseImplicitTypeWherePossible, offWithWarning),
SingleOption(CSharpCodeStyleOptions.UseImplicitTypeWhereApparent, offWithError),
SingleOption(CSharpCodeStyleOptions.UseImplicitTypeForIntrinsicTypes, offWithInfo));
private IDictionary<OptionKey, object> ExplicitTypeNoneEnforcement() => OptionsSet(
SingleOption(CSharpCodeStyleOptions.UseImplicitTypeWherePossible, offWithNone),
SingleOption(CSharpCodeStyleOptions.UseImplicitTypeWhereApparent, offWithNone),
SingleOption(CSharpCodeStyleOptions.UseImplicitTypeForIntrinsicTypes, offWithNone));
private IDictionary<OptionKey, object> Options(OptionKey option, object value)
{
var options = new Dictionary<OptionKey, object>();
options.Add(option, value);
return options;
}
#region Error Cases
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnFieldDeclaration()
{
await TestMissingAsync(
@"using System;
class Program
{
[|var|] _myfield = 5;
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnFieldLikeEvents()
{
await TestMissingAsync(
@"using System;
class Program
{
public event [|var|] _myevent;
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnAnonymousMethodExpression()
{
await TestMissingAsync(
@"using System;
class Program
{
void Method()
{
[|var|] comparer = delegate (string value) {
return value != ""0"";
};
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnLambdaExpression()
{
await TestMissingAsync(
@"using System;
class Program
{
void Method()
{
[|var|] x = y => y * y;
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnDeclarationWithMultipleDeclarators()
{
await TestMissingAsync(
@"using System;
class Program
{
void Method()
{
[|var|] x = 5, y = x;
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnDeclarationWithoutInitializer()
{
await TestMissingAsync(
@"using System;
class Program
{
void Method()
{
[|var|] x;
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotDuringConflicts()
{
await TestMissingAsync(
@"using System;
class Program
{
void Method()
{
[|var|] p = new var();
}
class var
{
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotIfAlreadyExplicitlyTyped()
{
await TestMissingAsync(
@"using System;
class Program
{
void Method()
{
[|Program|] p = new Program();
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnRHS()
{
await TestMissingAsync(
@"using System;
class C
{
void M()
{
var c = new [|var|]();
}
}
class var
{
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnErrorSymbol()
{
await TestMissingAsync(
@"using System;
class Program
{
void Method()
{
[|var|] x = new Foo();
}
}", options: ExplicitTypeEverywhere());
}
#endregion
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnDynamic()
{
await TestMissingAsync(
@"using System;
class Program
{
void Method()
{
[|dynamic|] x = 1;
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnForEachVarWithAnonymousType()
{
await TestMissingAsync(
@"using System;
using System.Linq;
class Program
{
void Method()
{
var values = Enumerable.Range(1, 5).Select(i => new { Value = i });
foreach ([|var|] value in values)
{
Console.WriteLine(value.Value);
}
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task OnForEachVarWithExplicitType()
{
await TestAsync(
@"using System;
using System.Linq;
class Program
{
void Method()
{
var values = Enumerable.Range(1, 5);
foreach ([|var|] value in values)
{
Console.WriteLine(value.Value);
}
}
}",
@"using System;
using System.Linq;
class Program
{
void Method()
{
var values = Enumerable.Range(1, 5);
foreach (int value in values)
{
Console.WriteLine(value.Value);
}
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnAnonymousType()
{
await TestMissingAsync(
@"using System;
class Program
{
void Method()
{
[|var|] x = new { Amount = 108, Message = ""Hello"" };
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnArrayOfAnonymousType()
{
await TestMissingAsync(
@"using System;
class Program
{
void Method()
{
[|var|] x = new[] { new { name = ""apple"", diam = 4 }, new { name = ""grape"", diam = 1 } };
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnEnumerableOfAnonymousTypeFromAQueryExpression()
{
await TestMissingAsync(
@"using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
void Method()
{
var products = new List<Product>();
[|var|] productQuery = from prod in products
select new { prod.Color, prod.Price };
}
}
class Product
{
public ConsoleColor Color { get; set; }
public int Price { get; set; }
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnLocalWithIntrinsicTypeString()
{
await TestAsync(
@"using System;
class C
{
static void M()
{
[|var|] s = ""hello"";
}
}",
@"using System;
class C
{
static void M()
{
string s = ""hello"";
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnIntrinsicType()
{
await TestAsync(
@"using System;
class C
{
static void M()
{
[|var|] s = 5;
}
}",
@"using System;
class C
{
static void M()
{
int s = 5;
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnFrameworkType()
{
await TestAsync(
@"using System.Collections.Generic;
class C
{
static void M()
{
[|var|] c = new List<int>();
}
}",
@"using System.Collections.Generic;
class C
{
static void M()
{
List<int> c = new List<int>();
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnUserDefinedType()
{
await TestAsync(
@"using System;
class C
{
void M()
{
[|var|] c = new C();
}
}",
@"using System;
class C
{
void M()
{
C c = new C();
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnGenericType()
{
await TestAsync(
@"using System;
class C<T>
{
static void M()
{
[|var|] c = new C<int>();
}
}",
@"using System;
class C<T>
{
static void M()
{
C<int> c = new C<int>();
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnSingleDimensionalArrayTypeWithNewOperator()
{
await TestAsync(
@"using System;
class C
{
static void M()
{
[|var|] n1 = new int[4] { 2, 4, 6, 8 };
}
}",
@"using System;
class C
{
static void M()
{
int[] n1 = new int[4] { 2, 4, 6, 8 };
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnSingleDimensionalArrayTypeWithNewOperator2()
{
await TestAsync(
@"using System;
class C
{
static void M()
{
[|var|] n1 = new[] { 2, 4, 6, 8 };
}
}",
@"using System;
class C
{
static void M()
{
int[] n1 = new[] { 2, 4, 6, 8 };
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnSingleDimensionalJaggedArrayType()
{
await TestAsync(
@"using System;
class C
{
static void M()
{
[|var|] cs = new[] {
new[] { 1, 2, 3, 4 },
new[] { 5, 6, 7, 8 }
};
}
}",
@"using System;
class C
{
static void M()
{
int[][] cs = new[] {
new[] { 1, 2, 3, 4 },
new[] { 5, 6, 7, 8 }
};
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnDeclarationWithObjectInitializer()
{
await TestAsync(
@"using System;
class C
{
static void M()
{
[|var|] cc = new Customer { City = ""Madras"" };
}
private class Customer
{
public string City { get; set; }
}
}",
@"using System;
class C
{
static void M()
{
Customer cc = new Customer { City = ""Madras"" };
}
private class Customer
{
public string City { get; set; }
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnDeclarationWithCollectionInitializer()
{
await TestAsync(
@"using System;
using System.Collections.Generic;
class C
{
static void M()
{
[|var|] digits = new List<int> { 1, 2, 3 };
}
}",
@"using System;
using System.Collections.Generic;
class C
{
static void M()
{
List<int> digits = new List<int> { 1, 2, 3 };
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnDeclarationWithCollectionAndObjectInitializers()
{
await TestAsync(
@"using System;
using System.Collections.Generic;
class C
{
static void M()
{
[|var|] cs = new List<Customer>
{
new Customer { City = ""Madras"" }
};
}
private class Customer
{
public string City { get; set; }
}
}",
@"using System;
using System.Collections.Generic;
class C
{
static void M()
{
List<Customer> cs = new List<Customer>
{
new Customer { City = ""Madras"" }
};
}
private class Customer
{
public string City { get; set; }
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnForStatement()
{
await TestAsync(
@"using System;
class C
{
static void M()
{
for ([|var|] i = 0; i < 5; i++)
{
}
}
}",
@"using System;
class C
{
static void M()
{
for (int i = 0; i < 5; i++)
{
}
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnForeachStatement()
{
await TestAsync(
@"using System;
using System.Collections.Generic;
class C
{
static void M()
{
var l = new List<int> { 1, 3, 5 };
foreach ([|var|] item in l)
{
}
}
}",
@"using System;
using System.Collections.Generic;
class C
{
static void M()
{
var l = new List<int> { 1, 3, 5 };
foreach (int item in l)
{
}
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnQueryExpression()
{
await TestAsync(
@"using System;
using System.Collections.Generic;
using System.Linq;
class C
{
static void M()
{
var customers = new List<Customer>();
[|var|] expr = from c in customers
where c.City == ""London""
select c;
}
private class Customer
{
public string City { get; set; }
}
}
}",
@"using System;
using System.Collections.Generic;
using System.Linq;
class C
{
static void M()
{
var customers = new List<Customer>();
IEnumerable<Customer> expr = from c in customers
where c.City == ""London""
select c;
}
private class Customer
{
public string City { get; set; }
}
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeInUsingStatement()
{
await TestAsync(
@"using System;
class C
{
static void M()
{
using ([|var|] r = new Res())
{
}
}
private class Res : IDisposable
{
public void Dispose()
{
throw new NotImplementedException();
}
}
}",
@"using System;
class C
{
static void M()
{
using (Res r = new Res())
{
}
}
private class Res : IDisposable
{
public void Dispose()
{
throw new NotImplementedException();
}
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnInterpolatedString()
{
await TestAsync(
@"using System;
class Program
{
void Method()
{
[|var|] s = $""Hello, {name}""
}
}",
@"using System;
class Program
{
void Method()
{
string s = $""Hello, {name}""
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnExplicitConversion()
{
await TestAsync(
@"using System;
class C
{
static void M()
{
double x = 1234.7;
[|var|] a = (int)x;
}
}",
@"using System;
class C
{
static void M()
{
double x = 1234.7;
int a = (int)x;
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnConditionalAccessExpression()
{
await TestAsync(
@"using System;
class C
{
static void M()
{
C obj = new C();
[|var|] anotherObj = obj?.Test();
}
C Test()
{
return this;
}
}",
@"using System;
class C
{
static void M()
{
C obj = new C();
C anotherObj = obj?.Test();
}
C Test()
{
return this;
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseImplicitType)]
public async Task SuggestExplicitTypeInCheckedExpression()
{
await TestAsync(
@"using System;
class C
{
static void M()
{
long number1 = int.MaxValue + 20L;
[|var|] intNumber = checked((int)number1);
}
}",
@"using System;
class C
{
static void M()
{
long number1 = int.MaxValue + 20L;
int intNumber = checked((int)number1);
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseImplicitType)]
public async Task SuggestExplicitTypeInAwaitExpression()
{
await TestAsync(
@"using System;
using System.Threading.Tasks;
class C
{
public async void ProcessRead()
{
[|var|] text = await ReadTextAsync(null);
}
private async Task<string> ReadTextAsync(string filePath)
{
return string.Empty;
}
}",
@"using System;
using System.Threading.Tasks;
class C
{
public async void ProcessRead()
{
string text = await ReadTextAsync(null);
}
private async Task<string> ReadTextAsync(string filePath)
{
return string.Empty;
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseImplicitType)]
public async Task SuggestExplicitTypeInBuiltInNumericType()
{
await TestAsync(
@"using System;
class C
{
public void ProcessRead()
{
[|var|] text = 1;
}
}",
@"using System;
class C
{
public void ProcessRead()
{
int text = 1;
}
}", options: ExplicitTypeForBuiltInTypesOnly());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseImplicitType)]
public async Task SuggestExplicitTypeInBuiltInCharType()
{
await TestAsync(
@"using System;
class C
{
public void ProcessRead()
{
[|var|] text = GetChar();
}
public char GetChar() => 'c';
}",
@"using System;
class C
{
public void ProcessRead()
{
char text = GetChar();
}
public char GetChar() => 'c';
}", options: ExplicitTypeForBuiltInTypesOnly());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseImplicitType)]
public async Task SuggestExplicitTypeInBuiltInType_string()
{
// though string isn't an intrinsic type per the compiler
// we in the IDE treat it as an intrinsic type for this feature.
await TestAsync(
@"using System;
class C
{
public void ProcessRead()
{
[|var|] text = string.Empty;
}
}",
@"using System;
class C
{
public void ProcessRead()
{
string text = string.Empty;
}
}", options: ExplicitTypeForBuiltInTypesOnly());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseImplicitType)]
public async Task SuggestExplicitTypeInBuiltInType_object()
{
// object isn't an intrinsic type per the compiler
// we in the IDE treat it as an intrinsic type for this feature.
await TestAsync(
@"using System;
class C
{
public void ProcessRead()
{
object j = new C();
[|var|] text = j;
}
}",
@"using System;
class C
{
public void ProcessRead()
{
object j = new C();
object text = j;
}
}", options: ExplicitTypeForBuiltInTypesOnly());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseImplicitType)]
public async Task SuggestExplicitTypeNotificationLevelNone()
{
var source =
@"using System;
class C
{
static void M()
{
[|var|] n1 = new C();
}
}";
await TestMissingAsync(source, ExplicitTypeNoneEnforcement());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseImplicitType)]
public async Task SuggestExplicitTypeNotificationLevelInfo()
{
var source =
@"using System;
class C
{
static void M()
{
[|var|] s = 5;
}
}";
await TestDiagnosticSeverityAndCountAsync(source,
options: ExplicitTypeEnforcements(),
diagnosticCount: 1,
diagnosticId: IDEDiagnosticIds.UseExplicitTypeDiagnosticId,
diagnosticSeverity: DiagnosticSeverity.Info);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseImplicitType)]
public async Task SuggestExplicitTypeNotificationLevelWarning()
{
var source =
@"using System;
class C
{
static void M()
{
[|var|] n1 = new[] {2, 4, 6, 8};
}
}";
await TestDiagnosticSeverityAndCountAsync(source,
options: ExplicitTypeEnforcements(),
diagnosticCount: 1,
diagnosticId: IDEDiagnosticIds.UseExplicitTypeDiagnosticId,
diagnosticSeverity: DiagnosticSeverity.Warning);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseImplicitType)]
public async Task SuggestExplicitTypeNotificationLevelError()
{
var source =
@"using System;
class C
{
static void M()
{
[|var|] n1 = new C();
}
}";
await TestDiagnosticSeverityAndCountAsync(source,
options: ExplicitTypeEnforcements(),
diagnosticCount: 1,
diagnosticId: IDEDiagnosticIds.UseExplicitTypeDiagnosticId,
diagnosticSeverity: DiagnosticSeverity.Error);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnLocalWithIntrinsicTypeTuple()
{
await TestAsync(
@"class C
{
static void M()
{
[|var|] s = (1, ""hello"");
}
}",
@"class C
{
static void M()
{
(int, string) s = (1, ""hello"");
}
}",
options: ExplicitTypeEverywhere(),
parseOptions: TestOptions.Regular,
withScriptOption: true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnLocalWithIntrinsicTypeTupleWithNames()
{
await TestAsync(
@"class C
{
static void M()
{
[|var|] s = (a: 1, b: ""hello"");
}
}",
@"class C
{
static void M()
{
(int a, string b) s = (a: 1, b: ""hello"");
}
}",
options: ExplicitTypeEverywhere(),
parseOptions: TestOptions.Regular,
withScriptOption: true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnLocalWithIntrinsicTypeTupleWithOneName()
{
await TestAsync(
@"class C
{
static void M()
{
[|var|] s = (a: 1, ""hello"");
}
}",
@"class C
{
static void M()
{
(int a, string) s = (a: 1, ""hello"");
}
}",
options: ExplicitTypeEverywhere(),
parseOptions: TestOptions.Regular,
withScriptOption: true);
}
}
}
| |
// 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.Text;
using System.Diagnostics;
using System.Runtime.Serialization; //For SR
using System.Globalization;
using System.Security;
namespace System.Text
{
internal class Base64Encoding : Encoding
{
private static byte[] s_char2val = new byte[128]
{
/* 0-15 */ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
/* 16-31 */ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
/* 32-47 */ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 62, 0xFF, 0xFF, 0xFF, 63,
/* 48-63 */ 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 0xFF, 0xFF, 0xFF, 64, 0xFF, 0xFF,
/* 64-79 */ 0xFF, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
/* 80-95 */ 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
/* 96-111 */ 0xFF, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
/* 112-127 */ 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
};
private static string s_val2char = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
private static byte[] s_val2byte = new byte[]
{
(byte)'A',(byte)'B',(byte)'C',(byte)'D',(byte)'E',(byte)'F',(byte)'G',(byte)'H',(byte)'I',(byte)'J',(byte)'K',(byte)'L',(byte)'M',(byte)'N',(byte)'O',(byte)'P',
(byte)'Q',(byte)'R',(byte)'S',(byte)'T',(byte)'U',(byte)'V',(byte)'W',(byte)'X',(byte)'Y',(byte)'Z',(byte)'a',(byte)'b',(byte)'c',(byte)'d',(byte)'e',(byte)'f',
(byte)'g',(byte)'h',(byte)'i',(byte)'j',(byte)'k',(byte)'l',(byte)'m',(byte)'n',(byte)'o',(byte)'p',(byte)'q',(byte)'r',(byte)'s',(byte)'t',(byte)'u',(byte)'v',
(byte)'w',(byte)'x',(byte)'y',(byte)'z',(byte)'0',(byte)'1',(byte)'2',(byte)'3',(byte)'4',(byte)'5',(byte)'6',(byte)'7',(byte)'8',(byte)'9',(byte)'+',(byte)'/'
};
public override int GetMaxByteCount(int charCount)
{
if (charCount < 0)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("charCount", string.Format(SRSerialization.ValueMustBeNonNegative)));
if ((charCount % 4) != 0)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(string.Format(SRSerialization.XmlInvalidBase64Length, charCount.ToString(NumberFormatInfo.CurrentInfo))));
return charCount / 4 * 3;
}
private bool IsValidLeadBytes(int v1, int v2, int v3, int v4)
{
// First two chars of a four char base64 sequence can't be ==, and must be valid
return ((v1 | v2) < 64) && ((v3 | v4) != 0xFF);
}
private bool IsValidTailBytes(int v3, int v4)
{
// If the third char is = then the fourth char must be =
return !(v3 == 64 && v4 != 64);
}
/// <SecurityNote>
/// Critical - contains unsafe code
/// Safe - unsafe code is effectively encapsulated, all inputs are validated
/// </SecurityNote>
[SecuritySafeCritical]
unsafe public override int GetByteCount(char[] chars, int index, int count)
{
if (chars == null)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("chars"));
if (index < 0)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("index", string.Format(SRSerialization.ValueMustBeNonNegative)));
if (index > chars.Length)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("index", string.Format(SRSerialization.OffsetExceedsBufferSize, chars.Length)));
if (count < 0)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", string.Format(SRSerialization.ValueMustBeNonNegative)));
if (count > chars.Length - index)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", string.Format(SRSerialization.SizeExceedsRemainingBufferSpace, chars.Length - index)));
if (count == 0)
return 0;
if ((count % 4) != 0)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(string.Format(SRSerialization.XmlInvalidBase64Length, count.ToString(NumberFormatInfo.CurrentInfo))));
fixed (byte* _char2val = s_char2val)
{
fixed (char* _chars = &chars[index])
{
int totalCount = 0;
char* pch = _chars;
char* pchMax = _chars + count;
while (pch < pchMax)
{
DiagnosticUtility.DebugAssert(pch + 4 <= pchMax, "");
char pch0 = pch[0];
char pch1 = pch[1];
char pch2 = pch[2];
char pch3 = pch[3];
if ((pch0 | pch1 | pch2 | pch3) >= 128)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(string.Format(SRSerialization.XmlInvalidBase64Sequence, new string(pch, 0, 4), index + (int)(pch - _chars))));
// xx765432 xx107654 xx321076 xx543210
// 76543210 76543210 76543210
int v1 = _char2val[pch0];
int v2 = _char2val[pch1];
int v3 = _char2val[pch2];
int v4 = _char2val[pch3];
if (!IsValidLeadBytes(v1, v2, v3, v4) || !IsValidTailBytes(v3, v4))
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(string.Format(SRSerialization.XmlInvalidBase64Sequence, new string(pch, 0, 4), index + (int)(pch - _chars))));
int byteCount = (v4 != 64 ? 3 : (v3 != 64 ? 2 : 1));
totalCount += byteCount;
pch += 4;
}
return totalCount;
}
}
}
/// <SecurityNote>
/// Critical - contains unsafe code
/// Safe - unsafe code is effectively encapsulated, all inputs are validated
/// </SecurityNote>
[SecuritySafeCritical]
unsafe public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex)
{
if (chars == null)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("chars"));
if (charIndex < 0)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("charIndex", string.Format(SRSerialization.ValueMustBeNonNegative)));
if (charIndex > chars.Length)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("charIndex", string.Format(SRSerialization.OffsetExceedsBufferSize, chars.Length)));
if (charCount < 0)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("charCount", string.Format(SRSerialization.ValueMustBeNonNegative)));
if (charCount > chars.Length - charIndex)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("charCount", string.Format(SRSerialization.SizeExceedsRemainingBufferSpace, chars.Length - charIndex)));
if (bytes == null)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("bytes"));
if (byteIndex < 0)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("byteIndex", string.Format(SRSerialization.ValueMustBeNonNegative)));
if (byteIndex > bytes.Length)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("byteIndex", string.Format(SRSerialization.OffsetExceedsBufferSize, bytes.Length)));
if (charCount == 0)
return 0;
if ((charCount % 4) != 0)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(string.Format(SRSerialization.XmlInvalidBase64Length, charCount.ToString(NumberFormatInfo.CurrentInfo))));
fixed (byte* _char2val = s_char2val)
{
fixed (char* _chars = &chars[charIndex])
{
fixed (byte* _bytes = &bytes[byteIndex])
{
char* pch = _chars;
char* pchMax = _chars + charCount;
byte* pb = _bytes;
byte* pbMax = _bytes + bytes.Length - byteIndex;
while (pch < pchMax)
{
DiagnosticUtility.DebugAssert(pch + 4 <= pchMax, "");
char pch0 = pch[0];
char pch1 = pch[1];
char pch2 = pch[2];
char pch3 = pch[3];
if ((pch0 | pch1 | pch2 | pch3) >= 128)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(string.Format(SRSerialization.XmlInvalidBase64Sequence, new string(pch, 0, 4), charIndex + (int)(pch - _chars))));
// xx765432 xx107654 xx321076 xx543210
// 76543210 76543210 76543210
int v1 = _char2val[pch0];
int v2 = _char2val[pch1];
int v3 = _char2val[pch2];
int v4 = _char2val[pch3];
if (!IsValidLeadBytes(v1, v2, v3, v4) || !IsValidTailBytes(v3, v4))
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(string.Format(SRSerialization.XmlInvalidBase64Sequence, new string(pch, 0, 4), charIndex + (int)(pch - _chars))));
int byteCount = (v4 != 64 ? 3 : (v3 != 64 ? 2 : 1));
if (pb + byteCount > pbMax)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(string.Format(SRSerialization.XmlArrayTooSmall), "bytes"));
pb[0] = (byte)((v1 << 2) | ((v2 >> 4) & 0x03));
if (byteCount > 1)
{
pb[1] = (byte)((v2 << 4) | ((v3 >> 2) & 0x0F));
if (byteCount > 2)
{
pb[2] = (byte)((v3 << 6) | ((v4 >> 0) & 0x3F));
}
}
pb += byteCount;
pch += 4;
}
return (int)(pb - _bytes);
}
}
}
}
/// <SecurityNote>
/// Critical - contains unsafe code
/// Safe - unsafe code is effectively encapsulated, all inputs are validated
/// </SecurityNote>
[SecuritySafeCritical]
unsafe public virtual int GetBytes(byte[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex)
{
if (chars == null)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("chars"));
if (charIndex < 0)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("charIndex", string.Format(SRSerialization.ValueMustBeNonNegative)));
if (charIndex > chars.Length)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("charIndex", string.Format(SRSerialization.OffsetExceedsBufferSize, chars.Length)));
if (charCount < 0)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("charCount", string.Format(SRSerialization.ValueMustBeNonNegative)));
if (charCount > chars.Length - charIndex)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("charCount", string.Format(SRSerialization.SizeExceedsRemainingBufferSpace, chars.Length - charIndex)));
if (bytes == null)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("bytes"));
if (byteIndex < 0)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("byteIndex", string.Format(SRSerialization.ValueMustBeNonNegative)));
if (byteIndex > bytes.Length)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("byteIndex", string.Format(SRSerialization.OffsetExceedsBufferSize, bytes.Length)));
if (charCount == 0)
return 0;
if ((charCount % 4) != 0)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(string.Format(SRSerialization.XmlInvalidBase64Length, charCount.ToString(NumberFormatInfo.CurrentInfo))));
fixed (byte* _char2val = s_char2val)
{
fixed (byte* _chars = &chars[charIndex])
{
fixed (byte* _bytes = &bytes[byteIndex])
{
byte* pch = _chars;
byte* pchMax = _chars + charCount;
byte* pb = _bytes;
byte* pbMax = _bytes + bytes.Length - byteIndex;
while (pch < pchMax)
{
DiagnosticUtility.DebugAssert(pch + 4 <= pchMax, "");
byte pch0 = pch[0];
byte pch1 = pch[1];
byte pch2 = pch[2];
byte pch3 = pch[3];
if ((pch0 | pch1 | pch2 | pch3) >= 128)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(string.Format(SRSerialization.XmlInvalidBase64Sequence, "?", charIndex + (int)(pch - _chars))));
// xx765432 xx107654 xx321076 xx543210
// 76543210 76543210 76543210
int v1 = _char2val[pch0];
int v2 = _char2val[pch1];
int v3 = _char2val[pch2];
int v4 = _char2val[pch3];
if (!IsValidLeadBytes(v1, v2, v3, v4) || !IsValidTailBytes(v3, v4))
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(string.Format(SRSerialization.XmlInvalidBase64Sequence, "?", charIndex + (int)(pch - _chars))));
int byteCount = (v4 != 64 ? 3 : (v3 != 64 ? 2 : 1));
if (pb + byteCount > pbMax)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(string.Format(SRSerialization.XmlArrayTooSmall), "bytes"));
pb[0] = (byte)((v1 << 2) | ((v2 >> 4) & 0x03));
if (byteCount > 1)
{
pb[1] = (byte)((v2 << 4) | ((v3 >> 2) & 0x0F));
if (byteCount > 2)
{
pb[2] = (byte)((v3 << 6) | ((v4 >> 0) & 0x3F));
}
}
pb += byteCount;
pch += 4;
}
return (int)(pb - _bytes);
}
}
}
}
public override int GetMaxCharCount(int byteCount)
{
if (byteCount < 0 || byteCount > int.MaxValue / 4 * 3 - 2)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("byteCount", string.Format(SRSerialization.ValueMustBeInRange, 0, int.MaxValue / 4 * 3 - 2)));
return ((byteCount + 2) / 3) * 4;
}
public override int GetCharCount(byte[] bytes, int index, int count)
{
return GetMaxCharCount(count);
}
/// <SecurityNote>
/// Critical - contains unsafe code
/// Safe - unsafe code is effectively encapsulated, all inputs are validated
/// </SecurityNote>
[SecuritySafeCritical]
unsafe public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
{
if (bytes == null)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("bytes"));
if (byteIndex < 0)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("byteIndex", string.Format(SRSerialization.ValueMustBeNonNegative)));
if (byteIndex > bytes.Length)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("byteIndex", string.Format(SRSerialization.OffsetExceedsBufferSize, bytes.Length)));
if (byteCount < 0)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("byteCount", string.Format(SRSerialization.ValueMustBeNonNegative)));
if (byteCount > bytes.Length - byteIndex)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("byteCount", string.Format(SRSerialization.SizeExceedsRemainingBufferSpace, bytes.Length - byteIndex)));
int charCount = GetCharCount(bytes, byteIndex, byteCount);
if (chars == null)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("chars"));
if (charIndex < 0)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("charIndex", string.Format(SRSerialization.ValueMustBeNonNegative)));
if (charIndex > chars.Length)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("charIndex", string.Format(SRSerialization.OffsetExceedsBufferSize, chars.Length)));
if (charCount < 0 || charCount > chars.Length - charIndex)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(string.Format(SRSerialization.XmlArrayTooSmall), "chars"));
// We've computed exactly how many chars there are and verified that
// there's enough space in the char buffer, so we can proceed without
// checking the charCount.
if (byteCount > 0)
{
fixed (char* _val2char = s_val2char)
{
fixed (byte* _bytes = &bytes[byteIndex])
{
fixed (char* _chars = &chars[charIndex])
{
byte* pb = _bytes;
byte* pbMax = pb + byteCount - 3;
char* pch = _chars;
// Convert chunks of 3 bytes to 4 chars
while (pb <= pbMax)
{
// 76543210 76543210 76543210
// xx765432 xx107654 xx321076 xx543210
// Inspect the code carefully before you change this
pch[0] = _val2char[(pb[0] >> 2)];
pch[1] = _val2char[((pb[0] & 0x03) << 4) | (pb[1] >> 4)];
pch[2] = _val2char[((pb[1] & 0x0F) << 2) | (pb[2] >> 6)];
pch[3] = _val2char[pb[2] & 0x3F];
pb += 3;
pch += 4;
}
// Handle 1 or 2 trailing bytes
if (pb - pbMax == 2)
{
// 1 trailing byte
// 76543210 xxxxxxxx xxxxxxxx
// xx765432 xx10xxxx xxxxxxxx xxxxxxxx
pch[0] = _val2char[(pb[0] >> 2)];
pch[1] = _val2char[((pb[0] & 0x03) << 4)];
pch[2] = '=';
pch[3] = '=';
}
else if (pb - pbMax == 1)
{
// 2 trailing bytes
// 76543210 76543210 xxxxxxxx
// xx765432 xx107654 xx3210xx xxxxxxxx
pch[0] = _val2char[(pb[0] >> 2)];
pch[1] = _val2char[((pb[0] & 0x03) << 4) | (pb[1] >> 4)];
pch[2] = _val2char[((pb[1] & 0x0F) << 2)];
pch[3] = '=';
}
else
{
// 0 trailing bytes
DiagnosticUtility.DebugAssert(pb - pbMax == 3, "");
}
}
}
}
}
return charCount;
}
/// <SecurityNote>
/// Critical - contains unsafe code
/// Safe - unsafe code is effectively encapsulated, all inputs are validated
/// </SecurityNote>
[SecuritySafeCritical]
unsafe public int GetChars(byte[] bytes, int byteIndex, int byteCount, byte[] chars, int charIndex)
{
if (bytes == null)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("bytes"));
if (byteIndex < 0)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("byteIndex", string.Format(SRSerialization.ValueMustBeNonNegative)));
if (byteIndex > bytes.Length)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("byteIndex", string.Format(SRSerialization.OffsetExceedsBufferSize, bytes.Length)));
if (byteCount < 0)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("byteCount", string.Format(SRSerialization.ValueMustBeNonNegative)));
if (byteCount > bytes.Length - byteIndex)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("byteCount", string.Format(SRSerialization.SizeExceedsRemainingBufferSpace, bytes.Length - byteIndex)));
int charCount = GetCharCount(bytes, byteIndex, byteCount);
if (chars == null)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("chars"));
if (charIndex < 0)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("charIndex", string.Format(SRSerialization.ValueMustBeNonNegative)));
if (charIndex > chars.Length)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("charIndex", string.Format(SRSerialization.OffsetExceedsBufferSize, chars.Length)));
if (charCount < 0 || charCount > chars.Length - charIndex)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(string.Format(SRSerialization.XmlArrayTooSmall), "chars"));
// We've computed exactly how many chars there are and verified that
// there's enough space in the char buffer, so we can proceed without
// checking the charCount.
if (byteCount > 0)
{
fixed (byte* _val2byte = s_val2byte)
{
fixed (byte* _bytes = &bytes[byteIndex])
{
fixed (byte* _chars = &chars[charIndex])
{
byte* pb = _bytes;
byte* pbMax = pb + byteCount - 3;
byte* pch = _chars;
// Convert chunks of 3 bytes to 4 chars
while (pb <= pbMax)
{
// 76543210 76543210 76543210
// xx765432 xx107654 xx321076 xx543210
// Inspect the code carefully before you change this
pch[0] = _val2byte[(pb[0] >> 2)];
pch[1] = _val2byte[((pb[0] & 0x03) << 4) | (pb[1] >> 4)];
pch[2] = _val2byte[((pb[1] & 0x0F) << 2) | (pb[2] >> 6)];
pch[3] = _val2byte[pb[2] & 0x3F];
pb += 3;
pch += 4;
}
// Handle 1 or 2 trailing bytes
if (pb - pbMax == 2)
{
// 1 trailing byte
// 76543210 xxxxxxxx xxxxxxxx
// xx765432 xx10xxxx xxxxxxxx xxxxxxxx
pch[0] = _val2byte[(pb[0] >> 2)];
pch[1] = _val2byte[((pb[0] & 0x03) << 4)];
pch[2] = (byte)'=';
pch[3] = (byte)'=';
}
else if (pb - pbMax == 1)
{
// 2 trailing bytes
// 76543210 76543210 xxxxxxxx
// xx765432 xx107654 xx3210xx xxxxxxxx
pch[0] = _val2byte[(pb[0] >> 2)];
pch[1] = _val2byte[((pb[0] & 0x03) << 4) | (pb[1] >> 4)];
pch[2] = _val2byte[((pb[1] & 0x0F) << 2)];
pch[3] = (byte)'=';
}
else
{
// 0 trailing bytes
DiagnosticUtility.DebugAssert(pb - pbMax == 3, "");
}
}
}
}
}
return charCount;
}
}
}
| |
// Copyright 2014 The Rector & Visitors of the University of Virginia
//
// 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.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using Newtonsoft.Json;
using SensusService.Probes;
using SensusService.Probes.Location;
using SensusUI.UiProperties;
using Xamarin;
using System.Collections.ObjectModel;
using SensusUI;
using SensusUI.Inputs;
using Xamarin.Forms;
using SensusService.Exceptions;
using ZXing.Mobile;
using ZXing;
using XLabs.Platform.Device;
using System.Collections;
using Plugin.Geolocator.Abstractions;
using Plugin.Permissions;
using Plugin.Permissions.Abstractions;
using System.Threading.Tasks;
namespace SensusService
{
/// <summary>
/// Provides platform-independent service functionality.
/// </summary>
public abstract class SensusServiceHelper
{
#region static members
private static SensusServiceHelper SINGLETON;
private static readonly object PROMPT_FOR_INPUTS_LOCKER = new object();
private static bool PROMPT_FOR_INPUTS_RUNNING = false;
public const string SENSUS_CALLBACK_KEY = "SENSUS-CALLBACK";
public const string SENSUS_CALLBACK_ID_KEY = "SENSUS-CALLBACK-ID";
public const string SENSUS_CALLBACK_REPEATING_KEY = "SENSUS-CALLBACK-REPEATING";
public const string SENSUS_CALLBACK_REPEAT_DELAY_KEY = "SENSUS-CALLBACK-REPEAT-DELAY";
public const string SENSUS_CALLBACK_REPEAT_LAG_KEY = "SENSUS-CALLBACK-REPEAT-LAG";
public const int PARTICIPATION_VERIFICATION_TIMEOUT_SECONDS = 60;
protected const string XAMARIN_INSIGHTS_APP_KEY = "";
private const string ENCRYPTION_KEY = "";
public static readonly string SHARE_DIRECTORY = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "share");
private static readonly string LOG_PATH = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "sensus_log.txt");
private static readonly string SERIALIZATION_PATH = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "sensus_service_helper.json");
public static bool PromptForInputsRunning
{
get { return PROMPT_FOR_INPUTS_RUNNING; }
}
#if DEBUG || UNIT_TESTING
// test every 30 seconds in debug
public const int HEALTH_TEST_DELAY_MS = 30000;
#elif RELEASE
// test every 5 minutes in release
public const int HEALTH_TEST_DELAY_MS = 300000;
#endif
/// <summary>
/// Health tests times are used to compute participation for the listening probes. They must
/// be as tight as possible.
/// </summary>
private const bool HEALTH_TEST_REPEAT_LAG = false;
public static readonly JsonSerializerSettings JSON_SERIALIZER_SETTINGS = new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.Objects,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
TypeNameHandling = TypeNameHandling.All,
ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor,
#region need the following in order to deserialize protocols between OSs, whose objects contain different members (e.g., iOS service helper has ActivationId, which Android does not)
Error = (o, e) =>
{
SensusServiceHelper.Get().Logger.Log("Failed to deserialize some part of the JSON: " + e.ErrorContext.Error.ToString(), LoggingLevel.Normal, typeof(Protocol));
e.ErrorContext.Handled = true;
},
MissingMemberHandling = MissingMemberHandling.Ignore, // need to ignore missing members for cross-platform deserialization
Formatting = Formatting.Indented // must use indented formatting in order for cross-platform type conversion to work (depends on each "$type" name-value pair being on own line).
#endregion
};
private static byte[] EncryptionKeyBytes
{
get
{
byte[] encryptionKeyBytes = new byte[32];
byte[] bytes = Encoding.UTF8.GetBytes(ENCRYPTION_KEY);
Array.Copy(bytes, encryptionKeyBytes, Math.Min(bytes.Length, encryptionKeyBytes.Length));
return encryptionKeyBytes;
}
}
/// <summary>
/// Initializes the sensus service helper. Must be called when app first starts, from the main / UI thread.
/// </summary>
/// <param name="createNew">Function for creating a new service helper, if one is needed.</param>
public static void Initialize(Func<SensusServiceHelper> createNew)
{
if (SINGLETON == null)
{
Exception deserializeException;
if (!TryDeserializeSingleton(out deserializeException))
{
// we failed to deserialize. wait a bit and try again. but don't wait too long since we're holding up the
// app-load sequence, which is not allowed to take too much time.
Thread.Sleep(5000);
if (!TryDeserializeSingleton(out deserializeException))
{
// we really couldn't deserialize the service helper! try to create a new service helper...
try
{
SINGLETON = createNew();
}
catch (Exception singletonCreationException)
{
#region crash app and report to insights
string error = "Failed to construct service helper: " + singletonCreationException.Message + System.Environment.NewLine + singletonCreationException.StackTrace;
Console.Error.WriteLine(error);
Exception exceptionToReport = new Exception(error);
try
{
Insights.Report(exceptionToReport, Xamarin.Insights.Severity.Error);
}
catch (Exception insightsReportException)
{
Console.Error.WriteLine("Failed to report exception to Xamarin Insights: " + insightsReportException.Message);
}
throw exceptionToReport;
#endregion
}
SINGLETON.Logger.Log("Repeatedly failed to deserialize service helper. Most recent exception: " + deserializeException.Message, LoggingLevel.Normal, SINGLETON.GetType());
SINGLETON.Logger.Log("Created new service helper after failing to deserialize the old one.", LoggingLevel.Normal, SINGLETON.GetType());
}
}
}
else
SINGLETON.Logger.Log("Serivce helper already initialized. Nothing to do.", LoggingLevel.Normal, SINGLETON.GetType());
}
private static bool TryDeserializeSingleton(out Exception ex)
{
ex = null;
string errorMessage = null;
// read bytes
byte[] encryptedJsonBytes = null;
try
{
encryptedJsonBytes = ReadAllBytes(SERIALIZATION_PATH);
}
catch (Exception exception)
{
errorMessage = "Failed to read service helper file into byte array: " + exception.Message;
Console.Error.WriteLine(errorMessage);
}
if (encryptedJsonBytes != null)
{
// decrypt JSON
string decryptedJSON = null;
try
{
decryptedJSON = Decrypt(encryptedJsonBytes);
}
catch (Exception exception)
{
errorMessage = "Failed to decrypt service helper byte array (length=" + encryptedJsonBytes.Length + ") into JSON: " + exception.Message;
Console.Error.WriteLine(errorMessage);
}
if (decryptedJSON != null)
{
// deserialize service helper
try
{
SINGLETON = JsonConvert.DeserializeObject<SensusServiceHelper>(decryptedJSON, JSON_SERIALIZER_SETTINGS);
}
catch (Exception exception)
{
errorMessage = "Failed to deserialize service helper JSON (length=" + decryptedJSON.Length + ") into service helper: " + exception.Message;
Console.Error.WriteLine(errorMessage);
}
}
}
if (errorMessage != null)
ex = new Exception(errorMessage);
if (SINGLETON != null)
SINGLETON.Logger.Log("Deserialized service helper with " + SINGLETON.RegisteredProtocols.Count + " protocols.", LoggingLevel.Normal, SINGLETON.GetType());
return SINGLETON != null;
}
public static SensusServiceHelper Get()
{
return SINGLETON;
}
/// <summary>
/// Reads all bytes from a file. There's a File.ReadAllBytes method in Android / iOS, but not in WinPhone.
/// </summary>
/// <returns>The bytes.</returns>
/// <param name="path">Path.</param>
public static byte[] ReadAllBytes(string path)
{
byte[] fileBytes = null;
using (FileStream file = new FileStream(path, FileMode.Open, FileAccess.Read))
{
fileBytes = new byte[file.Length];
byte[] blockBytes = new byte[1024];
int blockBytesRead;
int totalBytesRead = 0;
while ((blockBytesRead = file.Read(blockBytes, 0, blockBytes.Length)) > 0)
{
Array.Copy(blockBytes, 0, fileBytes, totalBytesRead, blockBytesRead);
totalBytesRead += blockBytesRead;
}
if (totalBytesRead != fileBytes.Length)
throw new Exception("Mismatch between file length (" + file.Length + ") and bytes read (" + totalBytesRead + ").");
}
return fileBytes;
}
public static double GetDirectorySizeMB(string directory)
{
double directorySizeMB = 0;
foreach (string path in Directory.GetFiles(directory))
directorySizeMB += new FileInfo(path).Length / (1024d * 1024d);
return directorySizeMB;
}
#region encryption
public static byte[] Encrypt(string unencryptedString)
{
#if (__ANDROID__ || __IOS__)
using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider())
{
byte[] encryptionKeyBytes = EncryptionKeyBytes;
aes.KeySize = encryptionKeyBytes.Length * 8;
byte[] initialization = new byte[16];
aes.BlockSize = initialization.Length * 8;
using (ICryptoTransform transform = aes.CreateEncryptor(encryptionKeyBytes, initialization))
{
byte[] unencrypted = Encoding.Unicode.GetBytes(unencryptedString);
return transform.TransformFinalBlock(unencrypted, 0, unencrypted.Length);
}
}
#elif WINDOWS_PHONE
return ProtectedData.Protect(Encoding.Unicode.GetBytes(unencryptedString), EncryptionKeyBytes);
#else
#error "Unrecognized platform."
#endif
}
public static string Decrypt(byte[] encryptedBytes)
{
#if __ANDROID__ || __IOS__
using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider())
{
byte[] encryptionKeyBytes = EncryptionKeyBytes;
aes.KeySize = encryptionKeyBytes.Length * 8;
byte[] initialization = new byte[16];
aes.BlockSize = initialization.Length * 8;
using (ICryptoTransform transform = aes.CreateDecryptor(encryptionKeyBytes, initialization))
{
return Encoding.Unicode.GetString(transform.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length));
}
}
#elif WINDOWS_PHONE
byte[] unencryptedBytes = ProtectedData.Unprotect(encryptedBytes, EncryptionKeyBytes);
return Encoding.Unicode.GetString(unencryptedBytes, 0, unencryptedBytes.Length);
#else
#error "Unrecognized platform."
#endif
}
#endregion
#endregion
private Logger _logger;
private ObservableCollection<Protocol> _registeredProtocols;
private List<string> _runningProtocolIds;
private string _healthTestCallbackId;
private Dictionary<string, ScheduledCallback> _idCallback;
private SHA256Managed _hasher;
private List<PointOfInterest> _pointsOfInterest;
private ZXing.Mobile.MobileBarcodeScanner _barcodeScanner;
private ZXing.Mobile.BarcodeWriter _barcodeWriter;
private readonly object _shareFileLocker = new object();
private readonly object _saveLocker = new object();
[JsonIgnore]
public Logger Logger
{
get { return _logger; }
}
public ObservableCollection<Protocol> RegisteredProtocols
{
get { return _registeredProtocols; }
}
public List<string> RunningProtocolIds
{
get{ return _runningProtocolIds; }
}
public List<PointOfInterest> PointsOfInterest
{
get { return _pointsOfInterest; }
}
[JsonIgnore]
public ZXing.Mobile.MobileBarcodeScanner BarcodeScanner
{
get
{
return _barcodeScanner;
}
set
{
_barcodeScanner = value;
}
}
[JsonIgnore]
public ZXing.Mobile.BarcodeWriter BarcodeWriter
{
get
{
return _barcodeWriter;
}
}
[JsonIgnore]
public float GpsDesiredAccuracyMeters
{
get
{
List<Protocol> runningProtocols = GetRunningProtocols();
return runningProtocols.Count == 0 ? Protocol.GPS_DEFAULT_ACCURACY_METERS : runningProtocols.Min(p => p.GpsDesiredAccuracyMeters);
}
}
[JsonIgnore]
public int GpsMinTimeDelayMS
{
get
{
List<Protocol> runningProtocols = GetRunningProtocols();
return runningProtocols.Count == 0 ? Protocol.GPS_DEFAULT_MIN_TIME_DELAY_MS : runningProtocols.Min(p => p.GpsMinTimeDelayMS);
}
}
[JsonIgnore]
public float GpsMinDistanceDelayMeters
{
get
{
List<Protocol> runningProtocols = GetRunningProtocols();
return runningProtocols.Count == 0 ? Protocol.GPS_DEFAULT_MIN_DISTANCE_DELAY_METERS : runningProtocols.Min(p => p.GpsMinDistanceDelayMeters);
}
}
#region platform-specific properties
[JsonIgnore]
public abstract bool IsCharging { get; }
[JsonIgnore]
public abstract bool WiFiConnected { get; }
[JsonIgnore]
public abstract string DeviceId { get; }
[JsonIgnore]
public abstract string OperatingSystem { get; }
[JsonIgnore]
protected abstract bool IsOnMainThread { get; }
#region iOS GPS listener settings
#if __IOS__
[JsonIgnore]
public bool GpsPauseLocationUpdatesAutomatically
{
get
{
List<Protocol> runningProtocols = GetRunningProtocols();
return runningProtocols.Count == 0 ? false : runningProtocols.All(p => p.GpsPauseLocationUpdatesAutomatically);
}
}
[JsonIgnore]
public ActivityType GpsActivityType
{
get
{
List<Protocol> runningProtocols = GetRunningProtocols();
return runningProtocols.Count == 0 || runningProtocols.Select(p => p.GpsPauseActivityType).Distinct().Count() > 1 ? ActivityType.Other : runningProtocols.First().GpsPauseActivityType;
}
}
[JsonIgnore]
public bool GpsListenForSignificantChanges
{
get
{
List<Protocol> runningProtocols = GetRunningProtocols();
return runningProtocols.Count == 0 ? false : runningProtocols.All(p => p.GpsListenForSignificantChanges);
}
}
[JsonIgnore]
public bool GpsDeferLocationUpdates
{
get
{
List<Protocol> runningProtocols = GetRunningProtocols();
return runningProtocols.Count == 0 ? false : runningProtocols.All(p => p.GpsDeferLocationUpdates);
}
}
[JsonIgnore]
public float GpsDeferralDistanceMeters
{
get
{
List<Protocol> runningProtocols = GetRunningProtocols();
return runningProtocols.Count == 0 ? -1 : runningProtocols.Min(p => p.GpsDeferralDistanceMeters);
}
}
[JsonIgnore]
public float GpsDeferralTimeMinutes
{
get
{
List<Protocol> runningProtocols = GetRunningProtocols();
return runningProtocols.Count == 0 ? -1 : runningProtocols.Min(p => p.GpsDeferralTimeMinutes);
}
}
#endif
#endregion
#endregion
protected SensusServiceHelper()
{
if (SINGLETON != null)
throw new SensusException("Attempted to construct new service helper when singleton already existed.");
_registeredProtocols = new ObservableCollection<Protocol>();
_runningProtocolIds = new List<string>();
_healthTestCallbackId = null;
_idCallback = new Dictionary<string, ScheduledCallback>();
_hasher = new SHA256Managed();
_pointsOfInterest = new List<PointOfInterest>();
// ensure that the entire QR code is always visible by using 90% the minimum screen dimension as the QR code size.
#if __ANDROID__
int qrCodeSize = (int)(0.9 * Math.Min(XLabs.Platform.Device.Display.Metrics.WidthPixels, XLabs.Platform.Device.Display.Metrics.HeightPixels));
#elif __IOS__
int qrCodeSize = (int)(0.9 * Math.Min(AppleDevice.CurrentDevice.Display.Height, AppleDevice.CurrentDevice.Display.Width));
#else
#error "Unrecognized platform"
#endif
_barcodeWriter = new ZXing.Mobile.BarcodeWriter
{
Format = BarcodeFormat.QR_CODE,
Options = new ZXing.Common.EncodingOptions
{
Height = qrCodeSize,
Width = qrCodeSize
}
};
if (!Directory.Exists(SHARE_DIRECTORY))
Directory.CreateDirectory(SHARE_DIRECTORY);
#if DEBUG || UNIT_TESTING
LoggingLevel loggingLevel = LoggingLevel.Debug;
#elif RELEASE
LoggingLevel loggingLevel = LoggingLevel.Normal;
#else
#error "Unrecognized configuration."
#endif
_logger = new Logger(LOG_PATH, loggingLevel, Console.Error);
_logger.Log("Log file started at \"" + LOG_PATH + "\".", LoggingLevel.Normal, GetType());
if (Insights.IsInitialized)
_logger.Log("Xamarin Insights is already initialized.", LoggingLevel.Normal, GetType());
else if (string.IsNullOrWhiteSpace(XAMARIN_INSIGHTS_APP_KEY))
_logger.Log("Xamarin Insights API key is empty. Not initializing.", LoggingLevel.Normal, GetType()); // xamarin allows to initialize with a null key, which fails with exception but results in IsInitialized being true. prevent that here.
else
{
try
{
_logger.Log("Initializing Xamarin Insights.", LoggingLevel.Normal, GetType());
// wait for startup crash to be logged -- https://insights.xamarin.com/docs
Insights.HasPendingCrashReport += (sender, isStartupCrash) =>
{
if (isStartupCrash)
Insights.PurgePendingCrashReports().Wait();
};
InitializeXamarinInsights();
}
catch (Exception ex)
{
_logger.Log("Failed to initialize Xamarin insights: " + ex.Message, LoggingLevel.Normal, GetType());
}
}
}
public string GetHash(string s)
{
if (s == null)
return null;
StringBuilder hashBuilder = new StringBuilder();
foreach (byte b in _hasher.ComputeHash(Encoding.UTF8.GetBytes(s)))
hashBuilder.Append(b.ToString("x"));
return hashBuilder.ToString();
}
#region platform-specific methods. this functionality cannot be implemented in a cross-platform way. it must be done separately for each platform.
protected abstract void InitializeXamarinInsights();
protected abstract void ScheduleRepeatingCallback(string callbackId, int initialDelayMS, int repeatDelayMS, bool repeatLag);
protected abstract void ScheduleOneTimeCallback(string callbackId, int delayMS);
protected abstract void UnscheduleCallbackPlatformSpecific(string callbackId);
protected abstract void ProtectedFlashNotificationAsync(string message, bool flashLaterIfNotVisible, Action callback);
public abstract void PromptForAndReadTextFileAsync(string promptTitle, Action<string> callback);
public abstract void ShareFileAsync(string path, string subject, string mimeType);
public abstract void SendEmailAsync(string toAddress, string subject, string message);
public abstract void TextToSpeechAsync(string text, Action callback);
public abstract void RunVoicePromptAsync(string prompt, Action postDisplayCallback, Action<string> callback);
public abstract void IssueNotificationAsync(string message, string id);
public abstract void KeepDeviceAwake();
public abstract void LetDeviceSleep();
public abstract void BringToForeground();
/// <summary>
/// The user can enable all probes at once. When this is done, it doesn't make sense to enable, e.g., the
/// listening location probe as well as the polling location probe. This method allows the platforms to
/// decide which probes to enable when enabling all probes.
/// </summary>
/// <returns><c>true</c>, if probe should be enabled, <c>false</c> otherwise.</returns>
/// <param name="probe">Probe.</param>
public abstract bool EnableProbeWhenEnablingAll(Probe probe);
public abstract ImageSource GetQrCodeImageSource(string contents);
#endregion
#region add/remove running protocol ids
public void AddRunningProtocolId(string id)
{
lock (_runningProtocolIds)
{
if (!_runningProtocolIds.Contains(id))
_runningProtocolIds.Add(id);
if (_healthTestCallbackId == null)
{
ScheduledCallback callback = new ScheduledCallback(TestHealthAsync, "Test Health", TimeSpan.FromMinutes(1));
_healthTestCallbackId = ScheduleRepeatingCallback(callback, HEALTH_TEST_DELAY_MS, HEALTH_TEST_DELAY_MS, HEALTH_TEST_REPEAT_LAG);
}
}
}
public void RemoveRunningProtocolId(string id)
{
lock (_runningProtocolIds)
{
_runningProtocolIds.Remove(id);
if (_runningProtocolIds.Count == 0)
{
UnscheduleCallback(_healthTestCallbackId);
_healthTestCallbackId = null;
}
}
}
public bool ProtocolShouldBeRunning(Protocol protocol)
{
return _runningProtocolIds.Contains(protocol.Id);
}
public List<Protocol> GetRunningProtocols()
{
return _registeredProtocols.Where(p => p.Running).ToList();
}
#endregion
public void SaveAsync(Action callback = null)
{
new Thread(() =>
{
Save();
if (callback != null)
callback();
}).Start();
}
public void Save()
{
lock (_saveLocker)
{
_logger.Log("Serializing service helper.", LoggingLevel.Normal, GetType());
try
{
string serviceHelperJSON = JsonConvert.SerializeObject(this, JSON_SERIALIZER_SETTINGS);
byte[] encryptedBytes = Encrypt(serviceHelperJSON);
File.WriteAllBytes(SERIALIZATION_PATH, encryptedBytes);
_logger.Log("Serialized service helper with " + _registeredProtocols.Count + " protocols.", LoggingLevel.Normal, GetType());
}
catch (Exception ex)
{
_logger.Log("Failed to serialize Sensus service helper: " + ex.Message, LoggingLevel.Normal, GetType());
}
// ensure that all logged messages make it into the file.
_logger.CommitMessageBuffer();
}
}
public void StartAsync(Action callback)
{
new Thread(() =>
{
Start();
if (callback != null)
callback();
}).Start();
}
/// <summary>
/// Starts platform-independent service functionality, including protocols that should be running. Okay to call multiple times, even if the service is already running.
/// </summary>
public void Start()
{
lock (_registeredProtocols)
{
foreach (Protocol protocol in _registeredProtocols)
if (!protocol.Running && _runningProtocolIds.Contains(protocol.Id))
protocol.Start();
}
}
public void RegisterProtocol(Protocol protocol)
{
lock (_registeredProtocols)
{
if (!_registeredProtocols.Contains(protocol))
_registeredProtocols.Add(protocol);
}
}
#region callback scheduling
public string ScheduleRepeatingCallback(ScheduledCallback callback, int initialDelayMS, int repeatDelayMS, bool repeatLag)
{
lock (_idCallback)
{
string callbackId = AddCallback(callback);
ScheduleRepeatingCallback(callbackId, initialDelayMS, repeatDelayMS, repeatLag);
return callbackId;
}
}
public string ScheduleOneTimeCallback(ScheduledCallback callback, int delayMS)
{
lock (_idCallback)
{
string callbackId = AddCallback(callback);
ScheduleOneTimeCallback(callbackId, delayMS);
return callbackId;
}
}
private string AddCallback(ScheduledCallback callback)
{
lock (_idCallback)
{
// treat the callback as if it were brand new, even if it might have been previously used (e.g., if it's being reschedueld). set a
// new ID and cancellation token.
callback.Id = Guid.NewGuid().ToString();
callback.Canceller = new CancellationTokenSource();
_idCallback.Add(callback.Id, callback);
return callback.Id;
}
}
public bool CallbackIsScheduled(string callbackId)
{
lock (_idCallback)
return _idCallback.ContainsKey(callbackId);
}
public string GetCallbackUserNotificationMessage(string callbackId)
{
lock (_idCallback)
{
if (_idCallback.ContainsKey(callbackId))
return _idCallback[callbackId].UserNotificationMessage;
else
return null;
}
}
public string RescheduleRepeatingCallback(string callbackId, int initialDelayMS, int repeatDelayMS, bool repeatLag)
{
lock (_idCallback)
{
ScheduledCallback scheduledCallback;
if (_idCallback.TryGetValue(callbackId, out scheduledCallback))
{
UnscheduleCallback(callbackId);
return ScheduleRepeatingCallback(scheduledCallback, initialDelayMS, repeatDelayMS, repeatLag);
}
else
return null;
}
}
public void RaiseCallbackAsync(string callbackId, bool repeating, int repeatDelayMS, bool repeatLag, bool notifyUser, Action<DateTime> scheduleRepeatCallback, Action letDeviceSleepCallback, Action finishedCallback)
{
DateTime callbackStartTime = DateTime.Now;
new Thread(async () =>
{
try
{
ScheduledCallback scheduledCallback = null;
lock (_idCallback)
{
// do we have callback information for the passed callbackId? we might not, in the case where the callback is canceled by the user and the system fires it subsequently.
if (!_idCallback.TryGetValue(callbackId, out scheduledCallback))
{
_logger.Log("Callback " + callbackId + " is not valid. Unscheduling.", LoggingLevel.Normal, GetType());
UnscheduleCallback(callbackId);
}
}
if (scheduledCallback != null)
{
// the same callback action cannot be run multiple times concurrently. drop the current callback if it's already running. multiple
// callers might compete for the same callback, but only one will win the lock below and it will exclude all others until it has executed.
bool actionAlreadyRunning = true;
lock (scheduledCallback)
{
if (!scheduledCallback.Running)
{
actionAlreadyRunning = false;
scheduledCallback.Running = true;
}
}
if (actionAlreadyRunning)
_logger.Log("Callback \"" + scheduledCallback.Name + "\" (" + callbackId + ") is already running. Not running again.", LoggingLevel.Normal, GetType());
else
{
try
{
if (scheduledCallback.Canceller.IsCancellationRequested)
_logger.Log("Callback \"" + scheduledCallback.Name + "\" (" + callbackId + ") was cancelled before it was raised.", LoggingLevel.Normal, GetType());
else
{
_logger.Log("Raising callback \"" + scheduledCallback.Name + "\" (" + callbackId + ").", LoggingLevel.Normal, GetType());
if (notifyUser)
IssueNotificationAsync(scheduledCallback.UserNotificationMessage, callbackId);
// if the callback specified a timeout, request cancellation at the specified time.
if (scheduledCallback.CallbackTimeout != null)
scheduledCallback.Canceller.CancelAfter(scheduledCallback.CallbackTimeout.GetValueOrDefault());
await scheduledCallback.Action(callbackId, scheduledCallback.Canceller.Token, letDeviceSleepCallback);
}
}
catch (Exception ex)
{
_logger.Log("Callback \"" + scheduledCallback.Name + "\" (" + callbackId + ") failed: " + ex.Message, LoggingLevel.Normal, GetType());
}
finally
{
// the cancellation token source for the current callback might have been canceled. if this is a repeating callback then we'll need a new
// cancellation token source because they cannot be reset and we're going to use the same scheduled callback again for the next repeat.
// if we enter the _idCallback lock before CancelRaisedCallback does, then the next raise will be cancelled. if CancelRaisedCallback enters the
// _idCallback lock first, then the cancellation token source will be overwritten here and the cancel will not have any effect on the next
// raise. the latter case is a reasonable outcome, since the purpose of CancelRaisedCallback is to terminate a callback that is currently in
// progress, and the current callback is no longer in progress. if the desired outcome is complete discontinuation of the repeating callback
// then UnscheduleRepeatingCallback should be used -- this method first cancels any raised callbacks and then removes the callback entirely.
try
{
if (repeating)
{
lock (_idCallback)
{
scheduledCallback.Canceller = new CancellationTokenSource();
}
}
}
catch (Exception)
{
}
finally
{
// if we marked the callback as running, ensure that we unmark it (note we're nested within two finally blocks so
// this will always execute). this will allow others to run the callback.
lock (scheduledCallback)
{
scheduledCallback.Running = false;
}
// schedule callback again if it was a repeating callback and is still scheduled with a valid repeat delay
if (repeating && CallbackIsScheduled(callbackId) && repeatDelayMS >= 0 && scheduleRepeatCallback != null)
{
DateTime nextCallbackTime;
// if this repeating callback is allowed to lag, schedule the repeat from the current time.
if (repeatLag)
nextCallbackTime = DateTime.Now.AddMilliseconds(repeatDelayMS);
else
{
// otherwise, schedule the repeat from the time at which the current callback was raised.
nextCallbackTime = callbackStartTime.AddMilliseconds(repeatDelayMS);
}
scheduleRepeatCallback(nextCallbackTime);
}
else
UnscheduleCallback(callbackId);
}
}
}
}
}
catch (Exception ex)
{
string errorMessage = "Failed to raise callback: " + ex.Message;
_logger.Log(errorMessage, LoggingLevel.Normal, GetType());
try
{
Insights.Report(new Exception(errorMessage), Insights.Severity.Critical);
}
catch (Exception)
{
}
}
finally
{
if (finishedCallback != null)
finishedCallback();
}
}).Start();
}
/// <summary>
/// Cancels a callback that has been raised and is currently executing.
/// </summary>
/// <param name="callbackId">Callback identifier.</param>
public void CancelRaisedCallback(string callbackId)
{
lock (_idCallback)
{
ScheduledCallback scheduledCallback;
if (_idCallback.TryGetValue(callbackId, out scheduledCallback))
{
scheduledCallback.Canceller.Cancel();
SensusServiceHelper.Get().Logger.Log("Cancelled callback \"" + scheduledCallback.Name + "\" (" + callbackId + ").", LoggingLevel.Normal, GetType());
}
else
SensusServiceHelper.Get().Logger.Log("Callback \"" + callbackId + "\" not present. Cannot cancel.", LoggingLevel.Normal, GetType());
}
}
public void UnscheduleCallback(string callbackId)
{
if (callbackId != null)
lock (_idCallback)
{
SensusServiceHelper.Get().Logger.Log("Unscheduling callback \"" + callbackId + "\".", LoggingLevel.Normal, GetType());
CancelRaisedCallback(callbackId);
_idCallback.Remove(callbackId);
UnscheduleCallbackPlatformSpecific(callbackId);
}
}
#endregion
public void TextToSpeechAsync(string text)
{
TextToSpeechAsync(text, () =>
{
});
}
public void FlashNotificationAsync(string message, bool flashLaterIfNotVisible = true, Action callback = null)
{
// do not show flash notifications when unit testing, as they can disrupt UI scripting on iOS.
#if !UNIT_TESTING
ProtectedFlashNotificationAsync(message, flashLaterIfNotVisible, callback);
#endif
}
public void PromptForInputAsync(string windowTitle, Input input, CancellationToken? cancellationToken, bool showCancelButton, string nextButtonText, string cancelConfirmation, string incompleteSubmissionConfirmation, string submitConfirmation, bool displayProgress, Action<Input> callback)
{
PromptForInputsAsync(windowTitle, new Input[] { input }, cancellationToken, showCancelButton, nextButtonText, cancelConfirmation, incompleteSubmissionConfirmation, submitConfirmation, displayProgress, inputs =>
{
if (inputs == null)
callback(null);
else
callback(inputs[0]);
});
}
public void PromptForInputsAsync(string windowTitle, IEnumerable<Input> inputs, CancellationToken? cancellationToken, bool showCancelButton, string nextButtonText, string cancelConfirmation, string incompleteSubmissionConfirmation, string submitConfirmation, bool displayProgress, Action<List<Input>> callback)
{
InputGroup inputGroup = new InputGroup(windowTitle);
foreach (Input input in inputs)
inputGroup.Inputs.Add(input);
PromptForInputsAsync(null, new InputGroup[] { inputGroup }, cancellationToken, showCancelButton, nextButtonText, cancelConfirmation, incompleteSubmissionConfirmation, submitConfirmation, displayProgress, null, inputGroups =>
{
if (inputGroups == null)
callback(null);
else
callback(inputGroups.SelectMany(g => g.Inputs).ToList());
});
}
public void PromptForInputsAsync(DateTimeOffset? firstPromptTimestamp, IEnumerable<InputGroup> inputGroups, CancellationToken? cancellationToken, bool showCancelButton, string nextButtonText, string cancelConfirmation, string incompleteSubmissionConfirmation, string submitConfirmation, bool displayProgress, Action postDisplayCallback, Action<IEnumerable<InputGroup>> callback)
{
new Thread(() =>
{
if (inputGroups == null || inputGroups.Count() == 0 || inputGroups.All(inputGroup => inputGroup == null))
{
callback(inputGroups);
return;
}
// only one prompt can run at a time...enforce that here.
lock (PROMPT_FOR_INPUTS_LOCKER)
{
if (PROMPT_FOR_INPUTS_RUNNING)
{
_logger.Log("A prompt is already running. Dropping current prompt request.", LoggingLevel.Normal, GetType());
callback(inputGroups);
return;
}
else
PROMPT_FOR_INPUTS_RUNNING = true;
}
bool firstPageDisplay = true;
Stack<int> inputGroupNumBackStack = new Stack<int>();
for (int inputGroupNum = 0; inputGroups != null && inputGroupNum < inputGroups.Count() && !cancellationToken.GetValueOrDefault().IsCancellationRequested; ++inputGroupNum)
{
InputGroup inputGroup = inputGroups.ElementAt(inputGroupNum);
ManualResetEvent responseWait = new ManualResetEvent(false);
// run voice inputs by themselves, and only if the input group contains exactly one input and that input is a voice input.
if (inputGroup.Inputs.Count == 1 && inputGroup.Inputs[0] is VoiceInput)
{
VoiceInput voiceInput = inputGroup.Inputs[0] as VoiceInput;
if (voiceInput.Enabled && voiceInput.Display)
{
// only run the post-display callback the first time a page is displayed. the caller expects the callback
// to fire only once upon first display.
voiceInput.RunAsync(firstPromptTimestamp, firstPageDisplay ? postDisplayCallback : null, response =>
{
firstPageDisplay = false;
responseWait.Set();
});
}
else
responseWait.Set();
}
else
{
BringToForeground();
Device.BeginInvokeOnMainThread(async () =>
{
PromptForInputsPage promptForInputsPage = new PromptForInputsPage(inputGroup, inputGroupNum + 1, inputGroups.Count(), showCancelButton, nextButtonText, cancellationToken, cancelConfirmation, incompleteSubmissionConfirmation, submitConfirmation, displayProgress, firstPromptTimestamp, result =>
{
SensusServiceHelper.Get().Logger.Log("Prompt page disappeared with result: " + result, LoggingLevel.Normal, GetType());
if (result == PromptForInputsPage.Result.Cancel || result == PromptForInputsPage.Result.NavigateBackward && inputGroupNumBackStack.Count == 0)
inputGroups = null;
else if (result == PromptForInputsPage.Result.NavigateBackward)
inputGroupNum = inputGroupNumBackStack.Pop() - 1;
else
inputGroupNumBackStack.Push(inputGroupNum);
responseWait.Set();
});
// do not display prompts page under the following conditions: 1) there are no inputs displayed on it. 2) the cancellation
// token has requested a cancellation. if any of these conditions are true, set the wait handle and continue to the next input group.
if (promptForInputsPage.DisplayedInputCount == 0)
{
// if we're on the final input group and no inputs were shown, then we're at the end and we're ready to submit the
// users' responses. first check that the user is ready to submit. if the user isn't ready then move back to the previous
// input group in the backstack, if there is one.
if (inputGroupNum >= inputGroups.Count() - 1 && // this is the final input group
inputGroupNumBackStack.Count > 0 && // there is an input group to go back to (the current one was not displayed)
!string.IsNullOrWhiteSpace(submitConfirmation) && // we have a submit confirmation
!(await App.Current.MainPage.DisplayAlert("Confirm", submitConfirmation, "Yes", "No"))) // user is not ready to submit
{
inputGroupNum = inputGroupNumBackStack.Pop() - 1;
}
responseWait.Set();
}
else if (cancellationToken.GetValueOrDefault().IsCancellationRequested)
responseWait.Set();
else
{
await App.Current.MainPage.Navigation.PushModalAsync(promptForInputsPage, firstPageDisplay); // only animate the display for the first page
// only run the post-display callback the first time a page is displayed. the caller expects the callback
// to fire only once upon first display.
if (firstPageDisplay && postDisplayCallback != null)
postDisplayCallback();
firstPageDisplay = false;
}
});
}
responseWait.WaitOne();
}
// at this point we're done showing pages to the user. anything that needs to happen below with GPS tagging or subsequently
// in the callback can happen concurrently with any calls that might happen to come into this method. if the callback
// calls into this method immediately, there could be a race condition between the call and a call from some other part of
// the system. this is okay, as the latter call is always in a race condition anyway. if the imagined callback is beaten
// to its reentrant call of this method by a call from somewhere else in the system, the callback might be prevented from
// executing; however, can't think of a place where this might happen with negative consequences.
PROMPT_FOR_INPUTS_RUNNING = false;
#if __ANDROID__
// clear input requested notification. the notification will be cleared if the user taps it or if the activity is resumed. however, if
// the prompt times out while the activity is stopped, neither of these will occur. so we have to manually clear the notification.
(SensusServiceHelper.Get() as Sensus.Android.AndroidSensusServiceHelper).IssueNotificationAsync("Sensus", null, true, false, Sensus.Android.AndroidMainActivity.INPUT_REQUESTED_NOTIFICATION_ID);
#endif
#region geotag input groups if the user didn't cancel and we've got input groups with inputs that are complete and lacking locations
if (inputGroups != null && inputGroups.Any(inputGroup => inputGroup.Geotag && inputGroup.Inputs.Any(input => input.Complete && (input.Latitude == null || input.Longitude == null))))
{
SensusServiceHelper.Get().Logger.Log("Geotagging input groups.", LoggingLevel.Normal, GetType());
try
{
Position currentPosition = GpsReceiver.Get().GetReading(cancellationToken.GetValueOrDefault());
if (currentPosition != null)
foreach (InputGroup inputGroup in inputGroups)
if (inputGroup.Geotag)
foreach (Input input in inputGroup.Inputs)
if (input.Complete)
{
bool locationUpdated = false;
if (input.Latitude == null)
{
input.Latitude = currentPosition.Latitude;
locationUpdated = true;
}
if (input.Longitude == null)
{
input.Longitude = currentPosition.Longitude;
locationUpdated = true;
}
if (locationUpdated)
input.LocationUpdateTimestamp = currentPosition.Timestamp;
}
}
catch (Exception ex)
{
SensusServiceHelper.Get().Logger.Log("Error geotagging input groups: " + ex.Message, LoggingLevel.Normal, GetType());
}
}
#endregion
callback(inputGroups);
}).Start();
}
public void GetPositionsFromMapAsync(Xamarin.Forms.Maps.Position address, string newPinName, Action<List<Xamarin.Forms.Maps.Position>> callback)
{
Device.BeginInvokeOnMainThread(async () =>
{
MapPage mapPage = new MapPage(address, newPinName);
mapPage.Disappearing += (o, e) =>
{
callback(mapPage.Pins.Select(pin => pin.Position).ToList());
};
await App.Current.MainPage.Navigation.PushModalAsync(mapPage);
});
}
public void GetPositionsFromMapAsync(string address, string newPinName, Action<List<Xamarin.Forms.Maps.Position>> callback)
{
Device.BeginInvokeOnMainThread(async () =>
{
MapPage mapPage = new MapPage(address, newPinName);
mapPage.Disappearing += (o, e) =>
{
callback(mapPage.Pins.Select(pin => pin.Position).ToList());
};
await App.Current.MainPage.Navigation.PushModalAsync(mapPage);
});
}
public Task TestHealthAsync(string callbackId, CancellationToken cancellationToken, Action letDeviceSleepCallback)
{
return Task.Run(() =>
{
lock (_registeredProtocols)
{
_logger.Log("Sensus health test is running on callback " + callbackId + ".", LoggingLevel.Normal, GetType());
foreach (Protocol protocol in _registeredProtocols)
{
if (cancellationToken.IsCancellationRequested)
break;
if (_runningProtocolIds.Contains(protocol.Id))
protocol.TestHealth(false);
}
}
});
}
public void UnregisterProtocol(Protocol protocol)
{
lock (_registeredProtocols)
{
protocol.Stop();
_registeredProtocols.Remove(protocol);
}
}
/// <summary>
/// Gets the share path with an extension.
/// </summary>
/// <returns>The share path.</returns>
/// <param name="extension">Extension (with or without preceding ".")</param>
public string GetSharePath(string extension)
{
lock (_shareFileLocker)
{
int fileNum = 0;
string path = null;
while (path == null || File.Exists(path))
path = Path.Combine(SHARE_DIRECTORY, fileNum++ + (string.IsNullOrWhiteSpace(extension) ? "" : "." + extension.Trim('.')));
return path;
}
}
public string ConvertJsonForCrossPlatform(string json)
{
string currentTypeName = GetType().Name;
StringBuilder convertedJSON = new StringBuilder(json.Length * 2);
bool conversionPerformed = false;
// run through each line in the JSON and modify .NET types appropriately. json.net escapes \r and \n when serializing, so we can safely split on these characters.
foreach (string jsonLine in json.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries))
{
if (jsonLine.Trim().StartsWith("\"$type\":"))
{
// convert platform namespace
string convertedJsonLine;
if (currentTypeName == "AndroidSensusServiceHelper")
convertedJsonLine = jsonLine.Replace("iOS", "Android").Replace("WinPhone", "Android");
else if (currentTypeName == "iOSSensusServiceHelper")
convertedJsonLine = jsonLine.Replace("Android", "iOS").Replace("WinPhone", "iOS");
else if (currentTypeName == "WinPhoneSensusServiceHelper")
convertedJsonLine = jsonLine.Replace("Android", "WinPhone").Replace("iOS", "WinPhone");
else
throw new SensusException("Attempted to convert JSON for unknown service helper type: " + SensusServiceHelper.Get().GetType().FullName);
if (convertedJsonLine != jsonLine)
conversionPerformed = true;
convertedJSON.AppendLine(convertedJsonLine);
}
else
convertedJSON.AppendLine(jsonLine);
}
if (conversionPerformed)
_logger.Log("Performed cross-platform conversion of JSON.", LoggingLevel.Normal, GetType());
else
_logger.Log("No cross-platform conversion required for JSON.", LoggingLevel.Normal, GetType());
return convertedJSON.ToString();
}
public Task<PermissionStatus> ObtainPermissionAsync(Permission permission)
{
return Task.Run(async () =>
{
string rationale = null;
if (permission == Permission.Camera)
rationale = "Sensus uses the camera to scan participation barcodes. Sensus will not record images or video.";
else if (permission == Permission.Location)
rationale = "Sensus uses GPS to collect location information for studies you have enrolled in.";
else if (permission == Permission.Microphone)
rationale = "Sensus uses the microphone to collect sound level information for studies you have enrolled in. Sensus will not record audio.";
else if (permission == Permission.Phone)
rationale = "Sensus monitors telephone call metadata for studies you have enrolled in. Sensus will not record audio from calls.";
else if (permission == Permission.Sensors)
rationale = "Sensus uses movement sensors to collect various types of information for studies you have enrolled in.";
else if (permission == Permission.Storage)
rationale = "Sensus must be able to write to your device's storage for proper operation. Please grant this permission.";
if (await CrossPermissions.Current.CheckPermissionStatusAsync(permission) == PermissionStatus.Granted)
return PermissionStatus.Granted;
else
{
// the Permissions plugin requires a main activity to be present on android. ensure this below.
BringToForeground();
if (rationale != null && await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(permission))
{
ManualResetEvent rationaleDialogWait = new ManualResetEvent(false);
Device.BeginInvokeOnMainThread(async () =>
{
await (App.Current as App).ProtocolsPage.DisplayAlert("Permission Request", "On the next screen, Sensus will request access to your device's " + permission.ToString().ToUpper() + ". " + rationale, "OK");
rationaleDialogWait.Set();
});
rationaleDialogWait.WaitOne();
}
return (await CrossPermissions.Current.RequestPermissionsAsync(new Permission[] { permission }))[permission];
}
});
}
/// <summary>
/// Obtains a permission. Must not call this method from the UI thread, since it blocks waiting for prompts that run on the UI thread (deadlock). If it
/// is necessary to call from the UI thread, call ObtainPermissionAsync instead.
/// </summary>
/// <returns>The permission status.</returns>
/// <param name="permission">Permission.</param>
public PermissionStatus ObtainPermission(Permission permission)
{
try
{
AssertNotOnMainThread(GetType() + " ObtainPermission");
}
catch (Exception)
{
return PermissionStatus.Unknown;
}
PermissionStatus status = PermissionStatus.Unknown;
ManualResetEvent wait = new ManualResetEvent(false);
new Thread(async () =>
{
status = await SensusServiceHelper.Get().ObtainPermissionAsync(permission);
wait.Set();
}).Start();
wait.WaitOne();
return status;
}
public void AssertNotOnMainThread(string actionDescription)
{
if (IsOnMainThread)
throw new SensusException("Attempted to execute on main thread: " + actionDescription);
}
public virtual void Stop()
{
// stop all protocols
lock (_registeredProtocols)
{
_logger.Log("Stopping protocols.", LoggingLevel.Normal, GetType());
foreach (Protocol protocol in _registeredProtocols)
{
try
{
protocol.Stop();
}
catch (Exception ex)
{
_logger.Log("Failed to stop protocol \"" + protocol.Name + "\": " + ex.Message, LoggingLevel.Normal, GetType());
}
}
}
// make sure all logged messages get into the file.
_logger.CommitMessageBuffer();
SINGLETON = null;
}
}
}
| |
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Berkelium.Managed;
using System.Runtime.InteropServices;
using System.IO;
using System.Text;
namespace BerkeliumXNATest {
public class BerkeliumTestGame : Game {
[DllImport("user32.dll")]
static extern int ToUnicode (
uint wVirtKey, uint wScanCode, byte[] lpKeyState,
[Out, MarshalAs(UnmanagedType.LPWStr, SizeConst = 64)] StringBuilder pwszBuff,
int cchBuff, uint wFlags
);
Texture2D background, oldPage;
RenderTarget2D oldPageRt;
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
TextureBackedWindow browser;
int fadeDirection = 0;
long? fadingSince = null;
long lastKeystrokeTime = 0;
MouseState oldMouseState;
KeyboardState oldKeyState;
public BerkeliumTestGame () {
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
graphics.PreferredBackBufferWidth = 1024;
graphics.PreferredBackBufferHeight = 600;
graphics.PreferredBackBufferFormat = SurfaceFormat.Bgr32;
graphics.PreferredDepthStencilFormat = DepthFormat.Depth16;
graphics.PreferMultiSampling = false;
#if !DEBUG_BERKELIUM
BerkeliumManaged.Init(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "BerkeliumXNATest"));
#else
BerkeliumManaged.Init(@"D:\build\berkelium-managed\bin");
#endif
}
protected override void Initialize () {
base.Initialize();
System.Windows.Forms.Cursor.Show();
}
int NextPowerOfTwo(int value) {
double v = Math.Log10((double)value) / Math.Log10(2.0);
if (Math.Floor(v) != Math.Ceiling(v)) {
return 1 << (int)Math.Ceiling(v);
}
return value;
}
protected override void LoadContent () {
// We have to inject our teardown code here because if we let XNA's
// normal disposal handlers run, Chrome's message pump gets confused
// and hangs our process
var form = (System.Windows.Forms.Control.FromHandle(Window.Handle) as System.Windows.Forms.Form);
form.FormClosing += (s, e) => Teardown();
spriteBatch = new SpriteBatch(GraphicsDevice);
background = Content.Load<Texture2D>("background");
var context = Context.Create();
browser = new TextureBackedWindow(context, GraphicsDevice);
browser.Transparent = true;
browser.LoadingStateChanged += WebKit_LoadingStateChanged;
browser.Load += WebKit_Load;
browser.AddressBarChanged += WebKit_AddressBarChanged;
browser.Resize(GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height);
int rtWidth = browser.Texture.Width;
int rtHeight = browser.Texture.Height;
try {
oldPageRt = new RenderTarget2D(
GraphicsDevice, rtWidth, rtHeight, 2,
SurfaceFormat.Color, RenderTargetUsage.DiscardContents
);
} catch {
rtWidth = NextPowerOfTwo(rtWidth);
rtHeight = NextPowerOfTwo(rtHeight);
oldPageRt = new RenderTarget2D(
GraphicsDevice, rtWidth, rtHeight, 2,
SurfaceFormat.Color, RenderTargetUsage.DiscardContents
);
}
browser.NavigateTo("http://www.google.com/");
}
void WebKit_Load (Window window) {
}
void WebKit_AddressBarChanged (Window window, string newUrl) {
}
private void CopyTextureToRenderTarget (Texture2D src, RenderTarget2D rt, ref Texture2D dest) {
var dsb = GraphicsDevice.DepthStencilBuffer;
GraphicsDevice.DepthStencilBuffer = null;
GraphicsDevice.SetRenderTarget(0, rt);
spriteBatch.Begin(SpriteBlendMode.None, SpriteSortMode.Immediate, SaveStateMode.None);
spriteBatch.Draw(src, new Rectangle(0, 0, src.Width, src.Height), Color.White);
spriteBatch.End();
GraphicsDevice.SetRenderTarget(0, null);
GraphicsDevice.DepthStencilBuffer = dsb;
dest = rt.GetTexture();
dest.GenerateMipMaps(TextureFilter.Linear);
}
private void WebKit_LoadingStateChanged (Window window, bool newState) {
if (newState == true)
CopyTextureToRenderTarget(browser.Texture, oldPageRt, ref oldPage);
int newDirection = newState ? -1 : 1;
if (fadeDirection != newDirection) {
fadeDirection = newDirection;
fadingSince = DateTime.UtcNow.Ticks;
}
}
private void WebKit_LoadError (Window window, string error) {
Console.WriteLine(error);
}
protected override void UnloadContent () {
}
public void Teardown () {
browser.Dispose();
BerkeliumManaged.Destroy();
}
protected override void Update (GameTime gameTime) {
var newMouseState = Mouse.GetState();
var newKeyState = Keyboard.GetState();
var scrollDelta = newMouseState.ScrollWheelValue - oldMouseState.ScrollWheelValue;
if ((newMouseState.X != oldMouseState.X) || (newMouseState.Y != oldMouseState.Y))
browser.MouseMoved(newMouseState.X, newMouseState.Y);
if (scrollDelta != 0)
browser.MouseWheel(0, scrollDelta);
if (newMouseState.LeftButton != oldMouseState.LeftButton)
browser.MouseButton(MouseButton.Left, newMouseState.LeftButton == ButtonState.Pressed);
if (newMouseState.MiddleButton != oldMouseState.MiddleButton)
browser.MouseButton(MouseButton.Middle, newMouseState.MiddleButton == ButtonState.Pressed);
if (newMouseState.RightButton != oldMouseState.RightButton)
browser.MouseButton(MouseButton.Right, newMouseState.RightButton == ButtonState.Pressed);
var buffer = new StringBuilder();
byte[] pressedKeys = new byte[256];
long now = DateTime.UtcNow.Ticks;
bool shouldRepeat = (now - lastKeystrokeTime) > TimeSpan.FromSeconds(0.15).Ticks;
for (int i = 0; i < 255; i++) {
var k = (Keys)i;
bool wasDown = oldKeyState.IsKeyDown(k);
bool isDown = newKeyState.IsKeyDown(k);
if ((wasDown != isDown) || (isDown && shouldRepeat)) {
lastKeystrokeTime = now;
browser.KeyEvent(isDown, 0, i, 0);
if (isDown) {
Array.Clear(pressedKeys, 0, 256);
foreach (var pk in newKeyState.GetPressedKeys()) {
int ik = (int)pk;
if ((pk == Keys.LeftShift) || (pk == Keys.RightShift))
ik = 0x0010;
pressedKeys[ik] = 255;
}
int chars = ToUnicode((uint)i, 0, pressedKeys, buffer, 1, 0);
if (chars > 0)
browser.TextEvent(buffer.ToString(0, chars));
}
}
}
oldMouseState = newMouseState;
oldKeyState = newKeyState;
browser.Cleanup();
if (browser != null)
BerkeliumManaged.Update();
base.Update(gameTime);
}
protected override void Draw (GameTime gameTime) {
GraphicsDevice.Clear(Color.Black);
int a = 511;
float blur = 0.0f;
long now = DateTime.UtcNow.Ticks;
long elapsed = now - fadingSince.GetValueOrDefault(0);
if (fadeDirection > 0) {
a = (int)MathHelper.Clamp(511 * elapsed / TimeSpan.FromSeconds(0.33).Ticks, 0, 511);
blur = 1.0f;
} else if (fadeDirection < 0) {
a = 0;
blur = MathHelper.Clamp(100 * elapsed / TimeSpan.FromSeconds(0.33).Ticks, 0, 100) / 100.0f;
}
spriteBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Immediate, SaveStateMode.None);
spriteBatch.Draw(background, new Rectangle(0, 0, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height), Color.White);
if ((fadeDirection < 0) || (a < 511)) {
spriteBatch.End();
spriteBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Immediate, SaveStateMode.None);
GraphicsDevice.SamplerStates[0].MinFilter = TextureFilter.Linear;
GraphicsDevice.SamplerStates[0].MipFilter = TextureFilter.Linear;
GraphicsDevice.SamplerStates[0].MagFilter = TextureFilter.Linear;
GraphicsDevice.SamplerStates[0].MipMapLevelOfDetailBias = blur;
byte a2;
if (fadeDirection > 0) {
a2 = (byte)MathHelper.Clamp(255 - (a - 256), 0, 255);
} else {
a2 = 255;
}
spriteBatch.Draw(
oldPage,
new Rectangle(0, 0, browser.Texture.Width, browser.Texture.Height),
new Rectangle(0, 0, browser.Texture.Width, browser.Texture.Height),
new Color(255, 255, 255, a2)
);
spriteBatch.End();
spriteBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Immediate, SaveStateMode.None);
GraphicsDevice.SamplerStates[0].MinFilter = TextureFilter.Point;
GraphicsDevice.SamplerStates[0].MipFilter = TextureFilter.Point;
GraphicsDevice.SamplerStates[0].MagFilter = TextureFilter.Point;
GraphicsDevice.SamplerStates[0].MipMapLevelOfDetailBias = 0.0f;
}
if (fadeDirection >= 0) {
foreach (var kvp in browser.RenderList) {
spriteBatch.Draw(
kvp.Key,
new Rectangle(kvp.Value.X, kvp.Value.Y, kvp.Key.Width, kvp.Key.Height),
new Color(255, 255, 255, (byte)MathHelper.Clamp(a, 0, 255))
);
}
}
spriteBatch.End();
base.Draw(gameTime);
}
}
}
| |
namespace System.Workflow.ComponentModel.Compiler
{
using System;
using System.CodeDom;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Text;
using System.Collections;
using System.Collections.Generic;
internal static class Helper
{
internal static ParameterAttributes ConvertToParameterAttributes(FieldDirection direction)
{
ParameterAttributes paramAttributes = ParameterAttributes.None;
// Only few param attributes are supported
switch (direction)
{
case FieldDirection.In:
paramAttributes = ParameterAttributes.In;
break;
case FieldDirection.Out:
paramAttributes = ParameterAttributes.Out;
break;
default:
paramAttributes = default(ParameterAttributes);
break;
}
return paramAttributes;
}
internal static MethodAttributes ConvertToMethodAttributes(MemberAttributes memberAttributes)
{
MethodAttributes methodAttributes = MethodAttributes.ReuseSlot;
// convert access attributes
if ((memberAttributes & MemberAttributes.AccessMask) == MemberAttributes.Assembly)
methodAttributes |= MethodAttributes.Assembly;
else if ((memberAttributes & MemberAttributes.AccessMask) == MemberAttributes.Family)
methodAttributes |= MethodAttributes.Family;
else if ((memberAttributes & MemberAttributes.AccessMask) == MemberAttributes.FamilyAndAssembly)
methodAttributes |= MethodAttributes.FamANDAssem;
else if ((memberAttributes & MemberAttributes.AccessMask) == MemberAttributes.FamilyOrAssembly)
methodAttributes |= MethodAttributes.FamORAssem;
else if ((memberAttributes & MemberAttributes.AccessMask) == MemberAttributes.Private)
methodAttributes |= MethodAttributes.Private;
else if ((memberAttributes & MemberAttributes.AccessMask) == MemberAttributes.Public)
methodAttributes |= MethodAttributes.Public;
// covert scope attributes
if ((memberAttributes & MemberAttributes.ScopeMask) == MemberAttributes.Abstract)
methodAttributes |= MethodAttributes.Abstract;
else if ((memberAttributes & MemberAttributes.ScopeMask) == MemberAttributes.Final)
methodAttributes |= MethodAttributes.Final;
else if ((memberAttributes & MemberAttributes.ScopeMask) == MemberAttributes.Static)
methodAttributes |= MethodAttributes.Static;
//else if ((memberAttributes & MemberAttributes.ScopeMask) == MemberAttributes.Override)
// methodAttributes |= MethodAttributes.ReuseSlot;//
// convert vtable slot
if ((memberAttributes & MemberAttributes.VTableMask) == MemberAttributes.New)
methodAttributes |= MethodAttributes.NewSlot;
//if ((memberAttributes & MemberAttributes.VTableMask) == MemberAttributes.Overloaded)
// methodAttributes |= MethodAttributes.HideBySig; //
return methodAttributes;
}
internal static FieldAttributes ConvertToFieldAttributes(MemberAttributes memberAttributes)
{
FieldAttributes fieldAttributes = default(FieldAttributes);
if ((memberAttributes & MemberAttributes.AccessMask) == MemberAttributes.Assembly)
fieldAttributes |= FieldAttributes.Assembly;
else if ((memberAttributes & MemberAttributes.AccessMask) == MemberAttributes.Family)
fieldAttributes |= FieldAttributes.Family;
else if ((memberAttributes & MemberAttributes.AccessMask) == MemberAttributes.FamilyAndAssembly)
fieldAttributes |= FieldAttributes.FamANDAssem;
else if ((memberAttributes & MemberAttributes.AccessMask) == MemberAttributes.FamilyOrAssembly)
fieldAttributes |= FieldAttributes.FamORAssem;
else if ((memberAttributes & MemberAttributes.AccessMask) == MemberAttributes.Private)
fieldAttributes |= FieldAttributes.Private;
else if ((memberAttributes & MemberAttributes.AccessMask) == MemberAttributes.Public)
fieldAttributes |= FieldAttributes.Public;
if ((memberAttributes & MemberAttributes.ScopeMask) == MemberAttributes.Const)
fieldAttributes |= (FieldAttributes.Static | FieldAttributes.Literal);
else if ((memberAttributes & MemberAttributes.ScopeMask) == MemberAttributes.Static)
fieldAttributes |= FieldAttributes.Static;
return fieldAttributes;
}
internal static TypeAttributes ConvertToTypeAttributes(MemberAttributes memberAttributes, Type declaringType)
{
TypeAttributes typeAttributes = default(TypeAttributes);
// convert access attributes
if ((memberAttributes & MemberAttributes.AccessMask) == MemberAttributes.Assembly)
typeAttributes |= ((declaringType != null) ? TypeAttributes.NestedAssembly : TypeAttributes.NotPublic);
else if ((memberAttributes & MemberAttributes.AccessMask) == MemberAttributes.Family)
typeAttributes |= ((declaringType != null) ? TypeAttributes.NestedFamily : TypeAttributes.NotPublic);
else if ((memberAttributes & MemberAttributes.AccessMask) == MemberAttributes.FamilyAndAssembly)
typeAttributes |= ((declaringType != null) ? TypeAttributes.NestedFamANDAssem : TypeAttributes.NotPublic);
else if ((memberAttributes & MemberAttributes.AccessMask) == MemberAttributes.FamilyOrAssembly)
typeAttributes |= ((declaringType != null) ? TypeAttributes.NestedFamORAssem : TypeAttributes.NotPublic);
else if ((memberAttributes & MemberAttributes.AccessMask) == MemberAttributes.Private)
typeAttributes |= ((declaringType != null) ? TypeAttributes.NestedPrivate : TypeAttributes.NotPublic);
else if ((memberAttributes & MemberAttributes.AccessMask) == MemberAttributes.Public)
typeAttributes |= ((declaringType != null) ? TypeAttributes.NestedPublic : TypeAttributes.Public);
// covert scope attributes
if ((memberAttributes & MemberAttributes.ScopeMask) == MemberAttributes.Abstract)
typeAttributes |= TypeAttributes.Abstract;
else if ((memberAttributes & MemberAttributes.ScopeMask) == MemberAttributes.Final)
typeAttributes |= TypeAttributes.Sealed;
else if ((memberAttributes & MemberAttributes.Static) == MemberAttributes.Static)
typeAttributes |= (TypeAttributes.Abstract | TypeAttributes.Sealed);
return typeAttributes;
}
internal static bool IncludeAccessor(MethodInfo accessor, bool nonPublic)
{
if (accessor == null)
return false;
if (nonPublic)
return true;
if (accessor.IsPublic)
return true;
return false;
}
internal static Attribute[] LoadCustomAttributes(CodeAttributeDeclarationCollection codeAttributeCollection, DesignTimeType declaringType)
{
if (declaringType == null)
throw new ArgumentNullException("declaringType");
if (codeAttributeCollection == null)
return new Attribute[0];
List<Attribute> attributes = new List<Attribute>();
// walk through the attributes
foreach (CodeAttributeDeclaration codeAttribute in codeAttributeCollection)
{
String[] argumentNames = new String[codeAttribute.Arguments.Count];
object[] argumentValues = new object[codeAttribute.Arguments.Count];
Type attributeType = declaringType.ResolveType(codeAttribute.Name);
if (attributeType != null)
{
int index = 0;
// walk through tha arguments
foreach (CodeAttributeArgument codeArgument in codeAttribute.Arguments)
{
argumentNames[index] = codeArgument.Name;
if (codeArgument.Value is CodePrimitiveExpression)
argumentValues[index] = (codeArgument.Value as CodePrimitiveExpression).Value;
else if (codeArgument.Value is CodeTypeOfExpression)
argumentValues[index] = codeArgument.Value;
else if (codeArgument.Value is CodeSnippetExpression)
argumentValues[index] = (codeArgument.Value as CodeSnippetExpression).Value;
else
argumentValues[index] = new ArgumentException(SR.GetString(SR.Error_TypeSystemAttributeArgument));
index++;
}
bool alreadyExists = false;
foreach (AttributeInfoAttribute attribInfo in attributes)
{
if (attribInfo.AttributeInfo.AttributeType.FullName.Equals(attributeType.FullName))
{
alreadyExists = true;
break;
}
}
//
bool allowMultiple = false;
if (alreadyExists && attributeType.Assembly != null)
{
object[] usageAttribs = attributeType.GetCustomAttributes(typeof(System.AttributeUsageAttribute), true);
if (usageAttribs != null && usageAttribs.Length > 0)
{
AttributeUsageAttribute usage = usageAttribs[0] as AttributeUsageAttribute;
allowMultiple = usage.AllowMultiple;
}
}
// now create and add the placeholder attribute
if (!alreadyExists || allowMultiple)
attributes.Add(AttributeInfoAttribute.CreateAttributeInfoAttribute(attributeType, argumentNames, argumentValues));
}
}
return attributes.ToArray();
}
internal static object[] GetCustomAttributes(Type attributeType, bool inherit, Attribute[] attributes, MemberInfo memberInfo)
{
if (attributeType == null)
throw new ArgumentNullException("attributeType");
ArrayList attributeList = new ArrayList();
ArrayList attributeTypes = new ArrayList();
if (attributeType == typeof(object))
{
attributeList.AddRange(attributes);
}
else
{
foreach (AttributeInfoAttribute attribute in attributes)
{
if (attribute.AttributeInfo.AttributeType == attributeType)
{
attributeList.Add(attribute);
attributeTypes.Add(attributeType);
}
}
}
if (inherit)
{
MemberInfo baseMemberInfo = null;
// we need to get a base type or the overriden member that might declare additional attributes
if (memberInfo is Type)
baseMemberInfo = ((Type)memberInfo).BaseType;
else
baseMemberInfo = ((DesignTimeType)memberInfo.DeclaringType).GetBaseMember(memberInfo.GetType(), memberInfo.DeclaringType.BaseType, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance, new DesignTimeType.MemberSignature(memberInfo));
// Add base attributes
if (baseMemberInfo != null)
{
object[] baseAttributes = baseMemberInfo.GetCustomAttributes(attributeType, inherit);
// check that attributes are not repeated
foreach (Attribute baseAttribute in baseAttributes)
{
if (!(baseAttribute is AttributeInfoAttribute) || (!attributeTypes.Contains(((AttributeInfoAttribute)baseAttribute).AttributeInfo.AttributeType)))
attributeList.Add(baseAttribute);
}
}
}
return attributeList.ToArray();
}
internal static bool IsDefined(Type attributeType, bool inherit, Attribute[] attributes, MemberInfo memberInfo)
{
if (attributeType == null)
throw new ArgumentNullException("attributeType");
foreach (Attribute attribute in attributes)
{
// check to see if a type is wrapped in an AttributeInfoAttribute
if ((attribute is AttributeInfoAttribute) && ((attribute as AttributeInfoAttribute).AttributeInfo.AttributeType == attributeType))
return true;
}
MemberInfo baseMemberInfo = null;
// we need to get a base type or the overriden member that might declare additional attributes
if (memberInfo is Type)
baseMemberInfo = ((Type)memberInfo).BaseType;
else
baseMemberInfo = ((DesignTimeType)memberInfo.DeclaringType).GetBaseMember(memberInfo.GetType(), memberInfo.DeclaringType.BaseType, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance, new DesignTimeType.MemberSignature(memberInfo));
// Add base attributes
if (baseMemberInfo != null)
return baseMemberInfo.IsDefined(attributeType, inherit);
return false;
}
internal static string EnsureTypeName(string typeName)
{
if (typeName == null || typeName.Length == 0)
return typeName;
if (typeName.IndexOf('.') == -1)
{
if (typeName.StartsWith("@", StringComparison.Ordinal))
typeName = typeName.Substring(1);
else if (typeName.StartsWith("[", StringComparison.Ordinal) && typeName.EndsWith("]", StringComparison.Ordinal))
typeName = typeName.Substring(1, typeName.Length - 1);
}
else
{
string[] tokens = typeName.Split(new char[] { '.' });
typeName = string.Empty;
int i;
for (i = 0; i < tokens.Length - 1; i++)
{
typeName += EnsureTypeName(tokens[i]);
typeName += ".";
}
typeName += EnsureTypeName(tokens[i]);
}
return typeName;
}
}
}
| |
// Copyright (C) 2015 Google, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using UnityEngine;
using System;
using System.Collections.Generic;
using GoogleMobileAds.Api;
using GoogleMobileAds.Api.Mediation;
using GoogleMobileAds.Common;
namespace GoogleMobileAds.Android
{
internal class Utils
{
#region Fully-qualified class names
#region Google Mobile Ads SDK class names
public const string AdListenerClassName = "com.google.android.gms.ads.AdListener";
public const string AdRequestClassName = "com.google.android.gms.ads.AdRequest";
public const string AdRequestBuilderClassName =
"com.google.android.gms.ads.AdRequest$Builder";
public const string AdSizeClassName = "com.google.android.gms.ads.AdSize";
public const string AdMobExtrasClassName =
"com.google.android.gms.ads.mediation.admob.AdMobExtras";
public const string AppOpenAdClassName =
"com.google.android.gms.ads.appopen.AppOpenAd";
public const string PlayStorePurchaseListenerClassName =
"com.google.android.gms.ads.purchase.PlayStorePurchaseListener";
public const string MobileAdsClassName = "com.google.android.gms.ads.MobileAds";
public const string RequestConfigurationClassName = "com.google.android.gms.ads.RequestConfiguration";
public const string RequestConfigurationBuilderClassName = "com.google.android.gms.ads.RequestConfiguration$Builder";
public const string ServerSideVerificationOptionsClassName =
"com.google.android.gms.ads.rewarded.ServerSideVerificationOptions";
public const string ServerSideVerificationOptionsBuilderClassName =
"com.google.android.gms.ads.rewarded.ServerSideVerificationOptions$Builder";
#endregion
#region Google Mobile Ads Unity Plugin class names
public const string UnityAdSizeClassName = "com.google.unity.ads.UnityAdSize";
public const string BannerViewClassName = "com.google.unity.ads.Banner";
public const string InterstitialClassName = "com.google.unity.ads.Interstitial";
public const string RewardBasedVideoClassName = "com.google.unity.ads.RewardBasedVideo";
public const string UnityRewardedAdClassName = "com.google.unity.ads.UnityRewardedAd";
public const string UnityAdListenerClassName = "com.google.unity.ads.UnityAdListener";
public const string UnityRewardedAdCallbackClassName =
"com.google.unity.ads.UnityRewardedAdCallback";
public const string UnityInterstitialAdCallbackClassName = "com.google.unity.ads.UnityInterstitialAdCallback";
public const string UnityFullScreenContentCallbackClassName = "com.google.unity.ads.UnityFullScreenContentCallback";
public const string UnityAdapterStatusEnumName =
"com.google.android.gms.ads.initialization.AdapterStatus$State";
public const string UnityAppOpenAdClassName = "com.google.unity.ads.UnityAppOpenAd";
public const string UnityAppOpenAdCallbackClassName =
"com.google.unity.ads.UnityAppOpenAdCallback";
public const string OnInitializationCompleteListenerClassName =
"com.google.android.gms.ads.initialization.OnInitializationCompleteListener";
public const string UnityAdLoaderListenerClassName =
"com.google.unity.ads.UnityAdLoaderListener";
public const string UnityAdInspectorClassName =
"com.google.unity.ads.UnityAdInspector";
public const string UnityAdInspectorListenerClassname =
"com.google.unity.ads.UnityAdInspectorListener";
public const string UnityPaidEventListenerClassName =
"com.google.unity.ads.UnityPaidEventListener";
public const string UnityRewardedInterstitialAdClassName =
"com.google.unity.ads.UnityRewardedInterstitialAd";
public const string UnityRewardedInterstitialAdCallbackClassName =
"com.google.unity.ads.UnityRewardedInterstitialAdCallback";
public const string PluginUtilsClassName = "com.google.unity.ads.PluginUtils";
#endregion
#region Unity class names
public const string UnityActivityClassName = "com.unity3d.player.UnityPlayer";
#endregion
#region Android SDK class names
public const string BundleClassName = "android.os.Bundle";
public const string DateClassName = "java.util.Date";
public const string DisplayMetricsClassName = "android.util.DisplayMetrics";
#endregion
#endregion
#region JavaObject creators
public static AndroidJavaObject GetAdSizeJavaObject(AdSize adSize)
{
AndroidJavaClass adSizeClass = new AndroidJavaClass(UnityAdSizeClassName);
switch (adSize.AdType)
{
case AdSize.Type.SmartBanner:
return adSizeClass.CallStatic<AndroidJavaObject>("getSmartBannerAdSize");
case AdSize.Type.AnchoredAdaptive:
AndroidJavaClass playerClass = new AndroidJavaClass(Utils.UnityActivityClassName);
AndroidJavaObject activity =
playerClass.GetStatic<AndroidJavaObject>("currentActivity");
switch (adSize.Orientation)
{
case Orientation.Landscape:
return adSizeClass.CallStatic<AndroidJavaObject>("getLandscapeAnchoredAdaptiveBannerAdSize", activity, adSize.Width);
case Orientation.Portrait:
return adSizeClass.CallStatic<AndroidJavaObject>("getPortraitAnchoredAdaptiveBannerAdSize", activity, adSize.Width);
case Orientation.Current:
return adSizeClass.CallStatic<AndroidJavaObject>("getCurrentOrientationAnchoredAdaptiveBannerAdSize", activity, adSize.Width);
default:
throw new ArgumentException("Invalid Orientation provided for ad size.");
}
case AdSize.Type.Standard:
return new AndroidJavaObject(AdSizeClassName, adSize.Width, adSize.Height);
default:
throw new ArgumentException("Invalid AdSize.Type provided for ad size.");
}
}
public static int GetAppOpenAdOrientation(ScreenOrientation orientation)
{
string orientationFieldName;
switch (orientation)
{
case ScreenOrientation.Landscape:
case ScreenOrientation.LandscapeRight:
orientationFieldName = "APP_OPEN_AD_ORIENTATION_LANDSCAPE";
break;
default:
orientationFieldName = "APP_OPEN_AD_ORIENTATION_PORTRAIT";
break;
}
AndroidJavaClass appOpenAdClass = new AndroidJavaClass(AppOpenAdClassName);
return appOpenAdClass.GetStatic<int>(orientationFieldName);
}
internal static int GetScreenWidth()
{
DisplayMetrics metrics = new DisplayMetrics();
return (int)(metrics.WidthPixels / metrics.Density);
}
/// <summary>
/// Converts the plugin AdRequest object to a native java proxy object for use by the sdk.
/// </summary>
/// <param name="AdRequest">the AdRequest from the unity plugin.</param>
/// <param name="nativePluginVersion">the version string of the native plugin.</param>
public static AndroidJavaObject GetAdRequestJavaObject(AdRequest request,
string nativePluginVersion = null)
{
AndroidJavaObject adRequestBuilder = new AndroidJavaObject(AdRequestBuilderClassName);
foreach (string keyword in request.Keywords)
{
adRequestBuilder.Call<AndroidJavaObject>("addKeyword", keyword);
}
// Denote that the request is coming from this Unity plugin.
adRequestBuilder.Call<AndroidJavaObject>(
"setRequestAgent",
nativePluginVersion);
AndroidJavaObject bundle = new AndroidJavaObject(BundleClassName);
foreach (KeyValuePair<string, string> entry in request.Extras)
{
bundle.Call("putString", entry.Key, entry.Value);
}
bundle.Call("putString", "is_unity", "1");
// Makes ads that contain WebP ad assets ineligible.
bundle.Call("putString", "adw", "true");
AndroidJavaObject extras = new AndroidJavaObject(AdMobExtrasClassName, bundle);
adRequestBuilder.Call<AndroidJavaObject>("addNetworkExtras", extras);
foreach (MediationExtras mediationExtra in request.MediationExtras)
{
AndroidJavaObject mediationExtrasBundleBuilder =
new AndroidJavaObject(mediationExtra.AndroidMediationExtraBuilderClassName);
AndroidJavaObject map = new AndroidJavaObject("java.util.HashMap");
foreach (KeyValuePair<string, string> entry in mediationExtra.Extras)
{
map.Call<AndroidJavaObject>("put", entry.Key, entry.Value);
}
AndroidJavaObject mediationExtras =
mediationExtrasBundleBuilder.Call<AndroidJavaObject>("buildExtras", map);
if (mediationExtras != null)
{
adRequestBuilder.Call<AndroidJavaObject>(
"addNetworkExtrasBundle",
mediationExtrasBundleBuilder.Call<AndroidJavaClass>("getAdapterClass"),
mediationExtras);
adRequestBuilder.Call<AndroidJavaObject>(
"addCustomEventExtrasBundle",
mediationExtrasBundleBuilder.Call<AndroidJavaClass>("getAdapterClass"),
mediationExtras);
}
}
return adRequestBuilder.Call<AndroidJavaObject>("build");
}
public static AndroidJavaObject GetJavaListObject(List<String> csTypeList)
{
AndroidJavaObject javaTypeArrayList = new AndroidJavaObject("java.util.ArrayList");
foreach (string itemList in csTypeList)
{
javaTypeArrayList.Call<bool>("add", itemList);
}
return javaTypeArrayList;
}
public static List<String> GetCsTypeList(AndroidJavaObject javaTypeList)
{
List<String> csTypeList = new List<String>();
int length = javaTypeList.Call<int>("size");
for (int i = 0; i < length; i++)
{
csTypeList.Add(javaTypeList.Call<string>("get", i));
}
return csTypeList;
}
public static AndroidJavaObject GetServerSideVerificationOptionsJavaObject(ServerSideVerificationOptions serverSideVerificationOptions)
{
AndroidJavaObject serverSideVerificationOptionsBuilder = new AndroidJavaObject(ServerSideVerificationOptionsBuilderClassName);
serverSideVerificationOptionsBuilder.Call<AndroidJavaObject>("setUserId", serverSideVerificationOptions.UserId);
serverSideVerificationOptionsBuilder.Call<AndroidJavaObject>("setCustomData", serverSideVerificationOptions.CustomData);
return serverSideVerificationOptionsBuilder.Call<AndroidJavaObject>("build");
}
#endregion
}
}
| |
#region Using directives
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Markup;
using System.Xml;
using System.IO;
using System.IO.Packaging;
using System.Xml.Schema;
using System.Net;
using System.Resources;
using System.Reflection;
using System.Globalization;
using System.Security;
using MS.Internal;
#endregion
namespace System.Windows.Documents
{
internal class XpsSchemaValidator
{
private class XmlEncodingEnforcingTextReader : XmlTextReader
{
public XmlEncodingEnforcingTextReader(Stream objectStream)
: base(objectStream)
{
}
public override bool Read()
{
bool result = base.Read();
if (result && !_encodingChecked)
{
if (base.NodeType == XmlNodeType.XmlDeclaration)
{
string encoding = base["encoding"];
if (encoding != null)
{
if (!encoding.Equals(Encoding.Unicode.WebName, StringComparison.OrdinalIgnoreCase) &&
!encoding.Equals(Encoding.UTF8.WebName, StringComparison.OrdinalIgnoreCase))
{
throw new FileFormatException(SR.Get(SRID.XpsValidatingLoaderUnsupportedEncoding));
}
}
}
if (!(base.Encoding is UTF8Encoding) && !(base.Encoding is UnicodeEncoding))
{
throw new FileFormatException(SR.Get(SRID.XpsValidatingLoaderUnsupportedEncoding));
}
_encodingChecked = true;
}
return result;
}
private bool _encodingChecked;
}
public
XpsSchemaValidator(
XpsValidatingLoader loader,
XpsSchema schema,
ContentType mimeType,
Stream objectStream,
Uri packageUri,
Uri baseUri
)
{
XmlTextReader xmlTextReader = new XmlEncodingEnforcingTextReader(objectStream);
xmlTextReader.ProhibitDtd = true;
xmlTextReader.Normalization = true;
XmlReader xmlReader = xmlTextReader;
string [] predefinedNamespaces = _predefinedNamespaces;
if ( !string.IsNullOrEmpty(schema.RootNamespaceUri) )
{
predefinedNamespaces = new string[_predefinedNamespaces.Length + 1];
predefinedNamespaces[0] = schema.RootNamespaceUri;
_predefinedNamespaces.CopyTo(predefinedNamespaces, 1);
}
xmlReader = new XmlCompatibilityReader(xmlReader, predefinedNamespaces);
xmlReader = XmlReader.Create(xmlReader, schema.GetXmlReaderSettings());
if (schema.HasUriAttributes(mimeType) && packageUri != null && baseUri != null)
{
xmlReader = new RootXMLNSAndUriValidatingXmlReader(loader, schema,
xmlReader, packageUri, baseUri);
}
else
{
xmlReader = new RootXMLNSAndUriValidatingXmlReader(loader, schema, xmlReader);
}
_compatReader = xmlReader;
}
public
XmlReader
XmlReader
{
get
{
return _compatReader;
}
}
private
XmlReader _compatReader;
static private string [] _predefinedNamespaces = new string [1] {
XamlReaderHelper.DefinitionMetroNamespaceURI
};
private class RootXMLNSAndUriValidatingXmlReader : XmlWrappingReader
{
public RootXMLNSAndUriValidatingXmlReader(
XpsValidatingLoader loader,
XpsSchema schema,
XmlReader xmlReader,
Uri packageUri,
Uri baseUri)
: base(xmlReader)
{
_loader = loader;
_schema = schema;
_packageUri = packageUri;
_baseUri = baseUri;
}
public RootXMLNSAndUriValidatingXmlReader(
XpsValidatingLoader loader,
XpsSchema schema,
XmlReader xmlReader )
: base(xmlReader)
{
_loader = loader;
_schema = schema;
}
private void CheckUri(string attr)
{
CheckUri(Reader.LocalName, attr);
}
private void CheckUri(string localName, string attr)
{
if (!object.ReferenceEquals(attr, _lastAttr)) // Check for same string object, not for equality!
{
_lastAttr = attr;
string [] uris = _schema.ExtractUriFromAttr(localName, attr);
if (uris != null)
{
foreach (string uriAttr in uris)
{
if (uriAttr.Length > 0)
{
Uri targetUri = PackUriHelper.ResolvePartUri(_baseUri, new Uri(uriAttr, UriKind.Relative));
Uri absTargetUri = PackUriHelper.Create(_packageUri, targetUri);
_loader.UriHitHandler(_node,absTargetUri);
}
}
}
}
}
public override string Value
{
get
{
CheckUri(Reader.Value);
return Reader.Value;
}
}
public override string GetAttribute( string name )
{
string attr= Reader.GetAttribute( name );
CheckUri(name,attr);
return attr;
}
public override string GetAttribute( string name, string namespaceURI )
{
string attr = Reader.GetAttribute(name, namespaceURI);
CheckUri(attr);
return attr;
}
public override string GetAttribute( int i )
{
string attr = Reader.GetAttribute( i );
CheckUri(attr);
return attr;
}
public override bool Read()
{
bool result;
_node++;
result = Reader.Read();
if ( (Reader.NodeType == XmlNodeType.Element) && !_rootXMLNSChecked )
{
if (!_schema.IsValidRootNamespaceUri(Reader.NamespaceURI))
{
throw new FileFormatException(SR.Get(SRID.XpsValidatingLoaderUnsupportedRootNamespaceUri));
}
_rootXMLNSChecked = true;
}
return result;
}
private XpsValidatingLoader _loader;
private XpsSchema _schema;
private Uri _packageUri;
private Uri _baseUri;
private string _lastAttr;
private int _node;
private bool _rootXMLNSChecked;
}
}
internal class XpsSchema
{
protected XpsSchema()
{
}
static protected void RegisterSchema(XpsSchema schema, ContentType[] handledMimeTypes)
{
foreach (ContentType mime in handledMimeTypes)
{
_schemas.Add(mime, schema);
}
}
protected void RegisterRequiredResourceMimeTypes(ContentType[] requiredResourceMimeTypes)
{
if (requiredResourceMimeTypes != null)
{
foreach (ContentType type in requiredResourceMimeTypes)
{
_requiredResourceMimeTypes.Add(type, true);
}
}
}
public virtual XmlReaderSettings GetXmlReaderSettings()
{
XmlReaderSettings xmlReaderSettings = new XmlReaderSettings();
xmlReaderSettings.ValidationFlags = System.Xml.Schema.XmlSchemaValidationFlags.ProcessIdentityConstraints | System.Xml.Schema.XmlSchemaValidationFlags.ReportValidationWarnings;
return xmlReaderSettings;
}
public virtual void ValidateRelationships(SecurityCriticalData<Package> package, Uri packageUri, Uri partUri, ContentType mimeType)
{
}
public virtual bool HasRequiredResources(ContentType mimeType)
{
return false;
}
public virtual bool HasUriAttributes(ContentType mimeType)
{
return false;
}
public virtual bool AllowsMultipleReferencesToSameUri(ContentType mimeType)
{
return true;
}
public virtual bool IsValidRootNamespaceUri(string namespaceUri)
{
return false;
}
public virtual string RootNamespaceUri
{
get
{
return "";
}
}
public bool IsValidRequiredResourceMimeType(ContentType mimeType)
{
foreach (ContentType ct in _requiredResourceMimeTypes.Keys)
{
if (ct.AreTypeAndSubTypeEqual(mimeType))
{
return true;
}
}
return false;
}
public virtual string [] ExtractUriFromAttr(string attrName, string attrValue)
{
return null;
}
static public XpsSchema GetSchema(ContentType mimeType)
{
XpsSchema schema = null;
if (!_schemas.TryGetValue(mimeType, out schema))
{
throw new FileFormatException(SR.Get(SRID.XpsValidatingLoaderUnsupportedMimeType));
}
return schema;
}
static private readonly Dictionary<ContentType, XpsSchema> _schemas = new Dictionary<ContentType, XpsSchema>(new ContentType.StrongComparer());
private Hashtable _requiredResourceMimeTypes = new Hashtable(11);
}
internal class XpsS0Schema:XpsSchema
{
// When creating a new schema, add a static member to XpsSchemaValidator to register it.
protected
XpsS0Schema()
{
}
public override XmlReaderSettings GetXmlReaderSettings()
{
if (_xmlReaderSettings == null)
{
_xmlReaderSettings = new XmlReaderSettings();
_xmlReaderSettings.ValidationFlags = System.Xml.Schema.XmlSchemaValidationFlags.ProcessIdentityConstraints | System.Xml.Schema.XmlSchemaValidationFlags.ReportValidationWarnings;
MemoryStream xpsSchemaStream = new MemoryStream(XpsS0Schema.S0SchemaBytes);
MemoryStream dictionarySchemaStream = new MemoryStream(XpsS0Schema.DictionarySchemaBytes);
XmlResolver resolver = new XmlUrlResolver();
_xmlReaderSettings.ValidationType = ValidationType.Schema;
_xmlReaderSettings.Schemas.XmlResolver = resolver;
_xmlReaderSettings.Schemas.Add(_xpsS0SchemaNamespace,
new XmlTextReader(xpsSchemaStream));
_xmlReaderSettings.Schemas.Add(null,
new XmlTextReader(dictionarySchemaStream));
}
return _xmlReaderSettings;
}
public override bool HasRequiredResources(ContentType mimeType)
{
if (_fixedPageContentType.AreTypeAndSubTypeEqual(mimeType))
{
return true;
}
return false;
}
public override bool HasUriAttributes(ContentType mimeType)
{
// All of the root elements for content types supported by this schema have Uri attributes that need to be checked
return true;
}
public override bool AllowsMultipleReferencesToSameUri(ContentType mimeType)
{
if (_fixedDocumentSequenceContentType.AreTypeAndSubTypeEqual(mimeType) ||
_fixedDocumentContentType.AreTypeAndSubTypeEqual(mimeType))
{
// FixedDocumentSequence - FixedDocument - FixedPage must form a tree. Cannot share elements
return false;
}
else
{
return true;
}
}
public override bool IsValidRootNamespaceUri(string namespaceUri)
{
return namespaceUri.Equals(_xpsS0SchemaNamespace, StringComparison.Ordinal);
}
public override string RootNamespaceUri
{
get
{
return _xpsS0SchemaNamespace;
}
}
public override string[] ExtractUriFromAttr(string attrName, string attrValue)
{
// Note: Do not check for "FixedPage.NavigateUri", because external references are allowed.
if (attrName.Equals("Source", StringComparison.Ordinal) ||
attrName.Equals("FontUri", StringComparison.Ordinal))
{
return new string[] { attrValue };
}
else if (attrName.Equals("ImageSource", StringComparison.Ordinal))
{
if (attrValue.StartsWith(_colorConvertedBitmap, StringComparison.Ordinal))
{
attrValue = attrValue.Substring(_colorConvertedBitmap.Length);
string[] pieces = attrValue.Split(new char[] { ' ', '}' });
return pieces;
}
else
{
return new string[] { attrValue };
}
}
else if (attrName.Equals("Color", StringComparison.Ordinal) ||
attrName.Equals("Fill", StringComparison.Ordinal) ||
attrName.Equals("Stroke", StringComparison.Ordinal))
{
attrValue = attrValue.Trim();
if (attrValue.StartsWith(_contextColor, StringComparison.Ordinal))
{
attrValue = attrValue.Substring(_contextColor.Length);
attrValue = attrValue.Trim();
string[] tokens = attrValue.Split(new char[] { ' ' });
if (tokens.GetLength(0) >= 1)
{
return new string[] { tokens[0] };
}
}
}
return null;
}
static
private
byte[]
S0SchemaBytes
{
get
{
ResourceManager resourceManager = new ResourceManager( "Schemas_S0", Assembly.GetAssembly(typeof(XpsS0Schema)));
return (byte[])resourceManager.GetObject("s0schema.xsd");
}
}
static
private
byte[]
DictionarySchemaBytes
{
get
{
ResourceManager resourceManager = new ResourceManager( "Schemas_S0", Assembly.GetAssembly(typeof(XpsS0Schema)));
return (byte[])resourceManager.GetObject("rdkey.xsd");
}
}
static
protected
ContentType _fontContentType = new ContentType("application/vnd.ms-opentype");
static
protected
ContentType _colorContextContentType = new ContentType("application/vnd.ms-color.iccprofile");
static
protected
ContentType _obfuscatedContentType = new ContentType("application/vnd.ms-package.obfuscated-opentype");
static
protected
ContentType _jpgContentType = new ContentType("image/jpeg");
static
protected
ContentType _pngContentType = new ContentType("image/png");
static
protected
ContentType _tifContentType = new ContentType("image/tiff");
static
protected
ContentType _wmpContentType = new ContentType("image/vnd.ms-photo");
static
protected
ContentType _fixedDocumentSequenceContentType = new ContentType("application/vnd.ms-package.xps-fixeddocumentsequence+xml");
static
protected
ContentType _fixedDocumentContentType = new ContentType("application/vnd.ms-package.xps-fixeddocument+xml");
static
protected
ContentType _fixedPageContentType = new ContentType("application/vnd.ms-package.xps-fixedpage+xml");
static
protected
ContentType _resourceDictionaryContentType = new ContentType("application/vnd.ms-package.xps-resourcedictionary+xml");
static
protected
ContentType _printTicketContentType = new ContentType("application/vnd.ms-printing.printticket+xml");
static
protected
ContentType _discardControlContentType = new ContentType("application/vnd.ms-package.xps-discard-control+xml");
private
const
String _xpsS0SchemaNamespace = "http://schemas.microsoft.com/xps/2005/06";
private
const
string _contextColor = "ContextColor ";
private
const
string _colorConvertedBitmap = "{ColorConvertedBitmap ";
static
private
XmlReaderSettings _xmlReaderSettings;
}
internal sealed class XpsS0FixedPageSchema : XpsS0Schema
{
public
XpsS0FixedPageSchema()
{
RegisterSchema(this,
new ContentType[] { _fixedDocumentSequenceContentType,
_fixedDocumentContentType,
_fixedPageContentType
}
);
RegisterRequiredResourceMimeTypes(
new ContentType[] {
_resourceDictionaryContentType,
_fontContentType,
_colorContextContentType,
_obfuscatedContentType,
_jpgContentType,
_pngContentType,
_tifContentType,
_wmpContentType
}
);
}
/// <SecurityNote>
/// Critical: Accesses SecurityCriticalData which is a package from PreloadedPackages
/// SecurityTreatAsSafe: No package instance or package related objects being handed
/// out from this method
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
public override void ValidateRelationships(SecurityCriticalData<Package> package, Uri packageUri, Uri partUri, ContentType mimeType)
{
PackagePart part = package.Value.GetPart(partUri);
PackageRelationshipCollection checkRels;
int count;
// Can only have 0 or 1 PrintTicket per FDS, FD or FP part
checkRels = part.GetRelationshipsByType(_printTicketRel);
count = 0;
foreach (PackageRelationship rel in checkRels)
{
count++;
if (count > 1)
{
throw new FileFormatException(SR.Get(SRID.XpsValidatingLoaderMoreThanOnePrintTicketPart));
}
// Also check for existence and type
Uri targetUri = PackUriHelper.ResolvePartUri(partUri, rel.TargetUri);
Uri absTargetUri = PackUriHelper.Create(packageUri, targetUri);
PackagePart targetPart = package.Value.GetPart(targetUri);
if (!_printTicketContentType.AreTypeAndSubTypeEqual(new ContentType(targetPart.ContentType)))
{
throw new FileFormatException(SR.Get(SRID.XpsValidatingLoaderPrintTicketHasIncorrectType));
}
}
checkRels = part.GetRelationshipsByType(_thumbnailRel);
count = 0;
foreach (PackageRelationship rel in checkRels)
{
count++;
if (count > 1)
{
throw new FileFormatException(SR.Get(SRID.XpsValidatingLoaderMoreThanOneThumbnailPart));
}
// Also check for existence and type
Uri targetUri = PackUriHelper.ResolvePartUri(partUri, rel.TargetUri);
Uri absTargetUri = PackUriHelper.Create(packageUri, targetUri);
PackagePart targetPart = package.Value.GetPart(targetUri);
if (!_jpgContentType.AreTypeAndSubTypeEqual(new ContentType(targetPart.ContentType)) &&
!_pngContentType.AreTypeAndSubTypeEqual(new ContentType(targetPart.ContentType)))
{
throw new FileFormatException(SR.Get(SRID.XpsValidatingLoaderThumbnailHasIncorrectType));
}
}
// FixedDocument only has restricted font relationships
if (_fixedDocumentContentType.AreTypeAndSubTypeEqual(mimeType))
{
// Check if target of restricted font relationship is present and is actually a font
checkRels = part.GetRelationshipsByType(_restrictedFontRel);
foreach (PackageRelationship rel in checkRels)
{
// Check for existence and type
Uri targetUri = PackUriHelper.ResolvePartUri(partUri, rel.TargetUri);
Uri absTargetUri = PackUriHelper.Create(packageUri, targetUri);
PackagePart targetPart = package.Value.GetPart(targetUri);
if (!_fontContentType.AreTypeAndSubTypeEqual(new ContentType(targetPart.ContentType)) &&
!_obfuscatedContentType.AreTypeAndSubTypeEqual(new ContentType(targetPart.ContentType)))
{
throw new FileFormatException(SR.Get(SRID.XpsValidatingLoaderRestrictedFontHasIncorrectType));
}
}
}
// check constraints for XPS fixed payload start part
if (_fixedDocumentSequenceContentType.AreTypeAndSubTypeEqual(mimeType))
{
// This is the XPS payload root part. We also should check if the Package only has at most one discardcontrol...
checkRels = package.Value.GetRelationshipsByType(_discardControlRel);
count = 0;
foreach (PackageRelationship rel in checkRels)
{
count++;
if (count > 1)
{
throw new FileFormatException(SR.Get(SRID.XpsValidatingLoaderMoreThanOneDiscardControlInPackage));
}
// Also check for existence and type
Uri targetUri = PackUriHelper.ResolvePartUri(partUri, rel.TargetUri);
Uri absTargetUri = PackUriHelper.Create(packageUri, targetUri);
PackagePart targetPart = package.Value.GetPart(targetUri);
if (!_discardControlContentType.AreTypeAndSubTypeEqual(new ContentType(targetPart.ContentType)))
{
throw new FileFormatException(SR.Get(SRID.XpsValidatingLoaderDiscardControlHasIncorrectType));
}
}
// This is the XPS payload root part. We also should check if the Package only has at most one thumbnail...
checkRels = package.Value.GetRelationshipsByType(_thumbnailRel);
count = 0;
foreach (PackageRelationship rel in checkRels)
{
count++;
if (count > 1)
{
throw new FileFormatException(SR.Get(SRID.XpsValidatingLoaderMoreThanOneThumbnailInPackage));
}
// Also check for existence and type
Uri targetUri = PackUriHelper.ResolvePartUri(partUri, rel.TargetUri);
Uri absTargetUri = PackUriHelper.Create(packageUri, targetUri);
PackagePart targetPart = package.Value.GetPart(targetUri);
if (!_jpgContentType.AreTypeAndSubTypeEqual(new ContentType(targetPart.ContentType)) &&
!_pngContentType.AreTypeAndSubTypeEqual(new ContentType(targetPart.ContentType)))
{
throw new FileFormatException(SR.Get(SRID.XpsValidatingLoaderThumbnailHasIncorrectType));
}
}
}
}
private
const
string _printTicketRel = "http://schemas.microsoft.com/xps/2005/06/printticket";
private
const
string _discardControlRel = "http://schemas.microsoft.com/xps/2005/06/discard-control";
private
const
string _restrictedFontRel = "http://schemas.microsoft.com/xps/2005/06/restricted-font";
private
const
string _thumbnailRel = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail";
}
internal sealed class XpsS0ResourceDictionarySchema : XpsS0Schema
{
// When creating a new schema, add a static member to XpsSchemaValidator to register it.
public
XpsS0ResourceDictionarySchema()
{
RegisterSchema(this,
new ContentType[] { _resourceDictionaryContentType
}
);
}
public override string [] ExtractUriFromAttr(string attrName, string attrValue)
{
if (attrName.Equals("Source", StringComparison.Ordinal)) // Cannot chain remote ResourceDictionary parts.
{
throw new FileFormatException(SR.Get(SRID.XpsValidatingLoaderUnsupportedMimeType));
}
return base.ExtractUriFromAttr(attrName, attrValue);
}
}
internal sealed class XpsDocStructSchema : XpsSchema
{
// When creating a new schema, add a static member to XpsSchemaValidator to register it.
public
XpsDocStructSchema()
{
RegisterSchema(this, new ContentType[] { _documentStructureContentType,
_storyFragmentsContentType } );
}
public override XmlReaderSettings GetXmlReaderSettings()
{
if (_xmlReaderSettings == null)
{
_xmlReaderSettings = new XmlReaderSettings();
_xmlReaderSettings.ValidationFlags = System.Xml.Schema.XmlSchemaValidationFlags.ProcessIdentityConstraints | System.Xml.Schema.XmlSchemaValidationFlags.ReportValidationWarnings;
MemoryStream xpsSchemaStream = new MemoryStream(XpsDocStructSchema.SchemaBytes);
XmlResolver resolver = new XmlUrlResolver();
_xmlReaderSettings.ValidationType = ValidationType.Schema;
_xmlReaderSettings.Schemas.XmlResolver = resolver;
_xmlReaderSettings.Schemas.Add(_xpsDocStructureSchemaNamespace,
new XmlTextReader(xpsSchemaStream));
}
return _xmlReaderSettings;
}
public override bool IsValidRootNamespaceUri(string namespaceUri)
{
return namespaceUri.Equals(_xpsDocStructureSchemaNamespace, StringComparison.Ordinal);
}
public override string RootNamespaceUri
{
get
{
return _xpsDocStructureSchemaNamespace;
}
}
static
private
byte[]
SchemaBytes
{
get
{
ResourceManager resourceManager = new ResourceManager("Schemas_DocStructure", Assembly.GetAssembly(typeof(XpsDocStructSchema)));
return (byte[])resourceManager.GetObject("DocStructure.xsd");
}
}
static
private
ContentType _documentStructureContentType = new ContentType("application/vnd.ms-package.xps-documentstructure+xml");
static
private
ContentType _storyFragmentsContentType = new ContentType("application/vnd.ms-package.xps-storyfragments+xml");
private
const
String _xpsDocStructureSchemaNamespace = "http://schemas.microsoft.com/xps/2005/06/documentstructure";
static
private
XmlReaderSettings _xmlReaderSettings;
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: TreeWire.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace SourceCode.Chasm.IO.Proto.Wire {
/// <summary>Holder for reflection information generated from TreeWire.proto</summary>
public static partial class TreeWireReflection {
#region Descriptor
/// <summary>File descriptor for TreeWire.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static TreeWireReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Cg5UcmVlV2lyZS5wcm90bxoOU2hhMVdpcmUucHJvdG8iVAoMVHJlZVdpcmVO",
"b2RlEgwKBE5hbWUYASABKAkSGwoES2luZBgCIAEoDjINLk5vZGVLaW5kV2ly",
"ZRIZCgZOb2RlSWQYAyABKAsyCS5TaGExV2lyZSIoCghUcmVlV2lyZRIcCgVO",
"b2RlcxgBIAMoCzINLlRyZWVXaXJlTm9kZSoiCgxOb2RlS2luZFdpcmUSCAoE",
"QmxvYhAAEggKBFRyZWUQAUIhqgIeU291cmNlQ29kZS5DaGFzbS5JTy5Qcm90",
"by5XaXJlYgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::SourceCode.Chasm.IO.Proto.Wire.Sha1WireReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(new[] {typeof(global::SourceCode.Chasm.IO.Proto.Wire.NodeKindWire), }, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::SourceCode.Chasm.IO.Proto.Wire.TreeWireNode), global::SourceCode.Chasm.IO.Proto.Wire.TreeWireNode.Parser, new[]{ "Name", "Kind", "NodeId" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::SourceCode.Chasm.IO.Proto.Wire.TreeWire), global::SourceCode.Chasm.IO.Proto.Wire.TreeWire.Parser, new[]{ "Nodes" }, null, null, null)
}));
}
#endregion
}
#region Enums
/// <summary>
/// NodeKindWire
/// </summary>
public enum NodeKindWire {
/// <summary>
/// Default
/// </summary>
[pbr::OriginalName("Blob")] Blob = 0,
[pbr::OriginalName("Tree")] Tree = 1,
}
#endregion
#region Messages
/// <summary>
/// TreeWireNode
/// </summary>
public sealed partial class TreeWireNode : pb::IMessage<TreeWireNode> {
private static readonly pb::MessageParser<TreeWireNode> _parser = new pb::MessageParser<TreeWireNode>(() => new TreeWireNode());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<TreeWireNode> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::SourceCode.Chasm.IO.Proto.Wire.TreeWireReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TreeWireNode() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TreeWireNode(TreeWireNode other) : this() {
name_ = other.name_;
kind_ = other.kind_;
NodeId = other.nodeId_ != null ? other.NodeId.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TreeWireNode Clone() {
return new TreeWireNode(this);
}
/// <summary>Field number for the "Name" field.</summary>
public const int NameFieldNumber = 1;
private string name_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Name {
get { return name_; }
set {
name_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "Kind" field.</summary>
public const int KindFieldNumber = 2;
private global::SourceCode.Chasm.IO.Proto.Wire.NodeKindWire kind_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::SourceCode.Chasm.IO.Proto.Wire.NodeKindWire Kind {
get { return kind_; }
set {
kind_ = value;
}
}
/// <summary>Field number for the "NodeId" field.</summary>
public const int NodeIdFieldNumber = 3;
private global::SourceCode.Chasm.IO.Proto.Wire.Sha1Wire nodeId_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::SourceCode.Chasm.IO.Proto.Wire.Sha1Wire NodeId {
get { return nodeId_; }
set {
nodeId_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as TreeWireNode);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(TreeWireNode other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Name != other.Name) return false;
if (Kind != other.Kind) return false;
if (!object.Equals(NodeId, other.NodeId)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Name.Length != 0) hash ^= Name.GetHashCode();
if (Kind != 0) hash ^= Kind.GetHashCode();
if (nodeId_ != null) hash ^= NodeId.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Name.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Name);
}
if (Kind != 0) {
output.WriteRawTag(16);
output.WriteEnum((int) Kind);
}
if (nodeId_ != null) {
output.WriteRawTag(26);
output.WriteMessage(NodeId);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Name.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
}
if (Kind != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Kind);
}
if (nodeId_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(NodeId);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(TreeWireNode other) {
if (other == null) {
return;
}
if (other.Name.Length != 0) {
Name = other.Name;
}
if (other.Kind != 0) {
Kind = other.Kind;
}
if (other.nodeId_ != null) {
if (nodeId_ == null) {
nodeId_ = new global::SourceCode.Chasm.IO.Proto.Wire.Sha1Wire();
}
NodeId.MergeFrom(other.NodeId);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Name = input.ReadString();
break;
}
case 16: {
kind_ = (global::SourceCode.Chasm.IO.Proto.Wire.NodeKindWire) input.ReadEnum();
break;
}
case 26: {
if (nodeId_ == null) {
nodeId_ = new global::SourceCode.Chasm.IO.Proto.Wire.Sha1Wire();
}
input.ReadMessage(nodeId_);
break;
}
}
}
}
}
/// <summary>
/// TreeWire
/// </summary>
public sealed partial class TreeWire : pb::IMessage<TreeWire> {
private static readonly pb::MessageParser<TreeWire> _parser = new pb::MessageParser<TreeWire>(() => new TreeWire());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<TreeWire> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::SourceCode.Chasm.IO.Proto.Wire.TreeWireReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TreeWire() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TreeWire(TreeWire other) : this() {
nodes_ = other.nodes_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TreeWire Clone() {
return new TreeWire(this);
}
/// <summary>Field number for the "Nodes" field.</summary>
public const int NodesFieldNumber = 1;
private static readonly pb::FieldCodec<global::SourceCode.Chasm.IO.Proto.Wire.TreeWireNode> _repeated_nodes_codec
= pb::FieldCodec.ForMessage(10, global::SourceCode.Chasm.IO.Proto.Wire.TreeWireNode.Parser);
private readonly pbc::RepeatedField<global::SourceCode.Chasm.IO.Proto.Wire.TreeWireNode> nodes_ = new pbc::RepeatedField<global::SourceCode.Chasm.IO.Proto.Wire.TreeWireNode>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::SourceCode.Chasm.IO.Proto.Wire.TreeWireNode> Nodes {
get { return nodes_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as TreeWire);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(TreeWire other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!nodes_.Equals(other.nodes_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= nodes_.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
nodes_.WriteTo(output, _repeated_nodes_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += nodes_.CalculateSize(_repeated_nodes_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(TreeWire other) {
if (other == null) {
return;
}
nodes_.Add(other.nodes_);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
nodes_.AddEntriesFrom(input, _repeated_nodes_codec);
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
using System;
using System.Collections.Generic;
using System.Composition.Hosting;
using System.Linq;
using System.Reflection;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyModel;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.PlatformAbstractions;
using OmniSharp.Mef;
using OmniSharp.Middleware;
using OmniSharp.Options;
using OmniSharp.Roslyn;
using OmniSharp.Services;
using OmniSharp.Stdio.Logging;
using OmniSharp.Stdio.Services;
namespace OmniSharp
{
public class Startup
{
public Startup()
{
var appEnv = PlatformServices.Default.Application;
var configBuilder = new ConfigurationBuilder()
.SetBasePath(appEnv.ApplicationBasePath)
.AddJsonFile("config.json", optional: true)
.AddEnvironmentVariables();
if (Program.Environment.OtherArgs != null)
{
configBuilder.AddCommandLine(Program.Environment.OtherArgs);
}
// Use the local omnisharp config if there's any in the root path
configBuilder.AddJsonFile(source =>
{
source.Path = "omnisharp.json";
source.Optional = true;
source.FileProvider = new PhysicalFileProvider(Program.Environment.Path);
});
Configuration = configBuilder.Build();
}
public IConfiguration Configuration { get; }
public OmnisharpWorkspace Workspace { get; set; }
public CompositionHost PluginHost { get; private set; }
public void ConfigureServices(IServiceCollection services)
{
// Add the omnisharp workspace to the container
services.AddSingleton(typeof(OmnisharpWorkspace), (x) => Workspace);
services.AddSingleton(typeof(CompositionHost), (x) => PluginHost);
// Caching
services.AddSingleton<IMemoryCache, MemoryCache>();
services.AddOptions();
// Setup the options from configuration
services.Configure<OmniSharpOptions>(Configuration);
}
public static CompositionHost ConfigureMef(IServiceProvider serviceProvider,
OmniSharpOptions options,
IEnumerable<Assembly> assemblies,
Func<ContainerConfiguration, ContainerConfiguration> configure = null)
{
var config = new ContainerConfiguration();
assemblies = assemblies
.Concat(new[] { typeof(OmnisharpWorkspace).GetTypeInfo().Assembly, typeof(IRequest).GetTypeInfo().Assembly })
.Distinct();
foreach (var assembly in assemblies)
{
config = config.WithAssembly(assembly);
}
var memoryCache = serviceProvider.GetService<IMemoryCache>();
var loggerFactory = serviceProvider.GetService<ILoggerFactory>();
var env = serviceProvider.GetService<IOmnisharpEnvironment>();
var writer = serviceProvider.GetService<ISharedTextWriter>();
var applicationLifetime = serviceProvider.GetService<IApplicationLifetime>();
var loader = serviceProvider.GetService<IOmnisharpAssemblyLoader>();
config = config
.WithProvider(MefValueProvider.From(serviceProvider))
.WithProvider(MefValueProvider.From<IFileSystemWatcher>(new ManualFileSystemWatcher()))
.WithProvider(MefValueProvider.From(memoryCache))
.WithProvider(MefValueProvider.From(loggerFactory))
.WithProvider(MefValueProvider.From(env))
.WithProvider(MefValueProvider.From(writer))
.WithProvider(MefValueProvider.From(applicationLifetime))
.WithProvider(MefValueProvider.From(options))
.WithProvider(MefValueProvider.From(options.FormattingOptions))
.WithProvider(MefValueProvider.From(loader))
.WithProvider(MefValueProvider.From(new MetadataHelper(loader))); // other way to do singleton and autowire?
if (env.TransportType == TransportType.Stdio)
{
config = config
.WithProvider(MefValueProvider.From<IEventEmitter>(new StdioEventEmitter(writer)));
}
else
{
config = config
.WithProvider(MefValueProvider.From<IEventEmitter>(new NullEventEmitter()));
}
if (configure != null)
config = configure(config);
var container = config.CreateContainer();
return container;
}
public void Configure(IApplicationBuilder app,
IServiceProvider serviceProvider,
IOmnisharpEnvironment env,
ILoggerFactory loggerFactory,
ISharedTextWriter writer,
IOmnisharpAssemblyLoader loader,
IOptions<OmniSharpOptions> optionsAccessor)
{
Func<RuntimeLibrary, bool> shouldLoad = lib => lib.Dependencies.Any(dep => dep.Name == "OmniSharp.Abstractions" ||
dep.Name == "OmniSharp.Roslyn");
var dependencyContext = DependencyContext.Default;
var assemblies = dependencyContext.RuntimeLibraries
.Where(shouldLoad)
.SelectMany(lib => lib.GetDefaultAssemblyNames(dependencyContext))
.Select(each => loader.Load(each.Name))
.ToList();
PluginHost = ConfigureMef(serviceProvider, optionsAccessor.Value, assemblies);
Workspace = PluginHost.GetExport<OmnisharpWorkspace>();
if (env.TransportType == TransportType.Stdio)
{
loggerFactory.AddStdio(writer, (category, level) => LogFilter(category, level, env));
}
else
{
loggerFactory.AddConsole((category, level) => LogFilter(category, level, env));
}
var logger = loggerFactory.CreateLogger<Startup>();
foreach (var assembly in assemblies)
{
logger.LogDebug($"Loaded {assembly.FullName}");
}
app.UseRequestLogging();
app.UseExceptionHandler("/error");
app.UseMiddleware<EndpointMiddleware>();
app.UseMiddleware<StatusMiddleware>();
app.UseMiddleware<StopServerMiddleware>();
if (env.TransportType == TransportType.Stdio)
{
logger.LogInformation($"Omnisharp server running using {nameof(TransportType.Stdio)} at location '{env.Path}' on host {env.HostPID}.");
}
else
{
logger.LogInformation($"Omnisharp server running on port '{env.Port}' at location '{env.Path}' on host {env.HostPID}.");
}
// ProjectEventForwarder register event to OmnisharpWorkspace during instantiation
PluginHost.GetExport<ProjectEventForwarder>();
// Initialize all the project systems
foreach (var projectSystem in PluginHost.GetExports<IProjectSystem>())
{
try
{
projectSystem.Initalize(Configuration.GetSection(projectSystem.Key));
}
catch (Exception e)
{
var message = $"The project system '{projectSystem.GetType().Name}' threw exception during initialization.\n{e.Message}\n{e.StackTrace}";
// if a project system throws an unhandled exception it should not crash the entire server
logger.LogError(message);
}
}
// Mark the workspace as initialized
Workspace.Initialized = true;
logger.LogInformation("Configuration finished.");
}
private static bool LogFilter(string category, LogLevel level, IOmnisharpEnvironment environment)
{
if (environment.TraceType > level)
{
return false;
}
if (string.Equals(category,
typeof(ExceptionHandlerMiddleware).FullName,
StringComparison.OrdinalIgnoreCase))
{
return true;
}
if (!category.StartsWith("OmniSharp", StringComparison.OrdinalIgnoreCase))
{
return false;
}
if (string.Equals(category,
typeof(WorkspaceInformationService).FullName,
StringComparison.OrdinalIgnoreCase))
{
return false;
}
if (string.Equals(category,
typeof(ProjectEventForwarder).FullName,
StringComparison.OrdinalIgnoreCase))
{
return false;
}
return true;
}
}
}
| |
using System;
#if FRB_MDX
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;
using Direct3D=Microsoft.DirectX.Direct3D;
using Texture2D = FlatRedBall.Texture2D;
#elif FRB_XNA || SILVERLIGHT || WINDOWS_PHONE
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
#endif
using FlatRedBall.Math.Geometry;
using FlatRedBall.Graphics;
using FlatRedBall.Graphics.Animation;
using FlatRedBall.ManagedSpriteGroups;
using FlatRedBall.Utilities;
using Point = FlatRedBall.Math.Geometry.Point;
namespace FlatRedBall.Gui
{
#region Enums
public enum ButtonPushedState
{
Down,
Up
}
#endregion
#region XML docs
/// <summary>
/// A UI element which displays text and visually responds to pushes.
/// </summary>
#endregion
public class Button : Window
{
#region Fields
bool mShowsToolTip = true;
internal string mText;
internal Point overlayTL;
internal Point overlayTR;
internal Point overlayBL;
internal Point overlayBR;
internal Point downOverlayTL;
internal Point downOverlayTR;
internal Point downOverlayBL;
internal Point downOverlayBR;
#region XML Docs
/// <summary>
/// Whether the base (center and borders) are drawn
/// </summary>
#endregion
bool mDrawBase;
protected Texture2D mOverlayTexture;
private bool mFlipVertical;
private bool mFlipHorizontal;
private bool mHighlightOnDown;
ButtonPushedState mButtonPushedState = ButtonPushedState.Up;
#region SpriteFrame values
Text mTextObject;
ButtonSkin mUpSkin;
ButtonSkin mDownSkin;
#endregion
#endregion
#region Properties
#region XML Docs
/// <summary>
/// Gets the current ButtonPushedState.
/// </summary>
#endregion
public ButtonPushedState ButtonPushedState
{
get { return mButtonPushedState; }
internal set
{
mButtonPushedState = value;
if (GuiManagerDrawn == false)
{
if (mButtonPushedState == ButtonPushedState.Up)
{
SetTexturePropertiesFromSkin(mUpSkin);
}
else
{
SetTexturePropertiesFromSkin(mDownSkin);
}
}
}
}
#region XML Docs
/// <summary>
/// Whether the Window draws its base and borders. Setting to false will only draw the Window's texture.
/// </summary>
/// <remarks>
/// Set this to false if the Button is used to draw a texture.
/// </remarks>
#endregion
public bool DrawBase
{
get { return mDrawBase; }
set { mDrawBase = value; }
}
#region XML Docs
/// <summary>
/// Gets and sets whether the Button can be interacted with.
/// </summary>
#endregion
public override bool Enabled
{
get
{
return base.Enabled;
}
set
{
base.Enabled = value;
#if FRB_MDX
if(value == true)
this.mColor = 0xFF000000;
else
this.mColor = 0xAA000000;
#else
if(value == true)
this.mColor.PackedValue = 0xFF000000;
else
this.mColor.PackedValue = 0xAA000000;
#endif
}
}
#region XML Docs
/// <summary>
/// Gets and sets whether to horizontally flip the overlayed texture.
/// </summary>
/// <remarks>
/// This property only affects the appearance of the Button if SetOverlayTexture is called to change the
/// overlay texture.
/// </remarks>
#endregion
public bool FlipHorizontal
{
get { return mFlipHorizontal; }
set { mFlipHorizontal = value; }
}
#region XML Docs
/// <summary>
/// Gets and sets whether to horizontally flip the overlayed texture.
/// </summary>
/// <remarks>
/// This property only affects the appearance of the Button if SetOverlayTexture is called to change the
/// overlay texture.
/// </remarks>
#endregion
public bool FlipVertical
{
get { return mFlipVertical; }
set { mFlipVertical = value; }
}
#region XML Docs
/// <summary>
/// Gets and sets whether the button should draw itself lighter when pressed if it
/// is referencing an overly texture. Default value is true.
/// </summary>
/// <remarks>
/// This property has no impact if the button is not referencing an overlay texture.
/// </remarks>
#endregion
public bool HighlightOnDown
{
get { return mHighlightOnDown; }
set { mHighlightOnDown = value; }
}
public bool ShowsToolTip
{
get { return mShowsToolTip; }
set { mShowsToolTip = value; }
}
#region XML Docs
/// <summary>
/// The string to display and the tool tip text to display when the cursor
/// moves over the button.
/// </summary>
/// <remarks>
/// This is only on the Button if the overlay texture is null. The tool tip will show
/// regardless of whether the button is showing a texture or not.
/// </remarks>
#endregion
public virtual string Text
{
get { return mText; }
set
{
mText = value;
if (mTextObject != null)
{
mTextObject.DisplayText = value;
}
}
}
#region XML Docs
/// <summary>
/// The overlay texture the button is displaying.
/// </summary>
#endregion
public Texture2D UpOverlayTexture
{
get { return mOverlayTexture; }
}
public override bool Visible
{
get
{
return base.Visible;
}
set
{
base.Visible = value;
if (mTextObject != null)
{
mTextObject.Visible = value;
}
}
}
#endregion
#region Methods
#region Constructor
public Button(Cursor cursor) :
base(cursor)
{
//overlayTexture = null; automatic
ScaleX = 1;
ScaleY = 1;
DrawBase = true;
overlayTL.X = overlayTL.Y = -1;
overlayTR.X = overlayTR.Y = -1;
overlayBL.X = overlayBL.Y = -1;
overlayBR.X = overlayBR.Y = -1;
downOverlayTL.X = downOverlayTL.Y = -1;
downOverlayTR.X = downOverlayTR.Y = -1;
downOverlayBL.X = downOverlayBL.Y = -1;
downOverlayBR.X = downOverlayBR.Y = -1;
HighlightOnDown = true;
// flipOnXAxis = false;
// flipOnYAxis = false;
mNumberOfVertices = 54; // 9 quads, 6 vertices per quad
}
public Button(string buttonTexture, Cursor cursor, string contentManagerName)
:
base(buttonTexture, cursor, contentManagerName)
{
ScaleX = 1;
ScaleY = 1;
}
public Button(GuiSkin guiSkin, Cursor cursor)
: base(guiSkin, cursor)
{
mUpSkin = guiSkin.ButtonSkin;
mDownSkin = guiSkin.ButtonDownSkin;
mTextObject = TextManager.AddText(this.Text, guiSkin.ButtonSkin.Font);
mTextObject.HorizontalAlignment = HorizontalAlignment.Center;
mTextObject.VerticalAlignment = VerticalAlignment.Center;
mTextObject.AttachTo(SpriteFrame, false);
mTextObject.RelativeZ = -.001f * FlatRedBall.Math.MathFunctions.ForwardVector3.Z;
SetTexturePropertiesFromSkin(mUpSkin);
ScaleX = 1;
ScaleY = 1;
}
#endregion
#region Public Methods
public virtual void Press()
{
OnClick();
}
public virtual void SetOverlayTextures(Texture2D upTexture, Texture2D downTexture)
{
mOverlayTexture = upTexture;
SetAnimationChain(null);
}
public void SetOverlayTextures(int col, int row)
{
overlayTL.X = col * 16 / 256.0f;
overlayTL.Y = .75f + row * 16 / 256.0f;
overlayTR.X = (1 + col) * 16 / 256.0f;
overlayTR.Y = .75f + row * 16 / 256.0f;
overlayBL.X = col * 16 / 256.0f;
overlayBL.Y = .75f + (1 + row) * 16 / 256.0f;
overlayBR.X = (1 + col) * 16 / 256.0f;
overlayBR.Y = .75f + (1 + row) * 16 / 256.0f;
mNumberOfVertices = 54 + 6; // 9 quads, 6 vertices per quad plus the new overlaying quad
}
public void SetOverlayTextures(int col, int row, int downCol, int downRow)
{
SetOverlayTextures(col, row);
downOverlayTL.X = downCol*16/256.0f;
downOverlayTL.Y = .75f + downRow*16/256.0f;
downOverlayTR.X = (1 + downCol)*16/256.0f;
downOverlayTR.Y = .75f + downRow*16/256.0f;
downOverlayBL.X = downCol*16/256.0f;
downOverlayBL.Y = .75f + (1 + downRow)*16/256.0f;
downOverlayBR.X = (1+downCol)*16/256.0f;
downOverlayBR.Y = .75f + (1 + downRow)*16/256.0f;
mNumberOfVertices = 54 + 6; // 9 quads, 6 vertices per quad plus the new overlaying quad
}
public void SetOverlayAnimationChain(AnimationChain achToSet)
{
throw new NotImplementedException();
//mSprite.SetAnimationChain(achToSet, TimeManager.CurrentTime);
}
#endregion
#region Protected Methods
public override void SetSkin(GuiSkin guiSkin)
{
SetSkin(guiSkin.ButtonSkin, guiSkin.ButtonDownSkin);
}
public void SetSkin(ButtonSkin upSkin, ButtonSkin downSkin)
{
mUpSkin = upSkin;
mDownSkin = downSkin;
switch (mButtonPushedState)
{
case ButtonPushedState.Up:
SetTexturePropertiesFromSkin(mUpSkin);
break;
case ButtonPushedState.Down:
SetTexturePropertiesFromSkin(mDownSkin);
break;
}
}
private void SetTexturePropertiesFromSkin(ButtonSkin buttonSkin)
{
SetFromWindowSkin(buttonSkin);
if (mTextObject != null)
{
mTextObject.Font = buttonSkin.Font;
mTextObject.Scale = buttonSkin.TextScale;
mTextObject.Spacing = buttonSkin.TextSpacing;
}
}
#endregion
#region Internal Methods
internal override void Destroy()
{
Destroy(false);
}
internal protected override void Destroy(bool keepEvents)
{
base.Destroy(keepEvents);
if (mTextObject != null)
{
TextManager.RemoveText(mTextObject);
}
}
#if !SILVERLIGHT
internal override void DrawSelfAndChildren(Camera camera)
{
if (Visible == false)
return;
float xToUse = mWorldUnitX;
float yToUse = mWorldUnitY;
float edgeWidth = .2f;
#region draw the basic button
StaticVertices[0].Position.Z = StaticVertices[1].Position.Z = StaticVertices[2].Position.Z =
StaticVertices[3].Position.Z = StaticVertices[4].Position.Z = StaticVertices[5].Position.Z =
camera.Z + FlatRedBall.Math.MathFunctions.ForwardVector3.Z * 100;
StaticVertices[0].Color = StaticVertices[1].Color = StaticVertices[2].Color = StaticVertices[3].Color = StaticVertices[4].Color = StaticVertices[5].Color = mColor;
if(mDrawBase)
{
#region state == "down"
if(ButtonPushedState == ButtonPushedState.Down)
{
#region Top Left of the Window
StaticVertices[0].Position.X = xToUse - ScaleX;
StaticVertices[0].Position.Y = yToUse + ScaleY - edgeWidth;
StaticVertices[0].TextureCoordinate.X = .179688f;
StaticVertices[0].TextureCoordinate.Y = .64453125f;
StaticVertices[1].Position.X = xToUse - ScaleX;
StaticVertices[1].Position.Y = yToUse + ScaleY;
StaticVertices[1].TextureCoordinate.X = .179688f;
StaticVertices[1].TextureCoordinate.Y = .640625f;
StaticVertices[2].Position.X = xToUse - ScaleX + edgeWidth;
StaticVertices[2].Position.Y = yToUse + ScaleY;
StaticVertices[2].TextureCoordinate.X = .18359375f;
StaticVertices[2].TextureCoordinate.Y = .640625f;
StaticVertices[3] = StaticVertices[0];
StaticVertices[4] = StaticVertices[2];
StaticVertices[5].Position.X = xToUse - ScaleX + edgeWidth;
StaticVertices[5].Position.Y = yToUse + ScaleY - edgeWidth;
StaticVertices[5].TextureCoordinate.X = .18359375f;
StaticVertices[5].TextureCoordinate.Y = .64453125f;
GuiManager.WriteVerts(StaticVertices);
#endregion
#region Top Border
StaticVertices[0].Position.X = xToUse - ScaleX + edgeWidth;
StaticVertices[0].Position.Y = yToUse + ScaleY - edgeWidth;
StaticVertices[0].TextureCoordinate.X = .1796875f;
StaticVertices[0].TextureCoordinate.Y = .64453125f;
StaticVertices[1].Position.X = xToUse - ScaleX + edgeWidth;
StaticVertices[1].Position.Y = yToUse + ScaleY;
StaticVertices[1].TextureCoordinate.X = .1796875f;
StaticVertices[1].TextureCoordinate.Y = .640625f;
StaticVertices[2].Position.X = xToUse + ScaleX - edgeWidth;
StaticVertices[2].Position.Y = yToUse + ScaleY;
StaticVertices[2].TextureCoordinate.X = .18359375f;
StaticVertices[2].TextureCoordinate.Y = .640625f;
StaticVertices[3] = StaticVertices[0];
StaticVertices[4] = StaticVertices[2];
StaticVertices[5].Position.X = xToUse + ScaleX - edgeWidth;
StaticVertices[5].Position.Y = yToUse + ScaleY - edgeWidth;
StaticVertices[5].TextureCoordinate.X = .18359375f;
StaticVertices[5].TextureCoordinate.Y = .64453125f;
GuiManager.WriteVerts(StaticVertices);
#endregion
#region Top Right of the Window
StaticVertices[0].Position.X = xToUse + ScaleX - edgeWidth;
StaticVertices[0].Position.Y = yToUse + ScaleY - edgeWidth;
StaticVertices[0].TextureCoordinate.X = .17578125f;
StaticVertices[0].TextureCoordinate.Y = .640625f;
StaticVertices[1].Position.X = xToUse + ScaleX - edgeWidth;
StaticVertices[1].Position.Y = yToUse + ScaleY;
StaticVertices[1].TextureCoordinate.X = .17578125f;
StaticVertices[1].TextureCoordinate.Y = .63671875f;
StaticVertices[2].Position.X = xToUse + ScaleX;
StaticVertices[2].Position.Y = yToUse + ScaleY;
StaticVertices[2].TextureCoordinate.X = .1796875f;
StaticVertices[2].TextureCoordinate.Y = .63671875f;
StaticVertices[3] = StaticVertices[0];
StaticVertices[4] = StaticVertices[2];
StaticVertices[5].Position.X = xToUse + ScaleX;
StaticVertices[5].Position.Y = yToUse + ScaleY - edgeWidth;
StaticVertices[5].TextureCoordinate.X = .1796875f;
StaticVertices[5].TextureCoordinate.Y = .640625f;
GuiManager.WriteVerts(StaticVertices);
#endregion
#region RightBorder
StaticVertices[0].Position.X = xToUse + ScaleX - edgeWidth;
StaticVertices[0].Position.Y = yToUse - ScaleY + edgeWidth;
StaticVertices[0].TextureCoordinate.X = .17578125f;
StaticVertices[0].TextureCoordinate.Y = .63671875f;
StaticVertices[1].Position.X = xToUse + ScaleX - edgeWidth;
StaticVertices[1].Position.Y = yToUse + ScaleY - edgeWidth;
StaticVertices[1].TextureCoordinate.X = .17578125f;
StaticVertices[1].TextureCoordinate.Y = .6328125f;
StaticVertices[2].Position.X = xToUse + ScaleX;
StaticVertices[2].Position.Y = yToUse + ScaleY - edgeWidth;
StaticVertices[2].TextureCoordinate.X = .1796875f;
StaticVertices[2].TextureCoordinate.Y = .6328125f;
StaticVertices[3] = StaticVertices[0];
StaticVertices[4] = StaticVertices[2];
StaticVertices[5].Position.X = xToUse + ScaleX;
StaticVertices[5].Position.Y = yToUse - ScaleY + edgeWidth;
StaticVertices[5].TextureCoordinate.X = .1796875f;
StaticVertices[5].TextureCoordinate.Y = .63671875f;
GuiManager.WriteVerts(StaticVertices);
#endregion
#region Bottom Border
StaticVertices[0].Position.X = xToUse - ScaleX + edgeWidth;
StaticVertices[0].Position.Y = yToUse - ScaleY;
StaticVertices[0].TextureCoordinate.X = .1796875f;
StaticVertices[0].TextureCoordinate.Y = .63671875f;
StaticVertices[1].Position.X = xToUse - ScaleX + edgeWidth;
StaticVertices[1].Position.Y = yToUse - ScaleY + edgeWidth;
StaticVertices[1].TextureCoordinate.X = .1796875f;
StaticVertices[1].TextureCoordinate.Y = .6328125f;
StaticVertices[2].Position.X = xToUse + ScaleX - edgeWidth;
StaticVertices[2].Position.Y = yToUse - ScaleY + edgeWidth;
StaticVertices[2].TextureCoordinate.X = .18359375f;
StaticVertices[2].TextureCoordinate.Y = .6328125f;
StaticVertices[3] = StaticVertices[0];
StaticVertices[4] = StaticVertices[2];
StaticVertices[5].Position.X = xToUse + ScaleX - edgeWidth;
StaticVertices[5].Position.Y = yToUse - ScaleY;
StaticVertices[5].TextureCoordinate.X = .18359375f;
StaticVertices[5].TextureCoordinate.Y = .63671875f;
GuiManager.WriteVerts(StaticVertices);
#endregion
#region LeftBorder
StaticVertices[0].Position.X = xToUse - ScaleX;
StaticVertices[0].Position.Y = yToUse - ScaleY + edgeWidth;
StaticVertices[0].TextureCoordinate.X = .18359375f;
StaticVertices[0].TextureCoordinate.Y = .640625f;
StaticVertices[1].Position.X = xToUse - ScaleX;
StaticVertices[1].Position.Y = yToUse + ScaleY - edgeWidth;
StaticVertices[1].TextureCoordinate.X = .18359375f;
StaticVertices[1].TextureCoordinate.Y = .63671875f;
StaticVertices[2].Position.X = xToUse - ScaleX + edgeWidth;
StaticVertices[2].Position.Y = yToUse + ScaleY - edgeWidth;
StaticVertices[2].TextureCoordinate.X = .1875f;
StaticVertices[2].TextureCoordinate.Y = .63671875f;
StaticVertices[3] = StaticVertices[0];
StaticVertices[4] = StaticVertices[2];
StaticVertices[5].Position.X = xToUse - ScaleX + edgeWidth;
StaticVertices[5].Position.Y = yToUse - ScaleY + edgeWidth;
StaticVertices[5].TextureCoordinate.X = .1875f;
StaticVertices[5].TextureCoordinate.Y = .640625f;
GuiManager.WriteVerts(StaticVertices);
#endregion
#region Bottom Left of the Window
StaticVertices[0].Position.X = xToUse - ScaleX;
StaticVertices[0].Position.Y = yToUse - ScaleY;
StaticVertices[0].TextureCoordinate.X = .179688f;
StaticVertices[0].TextureCoordinate.Y = .63671875f;
StaticVertices[1].Position.X = xToUse - ScaleX;
StaticVertices[1].Position.Y = yToUse - ScaleY + edgeWidth;
StaticVertices[1].TextureCoordinate.X = .179688f;
StaticVertices[1].TextureCoordinate.Y = .6328125f;
StaticVertices[2].Position.X = xToUse - ScaleX + edgeWidth;
StaticVertices[2].Position.Y = yToUse - ScaleY + edgeWidth;
StaticVertices[2].TextureCoordinate.X = .18359375f;
StaticVertices[2].TextureCoordinate.Y = .6328125f;
StaticVertices[3] = StaticVertices[0];
StaticVertices[4] = StaticVertices[2];
StaticVertices[5].Position.X = xToUse - ScaleX + edgeWidth;
StaticVertices[5].Position.Y = yToUse - ScaleY;
StaticVertices[5].TextureCoordinate.X = .18359375f;
StaticVertices[5].TextureCoordinate.Y = .63671875f;
GuiManager.WriteVerts(StaticVertices);
#endregion
#region Center
StaticVertices[0].Position.X = xToUse - ScaleX + edgeWidth;
StaticVertices[0].Position.Y = yToUse - ScaleY + edgeWidth;
StaticVertices[0].TextureCoordinate.X = .10938f;
StaticVertices[0].TextureCoordinate.Y = .63719f;
StaticVertices[1].Position.X = xToUse - ScaleX + edgeWidth;
StaticVertices[1].Position.Y = yToUse + ScaleY - edgeWidth;
StaticVertices[1].TextureCoordinate.X = .10938f;
StaticVertices[1].TextureCoordinate.Y = .6953125f;
StaticVertices[2].Position.X = xToUse + ScaleX - edgeWidth;
StaticVertices[2].Position.Y = yToUse + ScaleY - edgeWidth;
StaticVertices[2].TextureCoordinate.X = .10998f;
StaticVertices[2].TextureCoordinate.Y = .6953125f;
StaticVertices[3] = StaticVertices[0];
StaticVertices[4] = StaticVertices[2];
StaticVertices[5].Position.X = xToUse + ScaleX - edgeWidth;
StaticVertices[5].Position.Y = yToUse - ScaleY + edgeWidth;
StaticVertices[5].TextureCoordinate.X = .10998f;
StaticVertices[5].TextureCoordinate.Y = .63719f;
GuiManager.WriteVerts(StaticVertices);
#endregion
#region Bottom Right of the Window
StaticVertices[0].Position.X = xToUse + ScaleX - edgeWidth;
StaticVertices[0].Position.Y = yToUse - ScaleY;
StaticVertices[0].TextureCoordinate.X = .17578125f;
StaticVertices[0].TextureCoordinate.Y = .63671875f;
StaticVertices[1].Position.X = xToUse + ScaleX - edgeWidth;
StaticVertices[1].Position.Y = yToUse - ScaleY + edgeWidth;
StaticVertices[1].TextureCoordinate.X = .17578125f;
StaticVertices[1].TextureCoordinate.Y = .6328125f;
StaticVertices[2].Position.X = xToUse + ScaleX;
StaticVertices[2].Position.Y = yToUse - ScaleY + edgeWidth;
StaticVertices[2].TextureCoordinate.X = .1796875f;
StaticVertices[2].TextureCoordinate.Y = .6328125f;
StaticVertices[3] = StaticVertices[0];
StaticVertices[4] = StaticVertices[2];
StaticVertices[5].Position.X = xToUse + ScaleX;
StaticVertices[5].Position.Y = yToUse - ScaleY;
StaticVertices[5].TextureCoordinate.X = .1796875f;
StaticVertices[5].TextureCoordinate.Y = .63671875f;
GuiManager.WriteVerts(StaticVertices);
#endregion
}
#endregion
#region state == "up"
else
{
#region Top Left of the Window
StaticVertices[0].Position.X = xToUse - ScaleX;
StaticVertices[0].Position.Y = yToUse + ScaleY - edgeWidth;
StaticVertices[0].TextureCoordinate.X = .17578125f;
StaticVertices[0].TextureCoordinate.Y = .63671875f;
StaticVertices[1].Position.X = xToUse - ScaleX;
StaticVertices[1].Position.Y = yToUse + ScaleY;
StaticVertices[1].TextureCoordinate.X = .17578125f;
StaticVertices[1].TextureCoordinate.Y = .6328125f;
StaticVertices[2].Position.X = xToUse - ScaleX + edgeWidth;
StaticVertices[2].Position.Y = yToUse + ScaleY;
StaticVertices[2].TextureCoordinate.X = .1796875f;
StaticVertices[2].TextureCoordinate.Y = .6328125f;
StaticVertices[3] = StaticVertices[0];
StaticVertices[4] = StaticVertices[2];
StaticVertices[5].Position.X = xToUse - ScaleX + edgeWidth;
StaticVertices[5].Position.Y = yToUse + ScaleY - edgeWidth;
StaticVertices[5].TextureCoordinate.X = .1796875f;
StaticVertices[5].TextureCoordinate.Y = .63671875f;
GuiManager.WriteVerts(StaticVertices);
#endregion
#region Top Border
StaticVertices[0].Position.X = xToUse - ScaleX + edgeWidth;
StaticVertices[0].Position.Y = yToUse + ScaleY - edgeWidth;
StaticVertices[0].TextureCoordinate.X = .1796875f;
StaticVertices[0].TextureCoordinate.Y = .63671875f;
StaticVertices[1].Position.X = xToUse - ScaleX + edgeWidth;
StaticVertices[1].Position.Y = yToUse + ScaleY;
StaticVertices[1].TextureCoordinate.X = .1796875f;
StaticVertices[1].TextureCoordinate.Y = .6328125f;
StaticVertices[2].Position.X = xToUse + ScaleX - edgeWidth;
StaticVertices[2].Position.Y = yToUse + ScaleY;
StaticVertices[2].TextureCoordinate.X = .18359375f;
StaticVertices[2].TextureCoordinate.Y = .6328125f;
StaticVertices[3] = StaticVertices[0];
StaticVertices[4] = StaticVertices[2];
StaticVertices[5].Position.X = xToUse + ScaleX - edgeWidth;
StaticVertices[5].Position.Y = yToUse + ScaleY - edgeWidth;
StaticVertices[5].TextureCoordinate.X = .18359375f;
StaticVertices[5].TextureCoordinate.Y = .63671875f;
GuiManager.WriteVerts(StaticVertices);
#endregion
#region Top Right of the Window
StaticVertices[0].Position.X = xToUse + ScaleX - edgeWidth;
StaticVertices[0].Position.Y = yToUse + ScaleY - edgeWidth;
StaticVertices[0].TextureCoordinate.X = .179688f;
StaticVertices[0].TextureCoordinate.Y = .63671875f;
StaticVertices[1].Position.X = xToUse + ScaleX - edgeWidth;
StaticVertices[1].Position.Y = yToUse + ScaleY;
StaticVertices[1].TextureCoordinate.X = .179688f;
StaticVertices[1].TextureCoordinate.Y = .6328125f;
StaticVertices[2].Position.X = xToUse + ScaleX;
StaticVertices[2].Position.Y = yToUse + ScaleY;
StaticVertices[2].TextureCoordinate.X = .18359375f;
StaticVertices[2].TextureCoordinate.Y = .6328125f;
StaticVertices[3] = StaticVertices[0];
StaticVertices[4] = StaticVertices[2];
StaticVertices[5].Position.X = xToUse + ScaleX;
StaticVertices[5].Position.Y = yToUse + ScaleY - edgeWidth;
StaticVertices[5].TextureCoordinate.X = .18359375f;
StaticVertices[5].TextureCoordinate.Y = .63671875f;
GuiManager.WriteVerts(StaticVertices);
#endregion
#region RightBorder
StaticVertices[0].Position.X = xToUse + ScaleX - edgeWidth;
StaticVertices[0].Position.Y = yToUse - ScaleY + edgeWidth;
StaticVertices[0].TextureCoordinate.X = .18359375f;
StaticVertices[0].TextureCoordinate.Y = .640625f;
StaticVertices[1].Position.X = xToUse + ScaleX - edgeWidth;
StaticVertices[1].Position.Y = yToUse + ScaleY - edgeWidth;
StaticVertices[1].TextureCoordinate.X = .18359375f;
StaticVertices[1].TextureCoordinate.Y = .63671875f;
StaticVertices[2].Position.X = xToUse + ScaleX;
StaticVertices[2].Position.Y = yToUse + ScaleY - edgeWidth;
StaticVertices[2].TextureCoordinate.X = .1875f;
StaticVertices[2].TextureCoordinate.Y = .63671875f;
StaticVertices[3] = StaticVertices[0];
StaticVertices[4] = StaticVertices[2];
StaticVertices[5].Position.X = xToUse + ScaleX;
StaticVertices[5].Position.Y = yToUse - ScaleY + edgeWidth;
StaticVertices[5].TextureCoordinate.X = .1875f;
StaticVertices[5].TextureCoordinate.Y = .640625f;
GuiManager.WriteVerts(StaticVertices);
#endregion
#region Bottom Right of the Window
StaticVertices[0].Position.X = xToUse + ScaleX - edgeWidth;
StaticVertices[0].Position.Y = yToUse - ScaleY;
StaticVertices[0].TextureCoordinate.X = .179688f;
StaticVertices[0].TextureCoordinate.Y = .64453125f;
StaticVertices[1].Position.X = xToUse + ScaleX - edgeWidth;
StaticVertices[1].Position.Y = yToUse - ScaleY + edgeWidth;
StaticVertices[1].TextureCoordinate.X = .179688f;
StaticVertices[1].TextureCoordinate.Y = .640625f;
StaticVertices[2].Position.X = xToUse + ScaleX;
StaticVertices[2].Position.Y = yToUse - ScaleY + edgeWidth;
StaticVertices[2].TextureCoordinate.X = .18359375f;
StaticVertices[2].TextureCoordinate.Y = .640625f;
StaticVertices[3] = StaticVertices[0];
StaticVertices[4] = StaticVertices[2];
StaticVertices[5].Position.X = xToUse + ScaleX;
StaticVertices[5].Position.Y = yToUse - ScaleY;
StaticVertices[5].TextureCoordinate.X = .18359375f;
StaticVertices[5].TextureCoordinate.Y = .64453125f;
GuiManager.WriteVerts(StaticVertices);
#endregion
#region Bottom Border
StaticVertices[0].Position.X = xToUse - ScaleX + edgeWidth;
StaticVertices[0].Position.Y = yToUse - ScaleY;
StaticVertices[0].TextureCoordinate.X = .1796875f;
StaticVertices[0].TextureCoordinate.Y = .64453125f;
StaticVertices[1].Position.X = xToUse - ScaleX + edgeWidth;
StaticVertices[1].Position.Y = yToUse - ScaleY + edgeWidth;
StaticVertices[1].TextureCoordinate.X = .1796875f;
StaticVertices[1].TextureCoordinate.Y = .640625f;
StaticVertices[2].Position.X = xToUse + ScaleX - edgeWidth;
StaticVertices[2].Position.Y = yToUse - ScaleY + edgeWidth;
StaticVertices[2].TextureCoordinate.X = .18359375f;
StaticVertices[2].TextureCoordinate.Y = .640625f;
StaticVertices[3] = StaticVertices[0];
StaticVertices[4] = StaticVertices[2];
StaticVertices[5].Position.X = xToUse + ScaleX - edgeWidth;
StaticVertices[5].Position.Y = yToUse - ScaleY;
StaticVertices[5].TextureCoordinate.X = .18359375f;
StaticVertices[5].TextureCoordinate.Y = .64453125f;
GuiManager.WriteVerts(StaticVertices);
#endregion
#region LeftBorder
StaticVertices[0].Position.X = xToUse - ScaleX;
StaticVertices[0].Position.Y = yToUse - ScaleY + edgeWidth;
StaticVertices[0].TextureCoordinate.X = .17578125f;
StaticVertices[0].TextureCoordinate.Y = .63671875f;
StaticVertices[1].Position.X = xToUse - ScaleX;
StaticVertices[1].Position.Y = yToUse + ScaleY - edgeWidth;
StaticVertices[1].TextureCoordinate.X = .17578125f;
StaticVertices[1].TextureCoordinate.Y = .6328125f;
StaticVertices[2].Position.X = xToUse - ScaleX + edgeWidth;
StaticVertices[2].Position.Y = yToUse + ScaleY - edgeWidth;
StaticVertices[2].TextureCoordinate.X = .1796875f;
StaticVertices[2].TextureCoordinate.Y = .6328125f;
StaticVertices[3] = StaticVertices[0];
StaticVertices[4] = StaticVertices[2];
StaticVertices[5].Position.X = xToUse - ScaleX + edgeWidth;
StaticVertices[5].Position.Y = yToUse - ScaleY + edgeWidth;
StaticVertices[5].TextureCoordinate.X = .1796875f;
StaticVertices[5].TextureCoordinate.Y = .63671875f;
GuiManager.WriteVerts(StaticVertices);
#endregion
#region Bottom Left of the Window
StaticVertices[0].Position.X = xToUse - ScaleX;
StaticVertices[0].Position.Y = yToUse - ScaleY;
StaticVertices[0].TextureCoordinate.X = .17578125f;
StaticVertices[0].TextureCoordinate.Y = .640625f;
StaticVertices[1].Position.X = xToUse - ScaleX;
StaticVertices[1].Position.Y = yToUse - ScaleY + edgeWidth;
StaticVertices[1].TextureCoordinate.X = .17578125f;
StaticVertices[1].TextureCoordinate.Y = .63671875f;
StaticVertices[2].Position.X = xToUse - ScaleX + edgeWidth;
StaticVertices[2].Position.Y = yToUse - ScaleY + edgeWidth;
StaticVertices[2].TextureCoordinate.X = .1796875f;
StaticVertices[2].TextureCoordinate.Y = .63671875f;
StaticVertices[3] = StaticVertices[0];
StaticVertices[4] = StaticVertices[2];
StaticVertices[5].Position.X = xToUse - ScaleX + edgeWidth;
StaticVertices[5].Position.Y = yToUse - ScaleY;
StaticVertices[5].TextureCoordinate.X = .1796875f;
StaticVertices[5].TextureCoordinate.Y = .640625f;
GuiManager.WriteVerts(StaticVertices);
#endregion
#region Center
StaticVertices[0].Position.X = xToUse - ScaleX + edgeWidth;
StaticVertices[0].Position.Y = yToUse - ScaleY + edgeWidth;
StaticVertices[0].TextureCoordinate.X = .10938f;
StaticVertices[0].TextureCoordinate.Y = .6953125f;
StaticVertices[1].Position.X = xToUse - ScaleX + edgeWidth;
StaticVertices[1].Position.Y = yToUse + ScaleY - edgeWidth;
StaticVertices[1].TextureCoordinate.X = .10938f;
StaticVertices[1].TextureCoordinate.Y = .63719f;
StaticVertices[2].Position.X = xToUse + ScaleX - edgeWidth;
StaticVertices[2].Position.Y = yToUse + ScaleY - edgeWidth;
StaticVertices[2].TextureCoordinate.X = .10998f;
StaticVertices[2].TextureCoordinate.Y = .63719f;
StaticVertices[3] = StaticVertices[0];
StaticVertices[4] = StaticVertices[2];
StaticVertices[5].Position.X = xToUse + ScaleX - edgeWidth;
StaticVertices[5].Position.Y = yToUse - ScaleY + edgeWidth;
StaticVertices[5].TextureCoordinate.X = .10998f;
StaticVertices[5].TextureCoordinate.Y = .6953125f;
GuiManager.WriteVerts(StaticVertices);
#endregion
}
#endregion
}
#endregion
#region draw overlay texture if it is an icon in our Gui texture
#if FRB_MDX
uint colorBefore = mColor;
#else
Color colorBefore = mColor;
#endif
if(ButtonPushedState == ButtonPushedState.Down && mHighlightOnDown)
{
// This will only have an impact on the button if it is using an overlay texture.
#if FRB_MDX
StaticVertices[0].Color = StaticVertices[1].Color = StaticVertices[2].Color = StaticVertices[3].Color = StaticVertices[4].Color = StaticVertices[5].Color = 0xff333333;
#else
StaticVertices[0].Color.PackedValue = StaticVertices[1].Color.PackedValue = StaticVertices[2].Color.PackedValue =
StaticVertices[3].Color.PackedValue = StaticVertices[4].Color.PackedValue = StaticVertices[5].Color.PackedValue = 0xff333333;
#endif
}
if (ButtonPushedState == ButtonPushedState.Down && downOverlayTL.X != -1)
{
StaticVertices[0].Position.X = xToUse - ScaleX + edgeWidth;
StaticVertices[0].Position.Y = yToUse - ScaleY + edgeWidth;
StaticVertices[0].TextureCoordinate.X = (float)downOverlayBL.X;
StaticVertices[0].TextureCoordinate.Y = (float)downOverlayBL.Y;
StaticVertices[1].Position.X = xToUse - ScaleX + edgeWidth;
StaticVertices[1].Position.Y = yToUse + ScaleY - edgeWidth;
StaticVertices[1].TextureCoordinate.X = (float)downOverlayTL.X;
StaticVertices[1].TextureCoordinate.Y = (float)downOverlayTL.Y;
StaticVertices[2].Position.X = xToUse + ScaleX - edgeWidth;
StaticVertices[2].Position.Y = yToUse + ScaleY - edgeWidth;
StaticVertices[2].TextureCoordinate.X = (float)downOverlayTR.X;
StaticVertices[2].TextureCoordinate.Y = (float)downOverlayTR.Y;
StaticVertices[3] = StaticVertices[0];
StaticVertices[4] = StaticVertices[2];
StaticVertices[5].Position.X = xToUse + ScaleX - edgeWidth;
StaticVertices[5].Position.Y = yToUse - ScaleY + edgeWidth;
StaticVertices[5].TextureCoordinate.X = (float)downOverlayBR.X;
StaticVertices[5].TextureCoordinate.Y = (float)downOverlayBR.Y;
GuiManager.WriteVerts(StaticVertices);
#if FRB_MDX
mColor = 0xff000000;
#else
mColor.PackedValue = 0xff000000;
#endif
}
else if(overlayTL.X != -1)
{
StaticVertices[0].Position.X = xToUse - ScaleX + edgeWidth;
StaticVertices[0].Position.Y = yToUse - ScaleY + edgeWidth;
StaticVertices[0].TextureCoordinate.X = (float)overlayBL.X;
StaticVertices[0].TextureCoordinate.Y = (float)overlayBL.Y;
StaticVertices[1].Position.X = xToUse - ScaleX + edgeWidth;
StaticVertices[1].Position.Y = yToUse + ScaleY - edgeWidth;
StaticVertices[1].TextureCoordinate.X = (float)overlayTL.X;
StaticVertices[1].TextureCoordinate.Y = (float)overlayTL.Y;
StaticVertices[2].Position.X = xToUse + ScaleX - edgeWidth;
StaticVertices[2].Position.Y = yToUse + ScaleY - edgeWidth;
StaticVertices[2].TextureCoordinate.X = (float)overlayTR.X;
StaticVertices[2].TextureCoordinate.Y = (float)overlayTR.Y;
StaticVertices[3] = StaticVertices[0];
StaticVertices[4] = StaticVertices[2];
StaticVertices[5].Position.X = xToUse + ScaleX - edgeWidth;
StaticVertices[5].Position.Y = yToUse - ScaleY + edgeWidth;
StaticVertices[5].TextureCoordinate.X = (float)overlayBR.X;
StaticVertices[5].TextureCoordinate.Y = (float)overlayBR.Y;
GuiManager.WriteVerts(StaticVertices);
}
mColor = colorBefore;
#endregion
#region draw the overlay texture if it is in a different texture
if(this.mOverlayTexture != null)
{
float left = mTextureLeft;
float right = mTextureRight;
float top = mTextureTop;
float bottom = mTextureBottom;
if(mFlipHorizontal)
{
float temporary = left;
left = right;
right = temporary;
}
if(mFlipVertical)
{
float temporary = top;
top = bottom;
bottom = temporary;
}
GuiManager.AddTextureSwitch(mOverlayTexture);
StaticVertices[0].Position.X = xToUse - ScaleX + edgeWidth;
StaticVertices[0].Position.Y = yToUse - ScaleY + edgeWidth;
StaticVertices[0].TextureCoordinate.X = left;
StaticVertices[0].TextureCoordinate.Y = bottom;
StaticVertices[1].Position.X = xToUse - ScaleX + edgeWidth;
StaticVertices[1].Position.Y = yToUse + ScaleY - edgeWidth;
StaticVertices[1].TextureCoordinate.X = left;
StaticVertices[1].TextureCoordinate.Y = top;
StaticVertices[2].Position.X = xToUse + ScaleX - edgeWidth;
StaticVertices[2].Position.Y = yToUse + ScaleY - edgeWidth;
StaticVertices[2].TextureCoordinate.X = right;
StaticVertices[2].TextureCoordinate.Y = top;
StaticVertices[3] = StaticVertices[0];
StaticVertices[4] = StaticVertices[2];
StaticVertices[5].Position.X = xToUse + ScaleX - edgeWidth;
StaticVertices[5].Position.Y = yToUse - ScaleY + edgeWidth;
StaticVertices[5].TextureCoordinate.X = right;
StaticVertices[5].TextureCoordinate.Y = bottom;
GuiManager.WriteVerts(StaticVertices);
}
#endregion
#region Draw the text
#if FRB_MDX
TextManager.mZForVertexBuffer = camera.Position.Z + 100;
#else
TextManager.mZForVertexBuffer = camera.Position.Z - 100;
#endif
TextManager.mScaleForVertexBuffer = GuiManager.TextHeight / 2.0f;
TextManager.mSpacingForVertexBuffer = GuiManager.TextHeight / 2.0f;
TextManager.mAlignmentForVertexBuffer = HorizontalAlignment.Center;
TextManager.mMaxWidthForVertexBuffer = 1000;
if (this.overlayTL.X == -1 && this.mOverlayTexture == null && Text != null && Text != "")
{
TextManager.mXForVertexBuffer = xToUse;
TextManager.mYForVertexBuffer = yToUse;
int numberOfLines = StringFunctions.GetLineCount(mText);
if (numberOfLines > 1)
{
TextManager.mYForVertexBuffer += TextManager.mSpacingForVertexBuffer * (numberOfLines - 1);
}
TextManager.mRedForVertexBuffer = TextManager.mGreenForVertexBuffer = TextManager.mBlueForVertexBuffer = 20;
if(!Enabled)
TextManager.mAlphaForVertexBuffer = FlatRedBall.Graphics.GraphicalEnumerations.MaxColorComponentValue/2.0f;
else
TextManager.mAlphaForVertexBuffer = FlatRedBall.Graphics.GraphicalEnumerations.MaxColorComponentValue;
string textToDraw = this.Text;
TextManager.Draw(ref textToDraw);
}
#endregion
}
internal override int GetNumberOfVerticesToDraw()
{
int i = 0;
if (mDrawBase) i += 54;
if (ButtonPushedState == ButtonPushedState.Down && downOverlayTL.X != -1)
{
i += 6;
}
else if (overlayTL.X != -1)
i += 6;
if (this.mOverlayTexture != null)
i += 6;
// This was using mText before in the CharacterCountWithoutWhitespace call. It should
// use Text instead so that if the instance is a ToggleButton then the correct
// text is used.
if (this.overlayTL.X == -1 && this.mOverlayTexture == null && Text != null)
i += FlatRedBall.Utilities.StringFunctions.CharacterCountWithoutWhitespace(Text) * 6;
return i;
}
#endif
public override void TestCollision(Cursor cursor)
{
base.TestCollision(cursor);
if (cursor.WindowOver == this && ShowsToolTip)
{
GuiManager.ToolTipText = this.Text;
}
if (cursor.PrimaryDown == false)
{
ButtonPushedState = ButtonPushedState.Up;
}
if (cursor.WindowOver == this && cursor.PrimaryDown && cursor.WindowPushed == this)
{
ButtonPushedState = ButtonPushedState.Down;
}
}
#endregion
#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.Runtime.CompilerServices;
using System.Runtime.InteropServices;
internal class Test
{
[DllImport("kernel32.dll")]
private extern static IntPtr GetModuleHandle(string lpModuleName);
[DllImport("kernel32.dll")]
private extern static IntPtr VirtualAlloc(IntPtr lpAddress, IntPtr dwSize, int flAllocationType, int flProtect);
private static void EatAddressSpace()
{
IntPtr clrDllHandle = GetModuleHandle("clr.dll");
long clrDll = (long)clrDllHandle;
for (long i = clrDll - 0x300000000; i < clrDll + 0x300000000; i += 0x10000)
{
}
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void A1()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void A2()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void A3()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void A4()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void A5()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void A6()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void A7()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void A8()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void A9()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void A10()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void B1()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void B2()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void B3()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void B4()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void B5()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void B6()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void B7()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void B8()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void B9()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void B10()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void C1()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void C2()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void C3()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void C4()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void C5()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void C6()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void C7()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void C8()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void C9()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void C10()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void D1()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void D2()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void D3()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void D4()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void D5()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void D6()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void D7()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void D8()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void D9()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void D10()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void Dummy()
{
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static void GenericRecursion<T, U>(int level)
{
if (level == 0) return;
level--;
GenericRecursion<KeyValuePair<T, U>, U>(level);
GenericRecursion<KeyValuePair<U, T>, U>(level);
GenericRecursion<T, KeyValuePair<T, U>>(level);
GenericRecursion<T, KeyValuePair<U, T>>(level);
Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy();
Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy();
Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy();
Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy();
Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy();
Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy();
Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy();
Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy();
Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy();
Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy();
Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy();
Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy();
Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy();
Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy();
Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy();
Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy();
Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy();
Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy();
}
private static int Main()
{
try
{
Console.WriteLine("Eating address space");
EatAddressSpace();
Console.WriteLine("Eating code heap");
GenericRecursion<int, uint>(5);
A1(); A2(); A3(); A4(); A5(); A6(); A7(); A8(); A9(); A10();
B1(); B2(); B3(); B4(); B5(); B6(); B7(); B8(); B9(); B10();
C1(); C2(); C3(); C4(); C5(); C6(); C7(); C8(); C9(); C10();
D1(); D2(); D3(); D4(); D5(); D6(); D7(); D8(); D9(); D10();
A1(); A2(); A3(); A4(); A5(); A6(); A7(); A8(); A9(); A10();
B1(); B2(); B3(); B4(); B5(); B6(); B7(); B8(); B9(); B10();
C1(); C2(); C3(); C4(); C5(); C6(); C7(); C8(); C9(); C10();
D1(); D2(); D3(); D4(); D5(); D6(); D7(); D8(); D9(); D10();
Console.WriteLine("Done");
return 100;
}
catch (Exception e)
{
Console.WriteLine(e);
return 101;
}
}
}
| |
// 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.
/*============================================================
**
** Classes: Object Security family of classes
**
**
===========================================================*/
using Microsoft.Win32;
using System;
using System.Collections;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Threading;
using System.Diagnostics.Contracts;
using System.Reflection;
namespace System.Security.AccessControl
{
public enum AccessControlModification
{
Add = 0,
Set = 1,
Reset = 2,
Remove = 3,
RemoveAll = 4,
RemoveSpecific = 5,
}
public abstract class ObjectSecurity
{
#region Private Members
private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
internal CommonSecurityDescriptor _securityDescriptor;
private bool _ownerModified = false;
private bool _groupModified = false;
private bool _saclModified = false;
private bool _daclModified = false;
// only these SACL control flags will be automatically carry forward
// when update with new security descriptor.
static private readonly ControlFlags SACL_CONTROL_FLAGS =
ControlFlags.SystemAclPresent |
ControlFlags.SystemAclAutoInherited |
ControlFlags.SystemAclProtected;
// only these DACL control flags will be automatically carry forward
// when update with new security descriptor
static private readonly ControlFlags DACL_CONTROL_FLAGS =
ControlFlags.DiscretionaryAclPresent |
ControlFlags.DiscretionaryAclAutoInherited |
ControlFlags.DiscretionaryAclProtected;
#endregion
#region Constructors
protected ObjectSecurity()
{
}
protected ObjectSecurity( bool isContainer, bool isDS )
: this()
{
// we will create an empty DACL, denying anyone any access as the default. 5 is the capacity.
DiscretionaryAcl dacl = new DiscretionaryAcl(isContainer, isDS, 5);
_securityDescriptor = new CommonSecurityDescriptor( isContainer, isDS, ControlFlags.None, null, null, null, dacl );
}
protected ObjectSecurity(CommonSecurityDescriptor securityDescriptor)
: this()
{
if ( securityDescriptor == null )
{
throw new ArgumentNullException( "securityDescriptor" );
}
Contract.EndContractBlock();
_securityDescriptor = securityDescriptor;
}
#endregion
#region Private methods
private void UpdateWithNewSecurityDescriptor( RawSecurityDescriptor newOne, AccessControlSections includeSections )
{
Contract.Assert( newOne != null, "Must not supply a null parameter here" );
if (( includeSections & AccessControlSections.Owner ) != 0 )
{
_ownerModified = true;
_securityDescriptor.Owner = newOne.Owner;
}
if (( includeSections & AccessControlSections.Group ) != 0 )
{
_groupModified = true;
_securityDescriptor.Group = newOne.Group;
}
if (( includeSections & AccessControlSections.Audit ) != 0 )
{
_saclModified = true;
if ( newOne.SystemAcl != null )
{
_securityDescriptor.SystemAcl = new SystemAcl( IsContainer, IsDS, newOne.SystemAcl, true );
}
else
{
_securityDescriptor.SystemAcl = null;
}
// carry forward the SACL related control flags
_securityDescriptor.UpdateControlFlags(SACL_CONTROL_FLAGS, (ControlFlags)(newOne.ControlFlags & SACL_CONTROL_FLAGS));
}
if (( includeSections & AccessControlSections.Access ) != 0 )
{
_daclModified = true;
if ( newOne.DiscretionaryAcl != null )
{
_securityDescriptor.DiscretionaryAcl = new DiscretionaryAcl( IsContainer, IsDS, newOne.DiscretionaryAcl, true );
}
else
{
_securityDescriptor.DiscretionaryAcl = null;
}
// by the following property set, the _securityDescriptor's control flags
// may contains DACL present flag. That needs to be carried forward! Therefore, we OR
// the current _securityDescriptor.s DACL present flag.
ControlFlags daclFlag = (_securityDescriptor.ControlFlags & ControlFlags.DiscretionaryAclPresent);
_securityDescriptor.UpdateControlFlags(DACL_CONTROL_FLAGS,
(ControlFlags)((newOne.ControlFlags | daclFlag) & DACL_CONTROL_FLAGS));
}
}
#endregion
#region Protected Properties and Methods
protected void ReadLock()
{
_lock.EnterReadLock();
}
protected void ReadUnlock()
{
_lock.ExitReadLock();
}
protected void WriteLock()
{
_lock.EnterWriteLock();
}
protected void WriteUnlock()
{
_lock.ExitWriteLock();
}
protected bool OwnerModified
{
get
{
if (!( _lock.IsReadLockHeld || _lock.IsWriteLockHeld ))
{
throw new InvalidOperationException( SR.InvalidOperation_MustLockForReadOrWrite );
}
return _ownerModified;
}
set
{
if ( !_lock.IsWriteLockHeld )
{
throw new InvalidOperationException( SR.InvalidOperation_MustLockForWrite );
}
_ownerModified = value;
}
}
protected bool GroupModified
{
get
{
if (!( _lock.IsReadLockHeld || _lock.IsWriteLockHeld ))
{
throw new InvalidOperationException( SR.InvalidOperation_MustLockForReadOrWrite );
}
return _groupModified;
}
set
{
if ( !_lock.IsWriteLockHeld )
{
throw new InvalidOperationException( SR.InvalidOperation_MustLockForWrite );
}
_groupModified = value;
}
}
protected bool AuditRulesModified
{
get
{
if (!( _lock.IsReadLockHeld || _lock.IsWriteLockHeld ))
{
throw new InvalidOperationException( SR.InvalidOperation_MustLockForReadOrWrite );
}
return _saclModified;
}
set
{
if ( !_lock.IsWriteLockHeld )
{
throw new InvalidOperationException( SR.InvalidOperation_MustLockForWrite );
}
_saclModified = value;
}
}
protected bool AccessRulesModified
{
get
{
if (!( _lock.IsReadLockHeld || _lock.IsWriteLockHeld ))
{
throw new InvalidOperationException( SR.InvalidOperation_MustLockForReadOrWrite );
}
return _daclModified;
}
set
{
if ( !_lock.IsWriteLockHeld )
{
throw new InvalidOperationException( SR.InvalidOperation_MustLockForWrite );
}
_daclModified = value;
}
}
protected bool IsContainer
{
get { return _securityDescriptor.IsContainer; }
}
protected bool IsDS
{
get { return _securityDescriptor.IsDS; }
}
//
// Persists the changes made to the object
//
// This overloaded method takes a name of an existing object
//
protected virtual void Persist( string name, AccessControlSections includeSections )
{
throw NotImplemented.ByDesign;
}
//
// if Persist (by name) is implemented, then this function will also try to enable take ownership
// privilege while persisting if the enableOwnershipPrivilege is true.
// Integrators can override it if this is not desired.
//
protected virtual void Persist(bool enableOwnershipPrivilege, string name, AccessControlSections includeSections )
{
Privilege ownerPrivilege = null;
try
{
if (enableOwnershipPrivilege)
{
ownerPrivilege = new Privilege(Privilege.TakeOwnership);
try
{
ownerPrivilege.Enable();
}
catch (PrivilegeNotHeldException)
{
// we will ignore this exception and press on just in case this is a remote resource
}
}
Persist(name, includeSections);
}
catch
{
// protection against exception filter-based luring attacks
if ( ownerPrivilege != null )
{
ownerPrivilege.Revert();
}
throw;
}
finally
{
if (ownerPrivilege != null)
{
ownerPrivilege.Revert();
}
}
}
//
// Persists the changes made to the object
//
// This overloaded method takes a handle to an existing object
//
protected virtual void Persist( SafeHandle handle, AccessControlSections includeSections )
{
throw NotImplemented.ByDesign;
}
#endregion
#region Public Methods
//
// Sets and retrieves the owner of this object
//
public IdentityReference GetOwner( System.Type targetType )
{
ReadLock();
try
{
if ( _securityDescriptor.Owner == null )
{
return null;
}
return _securityDescriptor.Owner.Translate( targetType );
}
finally
{
ReadUnlock();
}
}
public void SetOwner( IdentityReference identity )
{
if ( identity == null )
{
throw new ArgumentNullException( "identity" );
}
Contract.EndContractBlock();
WriteLock();
try
{
_securityDescriptor.Owner = identity.Translate( typeof( SecurityIdentifier )) as SecurityIdentifier;
_ownerModified = true;
}
finally
{
WriteUnlock();
}
}
//
// Sets and retrieves the group of this object
//
public IdentityReference GetGroup( System.Type targetType )
{
ReadLock();
try
{
if ( _securityDescriptor.Group == null )
{
return null;
}
return _securityDescriptor.Group.Translate( targetType );
}
finally
{
ReadUnlock();
}
}
public void SetGroup( IdentityReference identity )
{
if ( identity == null )
{
throw new ArgumentNullException( "identity" );
}
Contract.EndContractBlock();
WriteLock();
try
{
_securityDescriptor.Group = identity.Translate( typeof( SecurityIdentifier )) as SecurityIdentifier;
_groupModified = true;
}
finally
{
WriteUnlock();
}
}
public virtual void PurgeAccessRules( IdentityReference identity )
{
if ( identity == null )
{
throw new ArgumentNullException( "identity" );
}
Contract.EndContractBlock();
WriteLock();
try
{
_securityDescriptor.PurgeAccessControl( identity.Translate( typeof( SecurityIdentifier )) as SecurityIdentifier );
_daclModified = true;
}
finally
{
WriteUnlock();
}
}
public virtual void PurgeAuditRules(IdentityReference identity)
{
if ( identity == null )
{
throw new ArgumentNullException( "identity" );
}
Contract.EndContractBlock();
WriteLock();
try
{
_securityDescriptor.PurgeAudit( identity.Translate( typeof( SecurityIdentifier )) as SecurityIdentifier );
_saclModified = true;
}
finally
{
WriteUnlock();
}
}
public bool AreAccessRulesProtected
{
get
{
ReadLock();
try
{
return (( _securityDescriptor.ControlFlags & ControlFlags.DiscretionaryAclProtected ) != 0 );
}
finally
{
ReadUnlock();
}
}
}
public void SetAccessRuleProtection( bool isProtected, bool preserveInheritance )
{
WriteLock();
try
{
_securityDescriptor.SetDiscretionaryAclProtection( isProtected, preserveInheritance );
_daclModified = true;
}
finally
{
WriteUnlock();
}
}
public bool AreAuditRulesProtected
{
get
{
ReadLock();
try
{
return (( _securityDescriptor.ControlFlags & ControlFlags.SystemAclProtected ) != 0 );
}
finally
{
ReadUnlock();
}
}
}
public void SetAuditRuleProtection( bool isProtected, bool preserveInheritance )
{
WriteLock();
try
{
_securityDescriptor.SetSystemAclProtection( isProtected, preserveInheritance );
_saclModified = true;
}
finally
{
WriteUnlock();
}
}
public bool AreAccessRulesCanonical
{
get
{
ReadLock();
try
{
return _securityDescriptor.IsDiscretionaryAclCanonical;
}
finally
{
ReadUnlock();
}
}
}
public bool AreAuditRulesCanonical
{
get
{
ReadLock();
try
{
return _securityDescriptor.IsSystemAclCanonical;
}
finally
{
ReadUnlock();
}
}
}
public static bool IsSddlConversionSupported()
{
return true; // SDDL to binary conversions are supported on Windows 2000 and higher
}
public string GetSecurityDescriptorSddlForm( AccessControlSections includeSections )
{
ReadLock();
try
{
return _securityDescriptor.GetSddlForm( includeSections );
}
finally
{
ReadUnlock();
}
}
public void SetSecurityDescriptorSddlForm( string sddlForm )
{
SetSecurityDescriptorSddlForm( sddlForm, AccessControlSections.All );
}
public void SetSecurityDescriptorSddlForm( string sddlForm, AccessControlSections includeSections )
{
if ( sddlForm == null )
{
throw new ArgumentNullException( "sddlForm" );
}
if (( includeSections & AccessControlSections.All ) == 0 )
{
throw new ArgumentException(
SR.Arg_EnumAtLeastOneFlag,
"includeSections" );
}
Contract.EndContractBlock();
WriteLock();
try
{
UpdateWithNewSecurityDescriptor( new RawSecurityDescriptor( sddlForm ), includeSections );
}
finally
{
WriteUnlock();
}
}
public byte[] GetSecurityDescriptorBinaryForm()
{
ReadLock();
try
{
byte[] result = new byte[_securityDescriptor.BinaryLength];
_securityDescriptor.GetBinaryForm( result, 0 );
return result;
}
finally
{
ReadUnlock();
}
}
public void SetSecurityDescriptorBinaryForm( byte[] binaryForm )
{
SetSecurityDescriptorBinaryForm( binaryForm, AccessControlSections.All );
}
public void SetSecurityDescriptorBinaryForm( byte[] binaryForm, AccessControlSections includeSections )
{
if ( binaryForm == null )
{
throw new ArgumentNullException( "binaryForm" );
}
if (( includeSections & AccessControlSections.All ) == 0 )
{
throw new ArgumentException(
SR.Arg_EnumAtLeastOneFlag,
"includeSections" );
}
Contract.EndContractBlock();
WriteLock();
try
{
UpdateWithNewSecurityDescriptor( new RawSecurityDescriptor( binaryForm, 0 ), includeSections );
}
finally
{
WriteUnlock();
}
}
public abstract Type AccessRightType { get; }
public abstract Type AccessRuleType { get; }
public abstract Type AuditRuleType { get; }
protected abstract bool ModifyAccess( AccessControlModification modification, AccessRule rule, out bool modified);
protected abstract bool ModifyAudit( AccessControlModification modification, AuditRule rule, out bool modified );
public virtual bool ModifyAccessRule(AccessControlModification modification, AccessRule rule, out bool modified)
{
if ( rule == null )
{
throw new ArgumentNullException( "rule" );
}
if ( !this.AccessRuleType.GetTypeInfo().IsAssignableFrom(rule.GetType().GetTypeInfo()) )
{
throw new ArgumentException(
SR.AccessControl_InvalidAccessRuleType,
"rule");
}
Contract.EndContractBlock();
WriteLock();
try
{
return ModifyAccess(modification, rule, out modified);
}
finally
{
WriteUnlock();
}
}
public virtual bool ModifyAuditRule(AccessControlModification modification, AuditRule rule, out bool modified)
{
if ( rule == null )
{
throw new ArgumentNullException( "rule" );
}
if ( !this.AuditRuleType.GetTypeInfo().IsAssignableFrom(rule.GetType().GetTypeInfo()) )
{
throw new ArgumentException(
SR.AccessControl_InvalidAuditRuleType,
"rule");
}
Contract.EndContractBlock();
WriteLock();
try
{
return ModifyAudit(modification, rule, out modified);
}
finally
{
WriteUnlock();
}
}
public abstract AccessRule AccessRuleFactory( IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type );
public abstract AuditRule AuditRuleFactory( IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags );
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Bond
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using Bond.Internal.Reflection;
/// <summary>
/// Utility to create runtime schema for dynamically specified Bond schema
/// </summary>
public static class Schema
{
/// <summary>
/// Get runtime schema for the specified Bond schema
/// </summary>
/// <param name="type">Type representing a Bond schema</param>
/// <returns>Instance of <see cref="RuntimeSchema"/></returns>
public static RuntimeSchema GetRuntimeSchema(Type type)
{
var runtimeSchema = typeof(Schema<>)
.MakeGenericType(type)
.GetDeclaredProperty("RuntimeSchema", typeof(RuntimeSchema));
return (RuntimeSchema)runtimeSchema.GetValue(null);
}
}
/// <summary>
/// Utility to create runtime schema for statically specified Bond schema
/// </summary>
/// <typeparam name="T"></typeparam>
public static class Schema<T>
{
static readonly Cache instance = new Cache(typeof (T));
/// <summary>
/// Runtime schema for the Bond schema type T
/// </summary>
public static RuntimeSchema RuntimeSchema { get { return new RuntimeSchema(instance.Schema); } }
internal static Metadata Metadata
{
get
{
return instance != null ? instance.Metadata : Cache.GetMetadata(typeof(T));
}
}
internal static Metadata[] Fields
{
get
{
return instance != null ? instance.Fields : Cache.GetFields(typeof(T));
}
}
class Cache
{
public readonly Metadata Metadata;
public readonly Metadata[] Fields;
public readonly SchemaDef Schema;
public Cache(Type type)
{
Metadata = GetMetadata(type);
Fields = GetFields(type);
// ReSharper disable once UseObjectOrCollectionInitializer
// The schema field must be instantiated before GetStructDef is called
Schema = new SchemaDef();
Schema.root.struct_def = GetStructDef(type, Metadata, Fields);
}
ushort GetStructDef(Type type, Metadata metadata, Metadata[] fields)
{
var index = Schema.structs.Count;
var structDef = new StructDef();
Schema.structs.Add(structDef);
structDef.metadata = metadata;
var baseType = type.GetBaseSchemaType();
if (baseType != null)
structDef.base_def = GetTypeDef(baseType);
var i = 0;
foreach (var field in type.GetSchemaFields())
{
var fieldDef = new FieldDef
{
id = field.Id,
metadata = fields[i++],
type = GetTypeDef(field.GetSchemaType())
};
structDef.fields.Add(fieldDef);
}
return (ushort) index;
}
TypeDef GetTypeDef(Type type)
{
TypeDef typeDef;
if (type.IsBonded())
{
typeDef = GetTypeDef(type.GetValueType());
typeDef.bonded_type = true;
}
else
{
typeDef = new TypeDef {id = type.GetBondDataType()};
}
if (type.IsBondContainer() || type.IsBondNullable() || type.IsBondBlob())
{
if (type.IsBondMap())
{
var itemType = type.GetKeyValueType();
typeDef.key = GetTypeDef(itemType.Key);
typeDef.element = GetTypeDef(itemType.Value);
}
else
{
typeDef.element = GetTypeDef(type.GetValueType());
}
}
if (type.IsBondStruct())
{
var i = Schema.structs.FindIndex(
s => s.metadata.qualified_name.Equals(type.GetSchemaFullName()));
if (i != -1)
{
typeDef.struct_def = (ushort) i;
}
else
{
var schemaT = typeof (Schema<>).MakeGenericType(type);
var metadataProp = schemaT.GetTypeInfo().GetDeclaredProperty("Metadata");
var fieldsProp = schemaT.GetTypeInfo().GetDeclaredProperty("Fields");
typeDef.struct_def = GetStructDef(
type,
metadataProp.GetValue(null) as Metadata,
fieldsProp.GetValue(null) as Metadata[]);
}
}
return typeDef;
}
public static Metadata GetMetadata(Type type)
{
return new Metadata
{
name = type.GetSchemaName(),
qualified_name = type.GetSchemaFullName(),
attributes = GetAttributes(type.GetTypeInfo())
};
}
public static Metadata[] GetFields(Type type)
{
return (from field in type.GetSchemaFields() select new Metadata
{
name = field.Name,
attributes = GetAttributes(field.MemberInfo),
modifier = field.GetModifier(),
default_value = GetDefaultValue(field)
}).ToArray();
}
static Variant GetDefaultValue(ISchemaField schemaField)
{
var defaultValue = schemaField.GetDefaultValue();
var variant = new Variant();
if (defaultValue == null)
{
if (!schemaField.GetSchemaType().IsBondNullable())
variant.nothing = true;
}
else
{
Type defaultValueType = defaultValue.GetType();
Type schemaFieldType = schemaField.GetSchemaType();
if (schemaFieldType == typeof (Tag.wstring))
schemaFieldType = typeof (string);
bool alias = defaultValueType != schemaFieldType;
switch (schemaField.GetSchemaType().GetBondDataType())
{
case BondDataType.BT_BOOL:
variant.uint_value = alias ? 0ul : ((bool) defaultValue ? 1ul : 0ul);
break;
case BondDataType.BT_UINT8:
case BondDataType.BT_UINT16:
case BondDataType.BT_UINT32:
case BondDataType.BT_UINT64:
variant.uint_value = alias ? 0 : Convert.ToUInt64(defaultValue);
break;
case BondDataType.BT_INT8:
case BondDataType.BT_INT16:
case BondDataType.BT_INT32:
case BondDataType.BT_INT64:
variant.int_value = alias ? 0 : Convert.ToInt64(defaultValue);
break;
case BondDataType.BT_FLOAT:
variant.double_value = alias ? 0 : Convert.ToSingle(defaultValue);
break;
case BondDataType.BT_DOUBLE:
variant.double_value = alias ? 0 : Convert.ToDouble(defaultValue);
break;
case BondDataType.BT_STRING:
variant.string_value = alias ? string.Empty : (string)defaultValue;
break;
case BondDataType.BT_WSTRING:
variant.wstring_value = alias ? string.Empty : (string)defaultValue;
break;
}
}
return variant;
}
static Dictionary<string, string> GetAttributes(MemberInfo memberInfo)
{
var attributes = new Dictionary<string, string>(StringComparer.Ordinal);
foreach (var a in memberInfo.GetCustomAttributes(typeof(AttributeAttribute), false))
{
Debug.Assert(a is AttributeAttribute);
var aa = a as AttributeAttribute;
attributes.Add(aa.Name, aa.Value);
}
return attributes;
}
}
}
}
| |
// 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;
namespace System.Runtime.Serialization
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using System.Xml;
using System.Linq;
using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, DataContract>;
using System.Security;
// The interface is a perf optimization.
// Only KeyValuePairAdapter should implement the interface.
internal interface IKeyValuePairAdapter { }
//Special Adapter class to serialize KeyValuePair as Dictionary needs it when polymorphism is involved
[DataContract(Namespace = "http://schemas.datacontract.org/2004/07/System.Collections.Generic")]
internal class KeyValuePairAdapter<K, T> : IKeyValuePairAdapter
{
private K _kvpKey;
private T _kvpValue;
public KeyValuePairAdapter(KeyValuePair<K, T> kvPair)
{
_kvpKey = kvPair.Key;
_kvpValue = kvPair.Value;
}
[DataMember(Name = "key")]
public K Key
{
get { return _kvpKey; }
set { _kvpKey = value; }
}
[DataMember(Name = "value")]
public T Value
{
get
{
return _kvpValue;
}
set
{
_kvpValue = value;
}
}
internal KeyValuePair<K, T> GetKeyValuePair()
{
return new KeyValuePair<K, T>(_kvpKey, _kvpValue);
}
internal static KeyValuePairAdapter<K, T> GetKeyValuePairAdapter(KeyValuePair<K, T> kvPair)
{
return new KeyValuePairAdapter<K, T>(kvPair);
}
}
#if USE_REFEMIT
public interface IKeyValue
#else
internal interface IKeyValue
#endif
{
object Key { get; set; }
object Value { get; set; }
}
[DataContract(Namespace = "http://schemas.microsoft.com/2003/10/Serialization/Arrays")]
#if USE_REFEMIT
public struct KeyValue<K, V> : IKeyValue
#else
internal struct KeyValue<K, V> : IKeyValue
#endif
{
private K _key;
private V _value;
internal KeyValue(K key, V value)
{
_key = key;
_value = value;
}
[DataMember(IsRequired = true)]
public K Key
{
get { return _key; }
set { _key = value; }
}
[DataMember(IsRequired = true)]
public V Value
{
get { return _value; }
set { _value = value; }
}
object IKeyValue.Key
{
get { return _key; }
set { _key = (K)value; }
}
object IKeyValue.Value
{
get { return _value; }
set { _value = (V)value; }
}
}
#if uapaot
public enum CollectionKind : byte
#else
internal enum CollectionKind : byte
#endif
{
None,
GenericDictionary,
Dictionary,
GenericList,
GenericCollection,
List,
GenericEnumerable,
Collection,
Enumerable,
Array,
}
#if USE_REFEMIT || uapaot
public sealed class CollectionDataContract : DataContract
#else
internal sealed class CollectionDataContract : DataContract
#endif
{
private XmlDictionaryString _collectionItemName;
private XmlDictionaryString _childElementNamespace;
private DataContract _itemContract;
private CollectionDataContractCriticalHelper _helper;
public CollectionDataContract(CollectionKind kind) : base(new CollectionDataContractCriticalHelper(kind))
{
InitCollectionDataContract(this);
}
internal CollectionDataContract(Type type) : base(new CollectionDataContractCriticalHelper(type))
{
InitCollectionDataContract(this);
}
private CollectionDataContract(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo addMethod, ConstructorInfo constructor)
: base(new CollectionDataContractCriticalHelper(type, kind, itemType, getEnumeratorMethod, addMethod, constructor))
{
InitCollectionDataContract(GetSharedTypeContract(type));
}
private CollectionDataContract(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo addMethod, ConstructorInfo constructor, bool isConstructorCheckRequired)
: base(new CollectionDataContractCriticalHelper(type, kind, itemType, getEnumeratorMethod, addMethod, constructor, isConstructorCheckRequired))
{
InitCollectionDataContract(GetSharedTypeContract(type));
}
private CollectionDataContract(Type type, string invalidCollectionInSharedContractMessage) : base(new CollectionDataContractCriticalHelper(type, invalidCollectionInSharedContractMessage))
{
InitCollectionDataContract(GetSharedTypeContract(type));
}
private void InitCollectionDataContract(DataContract sharedTypeContract)
{
_helper = base.Helper as CollectionDataContractCriticalHelper;
_collectionItemName = _helper.CollectionItemName;
if (_helper.Kind == CollectionKind.Dictionary || _helper.Kind == CollectionKind.GenericDictionary)
{
_itemContract = _helper.ItemContract;
}
_helper.SharedTypeContract = sharedTypeContract;
}
private static Type[] KnownInterfaces
{
get
{ return CollectionDataContractCriticalHelper.KnownInterfaces; }
}
internal CollectionKind Kind
{
get
{ return _helper.Kind; }
}
public Type ItemType
{
get
{ return _helper.ItemType; }
set { _helper.ItemType = value; }
}
public DataContract ItemContract
{
get
{
return _itemContract ?? _helper.ItemContract;
}
set
{
_itemContract = value;
_helper.ItemContract = value;
}
}
internal DataContract SharedTypeContract
{
get
{ return _helper.SharedTypeContract; }
}
public string ItemName
{
get
{ return _helper.ItemName; }
set
{ _helper.ItemName = value; }
}
public XmlDictionaryString CollectionItemName
{
get { return _collectionItemName; }
set { _collectionItemName = value; }
}
public string KeyName
{
get
{ return _helper.KeyName; }
set
{ _helper.KeyName = value; }
}
public string ValueName
{
get
{ return _helper.ValueName; }
set
{ _helper.ValueName = value; }
}
internal bool IsDictionary
{
get { return KeyName != null; }
}
public XmlDictionaryString ChildElementNamespace
{
get
{
if (_childElementNamespace == null)
{
lock (this)
{
if (_childElementNamespace == null)
{
if (_helper.ChildElementNamespace == null && !IsDictionary)
{
XmlDictionaryString tempChildElementNamespace = ClassDataContract.GetChildNamespaceToDeclare(this, ItemType, new XmlDictionary());
Interlocked.MemoryBarrier();
_helper.ChildElementNamespace = tempChildElementNamespace;
}
_childElementNamespace = _helper.ChildElementNamespace;
}
}
}
return _childElementNamespace;
}
}
internal bool IsItemTypeNullable
{
get { return _helper.IsItemTypeNullable; }
set { _helper.IsItemTypeNullable = value; }
}
internal bool IsConstructorCheckRequired
{
get
{ return _helper.IsConstructorCheckRequired; }
set
{ _helper.IsConstructorCheckRequired = value; }
}
internal MethodInfo GetEnumeratorMethod
{
get
{ return _helper.GetEnumeratorMethod; }
}
internal MethodInfo AddMethod
{
get
{ return _helper.AddMethod; }
}
internal ConstructorInfo Constructor
{
get
{ return _helper.Constructor; }
}
public override DataContractDictionary KnownDataContracts
{
get
{ return _helper.KnownDataContracts; }
set
{ _helper.KnownDataContracts = value; }
}
internal string InvalidCollectionInSharedContractMessage
{
get
{ return _helper.InvalidCollectionInSharedContractMessage; }
}
#if uapaot
private XmlFormatCollectionWriterDelegate _xmlFormatWriterDelegate;
public XmlFormatCollectionWriterDelegate XmlFormatWriterDelegate
#else
internal XmlFormatCollectionWriterDelegate XmlFormatWriterDelegate
#endif
{
get
{
#if uapaot
if (DataContractSerializer.Option == SerializationOption.CodeGenOnly
|| (DataContractSerializer.Option == SerializationOption.ReflectionAsBackup && _xmlFormatWriterDelegate != null))
{
return _xmlFormatWriterDelegate;
}
#endif
if (_helper.XmlFormatWriterDelegate == null)
{
lock (this)
{
if (_helper.XmlFormatWriterDelegate == null)
{
XmlFormatCollectionWriterDelegate tempDelegate = new XmlFormatWriterGenerator().GenerateCollectionWriter(this);
Interlocked.MemoryBarrier();
_helper.XmlFormatWriterDelegate = tempDelegate;
}
}
}
return _helper.XmlFormatWriterDelegate;
}
set
{
#if uapaot
_xmlFormatWriterDelegate = value;
#endif
}
}
#if uapaot
private XmlFormatCollectionReaderDelegate _xmlFormatReaderDelegate;
public XmlFormatCollectionReaderDelegate XmlFormatReaderDelegate
#else
internal XmlFormatCollectionReaderDelegate XmlFormatReaderDelegate
#endif
{
get
{
#if uapaot
if (DataContractSerializer.Option == SerializationOption.CodeGenOnly
|| (DataContractSerializer.Option == SerializationOption.ReflectionAsBackup && _xmlFormatReaderDelegate != null))
{
return _xmlFormatReaderDelegate;
}
#endif
if (_helper.XmlFormatReaderDelegate == null)
{
lock (this)
{
if (_helper.XmlFormatReaderDelegate == null)
{
XmlFormatCollectionReaderDelegate tempDelegate = new XmlFormatReaderGenerator().GenerateCollectionReader(this);
Interlocked.MemoryBarrier();
_helper.XmlFormatReaderDelegate = tempDelegate;
}
}
}
return _helper.XmlFormatReaderDelegate;
}
set
{
#if uapaot
_xmlFormatReaderDelegate = value;
#endif
}
}
#if uapaot
private XmlFormatGetOnlyCollectionReaderDelegate _xmlFormatGetOnlyCollectionReaderDelegate;
public XmlFormatGetOnlyCollectionReaderDelegate XmlFormatGetOnlyCollectionReaderDelegate
#else
internal XmlFormatGetOnlyCollectionReaderDelegate XmlFormatGetOnlyCollectionReaderDelegate
#endif
{
get
{
#if uapaot
if (DataContractSerializer.Option == SerializationOption.CodeGenOnly
|| (DataContractSerializer.Option == SerializationOption.ReflectionAsBackup && _xmlFormatGetOnlyCollectionReaderDelegate != null))
{
return _xmlFormatGetOnlyCollectionReaderDelegate;
}
#endif
if (_helper.XmlFormatGetOnlyCollectionReaderDelegate == null)
{
lock (this)
{
if (_helper.XmlFormatGetOnlyCollectionReaderDelegate == null)
{
if (UnderlyingType.IsInterface && (Kind == CollectionKind.Enumerable || Kind == CollectionKind.Collection || Kind == CollectionKind.GenericEnumerable))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.GetOnlyCollectionMustHaveAddMethod, GetClrTypeFullName(UnderlyingType))));
}
Debug.Assert(AddMethod != null || Kind == CollectionKind.Array, "Add method cannot be null if the collection is being used as a get-only property");
XmlFormatGetOnlyCollectionReaderDelegate tempDelegate = new XmlFormatReaderGenerator().GenerateGetOnlyCollectionReader(this);
Interlocked.MemoryBarrier();
_helper.XmlFormatGetOnlyCollectionReaderDelegate = tempDelegate;
}
}
}
return _helper.XmlFormatGetOnlyCollectionReaderDelegate;
}
set
{
#if uapaot
_xmlFormatGetOnlyCollectionReaderDelegate = value;
#endif
}
}
internal void IncrementCollectionCount(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context)
{
_helper.IncrementCollectionCount(xmlWriter, obj, context);
}
internal IEnumerator GetEnumeratorForCollection(object obj, out Type enumeratorReturnType)
{
return _helper.GetEnumeratorForCollection(obj, out enumeratorReturnType);
}
private class CollectionDataContractCriticalHelper : DataContract.DataContractCriticalHelper
{
private static Type[] s_knownInterfaces;
private Type _itemType;
private bool _isItemTypeNullable;
private CollectionKind _kind;
private readonly MethodInfo _getEnumeratorMethod, _addMethod;
private readonly ConstructorInfo _constructor;
private DataContract _itemContract;
private DataContract _sharedTypeContract;
private DataContractDictionary _knownDataContracts;
private bool _isKnownTypeAttributeChecked;
private string _itemName;
private bool _itemNameSetExplicit;
private XmlDictionaryString _collectionItemName;
private string _keyName;
private string _valueName;
private XmlDictionaryString _childElementNamespace;
private string _invalidCollectionInSharedContractMessage;
private XmlFormatCollectionReaderDelegate _xmlFormatReaderDelegate;
private XmlFormatGetOnlyCollectionReaderDelegate _xmlFormatGetOnlyCollectionReaderDelegate;
private XmlFormatCollectionWriterDelegate _xmlFormatWriterDelegate;
private bool _isConstructorCheckRequired = false;
internal static Type[] KnownInterfaces
{
get
{
if (s_knownInterfaces == null)
{
// Listed in priority order
s_knownInterfaces = new Type[]
{
Globals.TypeOfIDictionaryGeneric,
Globals.TypeOfIDictionary,
Globals.TypeOfIListGeneric,
Globals.TypeOfICollectionGeneric,
Globals.TypeOfIList,
Globals.TypeOfIEnumerableGeneric,
Globals.TypeOfICollection,
Globals.TypeOfIEnumerable
};
}
return s_knownInterfaces;
}
}
private void Init(CollectionKind kind, Type itemType, CollectionDataContractAttribute collectionContractAttribute)
{
_kind = kind;
if (itemType != null)
{
_itemType = itemType;
_isItemTypeNullable = DataContract.IsTypeNullable(itemType);
bool isDictionary = (kind == CollectionKind.Dictionary || kind == CollectionKind.GenericDictionary);
string itemName = null, keyName = null, valueName = null;
if (collectionContractAttribute != null)
{
if (collectionContractAttribute.IsItemNameSetExplicitly)
{
if (collectionContractAttribute.ItemName == null || collectionContractAttribute.ItemName.Length == 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractItemName, DataContract.GetClrTypeFullName(UnderlyingType))));
itemName = DataContract.EncodeLocalName(collectionContractAttribute.ItemName);
_itemNameSetExplicit = true;
}
if (collectionContractAttribute.IsKeyNameSetExplicitly)
{
if (collectionContractAttribute.KeyName == null || collectionContractAttribute.KeyName.Length == 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractKeyName, DataContract.GetClrTypeFullName(UnderlyingType))));
if (!isDictionary)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractKeyNoDictionary, DataContract.GetClrTypeFullName(UnderlyingType), collectionContractAttribute.KeyName)));
keyName = DataContract.EncodeLocalName(collectionContractAttribute.KeyName);
}
if (collectionContractAttribute.IsValueNameSetExplicitly)
{
if (collectionContractAttribute.ValueName == null || collectionContractAttribute.ValueName.Length == 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractValueName, DataContract.GetClrTypeFullName(UnderlyingType))));
if (!isDictionary)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractValueNoDictionary, DataContract.GetClrTypeFullName(UnderlyingType), collectionContractAttribute.ValueName)));
valueName = DataContract.EncodeLocalName(collectionContractAttribute.ValueName);
}
}
XmlDictionary dictionary = isDictionary ? new XmlDictionary(5) : new XmlDictionary(3);
this.Name = dictionary.Add(this.StableName.Name);
this.Namespace = dictionary.Add(this.StableName.Namespace);
_itemName = itemName ?? DataContract.GetStableName(DataContract.UnwrapNullableType(itemType)).Name;
_collectionItemName = dictionary.Add(_itemName);
if (isDictionary)
{
_keyName = keyName ?? Globals.KeyLocalName;
_valueName = valueName ?? Globals.ValueLocalName;
}
}
if (collectionContractAttribute != null)
{
this.IsReference = collectionContractAttribute.IsReference;
}
}
internal CollectionDataContractCriticalHelper(CollectionKind kind)
: base()
{
Init(kind, null, null);
}
// array
internal CollectionDataContractCriticalHelper(Type type) : base(type)
{
if (type == Globals.TypeOfArray)
type = Globals.TypeOfObjectArray;
if (type.GetArrayRank() > 1)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.SupportForMultidimensionalArraysNotPresent)));
this.StableName = DataContract.GetStableName(type);
Init(CollectionKind.Array, type.GetElementType(), null);
}
// collection
internal CollectionDataContractCriticalHelper(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo addMethod, ConstructorInfo constructor) : base(type)
{
if (getEnumeratorMethod == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionMustHaveGetEnumeratorMethod, DataContract.GetClrTypeFullName(type))));
if (addMethod == null && !type.IsInterface)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionMustHaveAddMethod, DataContract.GetClrTypeFullName(type))));
if (itemType == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionMustHaveItemType, DataContract.GetClrTypeFullName(type))));
CollectionDataContractAttribute collectionContractAttribute;
this.StableName = DataContract.GetCollectionStableName(type, itemType, out collectionContractAttribute);
Init(kind, itemType, collectionContractAttribute);
_getEnumeratorMethod = getEnumeratorMethod;
_addMethod = addMethod;
_constructor = constructor;
}
// collection
internal CollectionDataContractCriticalHelper(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo addMethod, ConstructorInfo constructor, bool isConstructorCheckRequired)
: this(type, kind, itemType, getEnumeratorMethod, addMethod, constructor)
{
_isConstructorCheckRequired = isConstructorCheckRequired;
}
internal CollectionDataContractCriticalHelper(Type type, string invalidCollectionInSharedContractMessage) : base(type)
{
Init(CollectionKind.Collection, null /*itemType*/, null);
_invalidCollectionInSharedContractMessage = invalidCollectionInSharedContractMessage;
}
internal CollectionKind Kind
{
get { return _kind; }
}
internal Type ItemType
{
get { return _itemType; }
set { _itemType = value; }
}
internal DataContract ItemContract
{
get
{
if (_itemContract == null && UnderlyingType != null)
{
if (IsDictionary)
{
if (String.CompareOrdinal(KeyName, ValueName) == 0)
{
DataContract.ThrowInvalidDataContractException(
SR.Format(SR.DupKeyValueName, DataContract.GetClrTypeFullName(UnderlyingType), KeyName),
UnderlyingType);
}
_itemContract = ClassDataContract.CreateClassDataContractForKeyValue(ItemType, Namespace, new string[] { KeyName, ValueName });
// Ensure that DataContract gets added to the static DataContract cache for dictionary items
DataContract.GetDataContract(ItemType);
}
else
{
_itemContract = DataContract.GetDataContractFromGeneratedAssembly(ItemType);
if (_itemContract == null)
{
_itemContract = DataContract.GetDataContract(ItemType);
}
}
}
return _itemContract;
}
set
{
_itemContract = value;
}
}
internal DataContract SharedTypeContract
{
get { return _sharedTypeContract; }
set { _sharedTypeContract = value; }
}
internal string ItemName
{
get { return _itemName; }
set { _itemName = value; }
}
internal bool IsConstructorCheckRequired
{
get { return _isConstructorCheckRequired; }
set { _isConstructorCheckRequired = value; }
}
public XmlDictionaryString CollectionItemName
{
get { return _collectionItemName; }
}
internal string KeyName
{
get { return _keyName; }
set { _keyName = value; }
}
internal string ValueName
{
get { return _valueName; }
set { _valueName = value; }
}
internal bool IsDictionary => KeyName != null;
public XmlDictionaryString ChildElementNamespace
{
get { return _childElementNamespace; }
set { _childElementNamespace = value; }
}
internal bool IsItemTypeNullable
{
get { return _isItemTypeNullable; }
set { _isItemTypeNullable = value; }
}
internal MethodInfo GetEnumeratorMethod => _getEnumeratorMethod;
internal MethodInfo AddMethod => _addMethod;
internal ConstructorInfo Constructor => _constructor;
internal override DataContractDictionary KnownDataContracts
{
get
{
if (!_isKnownTypeAttributeChecked && UnderlyingType != null)
{
lock (this)
{
if (!_isKnownTypeAttributeChecked)
{
_knownDataContracts = DataContract.ImportKnownTypeAttributes(this.UnderlyingType);
Interlocked.MemoryBarrier();
_isKnownTypeAttributeChecked = true;
}
}
}
return _knownDataContracts;
}
set
{ _knownDataContracts = value; }
}
internal string InvalidCollectionInSharedContractMessage => _invalidCollectionInSharedContractMessage;
internal bool ItemNameSetExplicit => _itemNameSetExplicit;
internal XmlFormatCollectionWriterDelegate XmlFormatWriterDelegate
{
get { return _xmlFormatWriterDelegate; }
set { _xmlFormatWriterDelegate = value; }
}
internal XmlFormatCollectionReaderDelegate XmlFormatReaderDelegate
{
get { return _xmlFormatReaderDelegate; }
set { _xmlFormatReaderDelegate = value; }
}
internal XmlFormatGetOnlyCollectionReaderDelegate XmlFormatGetOnlyCollectionReaderDelegate
{
get { return _xmlFormatGetOnlyCollectionReaderDelegate; }
set { _xmlFormatGetOnlyCollectionReaderDelegate = value; }
}
private delegate void IncrementCollectionCountDelegate(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context);
private IncrementCollectionCountDelegate _incrementCollectionCountDelegate = null;
private static void DummyIncrementCollectionCount(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context) { }
internal void IncrementCollectionCount(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context)
{
if (_incrementCollectionCountDelegate == null)
{
switch (Kind)
{
case CollectionKind.Collection:
case CollectionKind.List:
case CollectionKind.Dictionary:
{
_incrementCollectionCountDelegate = (x, o, c) =>
{
context.IncrementCollectionCount(x, (ICollection)o);
};
}
break;
case CollectionKind.GenericCollection:
case CollectionKind.GenericList:
{
var buildIncrementCollectionCountDelegate = BuildIncrementCollectionCountDelegateMethod.MakeGenericMethod(ItemType);
_incrementCollectionCountDelegate = (IncrementCollectionCountDelegate)buildIncrementCollectionCountDelegate.Invoke(null, Array.Empty<object>());
}
break;
case CollectionKind.GenericDictionary:
{
var buildIncrementCollectionCountDelegate = BuildIncrementCollectionCountDelegateMethod.MakeGenericMethod(Globals.TypeOfKeyValuePair.MakeGenericType(ItemType.GetGenericArguments()));
_incrementCollectionCountDelegate = (IncrementCollectionCountDelegate)buildIncrementCollectionCountDelegate.Invoke(null, Array.Empty<object>());
}
break;
default:
// Do nothing.
_incrementCollectionCountDelegate = DummyIncrementCollectionCount;
break;
}
}
_incrementCollectionCountDelegate(xmlWriter, obj, context);
}
private static MethodInfo s_buildIncrementCollectionCountDelegateMethod;
private static MethodInfo BuildIncrementCollectionCountDelegateMethod
{
get
{
if (s_buildIncrementCollectionCountDelegateMethod == null)
{
s_buildIncrementCollectionCountDelegateMethod = typeof(CollectionDataContractCriticalHelper).GetMethod(nameof(BuildIncrementCollectionCountDelegate), Globals.ScanAllMembers);
}
return s_buildIncrementCollectionCountDelegateMethod;
}
}
private static IncrementCollectionCountDelegate BuildIncrementCollectionCountDelegate<T>()
{
return (xmlwriter, obj, context) =>
{
context.IncrementCollectionCountGeneric<T>(xmlwriter, (ICollection<T>)obj);
};
}
private delegate IEnumerator CreateGenericDictionaryEnumeratorDelegate(IEnumerator enumerator);
private CreateGenericDictionaryEnumeratorDelegate _createGenericDictionaryEnumeratorDelegate;
internal IEnumerator GetEnumeratorForCollection(object obj, out Type enumeratorReturnType)
{
IEnumerator enumerator = ((IEnumerable)obj).GetEnumerator();
if (Kind == CollectionKind.GenericDictionary)
{
if (_createGenericDictionaryEnumeratorDelegate == null)
{
var keyValueTypes = ItemType.GetGenericArguments();
var buildCreateGenericDictionaryEnumerator = BuildCreateGenericDictionaryEnumerato.MakeGenericMethod(keyValueTypes[0], keyValueTypes[1]);
_createGenericDictionaryEnumeratorDelegate = (CreateGenericDictionaryEnumeratorDelegate)buildCreateGenericDictionaryEnumerator.Invoke(null, Array.Empty<object>());
}
enumerator = _createGenericDictionaryEnumeratorDelegate(enumerator);
}
else if (Kind == CollectionKind.Dictionary)
{
enumerator = new DictionaryEnumerator(((IDictionary)obj).GetEnumerator());
}
enumeratorReturnType = EnumeratorReturnType;
return enumerator;
}
private Type _enumeratorReturnType;
public Type EnumeratorReturnType
{
get
{
_enumeratorReturnType = _enumeratorReturnType ?? GetCollectionEnumeratorReturnType();
return _enumeratorReturnType;
}
}
private Type GetCollectionEnumeratorReturnType()
{
Type enumeratorReturnType;
if (Kind == CollectionKind.GenericDictionary)
{
var keyValueTypes = ItemType.GetGenericArguments();
enumeratorReturnType = Globals.TypeOfKeyValue.MakeGenericType(keyValueTypes);
}
else if (Kind == CollectionKind.Dictionary)
{
enumeratorReturnType = Globals.TypeOfObject;
}
else if (Kind == CollectionKind.GenericCollection
|| Kind == CollectionKind.GenericList)
{
enumeratorReturnType = ItemType;
}
else
{
var enumeratorType = GetEnumeratorMethod.ReturnType;
if (enumeratorType.IsGenericType)
{
MethodInfo getCurrentMethod = enumeratorType.GetMethod(Globals.GetCurrentMethodName, BindingFlags.Instance | BindingFlags.Public, Array.Empty<Type>());
enumeratorReturnType = getCurrentMethod.ReturnType;
}
else
{
enumeratorReturnType = Globals.TypeOfObject;
}
}
return enumeratorReturnType;
}
private static MethodInfo s_buildCreateGenericDictionaryEnumerator;
private static MethodInfo BuildCreateGenericDictionaryEnumerato
{
get
{
if (s_buildCreateGenericDictionaryEnumerator == null)
{
s_buildCreateGenericDictionaryEnumerator = typeof(CollectionDataContractCriticalHelper).GetMethod(nameof(BuildCreateGenericDictionaryEnumerator), Globals.ScanAllMembers);
}
return s_buildCreateGenericDictionaryEnumerator;
}
}
private static CreateGenericDictionaryEnumeratorDelegate BuildCreateGenericDictionaryEnumerator<K, V>()
{
return (enumerator) =>
{
return new GenericDictionaryEnumerator<K, V>((IEnumerator<KeyValuePair<K, V>>)enumerator);
};
}
}
private DataContract GetSharedTypeContract(Type type)
{
if (type.IsDefined(Globals.TypeOfCollectionDataContractAttribute, false))
{
return this;
}
if (type.IsDefined(Globals.TypeOfDataContractAttribute, false))
{
return new ClassDataContract(type);
}
return null;
}
internal static bool IsCollectionInterface(Type type)
{
if (type.IsGenericType)
type = type.GetGenericTypeDefinition();
return ((IList<Type>)KnownInterfaces).Contains(type);
}
internal static bool IsCollection(Type type)
{
Type itemType;
return IsCollection(type, out itemType);
}
internal static bool IsCollection(Type type, out Type itemType)
{
return IsCollectionHelper(type, out itemType, true /*constructorRequired*/);
}
internal static bool IsCollection(Type type, bool constructorRequired)
{
Type itemType;
return IsCollectionHelper(type, out itemType, constructorRequired);
}
private static bool IsCollectionHelper(Type type, out Type itemType, bool constructorRequired)
{
if (type.IsArray && DataContract.GetBuiltInDataContract(type) == null)
{
itemType = type.GetElementType();
return true;
}
DataContract dataContract;
return IsCollectionOrTryCreate(type, false /*tryCreate*/, out dataContract, out itemType, constructorRequired);
}
internal static bool TryCreate(Type type, out DataContract dataContract)
{
Type itemType;
return IsCollectionOrTryCreate(type, true /*tryCreate*/, out dataContract, out itemType, true /*constructorRequired*/);
}
internal static bool CreateGetOnlyCollectionDataContract(Type type, out DataContract dataContract)
{
Type itemType;
if (type.IsArray)
{
dataContract = new CollectionDataContract(type);
return true;
}
else
{
return IsCollectionOrTryCreate(type, true /*tryCreate*/, out dataContract, out itemType, false /*constructorRequired*/);
}
}
internal static bool TryCreateGetOnlyCollectionDataContract(Type type, out DataContract dataContract)
{
dataContract = DataContract.GetDataContractFromGeneratedAssembly(type);
if (dataContract == null)
{
Type itemType;
if (type.IsArray)
{
dataContract = new CollectionDataContract(type);
return true;
}
else
{
return IsCollectionOrTryCreate(type, true /*tryCreate*/, out dataContract, out itemType, false /*constructorRequired*/);
}
}
else
{
if (dataContract is CollectionDataContract)
{
return true;
}
else
{
dataContract = null;
return false;
}
}
}
internal static MethodInfo GetTargetMethodWithName(string name, Type type, Type interfaceType)
{
Type t = type.GetInterfaces().Where(it => it.Equals(interfaceType)).FirstOrDefault();
return t?.GetMethod(name);
}
private static bool IsArraySegment(Type t)
{
return t.IsGenericType && (t.GetGenericTypeDefinition() == typeof(ArraySegment<>));
}
private static bool IsCollectionOrTryCreate(Type type, bool tryCreate, out DataContract dataContract, out Type itemType, bool constructorRequired)
{
dataContract = null;
itemType = Globals.TypeOfObject;
if (DataContract.GetBuiltInDataContract(type) != null)
{
return HandleIfInvalidCollection(type, tryCreate, false/*hasCollectionDataContract*/, false/*isBaseTypeCollection*/,
SR.CollectionTypeCannotBeBuiltIn, null, ref dataContract);
}
MethodInfo addMethod, getEnumeratorMethod;
bool hasCollectionDataContract = IsCollectionDataContract(type);
Type baseType = type.BaseType;
bool isBaseTypeCollection = (baseType != null && baseType != Globals.TypeOfObject
&& baseType != Globals.TypeOfValueType && baseType != Globals.TypeOfUri) ? IsCollection(baseType) : false;
if (type.IsDefined(Globals.TypeOfDataContractAttribute, false))
{
return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, isBaseTypeCollection,
SR.CollectionTypeCannotHaveDataContract, null, ref dataContract);
}
if (Globals.TypeOfIXmlSerializable.IsAssignableFrom(type) || IsArraySegment(type))
{
return false;
}
if (!Globals.TypeOfIEnumerable.IsAssignableFrom(type))
{
return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, isBaseTypeCollection,
SR.CollectionTypeIsNotIEnumerable, null, ref dataContract);
}
if (type.IsInterface)
{
Type interfaceTypeToCheck = type.IsGenericType ? type.GetGenericTypeDefinition() : type;
Type[] knownInterfaces = KnownInterfaces;
for (int i = 0; i < knownInterfaces.Length; i++)
{
if (knownInterfaces[i] == interfaceTypeToCheck)
{
addMethod = null;
if (type.IsGenericType)
{
Type[] genericArgs = type.GetGenericArguments();
if (interfaceTypeToCheck == Globals.TypeOfIDictionaryGeneric)
{
itemType = Globals.TypeOfKeyValue.MakeGenericType(genericArgs);
addMethod = type.GetMethod(Globals.AddMethodName);
getEnumeratorMethod = Globals.TypeOfIEnumerableGeneric.MakeGenericType(Globals.TypeOfKeyValuePair.MakeGenericType(genericArgs)).GetMethod(Globals.GetEnumeratorMethodName);
}
else
{
itemType = genericArgs[0];
// ICollection<T> has AddMethod
var collectionType = Globals.TypeOfICollectionGeneric.MakeGenericType(itemType);
if (collectionType.IsAssignableFrom(type))
{
addMethod = collectionType.GetMethod(Globals.AddMethodName);
}
getEnumeratorMethod = Globals.TypeOfIEnumerableGeneric.MakeGenericType(itemType).GetMethod(Globals.GetEnumeratorMethodName);
}
}
else
{
if (interfaceTypeToCheck == Globals.TypeOfIDictionary)
{
itemType = typeof(KeyValue<object, object>);
addMethod = type.GetMethod(Globals.AddMethodName);
}
else
{
itemType = Globals.TypeOfObject;
// IList has AddMethod
if (interfaceTypeToCheck == Globals.TypeOfIList)
{
addMethod = type.GetMethod(Globals.AddMethodName);
}
}
getEnumeratorMethod = Globals.TypeOfIEnumerable.GetMethod(Globals.GetEnumeratorMethodName);
}
if (tryCreate)
dataContract = new CollectionDataContract(type, (CollectionKind)(i + 1), itemType, getEnumeratorMethod, addMethod, null/*defaultCtor*/);
return true;
}
}
}
ConstructorInfo defaultCtor = null;
if (!type.IsValueType)
{
defaultCtor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, Array.Empty<Type>());
if (defaultCtor == null && constructorRequired)
{
return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, isBaseTypeCollection/*createContractWithException*/,
SR.CollectionTypeDoesNotHaveDefaultCtor, null, ref dataContract);
}
}
Type knownInterfaceType = null;
CollectionKind kind = CollectionKind.None;
bool multipleDefinitions = false;
Type[] interfaceTypes = type.GetInterfaces();
foreach (Type interfaceType in interfaceTypes)
{
Type interfaceTypeToCheck = interfaceType.IsGenericType ? interfaceType.GetGenericTypeDefinition() : interfaceType;
Type[] knownInterfaces = KnownInterfaces;
for (int i = 0; i < knownInterfaces.Length; i++)
{
if (knownInterfaces[i] == interfaceTypeToCheck)
{
CollectionKind currentKind = (CollectionKind)(i + 1);
if (kind == CollectionKind.None || currentKind < kind)
{
kind = currentKind;
knownInterfaceType = interfaceType;
multipleDefinitions = false;
}
else if ((kind & currentKind) == currentKind)
multipleDefinitions = true;
break;
}
}
}
if (kind == CollectionKind.None)
{
return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, isBaseTypeCollection,
SR.CollectionTypeIsNotIEnumerable, null, ref dataContract);
}
if (kind == CollectionKind.Enumerable || kind == CollectionKind.Collection || kind == CollectionKind.GenericEnumerable)
{
if (multipleDefinitions)
knownInterfaceType = Globals.TypeOfIEnumerable;
itemType = knownInterfaceType.IsGenericType ? knownInterfaceType.GetGenericArguments()[0] : Globals.TypeOfObject;
GetCollectionMethods(type, knownInterfaceType, new Type[] { itemType },
false /*addMethodOnInterface*/,
out getEnumeratorMethod, out addMethod);
if (addMethod == null)
{
return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, isBaseTypeCollection/*createContractWithException*/,
SR.CollectionTypeDoesNotHaveAddMethod, DataContract.GetClrTypeFullName(itemType), ref dataContract);
}
if (tryCreate)
dataContract = new CollectionDataContract(type, kind, itemType, getEnumeratorMethod, addMethod, defaultCtor, !constructorRequired);
}
else
{
if (multipleDefinitions)
{
return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, isBaseTypeCollection/*createContractWithException*/,
SR.CollectionTypeHasMultipleDefinitionsOfInterface, KnownInterfaces[(int)kind - 1].Name, ref dataContract);
}
Type[] addMethodTypeArray = null;
switch (kind)
{
case CollectionKind.GenericDictionary:
addMethodTypeArray = knownInterfaceType.GetGenericArguments();
bool isOpenGeneric = knownInterfaceType.IsGenericTypeDefinition
|| (addMethodTypeArray[0].IsGenericParameter && addMethodTypeArray[1].IsGenericParameter);
itemType = isOpenGeneric ? Globals.TypeOfKeyValue : Globals.TypeOfKeyValue.MakeGenericType(addMethodTypeArray);
break;
case CollectionKind.Dictionary:
addMethodTypeArray = new Type[] { Globals.TypeOfObject, Globals.TypeOfObject };
itemType = Globals.TypeOfKeyValue.MakeGenericType(addMethodTypeArray);
break;
case CollectionKind.GenericList:
case CollectionKind.GenericCollection:
addMethodTypeArray = knownInterfaceType.GetGenericArguments();
itemType = addMethodTypeArray[0];
break;
case CollectionKind.List:
itemType = Globals.TypeOfObject;
addMethodTypeArray = new Type[] { itemType };
break;
}
if (tryCreate)
{
GetCollectionMethods(type, knownInterfaceType, addMethodTypeArray,
true /*addMethodOnInterface*/,
out getEnumeratorMethod, out addMethod);
dataContract = DataContract.GetDataContractFromGeneratedAssembly(type);
if (dataContract == null)
{
dataContract = new CollectionDataContract(type, kind, itemType, getEnumeratorMethod, addMethod, defaultCtor, !constructorRequired);
}
}
}
return true;
}
internal static bool IsCollectionDataContract(Type type)
{
return type.IsDefined(Globals.TypeOfCollectionDataContractAttribute, false);
}
private static bool HandleIfInvalidCollection(Type type, bool tryCreate, bool hasCollectionDataContract, bool createContractWithException, string message, string param, ref DataContract dataContract)
{
if (hasCollectionDataContract)
{
if (tryCreate)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(GetInvalidCollectionMessage(message, SR.Format(SR.InvalidCollectionDataContract, DataContract.GetClrTypeFullName(type)), param)));
return true;
}
if (createContractWithException)
{
if (tryCreate)
dataContract = new CollectionDataContract(type, GetInvalidCollectionMessage(message, SR.Format(SR.InvalidCollectionType, DataContract.GetClrTypeFullName(type)), param));
return true;
}
return false;
}
private static string GetInvalidCollectionMessage(string message, string nestedMessage, string param)
{
return (param == null) ? SR.Format(message, nestedMessage) : SR.Format(message, nestedMessage, param);
}
private static void FindCollectionMethodsOnInterface(Type type, Type interfaceType, ref MethodInfo addMethod, ref MethodInfo getEnumeratorMethod)
{
Type t = type.GetInterfaces().Where(it => it.Equals(interfaceType)).FirstOrDefault();
if (t != null)
{
addMethod = t.GetMethod(Globals.AddMethodName) ?? addMethod;
getEnumeratorMethod = t.GetMethod(Globals.GetEnumeratorMethodName) ?? getEnumeratorMethod;
}
}
private static void GetCollectionMethods(Type type, Type interfaceType, Type[] addMethodTypeArray, bool addMethodOnInterface, out MethodInfo getEnumeratorMethod, out MethodInfo addMethod)
{
addMethod = getEnumeratorMethod = null;
if (addMethodOnInterface)
{
addMethod = type.GetMethod(Globals.AddMethodName, BindingFlags.Instance | BindingFlags.Public, addMethodTypeArray);
if (addMethod == null || addMethod.GetParameters()[0].ParameterType != addMethodTypeArray[0])
{
FindCollectionMethodsOnInterface(type, interfaceType, ref addMethod, ref getEnumeratorMethod);
if (addMethod == null)
{
Type[] parentInterfaceTypes = interfaceType.GetInterfaces();
foreach (Type parentInterfaceType in parentInterfaceTypes)
{
if (IsKnownInterface(parentInterfaceType))
{
FindCollectionMethodsOnInterface(type, parentInterfaceType, ref addMethod, ref getEnumeratorMethod);
if (addMethod == null)
{
break;
}
}
}
}
}
}
else
{
// GetMethod returns Add() method with parameter closest matching T in assignability/inheritance chain
addMethod = type.GetMethod(Globals.AddMethodName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, addMethodTypeArray);
if (addMethod == null)
return;
}
if (getEnumeratorMethod == null)
{
getEnumeratorMethod = type.GetMethod(Globals.GetEnumeratorMethodName, BindingFlags.Instance | BindingFlags.Public, Array.Empty<Type>());
if (getEnumeratorMethod == null || !Globals.TypeOfIEnumerator.IsAssignableFrom(getEnumeratorMethod.ReturnType))
{
Type ienumerableInterface = interfaceType.GetInterfaces().Where(t => t.FullName.StartsWith("System.Collections.Generic.IEnumerable")).FirstOrDefault();
if (ienumerableInterface == null)
ienumerableInterface = Globals.TypeOfIEnumerable;
getEnumeratorMethod = GetTargetMethodWithName(Globals.GetEnumeratorMethodName, type, ienumerableInterface);
}
}
}
private static bool IsKnownInterface(Type type)
{
Type typeToCheck = type.IsGenericType ? type.GetGenericTypeDefinition() : type;
foreach (Type knownInterfaceType in KnownInterfaces)
{
if (typeToCheck == knownInterfaceType)
{
return true;
}
}
return false;
}
internal override DataContract GetValidContract(SerializationMode mode)
{
if (InvalidCollectionInSharedContractMessage != null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(InvalidCollectionInSharedContractMessage));
return this;
}
internal override DataContract GetValidContract()
{
if (this.IsConstructorCheckRequired)
{
CheckConstructor();
}
return this;
}
private void CheckConstructor()
{
if (this.Constructor == null)
{
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionTypeDoesNotHaveDefaultCtor, DataContract.GetClrTypeFullName(this.UnderlyingType))));
}
else
{
this.IsConstructorCheckRequired = false;
}
}
internal override bool IsValidContract(SerializationMode mode)
{
return (InvalidCollectionInSharedContractMessage == null);
}
/// <SecurityNote>
/// Review - calculates whether this collection requires MemberAccessPermission for deserialization.
/// since this information is used to determine whether to give the generated code access
/// permissions to private members, any changes to the logic should be reviewed.
/// </SecurityNote>
internal bool RequiresMemberAccessForRead(SecurityException securityException)
{
if (!IsTypeVisible(UnderlyingType))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustCollectionContractTypeNotPublic,
DataContract.GetClrTypeFullName(UnderlyingType)),
securityException));
}
return true;
}
if (ItemType != null && !IsTypeVisible(ItemType))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustCollectionContractTypeNotPublic,
DataContract.GetClrTypeFullName(ItemType)),
securityException));
}
return true;
}
if (ConstructorRequiresMemberAccess(Constructor))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustCollectionContractNoPublicConstructor,
DataContract.GetClrTypeFullName(UnderlyingType)),
securityException));
}
return true;
}
if (MethodRequiresMemberAccess(this.AddMethod))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustCollectionContractAddMethodNotPublic,
DataContract.GetClrTypeFullName(UnderlyingType),
this.AddMethod.Name),
securityException));
}
return true;
}
return false;
}
/// <SecurityNote>
/// Review - calculates whether this collection requires MemberAccessPermission for serialization.
/// since this information is used to determine whether to give the generated code access
/// permissions to private members, any changes to the logic should be reviewed.
/// </SecurityNote>
internal bool RequiresMemberAccessForWrite(SecurityException securityException)
{
if (!IsTypeVisible(UnderlyingType))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustCollectionContractTypeNotPublic,
DataContract.GetClrTypeFullName(UnderlyingType)),
securityException));
}
return true;
}
if (ItemType != null && !IsTypeVisible(ItemType))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustCollectionContractTypeNotPublic,
DataContract.GetClrTypeFullName(ItemType)),
securityException));
}
return true;
}
return false;
}
public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context)
{
// IsGetOnlyCollection value has already been used to create current collectiondatacontract, value can now be reset.
context.IsGetOnlyCollection = false;
XmlFormatWriterDelegate(xmlWriter, obj, context, this);
}
public override object ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context)
{
xmlReader.Read();
object o = null;
if (context.IsGetOnlyCollection)
{
// IsGetOnlyCollection value has already been used to create current collectiondatacontract, value can now be reset.
context.IsGetOnlyCollection = false;
#if uapaot
if (XmlFormatGetOnlyCollectionReaderDelegate == null)
{
throw new InvalidDataContractException(SR.Format(SR.SerializationCodeIsMissingForType, UnderlyingType.ToString()));
}
#endif
XmlFormatGetOnlyCollectionReaderDelegate(xmlReader, context, CollectionItemName, Namespace, this);
}
else
{
o = XmlFormatReaderDelegate(xmlReader, context, CollectionItemName, Namespace, this);
}
xmlReader.ReadEndElement();
return o;
}
internal class DictionaryEnumerator : IEnumerator<KeyValue<object, object>>
{
private IDictionaryEnumerator _enumerator;
public DictionaryEnumerator(IDictionaryEnumerator enumerator)
{
_enumerator = enumerator;
}
public void Dispose()
{
GC.SuppressFinalize(this);
}
public bool MoveNext()
{
return _enumerator.MoveNext();
}
public KeyValue<object, object> Current
{
get { return new KeyValue<object, object>(_enumerator.Key, _enumerator.Value); }
}
object System.Collections.IEnumerator.Current
{
get { return Current; }
}
public void Reset()
{
_enumerator.Reset();
}
}
internal class GenericDictionaryEnumerator<K, V> : IEnumerator<KeyValue<K, V>>
{
private IEnumerator<KeyValuePair<K, V>> _enumerator;
public GenericDictionaryEnumerator(IEnumerator<KeyValuePair<K, V>> enumerator)
{
_enumerator = enumerator;
}
public void Dispose()
{
GC.SuppressFinalize(this);
}
public bool MoveNext()
{
return _enumerator.MoveNext();
}
public KeyValue<K, V> Current
{
get
{
KeyValuePair<K, V> current = _enumerator.Current;
return new KeyValue<K, V>(current.Key, current.Value);
}
}
object System.Collections.IEnumerator.Current
{
get { return Current; }
}
public void Reset()
{
_enumerator.Reset();
}
}
}
}
| |
using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Threading;
using Caliburn.Micro;
using ICSharpCode.AvalonEdit.Document;
using Cocoa.Document.Controls;
using Cocoa.Document.EditorBehaviours;
using Cocoa.Document.Search;
using Cocoa.Document.SpellCheck;
using Cocoa.Events;
using Cocoa.Infrastructure.DialogService;
using Cocoa.Plugins;
using Cocoa.Settings;
using Cocoa.Settings.Models;
using Ookii.Dialogs.Wpf;
using Cocoa.Infrastructure;
using Action = System.Action;
namespace Cocoa.Document
{
public class DocumentViewModel : Screen, IHandle<SettingsChangedEvent>
{
static readonly ILog Log = LogManager.GetLog(typeof(DocumentViewModel));
const double ZoomDelta = 0.1;
double zoomLevel = 1;
readonly IDialogService dialogService;
readonly IWindowManager windowManager;
readonly ISettingsProvider settingsProvider;
readonly IDocumentParser documentParser;
readonly IShell shell;
readonly TimeSpan delay = TimeSpan.FromSeconds(0.5);
readonly DispatcherTimer timer;
readonly Regex wordCountRegex = new Regex(@"[\S]+", RegexOptions.Compiled);
public DocumentViewModel(
IDialogService dialogService,
IWindowManager windowManager,
ISettingsProvider settingsProvider,
IDocumentParser documentParser,
ISpellCheckProvider spellCheckProvider,
ISearchProvider searchProvider,
IShell shell,
IPairedCharsHighlightProvider pairedCharsHighlightProvider)
{
SpellCheckProvider = spellCheckProvider;
PairedCharsHighlightProvider = pairedCharsHighlightProvider;
this.dialogService = dialogService;
this.windowManager = windowManager;
this.settingsProvider = settingsProvider;
this.documentParser = documentParser;
this.shell = shell;
SearchProvider = searchProvider;
FontSize = GetFontSize();
IsColorsInverted = GetIsColorsInverted();
IndentType = settingsProvider.GetSettings<CocoaSettings>().IndentType;
Original = "";
Document = new TextDocument();
timer = new DispatcherTimer();
timer.Tick += TimerTick;
timer.Interval = delay;
}
private void UpdateWordCount()
{
WordCount = wordCountRegex.Matches(Document.Text).Count;
}
private void TimerTick(object sender, EventArgs e)
{
if (MarkpadDocument == null)
return;
timer.Stop();
Task.Factory.StartNew(text => documentParser.Parse(text.ToString()), Document.Text)
.ContinueWith(s =>
{
if (s.IsFaulted)
{
Log.Error(s.Exception);
return;
}
var result = MarkpadDocument.ConvertToAbsolutePaths(s.Result);
Render = result;
UpdateWordCount();
}, TaskScheduler.FromCurrentSynchronizationContext());
}
public void Open(IMarkpadDocument document, bool isNew = false)
{
MarkpadDocument = document;
Document.Text = document.MarkdownContent ?? string.Empty;
Original = isNew ? null : document.MarkdownContent;
Update();
}
public void Update()
{
timer.Stop();
timer.Start();
NotifyOfPropertyChange(() => HasChanges);
NotifyOfPropertyChange(() => DisplayName);
}
public Task<bool> SaveAs()
{
MarkpadDocument.MarkdownContent = Document.Text;
return MarkpadDocument
.SaveAs()
.ContinueWith(t=>
{
if (t.IsFaulted || t.IsCanceled)
return false;
MarkpadDocument = t.Result;
Original = MarkpadDocument.MarkdownContent;
Document.Text = MarkpadDocument.MarkdownContent;
return true;
}, TaskScheduler.FromCurrentSynchronizationContext());
}
public Task Publish()
{
MarkpadDocument.MarkdownContent = Document.Text;
return MarkpadDocument.Publish()
.ContinueWith(t =>
{
if (t.Result != null)
{
MarkpadDocument = t.Result;
Original = MarkpadDocument.MarkdownContent;
Document.Text = MarkpadDocument.MarkdownContent;
}
}, TaskScheduler.FromCurrentSynchronizationContext());
}
public Task<bool> Save()
{
if (Document.Text == Original)
return Task.FromResult(false);
MarkpadDocument.MarkdownContent = Document.Text;
//TODO async all the things
var dispatcher = Dispatcher.CurrentDispatcher;
return MarkpadDocument.Save()
.ContinueWith(t =>
{
if (t.IsCanceled)
return false;
if (t.IsFaulted)
{
var saveResult = (bool?) dispatcher.Invoke(new Action(() =>
{
dialogService.ShowConfirmation(
"Cocoa", "Cannot save file",
"You may not have permission to save this file to the selected location, or the location may not be currently available. Error: " + t.Exception.InnerException.Message,
new ButtonExtras(ButtonType.Yes, "Select a different location", "Save this file to a different location."),
new ButtonExtras(ButtonType.No, "Cancel", ""));
}),null);
return saveResult == true && SaveAs().Result;
}
dispatcher.Invoke(new Action(() =>
{
MarkpadDocument = t.Result;
Original = MarkpadDocument.MarkdownContent;
Document.Text = MarkpadDocument.MarkdownContent;
}));
return true;
});
}
public TextDocument Document { get; private set; }
public string MarkdownContent { get { return Document.Text; } }
public string Original { get; set; }
public string Render { get; private set; }
public bool HasChanges
{
get { return Original != Document.Text; }
}
new public string DisplayName
{
get { return MarkpadDocument == null ? string.Empty : MarkpadDocument.Title; }
}
public IMarkpadDocument MarkpadDocument { get; private set; }
public bool FloatingToolbarEnabled
{
get
{
var settings = settingsProvider.GetSettings<CocoaSettings>();
return settings.FloatingToolBarEnabled;
}
}
public override void CanClose(Action<bool> callback)
{
if (!HasChanges)
{
CheckAndCloseView();
callback(true);
return;
}
var saveResult = dialogService.ShowConfirmationWithCancel("Cocoa", "Save file", "Do you want to save the changes to '" + MarkpadDocument.Title + "'?",
new ButtonExtras(ButtonType.Yes, "Save",
string.IsNullOrEmpty(MarkpadDocument.SaveLocation) ? "The file has not been saved yet" : "The file will be saved to " + Path.GetFullPath(MarkpadDocument.SaveLocation)),
new ButtonExtras(ButtonType.No, "Discard", "Discard the changes to this file"),
new ButtonExtras(ButtonType.Cancel, "Cancel", "Cancel closing the application")
);
if (saveResult == true)
{
var finishedWork = shell.DoingWork(string.Format("Saving {0}", MarkpadDocument.Title));
Save()
.ContinueWith(t =>
{
finishedWork.Dispose();
if (t.IsCompleted)
CheckAndCloseView();
else
callback(false);
}, TaskScheduler.FromCurrentSynchronizationContext());
return;
}
if (saveResult == false)
{
CheckAndCloseView();
callback(true);
return;
}
callback(false);
}
private void CheckAndCloseView()
{
if (SpellCheckProvider != null)
SpellCheckProvider.Disconnect();
if (PairedCharsHighlightProvider != null)
PairedCharsHighlightProvider.Disconnect();
var disposableSiteContext = MarkpadDocument.SiteContext as IDisposable;
if (disposableSiteContext != null)
disposableSiteContext.Dispose();
}
public bool DistractionFree { get; set; }
public int WordCount { get; private set; }
public double FontSize { get; private set; }
public bool IsColorsInverted { get; set; }
public double ZoomLevel
{
get { return zoomLevel; }
set
{
zoomLevel = value;
FontSize = GetFontSize()*value;
}
}
public double MaxZoom
{
get { return 2; }
}
public double MinZoom
{
get { return 0.5; }
}
public IndentType IndentType { get; private set; }
/// <summary>
/// Get the font size that was set in the settings.
/// </summary>
/// <returns>Font size.</returns>
private int GetFontSize()
{
return Constants.FONT_SIZE_ENUM_ADJUSTMENT + (int)settingsProvider.GetSettings<CocoaSettings>().FontSize;
}
private bool GetIsColorsInverted()
{
return settingsProvider.GetSettings<CocoaSettings>().IsEditorColorsInverted;
}
public void ZoomIn()
{
AdjustZoom(ZoomDelta);
}
public void ZoomOut()
{
AdjustZoom(-ZoomDelta);
}
private void AdjustZoom(double delta)
{
var newZoom = ZoomLevel + delta;
if (newZoom < MinZoom)
{
//Don't cause a change if we don't have to
if (Math.Abs(ZoomLevel - MinZoom) < 0.1) return;
newZoom = MinZoom;
}
if (newZoom > MaxZoom)
{
//Don't cause a change if we don't have to
if (Math.Abs(ZoomLevel - MaxZoom) < 0.1)return;
newZoom = MaxZoom;
}
ZoomLevel = newZoom;
}
public void ZoomReset()
{
ZoomLevel = 1;
}
public CocoaHyperlink GetHyperlink(CocoaHyperlink hyperlink)
{
var viewModel = new HyperlinkEditorViewModel(hyperlink.Text, hyperlink.Url)
{
IsUrlFocussed = !String.IsNullOrWhiteSpace(hyperlink.Text)
};
windowManager.ShowDialog(viewModel);
if (!viewModel.WasCancelled)
{
hyperlink.Set(viewModel.Text, viewModel.Url);
return hyperlink;
}
return null;
}
public void RefreshFont()
{
FontSize = GetFontSize()*ZoomLevel;
}
public void RefreshColors()
{
IsColorsInverted = GetIsColorsInverted();
}
public void Handle(SettingsChangedEvent message)
{
IndentType = settingsProvider.GetSettings<CocoaSettings>().IndentType;
}
public DocumentView View
{
get { return (DocumentView)GetView(); }
}
public ISpellCheckProvider SpellCheckProvider { get; private set; }
public IPairedCharsHighlightProvider PairedCharsHighlightProvider { get; private set; }
protected override void OnViewLoaded(object view)
{
SpellCheckProvider.Initialise((DocumentView)view);
PairedCharsHighlightProvider.Initialise((DocumentView)view);
SearchProvider.Initialise((DocumentView)view);
base.OnViewLoaded(view);
NotifyOfPropertyChange(()=>View);
}
protected override void OnDeactivate(bool close)
{
if (View != null)
View.siteView.UndoRename();
}
public ISearchProvider SearchProvider { get; private set; }
public bool Overtype { get; set; }
}
}
| |
// Copyright 2004-2009 Castle Project - http://www.castleproject.org/
//
// 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 AspectSharp.Lang.AST.Visitors
{
using System;
using System.Xml;
using System.Collections;
/// <summary>
/// Summary description for PrintTreeVisitor.
/// </summary>
public class XmlTreeVisitor : DepthFirstVisitor
{
private XmlDocument _document;
private Stack _nodes = new Stack();
public XmlTreeVisitor()
{
_document = new XmlDocument();
}
private void Push( XmlNode node )
{
if (Current != null)
{
Current.AppendChild( node );
}
else
{
_document.AppendChild(node);
}
_nodes.Push(node);
}
private void Pop()
{
XmlNode node = (XmlNode) _nodes.Pop();
}
private XmlNode Current
{
get { return _nodes.Count != 0 ? _nodes.Peek() as XmlNode : _document.DocumentElement; }
}
public XmlDocument Document
{
get { return _document; }
}
public override void OnEngineConfiguration(EngineConfiguration conf)
{
Push( Document.CreateNode(XmlNodeType.Element, "configuration", null) );
base.OnEngineConfiguration (conf);
Pop();
}
public override void OnGlobalInterceptorDeclaration(NodeCollectionBase dict)
{
if (dict.Count == 0) return;
Push( Document.CreateNode(XmlNodeType.Element, "interceptors", null) );
base.OnGlobalInterceptorDeclaration(dict);
Pop();
}
public override void OnGlobalMixinDeclaration(NodeCollectionBase dict)
{
if (dict.Count == 0) return;
Push( Document.CreateNode(XmlNodeType.Element, "mixins", null) );
base.OnGlobalMixinDeclaration(dict);
Pop();
}
public override void OnAspectDefinition(AspectDefinition aspect)
{
Push( Document.CreateNode(XmlNodeType.Element, "aspect", null) );
XmlAttribute att = Document.CreateAttribute("name");
att.Value = aspect.Name;
Current.Attributes.Append( att );
Push( Document.CreateNode(XmlNodeType.Element, "for", null) );
SerializeTargetType( aspect.TargetType );
Pop();
base.OnAspectDefinition (aspect);
Pop();
}
public override void OnImportDirective(ImportDirective import)
{
Push( Document.CreateNode(XmlNodeType.Element, "import", null) );
XmlAttribute att = Document.CreateAttribute("namespace");
att.Value = import.Namespace;
Current.Attributes.Append( att );
SerializeAssemblyReference( import.AssemblyReference );
Pop();
}
public override void OnInterceptorDefinition(InterceptorDefinition interceptor)
{
Push( Document.CreateNode(XmlNodeType.Element, "interceptor", null) );
SerializeTypeReference(interceptor.TypeReference);
Pop();
}
public override void OnMixinDefinition(MixinDefinition mixin)
{
Push( Document.CreateNode(XmlNodeType.Element, "mixin", null) );
SerializeTypeReference(mixin.TypeReference);
Pop();
}
public override void OnInterceptorEntryDefinition(InterceptorEntryDefinition interceptor)
{
Push( Document.CreateNode(XmlNodeType.Element, "interceptor", null) );
XmlAttribute att = Document.CreateAttribute("key");
att.Value = interceptor.Key;
Current.Attributes.Append( att );
SerializeTypeReference(interceptor.TypeReference);
Pop();
}
public override void OnMixinEntryDefinition(MixinEntryDefinition mixin)
{
Push( Document.CreateNode(XmlNodeType.Element, "mixin", null) );
XmlAttribute att = Document.CreateAttribute("key");
att.Value = mixin.Key;
Current.Attributes.Append( att );
SerializeTypeReference(mixin.TypeReference);
Pop();
}
public override void OnPointCutDefinition(PointCutDefinition pointcut)
{
Push( Document.CreateNode(XmlNodeType.Element, "pointcut", null) );
XmlAttribute att = Document.CreateAttribute("symbol");
att.Value = pointcut.Flags.ToString();
Current.Attributes.Append( att );
Push( Document.CreateNode(XmlNodeType.Element, "signature", null) );
Current.InnerText = pointcut.Method.ToString();
Pop();
base.OnPointCutDefinition (pointcut);
Pop();
}
private void SerializeTargetType( TargetTypeDefinition def )
{
Push( Document.CreateNode(XmlNodeType.Element, "singletype", null) );
SerializeTypeReference( def.SingleType );
Pop();
}
private void SerializeTypeReference(TypeReference def)
{
XmlAttribute att = Document.CreateAttribute("type");
if (def.TargetType == TargetTypeEnum.Link)
{
att.Value = def.LinkRef;
}
else
{
att.Value = def.TypeName;
}
Current.Attributes.Append( att );
att = Document.CreateAttribute("refTypeEnum");
att.Value = def.TargetType.ToString();
Current.Attributes.Append( att );
SerializeAssemblyReference(def.AssemblyReference);
}
private void SerializeAssemblyReference(AssemblyReference def)
{
if (def == null) return;
XmlAttribute att = Document.CreateAttribute("assembly");
att.Value = def.AssemblyName;
Current.Attributes.Append( att );
}
}
}
| |
// 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.Dynamic.Utils;
using System.Reflection;
using System.Reflection.Emit;
using static System.Linq.Expressions.CachedReflectionInfo;
namespace System.Linq.Expressions.Compiler
{
internal static class ILGen
{
internal static void Emit(this ILGenerator il, OpCode opcode, MethodBase methodBase)
{
Debug.Assert(methodBase is MethodInfo || methodBase is ConstructorInfo);
var ctor = methodBase as ConstructorInfo;
if ((object)ctor != null)
{
il.Emit(opcode, ctor);
}
else
{
il.Emit(opcode, (MethodInfo)methodBase);
}
}
#region Instruction helpers
internal static void EmitLoadArg(this ILGenerator il, int index)
{
Debug.Assert(index >= 0);
switch (index)
{
case 0:
il.Emit(OpCodes.Ldarg_0);
break;
case 1:
il.Emit(OpCodes.Ldarg_1);
break;
case 2:
il.Emit(OpCodes.Ldarg_2);
break;
case 3:
il.Emit(OpCodes.Ldarg_3);
break;
default:
if (index <= byte.MaxValue)
{
il.Emit(OpCodes.Ldarg_S, (byte)index);
}
else
{
il.Emit(OpCodes.Ldarg, index);
}
break;
}
}
internal static void EmitLoadArgAddress(this ILGenerator il, int index)
{
Debug.Assert(index >= 0);
if (index <= byte.MaxValue)
{
il.Emit(OpCodes.Ldarga_S, (byte)index);
}
else
{
il.Emit(OpCodes.Ldarga, index);
}
}
internal static void EmitStoreArg(this ILGenerator il, int index)
{
Debug.Assert(index >= 0);
if (index <= byte.MaxValue)
{
il.Emit(OpCodes.Starg_S, (byte)index);
}
else
{
il.Emit(OpCodes.Starg, index);
}
}
/// <summary>
/// Emits a Ldind* instruction for the appropriate type
/// </summary>
internal static void EmitLoadValueIndirect(this ILGenerator il, Type type)
{
Debug.Assert(type != null);
switch (type.GetTypeCode())
{
case TypeCode.Byte:
il.Emit(OpCodes.Ldind_I1);
break;
case TypeCode.Boolean:
case TypeCode.SByte:
il.Emit(OpCodes.Ldind_U1);
break;
case TypeCode.Int16:
il.Emit(OpCodes.Ldind_I2);
break;
case TypeCode.Char:
case TypeCode.UInt16:
il.Emit(OpCodes.Ldind_U2);
break;
case TypeCode.Int32:
il.Emit(OpCodes.Ldind_I4);
break;
case TypeCode.UInt32:
il.Emit(OpCodes.Ldind_U4);
break;
case TypeCode.Int64:
case TypeCode.UInt64:
il.Emit(OpCodes.Ldind_I8);
break;
case TypeCode.Single:
il.Emit(OpCodes.Ldind_R4);
break;
case TypeCode.Double:
il.Emit(OpCodes.Ldind_R8);
break;
default:
if (type.IsValueType)
{
il.Emit(OpCodes.Ldobj, type);
}
else
{
il.Emit(OpCodes.Ldind_Ref);
}
break;
}
}
/// <summary>
/// Emits a Stind* instruction for the appropriate type.
/// </summary>
internal static void EmitStoreValueIndirect(this ILGenerator il, Type type)
{
Debug.Assert(type != null);
switch (type.GetTypeCode())
{
case TypeCode.Boolean:
case TypeCode.Byte:
case TypeCode.SByte:
il.Emit(OpCodes.Stind_I1);
break;
case TypeCode.Char:
case TypeCode.Int16:
case TypeCode.UInt16:
il.Emit(OpCodes.Stind_I2);
break;
case TypeCode.Int32:
case TypeCode.UInt32:
il.Emit(OpCodes.Stind_I4);
break;
case TypeCode.Int64:
case TypeCode.UInt64:
il.Emit(OpCodes.Stind_I8);
break;
case TypeCode.Single:
il.Emit(OpCodes.Stind_R4);
break;
case TypeCode.Double:
il.Emit(OpCodes.Stind_R8);
break;
default:
if (type.IsValueType)
{
il.Emit(OpCodes.Stobj, type);
}
else
{
il.Emit(OpCodes.Stind_Ref);
}
break;
}
}
// Emits the Ldelem* instruction for the appropriate type
internal static void EmitLoadElement(this ILGenerator il, Type type)
{
Debug.Assert(type != null);
if (!type.IsValueType)
{
il.Emit(OpCodes.Ldelem_Ref);
}
else
{
switch (type.GetTypeCode())
{
case TypeCode.Boolean:
case TypeCode.SByte:
il.Emit(OpCodes.Ldelem_I1);
break;
case TypeCode.Byte:
il.Emit(OpCodes.Ldelem_U1);
break;
case TypeCode.Int16:
il.Emit(OpCodes.Ldelem_I2);
break;
case TypeCode.Char:
case TypeCode.UInt16:
il.Emit(OpCodes.Ldelem_U2);
break;
case TypeCode.Int32:
il.Emit(OpCodes.Ldelem_I4);
break;
case TypeCode.UInt32:
il.Emit(OpCodes.Ldelem_U4);
break;
case TypeCode.Int64:
case TypeCode.UInt64:
il.Emit(OpCodes.Ldelem_I8);
break;
case TypeCode.Single:
il.Emit(OpCodes.Ldelem_R4);
break;
case TypeCode.Double:
il.Emit(OpCodes.Ldelem_R8);
break;
default:
il.Emit(OpCodes.Ldelem, type);
break;
}
}
}
/// <summary>
/// Emits a Stelem* instruction for the appropriate type.
/// </summary>
internal static void EmitStoreElement(this ILGenerator il, Type type)
{
Debug.Assert(type != null);
switch (type.GetTypeCode())
{
case TypeCode.Boolean:
case TypeCode.SByte:
case TypeCode.Byte:
il.Emit(OpCodes.Stelem_I1);
break;
case TypeCode.Char:
case TypeCode.Int16:
case TypeCode.UInt16:
il.Emit(OpCodes.Stelem_I2);
break;
case TypeCode.Int32:
case TypeCode.UInt32:
il.Emit(OpCodes.Stelem_I4);
break;
case TypeCode.Int64:
case TypeCode.UInt64:
il.Emit(OpCodes.Stelem_I8);
break;
case TypeCode.Single:
il.Emit(OpCodes.Stelem_R4);
break;
case TypeCode.Double:
il.Emit(OpCodes.Stelem_R8);
break;
default:
if (type.IsValueType)
{
il.Emit(OpCodes.Stelem, type);
}
else
{
il.Emit(OpCodes.Stelem_Ref);
}
break;
}
}
internal static void EmitType(this ILGenerator il, Type type)
{
Debug.Assert(type != null);
il.Emit(OpCodes.Ldtoken, type);
il.Emit(OpCodes.Call, Type_GetTypeFromHandle);
}
#endregion
#region Fields, properties and methods
internal static void EmitFieldAddress(this ILGenerator il, FieldInfo fi)
{
Debug.Assert(fi != null);
il.Emit(fi.IsStatic ? OpCodes.Ldsflda : OpCodes.Ldflda, fi);
}
internal static void EmitFieldGet(this ILGenerator il, FieldInfo fi)
{
Debug.Assert(fi != null);
il.Emit(fi.IsStatic ? OpCodes.Ldsfld : OpCodes.Ldfld, fi);
}
internal static void EmitFieldSet(this ILGenerator il, FieldInfo fi)
{
Debug.Assert(fi != null);
il.Emit(fi.IsStatic ? OpCodes.Stsfld : OpCodes.Stfld, fi);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
internal static void EmitNew(this ILGenerator il, ConstructorInfo ci)
{
Debug.Assert(ci != null);
Debug.Assert(!ci.DeclaringType.ContainsGenericParameters);
il.Emit(OpCodes.Newobj, ci);
}
#endregion
#region Constants
internal static void EmitNull(this ILGenerator il)
{
il.Emit(OpCodes.Ldnull);
}
internal static void EmitString(this ILGenerator il, string value)
{
Debug.Assert(value != null);
il.Emit(OpCodes.Ldstr, value);
}
internal static void EmitPrimitive(this ILGenerator il, bool value)
{
il.Emit(value ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0);
}
internal static void EmitPrimitive(this ILGenerator il, int value)
{
OpCode c;
switch (value)
{
case -1:
c = OpCodes.Ldc_I4_M1;
break;
case 0:
c = OpCodes.Ldc_I4_0;
break;
case 1:
c = OpCodes.Ldc_I4_1;
break;
case 2:
c = OpCodes.Ldc_I4_2;
break;
case 3:
c = OpCodes.Ldc_I4_3;
break;
case 4:
c = OpCodes.Ldc_I4_4;
break;
case 5:
c = OpCodes.Ldc_I4_5;
break;
case 6:
c = OpCodes.Ldc_I4_6;
break;
case 7:
c = OpCodes.Ldc_I4_7;
break;
case 8:
c = OpCodes.Ldc_I4_8;
break;
default:
if (value >= sbyte.MinValue && value <= sbyte.MaxValue)
{
il.Emit(OpCodes.Ldc_I4_S, (sbyte)value);
}
else
{
il.Emit(OpCodes.Ldc_I4, value);
}
return;
}
il.Emit(c);
}
private static void EmitPrimitive(this ILGenerator il, uint value)
{
il.EmitPrimitive(unchecked((int)value));
}
private static void EmitPrimitive(this ILGenerator il, long value)
{
if (int.MinValue <= value & value <= uint.MaxValue)
{
il.EmitPrimitive(unchecked((int)value));
// While often not of consequence depending on what follows, there are cases where this
// casting matters. Values [0, int.MaxValue] can use either safely, but negative values
// must use conv.i8 and those (int.MaxValue, uint.MaxValue] must use conv.u8, or else
// the higher bits will be wrong.
il.Emit(value > 0 ? OpCodes.Conv_U8 : OpCodes.Conv_I8);
}
else
{
il.Emit(OpCodes.Ldc_I8, value);
}
}
private static void EmitPrimitive(this ILGenerator il, ulong value)
{
il.EmitPrimitive(unchecked((long)value));
}
private static void EmitPrimitive(this ILGenerator il, double value)
{
il.Emit(OpCodes.Ldc_R8, value);
}
private static void EmitPrimitive(this ILGenerator il, float value)
{
il.Emit(OpCodes.Ldc_R4, value);
}
// matches TryEmitConstant
internal static bool CanEmitConstant(object value, Type type)
{
if (value == null || CanEmitILConstant(type))
{
return true;
}
Type t = value as Type;
if (t != null)
{
return ShouldLdtoken(t);
}
MethodBase mb = value as MethodBase;
return mb != null && ShouldLdtoken(mb);
}
// matches TryEmitILConstant
private static bool CanEmitILConstant(Type type)
{
switch (type.GetNonNullableType().GetTypeCode())
{
case TypeCode.Boolean:
case TypeCode.SByte:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Char:
case TypeCode.Byte:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
case TypeCode.Decimal:
case TypeCode.String:
return true;
}
return false;
}
//
// Note: we support emitting more things as IL constants than
// Linq does
internal static bool TryEmitConstant(this ILGenerator il, object value, Type type, ILocalCache locals)
{
if (value == null)
{
// Smarter than the Linq implementation which uses the initobj
// pattern for all value types (works, but requires a local and
// more IL)
il.EmitDefault(type, locals);
return true;
}
// Handle the easy cases
if (il.TryEmitILConstant(value, type))
{
return true;
}
// Check for a few more types that we support emitting as constants
Type t = value as Type;
if (t != null)
{
if (ShouldLdtoken(t))
{
il.EmitType(t);
if (type != typeof(Type))
{
il.Emit(OpCodes.Castclass, type);
}
return true;
}
return false;
}
MethodBase mb = value as MethodBase;
if (mb != null && ShouldLdtoken(mb))
{
il.Emit(OpCodes.Ldtoken, mb);
Type dt = mb.DeclaringType;
if (dt != null && dt.IsGenericType)
{
il.Emit(OpCodes.Ldtoken, dt);
il.Emit(OpCodes.Call, MethodBase_GetMethodFromHandle_RuntimeMethodHandle_RuntimeTypeHandle);
}
else
{
il.Emit(OpCodes.Call, MethodBase_GetMethodFromHandle_RuntimeMethodHandle);
}
if (type != typeof(MethodBase))
{
il.Emit(OpCodes.Castclass, type);
}
return true;
}
return false;
}
private static bool ShouldLdtoken(Type t)
{
// If CompileToMethod is re-enabled, t is TypeBuilder should also return
// true when not compiling to a DynamicMethod
return t.IsGenericParameter || t.IsVisible;
}
internal static bool ShouldLdtoken(MethodBase mb)
{
// Can't ldtoken on a DynamicMethod
if (mb is DynamicMethod)
{
return false;
}
Type dt = mb.DeclaringType;
return dt == null || ShouldLdtoken(dt);
}
private static bool TryEmitILConstant(this ILGenerator il, object value, Type type)
{
Debug.Assert(value != null);
if (type.IsNullableType())
{
Type nonNullType = type.GetNonNullableType();
if (TryEmitILConstant(il, value, nonNullType))
{
il.Emit(OpCodes.Newobj, type.GetConstructor(new[] { nonNullType }));
return true;
}
return false;
}
switch (type.GetTypeCode())
{
case TypeCode.Boolean:
il.EmitPrimitive((bool)value);
return true;
case TypeCode.SByte:
il.EmitPrimitive((sbyte)value);
return true;
case TypeCode.Int16:
il.EmitPrimitive((short)value);
return true;
case TypeCode.Int32:
il.EmitPrimitive((int)value);
return true;
case TypeCode.Int64:
il.EmitPrimitive((long)value);
return true;
case TypeCode.Single:
il.EmitPrimitive((float)value);
return true;
case TypeCode.Double:
il.EmitPrimitive((double)value);
return true;
case TypeCode.Char:
il.EmitPrimitive((char)value);
return true;
case TypeCode.Byte:
il.EmitPrimitive((byte)value);
return true;
case TypeCode.UInt16:
il.EmitPrimitive((ushort)value);
return true;
case TypeCode.UInt32:
il.EmitPrimitive((uint)value);
return true;
case TypeCode.UInt64:
il.EmitPrimitive((ulong)value);
return true;
case TypeCode.Decimal:
il.EmitDecimal((decimal)value);
return true;
case TypeCode.String:
il.EmitString((string)value);
return true;
default:
return false;
}
}
#endregion
#region Linq Conversions
internal static void EmitConvertToType(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked, ILocalCache locals)
{
if (TypeUtils.AreEquivalent(typeFrom, typeTo))
{
return;
}
Debug.Assert(typeFrom != typeof(void) && typeTo != typeof(void));
bool isTypeFromNullable = typeFrom.IsNullableType();
bool isTypeToNullable = typeTo.IsNullableType();
Type nnExprType = typeFrom.GetNonNullableType();
Type nnType = typeTo.GetNonNullableType();
if (typeFrom.IsInterface || // interface cast
typeTo.IsInterface ||
typeFrom == typeof(object) || // boxing cast
typeTo == typeof(object) ||
typeFrom == typeof(System.Enum) ||
typeFrom == typeof(System.ValueType) ||
TypeUtils.IsLegalExplicitVariantDelegateConversion(typeFrom, typeTo))
{
il.EmitCastToType(typeFrom, typeTo);
}
else if (isTypeFromNullable || isTypeToNullable)
{
il.EmitNullableConversion(typeFrom, typeTo, isChecked, locals);
}
else if (!(typeFrom.IsConvertible() && typeTo.IsConvertible()) // primitive runtime conversion
&&
(nnExprType.IsAssignableFrom(nnType) || // down cast
nnType.IsAssignableFrom(nnExprType))) // up cast
{
il.EmitCastToType(typeFrom, typeTo);
}
else if (typeFrom.IsArray && typeTo.IsArray)
{
// See DevDiv Bugs #94657.
il.EmitCastToType(typeFrom, typeTo);
}
else
{
il.EmitNumericConversion(typeFrom, typeTo, isChecked);
}
}
private static void EmitCastToType(this ILGenerator il, Type typeFrom, Type typeTo)
{
if (typeFrom.IsValueType)
{
Debug.Assert(!typeTo.IsValueType);
il.Emit(OpCodes.Box, typeFrom);
if (typeTo != typeof(object))
{
il.Emit(OpCodes.Castclass, typeTo);
}
}
else
{
il.Emit(typeTo.IsValueType ? OpCodes.Unbox_Any : OpCodes.Castclass, typeTo);
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
private static void EmitNumericConversion(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked)
{
TypeCode tc = typeTo.GetTypeCode();
TypeCode tf = typeFrom.GetTypeCode();
if (tc == tf)
{
// Between enums of same underlying type, or between such an enum and the underlying type itself.
// Includes bool-backed enums, which is the only valid conversion to or from bool.
// Just leave the value on the stack, and treat it as the wanted type.
return;
}
bool isFromUnsigned = tf.IsUnsigned();
OpCode convCode;
switch (tc)
{
case TypeCode.Single:
if (isFromUnsigned)
il.Emit(OpCodes.Conv_R_Un);
convCode = OpCodes.Conv_R4;
break;
case TypeCode.Double:
if (isFromUnsigned)
il.Emit(OpCodes.Conv_R_Un);
convCode = OpCodes.Conv_R8;
break;
case TypeCode.Decimal:
// NB: TypeUtils.IsImplicitNumericConversion makes the promise that implicit conversions
// from various integral types and char to decimal are possible. Coalesce allows the
// conversion lambda to be omitted in these cases, so we have to handle this case in
// here as well, by using the op_Implicit operator implementation on System.Decimal
// because there are no opcodes for System.Decimal.
Debug.Assert(typeFrom != typeTo);
MethodInfo method;
switch (tf)
{
case TypeCode.Byte: method = Decimal_op_Implicit_Byte; break;
case TypeCode.SByte: method = Decimal_op_Implicit_SByte; break;
case TypeCode.Int16: method = Decimal_op_Implicit_Int16; break;
case TypeCode.UInt16: method = Decimal_op_Implicit_UInt16; break;
case TypeCode.Int32: method = Decimal_op_Implicit_Int32; break;
case TypeCode.UInt32: method = Decimal_op_Implicit_UInt32; break;
case TypeCode.Int64: method = Decimal_op_Implicit_Int64; break;
case TypeCode.UInt64: method = Decimal_op_Implicit_UInt64; break;
case TypeCode.Char: method = Decimal_op_Implicit_Char; break;
default:
throw ContractUtils.Unreachable;
}
il.Emit(OpCodes.Call, method);
return;
case TypeCode.SByte:
if (isChecked)
{
convCode = isFromUnsigned ? OpCodes.Conv_Ovf_I1_Un : OpCodes.Conv_Ovf_I1;
}
else
{
if (tf == TypeCode.Byte)
{
return;
}
convCode = OpCodes.Conv_I1;
}
break;
case TypeCode.Byte:
if (isChecked)
{
convCode = isFromUnsigned ? OpCodes.Conv_Ovf_U1_Un : OpCodes.Conv_Ovf_U1;
}
else
{
if (tf == TypeCode.SByte)
{
return;
}
convCode = OpCodes.Conv_U1;
}
break;
case TypeCode.Int16:
switch (tf)
{
case TypeCode.SByte:
case TypeCode.Byte:
return;
case TypeCode.Char:
case TypeCode.UInt16:
if (!isChecked)
{
return;
}
break;
}
convCode = isChecked
? (isFromUnsigned ? OpCodes.Conv_Ovf_I2_Un : OpCodes.Conv_Ovf_I2)
: OpCodes.Conv_I2;
break;
case TypeCode.Char:
case TypeCode.UInt16:
switch (tf)
{
case TypeCode.Byte:
case TypeCode.Char:
case TypeCode.UInt16:
return;
case TypeCode.SByte:
case TypeCode.Int16:
if (!isChecked)
{
return;
}
break;
}
convCode = isChecked
? (isFromUnsigned ? OpCodes.Conv_Ovf_U2_Un : OpCodes.Conv_Ovf_U2)
: OpCodes.Conv_U2;
break;
case TypeCode.Int32:
switch (tf)
{
case TypeCode.Byte:
case TypeCode.SByte:
case TypeCode.Int16:
case TypeCode.UInt16:
return;
case TypeCode.UInt32:
if (!isChecked)
{
return;
}
break;
}
convCode = isChecked
? (isFromUnsigned ? OpCodes.Conv_Ovf_I4_Un : OpCodes.Conv_Ovf_I4)
: OpCodes.Conv_I4;
break;
case TypeCode.UInt32:
switch (tf)
{
case TypeCode.Byte:
case TypeCode.Char:
case TypeCode.UInt16:
return;
case TypeCode.SByte:
case TypeCode.Int16:
case TypeCode.Int32:
if (!isChecked)
{
return;
}
break;
}
convCode = isChecked
? (isFromUnsigned ? OpCodes.Conv_Ovf_U4_Un : OpCodes.Conv_Ovf_U4)
: OpCodes.Conv_U4;
break;
case TypeCode.Int64:
if (!isChecked && tf == TypeCode.UInt64)
{
return;
}
convCode = isChecked
? (isFromUnsigned ? OpCodes.Conv_Ovf_I8_Un : OpCodes.Conv_Ovf_I8)
: (isFromUnsigned ? OpCodes.Conv_U8 : OpCodes.Conv_I8);
break;
case TypeCode.UInt64:
if (!isChecked && tf == TypeCode.Int64)
{
return;
}
convCode = isChecked
? (isFromUnsigned || tf.IsFloatingPoint() ? OpCodes.Conv_Ovf_U8_Un : OpCodes.Conv_Ovf_U8)
: (isFromUnsigned || tf.IsFloatingPoint() ? OpCodes.Conv_U8 : OpCodes.Conv_I8);
break;
default:
throw ContractUtils.Unreachable;
}
il.Emit(convCode);
}
private static void EmitNullableToNullableConversion(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked, ILocalCache locals)
{
Debug.Assert(typeFrom.IsNullableType());
Debug.Assert(typeTo.IsNullableType());
Label labIfNull;
Label labEnd;
LocalBuilder locFrom = locals.GetLocal(typeFrom);
il.Emit(OpCodes.Stloc, locFrom);
// test for null
il.Emit(OpCodes.Ldloca, locFrom);
il.EmitHasValue(typeFrom);
labIfNull = il.DefineLabel();
il.Emit(OpCodes.Brfalse_S, labIfNull);
il.Emit(OpCodes.Ldloca, locFrom);
locals.FreeLocal(locFrom);
il.EmitGetValueOrDefault(typeFrom);
Type nnTypeFrom = typeFrom.GetNonNullableType();
Type nnTypeTo = typeTo.GetNonNullableType();
il.EmitConvertToType(nnTypeFrom, nnTypeTo, isChecked, locals);
// construct result type
ConstructorInfo ci = typeTo.GetConstructor(new Type[] { nnTypeTo });
il.Emit(OpCodes.Newobj, ci);
labEnd = il.DefineLabel();
il.Emit(OpCodes.Br_S, labEnd);
// if null then create a default one
il.MarkLabel(labIfNull);
LocalBuilder locTo = locals.GetLocal(typeTo);
il.Emit(OpCodes.Ldloca, locTo);
il.Emit(OpCodes.Initobj, typeTo);
il.Emit(OpCodes.Ldloc, locTo);
locals.FreeLocal(locTo);
il.MarkLabel(labEnd);
}
private static void EmitNonNullableToNullableConversion(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked, ILocalCache locals)
{
Debug.Assert(!typeFrom.IsNullableType());
Debug.Assert(typeTo.IsNullableType());
Type nnTypeTo = typeTo.GetNonNullableType();
il.EmitConvertToType(typeFrom, nnTypeTo, isChecked, locals);
ConstructorInfo ci = typeTo.GetConstructor(new Type[] { nnTypeTo });
il.Emit(OpCodes.Newobj, ci);
}
private static void EmitNullableToNonNullableConversion(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked, ILocalCache locals)
{
Debug.Assert(typeFrom.IsNullableType());
Debug.Assert(!typeTo.IsNullableType());
if (typeTo.IsValueType)
il.EmitNullableToNonNullableStructConversion(typeFrom, typeTo, isChecked, locals);
else
il.EmitNullableToReferenceConversion(typeFrom);
}
private static void EmitNullableToNonNullableStructConversion(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked, ILocalCache locals)
{
Debug.Assert(typeFrom.IsNullableType());
Debug.Assert(!typeTo.IsNullableType());
Debug.Assert(typeTo.IsValueType);
LocalBuilder locFrom = locals.GetLocal(typeFrom);
il.Emit(OpCodes.Stloc, locFrom);
il.Emit(OpCodes.Ldloca, locFrom);
locals.FreeLocal(locFrom);
il.EmitGetValue(typeFrom);
Type nnTypeFrom = typeFrom.GetNonNullableType();
il.EmitConvertToType(nnTypeFrom, typeTo, isChecked, locals);
}
private static void EmitNullableToReferenceConversion(this ILGenerator il, Type typeFrom)
{
Debug.Assert(typeFrom.IsNullableType());
// We've got a conversion from nullable to Object, ValueType, Enum, etc. Just box it so that
// we get the nullable semantics.
il.Emit(OpCodes.Box, typeFrom);
}
private static void EmitNullableConversion(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked, ILocalCache locals)
{
bool isTypeFromNullable = typeFrom.IsNullableType();
bool isTypeToNullable = typeTo.IsNullableType();
Debug.Assert(isTypeFromNullable || isTypeToNullable);
if (isTypeFromNullable && isTypeToNullable)
il.EmitNullableToNullableConversion(typeFrom, typeTo, isChecked, locals);
else if (isTypeFromNullable)
il.EmitNullableToNonNullableConversion(typeFrom, typeTo, isChecked, locals);
else
il.EmitNonNullableToNullableConversion(typeFrom, typeTo, isChecked, locals);
}
internal static void EmitHasValue(this ILGenerator il, Type nullableType)
{
MethodInfo mi = nullableType.GetMethod("get_HasValue", BindingFlags.Instance | BindingFlags.Public);
Debug.Assert(nullableType.IsValueType);
il.Emit(OpCodes.Call, mi);
}
internal static void EmitGetValue(this ILGenerator il, Type nullableType)
{
MethodInfo mi = nullableType.GetMethod("get_Value", BindingFlags.Instance | BindingFlags.Public);
Debug.Assert(nullableType.IsValueType);
il.Emit(OpCodes.Call, mi);
}
internal static void EmitGetValueOrDefault(this ILGenerator il, Type nullableType)
{
MethodInfo mi = nullableType.GetMethod("GetValueOrDefault", System.Type.EmptyTypes);
Debug.Assert(nullableType.IsValueType);
il.Emit(OpCodes.Call, mi);
}
#endregion
#region Arrays
#if FEATURE_COMPILE_TO_METHODBUILDER
/// <summary>
/// Emits an array of constant values provided in the given array.
/// The array is strongly typed.
/// </summary>
internal static void EmitArray<T>(this ILGenerator il, T[] items, ILocalCache locals)
{
Debug.Assert(items != null);
il.EmitPrimitive(items.Length);
il.Emit(OpCodes.Newarr, typeof(T));
for (int i = 0; i < items.Length; i++)
{
il.Emit(OpCodes.Dup);
il.EmitPrimitive(i);
il.TryEmitConstant(items[i], typeof(T), locals);
il.EmitStoreElement(typeof(T));
}
}
#endif
/// <summary>
/// Emits an array of values of count size.
/// </summary>
internal static void EmitArray(this ILGenerator il, Type elementType, int count)
{
Debug.Assert(elementType != null);
Debug.Assert(count >= 0);
il.EmitPrimitive(count);
il.Emit(OpCodes.Newarr, elementType);
}
/// <summary>
/// Emits an array construction code.
/// The code assumes that bounds for all dimensions
/// are already emitted.
/// </summary>
internal static void EmitArray(this ILGenerator il, Type arrayType)
{
Debug.Assert(arrayType != null);
Debug.Assert(arrayType.IsArray);
if (arrayType.IsSZArray)
{
il.Emit(OpCodes.Newarr, arrayType.GetElementType());
}
else
{
Type[] types = new Type[arrayType.GetArrayRank()];
for (int i = 0; i < types.Length; i++)
{
types[i] = typeof(int);
}
ConstructorInfo ci = arrayType.GetConstructor(types);
Debug.Assert(ci != null);
il.EmitNew(ci);
}
}
#endregion
#region Support for emitting constants
private static void EmitDecimal(this ILGenerator il, decimal value)
{
int[] bits = decimal.GetBits(value);
int scale = (bits[3] & int.MaxValue) >> 16;
if (scale == 0)
{
if (int.MinValue <= value)
{
if (value <= int.MaxValue)
{
int intValue = decimal.ToInt32(value);
switch (intValue)
{
case -1:
il.Emit(OpCodes.Ldsfld, Decimal_MinusOne);
return;
case 0:
il.EmitDefault(typeof(decimal), locals: null); // locals won't be used.
return;
case 1:
il.Emit(OpCodes.Ldsfld, Decimal_One);
return;
default:
il.EmitPrimitive(intValue);
il.EmitNew(Decimal_Ctor_Int32);
return;
}
}
if (value <= uint.MaxValue)
{
il.EmitPrimitive(decimal.ToUInt32(value));
il.EmitNew(Decimal_Ctor_UInt32);
return;
}
}
if (long.MinValue <= value)
{
if (value <= long.MaxValue)
{
il.EmitPrimitive(decimal.ToInt64(value));
il.EmitNew(Decimal_Ctor_Int64);
return;
}
if (value <= ulong.MaxValue)
{
il.EmitPrimitive(decimal.ToUInt64(value));
il.EmitNew(Decimal_Ctor_UInt64);
return;
}
if (value == decimal.MaxValue)
{
il.Emit(OpCodes.Ldsfld, Decimal_MaxValue);
return;
}
}
else if (value == decimal.MinValue)
{
il.Emit(OpCodes.Ldsfld, Decimal_MinValue);
return;
}
}
il.EmitPrimitive(bits[0]);
il.EmitPrimitive(bits[1]);
il.EmitPrimitive(bits[2]);
il.EmitPrimitive((bits[3] & 0x80000000) != 0);
il.EmitPrimitive(unchecked((byte)scale));
il.EmitNew(Decimal_Ctor_Int32_Int32_Int32_Bool_Byte);
}
/// <summary>
/// Emits default(T)
/// Semantics match C# compiler behavior
/// </summary>
internal static void EmitDefault(this ILGenerator il, Type type, ILocalCache locals)
{
switch (type.GetTypeCode())
{
case TypeCode.DateTime:
il.Emit(OpCodes.Ldsfld, DateTime_MinValue);
break;
case TypeCode.Object:
if (type.IsValueType)
{
// Type.GetTypeCode on an enum returns the underlying
// integer TypeCode, so we won't get here.
Debug.Assert(!type.IsEnum);
// This is the IL for default(T) if T is a generic type
// parameter, so it should work for any type. It's also
// the standard pattern for structs.
LocalBuilder lb = locals.GetLocal(type);
il.Emit(OpCodes.Ldloca, lb);
il.Emit(OpCodes.Initobj, type);
il.Emit(OpCodes.Ldloc, lb);
locals.FreeLocal(lb);
break;
}
goto case TypeCode.Empty;
case TypeCode.Empty:
case TypeCode.String:
case TypeCode.DBNull:
il.Emit(OpCodes.Ldnull);
break;
case TypeCode.Boolean:
case TypeCode.Char:
case TypeCode.SByte:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
il.Emit(OpCodes.Ldc_I4_0);
break;
case TypeCode.Int64:
case TypeCode.UInt64:
il.Emit(OpCodes.Ldc_I4_0);
il.Emit(OpCodes.Conv_I8);
break;
case TypeCode.Single:
il.Emit(OpCodes.Ldc_R4, default(float));
break;
case TypeCode.Double:
il.Emit(OpCodes.Ldc_R8, default(double));
break;
case TypeCode.Decimal:
il.Emit(OpCodes.Ldsfld, Decimal_Zero);
break;
default:
throw ContractUtils.Unreachable;
}
}
#endregion
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="BehaviorTreeLibrary.cs" company="Slash Games">
// Copyright (c) Slash Games. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Slash.AI.BehaviorTrees.Management
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Serialization;
using Slash.AI.BehaviorTrees.Editor;
using Slash.AI.BehaviorTrees.Implementations;
using Slash.AI.BehaviorTrees.Implementations.Actions;
using Slash.AI.BehaviorTrees.Interfaces;
using Slash.AI.BehaviorTrees.Tree;
using Slash.Collections.Utils;
/// <summary>
/// Library which stores behavior trees by key.
/// </summary>
[Serializable]
public class BehaviorTreeLibrary
{
#region Constructors and Destructors
/// <summary>
/// Initializes a new instance of the <see cref="BehaviorTreeLibrary" /> class.
/// </summary>
public BehaviorTreeLibrary()
{
this.Entries = new List<Entry>();
}
#endregion
#region Delegates
/// <summary>
/// Called when the library was changed by the editor.
/// </summary>
/// <param name="library"> Library which changed. </param>
public delegate void LibraryChangedDelegate(BehaviorTreeLibrary library);
#endregion
#region Public Events
/// <summary>
/// Called when the library was changed by the editor.
/// </summary>
[field: NonSerialized]
public event LibraryChangedDelegate LibraryChanged;
#endregion
#region Public Properties
/// <summary>
/// Returns the number of available behavior trees.
/// </summary>
[XmlIgnore]
public int Count
{
get
{
return this.Entries.Count;
}
}
/// <summary>
/// Returns all available trees as a read-only list.
/// </summary>
public List<Entry> Entries { get; set; }
#endregion
#region Public Methods and Operators
/// <summary>
/// Adds a behavior tree to the library and uses the passed name as its key.
/// </summary>
/// <param name="behaviorTreeName"> Name of the behavior tree. </param>
/// <param name="behaviorTree"> Behavior tree. </param>
public void Add(string behaviorTreeName, ITask behaviorTree)
{
this.Entries.Add(new Entry { Identifier = behaviorTreeName, Tree = behaviorTree });
// Invoke event.
this.InvokeLibraryChanged();
}
/// <summary>
/// Determines whether the library contains a behavior tree with the passed name.
/// </summary>
/// <param name="behaviorTreeName"> Behavior tree name. </param>
/// <returns> True if the library contains a behavior tree with the passed name; otherwise, false. </returns>
public bool Contains(string behaviorTreeName)
{
return this.Entries.Exists(entry => entry.Identifier == behaviorTreeName);
}
/// <summary>
/// The equals.
/// </summary>
/// <param name="other"> The other. </param>
/// <returns> The System.Boolean. </returns>
public bool Equals(BehaviorTreeLibrary other)
{
if (ReferenceEquals(null, other))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return CollectionUtils.SequenceEqual(other.Entries, this.Entries);
}
/// <summary>
/// The equals.
/// </summary>
/// <param name="obj"> The obj. </param>
/// <returns> The System.Boolean. </returns>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj.GetType() != typeof(BehaviorTreeLibrary))
{
return false;
}
return this.Equals((BehaviorTreeLibrary)obj);
}
/// <summary>
/// Returns the behavior tree with the passed name from this library.
/// </summary>
/// <param name="behaviorTreeName"> Behavior tree name. </param>
/// <returns> Behavior tree which was stored under the passed name. </returns>
public ITask Get(string behaviorTreeName)
{
Entry foundEntry = this.Entries.First(entry => entry.Identifier == behaviorTreeName);
return foundEntry == null ? null : foundEntry.Tree;
}
/// <summary>
/// The get hash code.
/// </summary>
/// <returns> The System.Int32. </returns>
public override int GetHashCode()
{
return this.Entries != null ? this.Entries.GetHashCode() : 0;
}
/// <summary>
/// Removes the behavior tree with the passed name from the library.
/// </summary>
/// <param name="behaviorTreeName"> Name of the behavior tree. </param>
/// <returns> Returns if the behavior tree was successfully removed. </returns>
public bool Remove(string behaviorTreeName)
{
bool entryRemoved = this.Entries.RemoveAll(entry => entry.Identifier == behaviorTreeName) > 0;
if (!entryRemoved)
{
return false;
}
// Invoke event.
this.InvokeLibraryChanged();
return true;
}
/// <summary>
/// Removes the behavior tree from the library.
/// </summary>
/// <param name="behaviorTree"> Behavior tree. </param>
/// <returns> Returns if the behavior tree was successfully removed. </returns>
public bool Remove(ITask behaviorTree)
{
bool entryRemoved = this.Entries.RemoveAll(entry => entry.Tree == behaviorTree) > 0;
if (!entryRemoved)
{
return false;
}
// Invoke event.
this.InvokeLibraryChanged();
return true;
}
/// <summary>
/// Sets a behavior tree to the library and uses the passed name as its key. Overwrites a behavior tree if the library already contains a behavior tree with the passed name.
/// </summary>
/// <param name="behaviorTreeName"> Name of the behavior tree. </param>
/// <param name="behaviorTree"> Behavior tree. </param>
public void Set(string behaviorTreeName, ITask behaviorTree)
{
this.Entries.RemoveAll(entry => entry.Identifier == behaviorTreeName);
this.Entries.Add(new Entry { Identifier = behaviorTreeName, Tree = behaviorTree });
// Invoke event.
this.InvokeLibraryChanged();
}
/// <summary>
/// Solves all sub tree reference tasks and replaces them by real references to the sub tree.
/// </summary>
public void SolveReferences()
{
foreach (Entry entry in this.Entries)
{
entry.Tree = this.SolveReferences(entry.Tree);
}
}
/// <summary>
/// Solves all sub tree reference tasks and replaces them by real references to the sub tree.
/// </summary>
/// <param name="tree"> Tree in which to solve references. </param>
public void SolveReferences(IBehaviorTree tree)
{
tree.Root = this.SolveReferences(tree.Root);
}
/// <summary>
/// Tries to get the behavior tree with the passed name from this library.
/// </summary>
/// <param name="behaviorTreeName"> Behavior tree name. </param>
/// <param name="behaviorTree"> Behavior tree. </param>
/// <returns> True if a behavior tree was found, else false. </returns>
public bool TryGet(string behaviorTreeName, out ITask behaviorTree)
{
Entry foundEntry = this.Entries.Find(entry => entry.Identifier == behaviorTreeName);
if (foundEntry == null)
{
behaviorTree = null;
return false;
}
behaviorTree = foundEntry.Tree;
return true;
}
#endregion
#region Methods
/// <summary>
/// The invoke library changed.
/// </summary>
private void InvokeLibraryChanged()
{
LibraryChangedDelegate handler = this.LibraryChanged;
if (handler != null)
{
handler(this);
}
}
/// <summary>
/// Solves a sub tree reference by searching for the tree with the name specified in the reference. Also encapsulates the tree if necessary (e.g. because a blackboard is provided).
/// </summary>
/// <param name="subTreeReference"> Reference to resolve. </param>
/// <returns> Task to use instead of the reference. </returns>
private ITask SolveReference(SubTreeReference subTreeReference)
{
// Find tree reference.
ITask treeReference = this.Get(subTreeReference.SubTreeName);
if (treeReference == null && !string.IsNullOrEmpty(subTreeReference.SubTreeName))
{
throw new Exception(
string.Format(
"No tree reference found for tree named '{0}' in sub tree reference task.",
subTreeReference.SubTreeName));
}
// Encapsulate with CreateBlackboard task if blackboard is set.
if (subTreeReference.Blackboard != null)
{
treeReference = new CreateBlackboard { Task = treeReference, Blackboard = subTreeReference.Blackboard };
}
return treeReference;
}
/// <summary>
/// Solves all sub tree reference tasks and replaces them by real references to the sub tree.
/// </summary>
/// <param name="tree"> Tree in which to solve references. </param>
/// <returns> Task to use instead of the passed one. </returns>
private ITask SolveReferences(ITask tree)
{
if (tree == null)
{
return tree;
}
// Check if root is reference.
if (tree is SubTreeReference)
{
SubTreeReference subTreeReference = tree as SubTreeReference;
// Resolve reference.
ITask treeReference = this.SolveReference(subTreeReference);
return treeReference;
}
// Find sub tree reference tasks in tree.
ICollection<TaskNode> referenceNodes = new List<TaskNode>();
TaskNode rootNode = new TaskNode { Task = tree };
tree.FindTasks(rootNode, task => task is SubTreeReference, ref referenceNodes);
// Replace tasks in found nodes by referenced tree.
foreach (TaskNode referenceNode in referenceNodes)
{
SubTreeReference subTreeReference = referenceNode.Task as SubTreeReference;
if (subTreeReference == null)
{
throw new Exception(
"Searched for SubTreeReference nodes, but found a task which is no sub tree reference node.");
}
IComposite parentComposite = referenceNode.ParentTask as IComposite;
if (parentComposite == null)
{
throw new Exception("Found task which has no parent composite.");
}
// Resolve reference.
ITask treeReference = this.SolveReference(subTreeReference);
// Remove from parent.
parentComposite.RemoveChild(referenceNode.Task);
// Add tree reference to parent at same position.
parentComposite.InsertChild(referenceNode.Index, treeReference);
}
return tree;
}
#endregion
/// <summary>
/// Entry in library.
/// </summary>
[Serializable]
public class Entry
{
#region Public Properties
/// <summary>
/// Identifier.
/// </summary>
public string Identifier { get; set; }
/// <summary>
/// Tree.
/// </summary>
[XmlIgnore]
public ITask Tree { get; set; }
/// <summary>
/// Tree.
/// </summary>
[XmlElement("Tree")]
public XmlWrapper TreeSerialized
{
get
{
return new XmlWrapper(this.Tree);
}
set
{
this.Tree = value.Task;
}
}
#endregion
#region Public Methods and Operators
/// <summary>
/// The equals.
/// </summary>
/// <param name="other"> The other. </param>
/// <returns> The System.Boolean. </returns>
public bool Equals(Entry other)
{
if (ReferenceEquals(null, other))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return Equals(other.Identifier, this.Identifier) && Equals(other.Tree, this.Tree);
}
/// <summary>
/// The equals.
/// </summary>
/// <param name="obj"> The obj. </param>
/// <returns> The System.Boolean. </returns>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj.GetType() != typeof(Entry))
{
return false;
}
return this.Equals((Entry)obj);
}
/// <summary>
/// The get hash code.
/// </summary>
/// <returns> The System.Int32. </returns>
public override int GetHashCode()
{
unchecked
{
return ((this.Identifier != null ? this.Identifier.GetHashCode() : 0) * 397)
^ (this.Tree != null ? this.Tree.GetHashCode() : 0);
}
}
#endregion
}
}
}
| |
/*
* Copyright 2012-2021 The Pkcs11Interop Project
*
* 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.
*/
/*
* Written for the Pkcs11Interop project by:
* Jaroslav IMRICH <jimrich@jimrich.sk>
*/
using System;
using System.IO;
using Net.Pkcs11Interop.Common;
using Net.Pkcs11Interop.LowLevelAPI80;
using NUnit.Framework;
using NativeULong = System.UInt64;
// Note: Code in this file is generated automatically.
namespace Net.Pkcs11Interop.Tests.LowLevelAPI80
{
/// <summary>
/// C_SignInit, C_Sign, C_SignUpdate, C_SignFinal, C_VerifyInit, C_Verify, C_VerifyUpdate and C_VerifyFinal tests.
/// </summary>
[TestFixture()]
public class _21_SignAndVerifyTest
{
/// <summary>
/// C_SignInit, C_Sign, C_VerifyInit and C_Verify test with CKM_RSA_PKCS mechanism.
/// </summary>
[Test()]
public void _01_SignAndVerifySinglePartTest()
{
Helpers.CheckPlatform();
CKR rv = CKR.CKR_OK;
using (Pkcs11Library pkcs11Library = new Pkcs11Library(Settings.Pkcs11LibraryPath))
{
rv = pkcs11Library.C_Initialize(Settings.InitArgs80);
if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED))
Assert.Fail(rv.ToString());
// Find first slot with token present
NativeULong slotId = Helpers.GetUsableSlot(pkcs11Library);
NativeULong session = CK.CK_INVALID_HANDLE;
rv = pkcs11Library.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Login as normal user
rv = pkcs11Library.C_Login(session, CKU.CKU_USER, Settings.NormalUserPinArray, ConvertUtils.UInt64FromInt32(Settings.NormalUserPinArray.Length));
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Generate asymetric key pair
NativeULong pubKeyId = CK.CK_INVALID_HANDLE;
NativeULong privKeyId = CK.CK_INVALID_HANDLE;
rv = Helpers.GenerateKeyPair(pkcs11Library, session, ref pubKeyId, ref privKeyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Specify signing mechanism (needs no parameter => no unamanaged memory is needed)
CK_MECHANISM mechanism = CkmUtils.CreateMechanism(CKM.CKM_SHA1_RSA_PKCS);
// Initialize signing operation
rv = pkcs11Library.C_SignInit(session, ref mechanism, privKeyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
byte[] sourceData = ConvertUtils.Utf8StringToBytes("Hello world");
// Get length of signature in first call
NativeULong signatureLen = 0;
rv = pkcs11Library.C_Sign(session, sourceData, ConvertUtils.UInt64FromInt32(sourceData.Length), null, ref signatureLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
Assert.IsTrue(signatureLen > 0);
// Allocate array for signature
byte[] signature = new byte[signatureLen];
// Get signature in second call
rv = pkcs11Library.C_Sign(session, sourceData, ConvertUtils.UInt64FromInt32(sourceData.Length), signature, ref signatureLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Do something interesting with signature
// Initialize verification operation
rv = pkcs11Library.C_VerifyInit(session, ref mechanism, pubKeyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Verify signature
rv = pkcs11Library.C_Verify(session, sourceData, ConvertUtils.UInt64FromInt32(sourceData.Length), signature, ConvertUtils.UInt64FromInt32(signature.Length));
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Do something interesting with verification result
rv = pkcs11Library.C_DestroyObject(session, privKeyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11Library.C_DestroyObject(session, pubKeyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11Library.C_Logout(session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11Library.C_CloseSession(session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11Library.C_Finalize(IntPtr.Zero);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
}
}
/// <summary>
/// C_SignInit, C_SignUpdate, C_SignFinal, C_VerifyInit, C_VerifyUpdate and C_VerifyFinal test.
/// </summary>
[Test()]
public void _02_SignAndVerifyMultiPartTest()
{
Helpers.CheckPlatform();
CKR rv = CKR.CKR_OK;
using (Pkcs11Library pkcs11Library = new Pkcs11Library(Settings.Pkcs11LibraryPath))
{
rv = pkcs11Library.C_Initialize(Settings.InitArgs80);
if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED))
Assert.Fail(rv.ToString());
// Find first slot with token present
NativeULong slotId = Helpers.GetUsableSlot(pkcs11Library);
NativeULong session = CK.CK_INVALID_HANDLE;
rv = pkcs11Library.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Login as normal user
rv = pkcs11Library.C_Login(session, CKU.CKU_USER, Settings.NormalUserPinArray, ConvertUtils.UInt64FromInt32(Settings.NormalUserPinArray.Length));
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Generate asymetric key pair
NativeULong pubKeyId = CK.CK_INVALID_HANDLE;
NativeULong privKeyId = CK.CK_INVALID_HANDLE;
rv = Helpers.GenerateKeyPair(pkcs11Library, session, ref pubKeyId, ref privKeyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Specify signing mechanism (needs no parameter => no unamanaged memory is needed)
CK_MECHANISM mechanism = CkmUtils.CreateMechanism(CKM.CKM_SHA1_RSA_PKCS);
byte[] sourceData = ConvertUtils.Utf8StringToBytes("Hello world");
byte[] signature = null;
// Multipart signature functions C_SignUpdate and C_SignFinal can be used i.e. for signing of streamed data
using (MemoryStream inputStream = new MemoryStream(sourceData))
{
// Initialize signing operation
rv = pkcs11Library.C_SignInit(session, ref mechanism, privKeyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Prepare buffer for source data part
// Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long
byte[] part = new byte[8];
// Read input stream with source data
int bytesRead = 0;
while ((bytesRead = inputStream.Read(part, 0, part.Length)) > 0)
{
// Process each individual source data part
rv = pkcs11Library.C_SignUpdate(session, part, ConvertUtils.UInt64FromInt32(bytesRead));
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
}
// Get the length of signature in first call
NativeULong signatureLen = 0;
rv = pkcs11Library.C_SignFinal(session, null, ref signatureLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
Assert.IsTrue(signatureLen > 0);
// Allocate array for signature
signature = new byte[signatureLen];
// Get signature in second call
rv = pkcs11Library.C_SignFinal(session, signature, ref signatureLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
}
// Do something interesting with signature
// Multipart verification functions C_VerifyUpdate and C_VerifyFinal can be used i.e. for signature verification of streamed data
using (MemoryStream inputStream = new MemoryStream(sourceData))
{
// Initialize verification operation
rv = pkcs11Library.C_VerifyInit(session, ref mechanism, pubKeyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Prepare buffer for source data part
// Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long
byte[] part = new byte[8];
// Read input stream with source data
int bytesRead = 0;
while ((bytesRead = inputStream.Read(part, 0, part.Length)) > 0)
{
// Process each individual source data part
rv = pkcs11Library.C_VerifyUpdate(session, part, ConvertUtils.UInt64FromInt32(bytesRead));
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
}
// Verify signature
rv = pkcs11Library.C_VerifyFinal(session, signature, ConvertUtils.UInt64FromInt32(signature.Length));
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
}
// Do something interesting with verification result
rv = pkcs11Library.C_DestroyObject(session, privKeyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11Library.C_DestroyObject(session, pubKeyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11Library.C_Logout(session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11Library.C_CloseSession(session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11Library.C_Finalize(IntPtr.Zero);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
}
}
}
}
| |
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;
FileSystemInfo FileInfoCache;
readonly string InternalName;
public SmbFile() => InternalName = "";
SmbFile(string internalName, bool autoCreateDirectories)
{
InternalName = internalName;
AutoCreateDirectories = autoCreateDirectories;
}
/// <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];
f.Read(result, 0, (int)Size);
f.Close();
return result;
}
set
{
var f = File.OpenWrite(InternalName);
f.Write(value, 0, value.Length);
f.Close();
}
}
[DisableDump]
public FileStream Reader
=> new FileStream(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
? (FileSystemInfo)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];
f.Read(buffer, 0, size);
return Encoding.UTF8.GetString(buffer);
}
public void CheckedEnsureDirectoryOfFileExists()
{
if(AutoCreateDirectories)
EnsureDirectoryOfFileExists();
}
public void EnsureDirectoryOfFileExists()
=> DirectoryName?.ToSmbFile(false).EnsureIsExistentDirectory();
public void EnsureIsExistentDirectory()
{
if(Exists)
Tracer.Assert(IsDirectory);
else
{
EnsureDirectoryOfFileExists();
System.IO.Directory.CreateDirectory(FullName);
FileInfoCache = null;
}
}
public override string ToString() => FullName;
/// <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 ProcessStartInfo
{
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 SmbFile(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);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.